@contello/store 3.0.0 → 3.0.1

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
@@ -1,93 +1,86 @@
1
- "use strict";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
9
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
19
18
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Store: () => Store,
34
- createStore: () => createStore,
35
- maybeCatch: () => import_projected9.maybeCatch,
36
- maybeThen: () => import_projected9.maybeThen
37
- });
38
- module.exports = __toCommonJS(index_exports);
39
-
40
- // src/store.ts
41
- var import_client11 = require("@contello/client");
42
-
43
- // src/assets.ts
44
- var import_client2 = require("@contello/client");
45
- var import_projected = require("projected");
46
-
47
- // src/diagnostics.ts
48
- var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
49
- var channels = {
50
- start: "@contello/store:start",
51
- end: "@contello/store:end",
52
- error: "@contello/store:error"
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let _contello_client = require("@contello/client");
25
+ let projected = require("projected");
26
+ let node_diagnostics_channel = require("node:diagnostics_channel");
27
+ node_diagnostics_channel = __toESM(node_diagnostics_channel, 1);
28
+ let lru_cache = require("lru-cache");
29
+ //#region src/diagnostics.ts
30
+ const channels = {
31
+ start: "@contello/store:start",
32
+ end: "@contello/store:end",
33
+ error: "@contello/store:error"
53
34
  };
54
- var onStart = import_node_diagnostics_channel.default.channel(channels.start);
55
- var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
56
- var onError = import_node_diagnostics_channel.default.channel(channels.error);
35
+ const onStart = node_diagnostics_channel.default.channel(channels.start);
36
+ const onEnd = node_diagnostics_channel.default.channel(channels.end);
37
+ const onError = node_diagnostics_channel.default.channel(channels.error);
57
38
  function hasSubscribers() {
58
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
39
+ return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
59
40
  }
60
41
  function wrap(name, fn) {
61
- if (!hasSubscribers()) {
62
- return fn();
63
- }
64
- const start = performance.now();
65
- onStart.publish({ name });
66
- let result;
67
- try {
68
- result = fn();
69
- } catch (error) {
70
- onError.publish({ name, error, durationMs: performance.now() - start });
71
- throw error;
72
- }
73
- if (result instanceof Promise) {
74
- return result.then(
75
- (r) => {
76
- onEnd.publish({ name, cached: false, durationMs: performance.now() - start });
77
- return r;
78
- },
79
- (error) => {
80
- onError.publish({ name, error, durationMs: performance.now() - start });
81
- throw error;
82
- }
83
- );
84
- }
85
- onEnd.publish({ name, cached: true, durationMs: performance.now() - start });
86
- return result;
42
+ if (!hasSubscribers()) return fn();
43
+ const start = performance.now();
44
+ onStart.publish({ name });
45
+ let result;
46
+ try {
47
+ result = fn();
48
+ } catch (error) {
49
+ onError.publish({
50
+ name,
51
+ error,
52
+ durationMs: performance.now() - start
53
+ });
54
+ throw error;
55
+ }
56
+ if (result instanceof Promise) return (async () => {
57
+ try {
58
+ const r = await result;
59
+ onEnd.publish({
60
+ name,
61
+ cached: false,
62
+ durationMs: performance.now() - start
63
+ });
64
+ return r;
65
+ } catch (error) {
66
+ onError.publish({
67
+ name,
68
+ error,
69
+ durationMs: performance.now() - start
70
+ });
71
+ throw error;
72
+ }
73
+ })();
74
+ onEnd.publish({
75
+ name,
76
+ cached: true,
77
+ durationMs: performance.now() - start
78
+ });
79
+ return result;
87
80
  }
88
-
89
- // src/generated/graphql.ts
90
- var MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
81
+ //#endregion
82
+ //#region src/generated/graphql.ts
83
+ const MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
91
84
  id
92
85
  original {
93
86
  ...MediaFile
@@ -106,7 +99,7 @@ var MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
106
99
  }
107
100
  }
108
101
  }`;
109
- var MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {
102
+ const MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {
110
103
  uid
111
104
  mimeType
112
105
  metadata {
@@ -120,10 +113,10 @@ var MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {
120
113
  }
121
114
  }
122
115
  }`;
123
- var StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {
116
+ const StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {
124
117
  ...MediaAsset
125
118
  }`;
126
- var StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {
119
+ const StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {
127
120
  id
128
121
  token
129
122
  description
@@ -133,7 +126,7 @@ var StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nM
133
126
  value
134
127
  }
135
128
  }`;
136
- var StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
129
+ const StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
137
130
  id
138
131
  path
139
132
  target {
@@ -170,7 +163,7 @@ var StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
170
163
  value
171
164
  }
172
165
  }`;
173
- var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
166
+ const storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
174
167
  registerContelloI18nMessages(
175
168
  collectionReferenceName: $collection
176
169
  messages: $messages
@@ -179,7 +172,7 @@ var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($col
179
172
  ids
180
173
  }
181
174
  }`;
182
- var storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}
175
+ const storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}
183
176
  subscription StoreWatchUpdates {
184
177
  contelloUpdatesBatch {
185
178
  events {
@@ -211,1936 +204,1637 @@ subscription StoreWatchUpdates {
211
204
  }
212
205
  }
213
206
  }`;
214
- var operations = {
215
- storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: "mutation" },
216
- storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: "subscription" }
217
- };
218
- var sources = {
219
- storeAsset: {
220
- document: `${MediaFileFragmentSchema}
207
+ const schema = {
208
+ operations: {
209
+ storeRegisterI18nMessages: {
210
+ document: storeRegisterI18nMessagesDocument,
211
+ kind: "mutation"
212
+ },
213
+ storeWatchUpdates: {
214
+ document: storeWatchUpdatesDocument,
215
+ kind: "subscription"
216
+ }
217
+ },
218
+ sources: {
219
+ storeAsset: {
220
+ document: `${MediaFileFragmentSchema}
221
221
  ${MediaAssetFragmentSchema}
222
222
  ${StoreAssetFragmentSchema}`,
223
- fragment: "StoreAsset",
224
- subscription: "contelloAssetsBatch",
225
- __model: "storeAsset",
226
- __cardinality: "asset"
227
- },
228
- storeI18nMessage: {
229
- document: StoreI18nMessageFragmentSchema,
230
- fragment: "StoreI18nMessage",
231
- subscription: "contelloI18nMessagesBatch",
232
- __model: "storeI18nMessage",
233
- __cardinality: "i18nMessage"
234
- },
235
- storeRoute: {
236
- document: StoreRouteFragmentSchema,
237
- fragment: "StoreRoute",
238
- subscription: "contelloRoutesBatch",
239
- __model: "storeRoute",
240
- __cardinality: "route"
241
- }
242
- };
243
- var models = {
244
- dummy: "DummyEntity"
223
+ fragment: "StoreAsset",
224
+ subscription: "contelloAssetsBatch",
225
+ __model: "storeAsset",
226
+ __cardinality: "asset"
227
+ },
228
+ storeI18nMessage: {
229
+ document: StoreI18nMessageFragmentSchema,
230
+ fragment: "StoreI18nMessage",
231
+ subscription: "contelloI18nMessagesBatch",
232
+ __model: "storeI18nMessage",
233
+ __cardinality: "i18nMessage"
234
+ },
235
+ storeRoute: {
236
+ document: StoreRouteFragmentSchema,
237
+ fragment: "StoreRoute",
238
+ subscription: "contelloRoutesBatch",
239
+ __model: "storeRoute",
240
+ __cardinality: "route"
241
+ }
242
+ },
243
+ models: { dummy: "DummyEntity" }
245
244
  };
246
- var schema = { operations, sources, models };
247
-
248
- // src/utils.ts
249
- var import_client = require("@contello/client");
250
- var DEFAULT_TTL_MS = 3 * 60 * 60 * 1e3;
251
- var DEFAULT_LRU_MAX = 1e3;
245
+ //#endregion
246
+ //#region src/utils.ts
247
+ /**
248
+ * default `cache.ttl` applied across all store kinds. eager stores (collections, singletons)
249
+ * use it as the interval for a periodic full refresh; lazy stores use it as the per-item
250
+ * LRU eviction window. 3 hours.
251
+ */
252
+ const DEFAULT_TTL_MS = 10800 * 1e3;
253
+ /**
254
+ * resolves the consumer-supplied `ttl` (number | false | undefined) into a runtime
255
+ * value: undefined → default, false or 0 → disabled (undefined), positive → as-is.
256
+ */
252
257
  function resolveTtl(ttl) {
253
- if (ttl === void 0) return DEFAULT_TTL_MS;
254
- if (ttl === false || ttl <= 0) return void 0;
255
- return ttl;
258
+ if (ttl === void 0) return DEFAULT_TTL_MS;
259
+ if (ttl === false || ttl <= 0) return void 0;
260
+ return ttl;
256
261
  }
257
- function createRefresher(fn, onRefreshed, onStart2) {
258
- let refreshing = false;
259
- let inFlightKind;
260
- let pendingKind;
261
- function scheduleRefresh(kind) {
262
- if (refreshing) {
263
- pendingKind = { kind };
264
- return;
265
- }
266
- refreshing = true;
267
- inFlightKind = kind;
268
- onStart2?.();
269
- void (0, import_client.runWithBackoff)(fn).then(() => {
270
- const finished = inFlightKind;
271
- refreshing = false;
272
- inFlightKind = void 0;
273
- onRefreshed(finished);
274
- if (pendingKind) {
275
- const { kind: next } = pendingKind;
276
- pendingKind = void 0;
277
- scheduleRefresh(next);
278
- }
279
- });
280
- }
281
- return scheduleRefresh;
262
+ /**
263
+ * creates a coalescing refresh scheduler with exponential-backoff retry on failure.
264
+ *
265
+ * at most one refresh runs at a time. if a new refresh is requested while one is in-flight,
266
+ * it is queued as pending — the queued slot keeps the latest `kind` passed via
267
+ * scheduleRefresh. once the in-flight refresh completes, at most one queued refresh
268
+ * starts, with that latest kind — collapsing any number of intermediate requests into one.
269
+ *
270
+ * on error, retries indefinitely with exponential backoff. the projected value keeps serving
271
+ * the stale cached value throughout (SWR). the `onRefreshed` callback receives the kind that
272
+ * triggered the just-completed refresh.
273
+ */
274
+ function createRefresher(fn, onRefreshed, onStart) {
275
+ let refreshing = false;
276
+ let inFlightKind;
277
+ let pendingKind;
278
+ function scheduleRefresh(kind) {
279
+ if (refreshing) {
280
+ pendingKind = { kind };
281
+ return;
282
+ }
283
+ refreshing = true;
284
+ inFlightKind = kind;
285
+ onStart?.();
286
+ (0, _contello_client.runWithBackoff)(fn).then(() => {
287
+ const finished = inFlightKind;
288
+ refreshing = false;
289
+ inFlightKind = void 0;
290
+ onRefreshed(finished);
291
+ if (pendingKind) {
292
+ const { kind: next } = pendingKind;
293
+ pendingKind = void 0;
294
+ scheduleRefresh(next);
295
+ }
296
+ });
297
+ }
298
+ return scheduleRefresh;
282
299
  }
283
300
  function createRefreshChannel(onRefresh) {
284
- const stream$ = (0, import_client.createAsyncIterableSubject)();
285
- return {
286
- stream$,
287
- emit(event) {
288
- stream$.next(event);
289
- onRefresh?.(event);
290
- },
291
- complete() {
292
- stream$.complete();
293
- }
294
- };
301
+ const stream$ = (0, _contello_client.createAsyncIterableSubject)();
302
+ return {
303
+ stream$,
304
+ emit(event) {
305
+ stream$.next(event);
306
+ onRefresh?.(event);
307
+ },
308
+ complete() {
309
+ stream$.complete();
310
+ }
311
+ };
295
312
  }
296
313
  function createTtlOrchestrator(options) {
297
- let timer;
298
- return {
299
- mark() {
300
- if (timer !== void 0) {
301
- clearTimeout(timer);
302
- timer = void 0;
303
- }
304
- if (options.ttl === void 0) {
305
- return;
306
- }
307
- timer = setTimeout(options.run, options.ttl);
308
- },
309
- clear() {
310
- if (timer !== void 0) {
311
- clearTimeout(timer);
312
- timer = void 0;
313
- }
314
- }
315
- };
314
+ let timer;
315
+ return {
316
+ mark() {
317
+ if (timer !== void 0) {
318
+ clearTimeout(timer);
319
+ timer = void 0;
320
+ }
321
+ if (options.ttl === void 0) return;
322
+ timer = setTimeout(options.run, options.ttl);
323
+ },
324
+ clear() {
325
+ if (timer === void 0) return;
326
+ clearTimeout(timer);
327
+ timer = void 0;
328
+ }
329
+ };
316
330
  }
317
331
  function createRefreshByTtlQueue() {
318
- const waiting = [];
319
- let running = false;
320
- function next() {
321
- if (running) return;
322
- const task = waiting.shift();
323
- if (!task) return;
324
- running = true;
325
- Promise.resolve().then(task).catch(() => {
326
- }).finally(() => {
327
- running = false;
328
- next();
329
- });
330
- }
331
- return {
332
- enqueue(task) {
333
- waiting.push(task);
334
- next();
335
- }
336
- };
332
+ const waiting = [];
333
+ let running = false;
334
+ function next() {
335
+ if (running) return;
336
+ const task = waiting.shift();
337
+ if (!task) return;
338
+ running = true;
339
+ (async () => {
340
+ try {
341
+ await task();
342
+ } catch {} finally {
343
+ running = false;
344
+ next();
345
+ }
346
+ })();
347
+ }
348
+ return { enqueue(task) {
349
+ waiting.push(task);
350
+ next();
351
+ } };
337
352
  }
338
-
339
- // src/assets.ts
340
- function mapFile(raw) {
341
- return {
342
- uid: raw.uid,
343
- mimeType: raw.mimeType,
344
- metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : void 0
345
- };
353
+ //#endregion
354
+ //#region src/assets.ts
355
+ function mapFile$1(raw) {
356
+ return {
357
+ uid: raw.uid,
358
+ mimeType: raw.mimeType,
359
+ metadata: raw.metadata ? {
360
+ width: raw.metadata.width,
361
+ height: raw.metadata.height
362
+ } : void 0
363
+ };
346
364
  }
347
- function mapAsset(raw) {
348
- return {
349
- id: raw.id,
350
- original: mapFile(raw.original),
351
- preview: raw.preview ? mapFile(raw.preview) : void 0,
352
- optimized: raw.optimized.map((file) => mapFile(file))
353
- };
365
+ function mapAsset$1(raw) {
366
+ return {
367
+ id: raw.id,
368
+ original: mapFile$1(raw.original),
369
+ preview: raw.preview ? mapFile$1(raw.preview) : void 0,
370
+ optimized: raw.optimized.map((file) => mapFile$1(file))
371
+ };
354
372
  }
355
373
  function createAssetsCollection(options, client, updates$, refreshByTtl) {
356
- const opts = options ?? {};
357
- const cache = {
358
- ttl: resolveTtl(opts.cache?.ttl),
359
- eviction: opts.cache?.eviction ?? "refresh"
360
- };
361
- const channel = createRefreshChannel(opts.onRefresh);
362
- const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
363
- let loaded = false;
364
- const assetsSourceDoc = (0, import_client2.createSourceSubscription)(schema.sources.storeAsset);
365
- const projected = new import_projected.ProjectedMap({
366
- key: (asset) => asset.id,
367
- values: (ids) => wrap(
368
- "assets",
369
- () => (0, import_client2.collectAsync)(
370
- (0, import_client2.mapAsync)(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
371
- ).then((rawItems) => {
372
- const items = rawItems.map((item) => mapAsset(item));
373
- if (ids === void 0 && !loaded) {
374
- loaded = true;
375
- ttl.mark();
376
- opts.onLoad?.(items.map((a) => a.id));
377
- }
378
- return items;
379
- })
380
- )
381
- });
382
- function emit(ids, kind) {
383
- channel.emit({ ids, kind });
384
- }
385
- function runFullRefresh(kind) {
386
- refreshByTtl.enqueue(
387
- () => (0, import_client2.runWithBackoff)(
388
- () => projected.refresh().then((map) => {
389
- emit([...map.keys()], kind);
390
- ttl.mark();
391
- })
392
- )
393
- );
394
- }
395
- function runPartialRefresh(refreshIds, deletedIds) {
396
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
397
- if (refreshIds.length === 0) {
398
- emit(changedIds, "upstream-update");
399
- return;
400
- }
401
- void (0, import_client2.runWithBackoff)(
402
- () => projected.refresh(refreshIds).then(() => {
403
- emit(changedIds, "upstream-update");
404
- })
405
- );
406
- }
407
- const unsubUpdates = updates$.subscribe((batch) => {
408
- if (!loaded || batch.asset.length === 0) {
409
- return;
410
- }
411
- const deleted = [];
412
- const upserted = /* @__PURE__ */ new Set();
413
- for (const event of batch.asset) {
414
- if (event.mutation === "delete") {
415
- deleted.push(event.id);
416
- } else {
417
- upserted.add(event.id);
418
- }
419
- }
420
- if (cache.eviction === "clear") {
421
- projected.clear();
422
- return;
423
- }
424
- if (deleted.length > 0) {
425
- projected.delete(deleted);
426
- }
427
- runPartialRefresh([...upserted], deleted);
428
- });
429
- const instance = {
430
- refresh$: channel.stream$,
431
- async load() {
432
- if (!loaded) {
433
- await projected.getAllAsMap();
434
- }
435
- },
436
- get(idOrIds) {
437
- return projected.get(idOrIds);
438
- },
439
- upload(data, meta, options2) {
440
- return client.upload(data, meta, options2);
441
- },
442
- download(fileId) {
443
- return client.download(fileId);
444
- },
445
- proxyHls(path, signal) {
446
- return client.proxyHls(path, signal);
447
- },
448
- refresh() {
449
- runFullRefresh("on-demand");
450
- }
451
- };
452
- return {
453
- instance,
454
- destroy() {
455
- unsubUpdates();
456
- ttl.clear();
457
- channel.complete();
458
- }
459
- };
374
+ const opts = options ?? {};
375
+ const cache = {
376
+ ttl: resolveTtl(opts.cache?.ttl),
377
+ eviction: opts.cache?.eviction ?? "refresh"
378
+ };
379
+ const channel = createRefreshChannel(opts.onRefresh);
380
+ const ttl = createTtlOrchestrator({
381
+ ttl: cache.ttl,
382
+ run: () => runFullRefresh("ttl")
383
+ });
384
+ let loaded = false;
385
+ const assetsSourceDoc = (0, _contello_client.createSourceSubscription)(schema.sources.storeAsset);
386
+ const projected$8 = new projected.ProjectedMap({
387
+ key: (asset) => asset.id,
388
+ values: (ids) => wrap("assets", async () => {
389
+ const items = (await (0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source))).map((item) => mapAsset$1(item));
390
+ if (ids === void 0 && !loaded) {
391
+ loaded = true;
392
+ ttl.mark();
393
+ opts.onLoad?.(items.map((a) => a.id));
394
+ }
395
+ return items;
396
+ })
397
+ });
398
+ function emit(ids, kind) {
399
+ channel.emit({
400
+ ids,
401
+ kind
402
+ });
403
+ }
404
+ function runFullRefresh(kind) {
405
+ refreshByTtl.enqueue(() => (0, _contello_client.runWithBackoff)(async () => {
406
+ emit((await projected$8.refresh()).keys().toArray(), kind);
407
+ ttl.mark();
408
+ }));
409
+ }
410
+ function runPartialRefresh(refreshIds, deletedIds) {
411
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
412
+ if (refreshIds.length === 0) {
413
+ emit(changedIds, "upstream-update");
414
+ return;
415
+ }
416
+ (0, _contello_client.runWithBackoff)(async () => {
417
+ await projected$8.refresh(refreshIds);
418
+ emit(changedIds, "upstream-update");
419
+ });
420
+ }
421
+ const unsubUpdates = updates$.subscribe((batch) => {
422
+ if (!loaded || batch.asset.length === 0) return;
423
+ const deleted = [];
424
+ const upserted = /* @__PURE__ */ new Set();
425
+ for (const event of batch.asset) if (event.mutation === "delete") deleted.push(event.id);
426
+ else upserted.add(event.id);
427
+ if (cache.eviction === "clear") {
428
+ projected$8.clear();
429
+ return;
430
+ }
431
+ if (deleted.length > 0) projected$8.delete(deleted);
432
+ runPartialRefresh([...upserted], deleted);
433
+ });
434
+ return {
435
+ instance: {
436
+ refresh$: channel.stream$,
437
+ async load() {
438
+ if (!loaded) await projected$8.getAllAsMap();
439
+ },
440
+ get(idOrIds) {
441
+ return projected$8.get(idOrIds);
442
+ },
443
+ upload(data, meta, options) {
444
+ return client.upload(data, meta, options);
445
+ },
446
+ download(fileId) {
447
+ return client.download(fileId);
448
+ },
449
+ proxyHls(path, signal) {
450
+ return client.proxyHls(path, signal);
451
+ },
452
+ refresh() {
453
+ runFullRefresh("on-demand");
454
+ }
455
+ },
456
+ destroy() {
457
+ unsubUpdates();
458
+ ttl.clear();
459
+ channel.complete();
460
+ }
461
+ };
460
462
  }
461
463
  function createAssetsSyncCollection(options, client, updates$, refreshByTtl) {
462
- const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);
463
- function assertSync(value, method) {
464
- if (value instanceof Promise) {
465
- throw new TypeError(`assets.${method}() is not initialized yet \u2014 call assets.load() first`);
466
- }
467
- return value;
468
- }
469
- return {
470
- instance: {
471
- ...base,
472
- get(idOrIds) {
473
- return assertSync(base.get(idOrIds), "get");
474
- }
475
- },
476
- destroy
477
- };
464
+ const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);
465
+ function assertSync(value, method) {
466
+ if (value instanceof Promise) throw new TypeError(`assets.${method}() is not initialized yet — call assets.load() first`);
467
+ return value;
468
+ }
469
+ return {
470
+ instance: {
471
+ ...base,
472
+ get(idOrIds) {
473
+ return assertSync(base.get(idOrIds), "get");
474
+ }
475
+ },
476
+ destroy
477
+ };
478
478
  }
479
-
480
- // src/collection.ts
481
- var import_client3 = require("@contello/client");
482
- var import_projected2 = require("projected");
483
-
484
- // src/dependency-collector.ts
485
- var EMPTY_KEYS = /* @__PURE__ */ new Set();
479
+ //#endregion
480
+ //#region src/dependency-collector.ts
481
+ const EMPTY_KEYS = /* @__PURE__ */ new Set();
486
482
  function createDependencyKey(target, id) {
487
- return `${target}\0${id}`;
483
+ return `${target}\0${id}`;
488
484
  }
489
485
  function createEntityDependencyKey(typename, id) {
490
- return `entity\0${typename}\0${id}`;
486
+ return `entity\0${typename}\0${id}`;
491
487
  }
492
488
  function createRouteTargetKey(typename, id) {
493
- return `routeTarget\0${typename}\0${id}`;
489
+ return `routeTarget\0${typename}\0${id}`;
494
490
  }
491
+ /**
492
+ * bidirectional dependency index for a single collection.
493
+ *
494
+ * during each map cycle, `createContext` is called per item. it creates a `MapperContext` the mapper
495
+ * uses to declare cross-entity dependencies, and a `register(key)` function the caller invokes
496
+ * once the item key is known. `register` flushes the collected deps into two maps:
497
+ *
498
+ * forwardIndex: item key -> set of dep keys it declared
499
+ * reverseIndex: dep key -> set of item keys that declared it
500
+ *
501
+ * the reverse map is the hot path: given an update event (typename + id), `getAffectedKeys()`
502
+ * looks up the dep key and returns all item keys that need to be invalidated.
503
+ *
504
+ * lifecycle per map cycle:
505
+ * 1. createContext(fn) — allocates deps array, creates MapperContext, calls fn(ctx, register)
506
+ * 2. fn calls map(raw, ctx) — mapper runs, calls track methods, fills deps array
507
+ * 3. fn calls register(key) — real item key is known, deps written into both maps
508
+ */
495
509
  var DependencyCollector = class {
496
- constructor(model, resolver) {
497
- this.model = model;
498
- this.resolver = resolver;
499
- }
500
- /** dep key -> item keys that declared a dependency on it */
501
- reverseIndex = /* @__PURE__ */ new Map();
502
- /** item key -> dep keys it currently declares */
503
- forwardIndex = /* @__PURE__ */ new Map();
504
- /**
505
- * creates a scoped MapperContext for one item and runs `fn` with it.
506
- * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function
507
- * that must be called once the item key is known — it writes all declared deps into the index.
508
- * returns whatever `fn` returns, preserving MaybePromise semantics.
509
- */
510
- createContext(fn) {
511
- const deps = [];
512
- const ctx = {
513
- track: (obj) => {
514
- if (!obj.id) {
515
- throw new Error(`track(): object with __typename "${obj.__typename}" has no "id" field`);
516
- }
517
- switch (obj.__typename) {
518
- case "ContelloAsset": {
519
- deps.push(createDependencyKey("asset", obj.id));
520
- break;
521
- }
522
- case "ContelloRoute": {
523
- deps.push(createDependencyKey("route", obj.id));
524
- break;
525
- }
526
- default: {
527
- const model = this.resolver.getModel(obj.__typename);
528
- if (!model) {
529
- throw new Error(
530
- `track(): unexpected __typename "${obj.__typename}" \u2014 expected ContelloAsset, ContelloRoute, or a known entity model`
531
- );
532
- }
533
- deps.push(createEntityDependencyKey(model, obj.id));
534
- }
535
- }
536
- },
537
- trackEntity: (model, id) => {
538
- this.warnIfUnknownModel(model);
539
- deps.push(createEntityDependencyKey(model, id));
540
- },
541
- trackAsset: (id) => deps.push(createDependencyKey("asset", id)),
542
- trackRoute: (id) => deps.push(createDependencyKey("route", id))
543
- };
544
- const register = (key) => {
545
- this.clearItem(key);
546
- deps.push(createRouteTargetKey(this.model, String(key)));
547
- const fwd = /* @__PURE__ */ new Set();
548
- for (const dk of deps) {
549
- fwd.add(dk);
550
- let set = this.reverseIndex.get(dk);
551
- if (!set) {
552
- set = /* @__PURE__ */ new Set();
553
- this.reverseIndex.set(dk, set);
554
- }
555
- set.add(key);
556
- }
557
- if (fwd.size > 0) {
558
- this.forwardIndex.set(key, fwd);
559
- }
560
- };
561
- return fn(ctx, register);
562
- }
563
- /**
564
- * looks up which item keys are affected by an update event.
565
- * for route events, checks route-target deps for both the new and previous entity targets.
566
- */
567
- getAffectedKeys(event) {
568
- if (event.target === "entity") {
569
- return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;
570
- }
571
- let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));
572
- if (event.target === "route") {
573
- if ("after" in event && event.after.type === "entity") {
574
- affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);
575
- }
576
- if ("before" in event && event.before.type === "entity") {
577
- affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);
578
- }
579
- }
580
- return affected ?? EMPTY_KEYS;
581
- }
582
- mergeRouteTargetKeys(existing, entityType, entityId) {
583
- const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));
584
- if (!items) {
585
- return existing;
586
- }
587
- return existing ? /* @__PURE__ */ new Set([...existing, ...items]) : items;
588
- }
589
- /** removes all recorded deps for a single item (called on eviction) */
590
- removeItem(key) {
591
- this.clearItem(key);
592
- }
593
- /** drops all recorded deps — used when clearing the entire cache */
594
- clear() {
595
- this.reverseIndex.clear();
596
- this.forwardIndex.clear();
597
- }
598
- /**
599
- * removes index entries for any item key NOT present in `keys`.
600
- * called after a full re-fetch to prune refs from items that were deleted upstream.
601
- */
602
- retainOnly(keys) {
603
- for (const key of this.forwardIndex.keys()) {
604
- if (!keys.has(key)) {
605
- this.clearItem(key);
606
- }
607
- }
608
- }
609
- warnIfUnknownModel(model) {
610
- if (!this.resolver.hasModel(model)) {
611
- console.warn(
612
- `[contello/store] tracking model "${model}" which is not in models \u2014 updates for this model will be ignored`
613
- );
614
- }
615
- }
616
- /**
617
- * removes all index entries for one item key.
618
- * cleans up the forward entry and removes the item from every reverse set it appeared in.
619
- * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.
620
- */
621
- clearItem(key) {
622
- const existingDeps = this.forwardIndex.get(key);
623
- if (!existingDeps) {
624
- return;
625
- }
626
- for (const dk of existingDeps) {
627
- const set = this.reverseIndex.get(dk);
628
- if (set) {
629
- set.delete(key);
630
- if (set.size === 0) {
631
- this.reverseIndex.delete(dk);
632
- }
633
- }
634
- }
635
- this.forwardIndex.delete(key);
636
- }
510
+ model;
511
+ resolver;
512
+ /** dep key -> item keys that declared a dependency on it */
513
+ reverseIndex = /* @__PURE__ */ new Map();
514
+ /** item key -> dep keys it currently declares */
515
+ forwardIndex = /* @__PURE__ */ new Map();
516
+ constructor(model, resolver) {
517
+ this.model = model;
518
+ this.resolver = resolver;
519
+ }
520
+ mergeRouteTargetKeys(existing, entityType, entityId) {
521
+ const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));
522
+ if (!items) return existing;
523
+ return existing ? existing.union(items) : items;
524
+ }
525
+ warnIfUnknownModel(model) {
526
+ if (!this.resolver.hasModel(model)) console.warn(`[contello/store] tracking model "${model}" which is not in models — updates for this model will be ignored`);
527
+ }
528
+ /**
529
+ * removes all index entries for one item key.
530
+ * cleans up the forward entry and removes the item from every reverse set it appeared in.
531
+ * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.
532
+ */
533
+ clearItem(key) {
534
+ const existingDeps = this.forwardIndex.get(key);
535
+ if (!existingDeps) return;
536
+ for (const dk of existingDeps) {
537
+ const set = this.reverseIndex.get(dk);
538
+ if (set) {
539
+ set.delete(key);
540
+ if (set.size === 0) this.reverseIndex.delete(dk);
541
+ }
542
+ }
543
+ this.forwardIndex.delete(key);
544
+ }
545
+ /**
546
+ * creates a scoped MapperContext for one item and runs `fn` with it.
547
+ * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function
548
+ * that must be called once the item key is known — it writes all declared deps into the index.
549
+ * returns whatever `fn` returns, preserving MaybePromise semantics.
550
+ */
551
+ createContext(fn) {
552
+ const deps = [];
553
+ const ctx = {
554
+ track: (obj) => {
555
+ if (!obj.id) throw new Error(`track(): object with __typename "${obj.__typename}" has no "id" field`);
556
+ switch (obj.__typename) {
557
+ case "ContelloAsset":
558
+ deps.push(createDependencyKey("asset", obj.id));
559
+ break;
560
+ case "ContelloRoute":
561
+ deps.push(createDependencyKey("route", obj.id));
562
+ break;
563
+ default: {
564
+ const model = this.resolver.getModel(obj.__typename);
565
+ if (!model) throw new Error(`track(): unexpected __typename "${obj.__typename}" — expected ContelloAsset, ContelloRoute, or a known entity model`);
566
+ deps.push(createEntityDependencyKey(model, obj.id));
567
+ }
568
+ }
569
+ },
570
+ trackEntity: (model, id) => {
571
+ this.warnIfUnknownModel(model);
572
+ deps.push(createEntityDependencyKey(model, id));
573
+ },
574
+ trackAsset: (id) => {
575
+ deps.push(createDependencyKey("asset", id));
576
+ },
577
+ trackRoute: (id) => {
578
+ deps.push(createDependencyKey("route", id));
579
+ }
580
+ };
581
+ const register = (key) => {
582
+ this.clearItem(key);
583
+ deps.push(createRouteTargetKey(this.model, String(key)));
584
+ const fwd = /* @__PURE__ */ new Set();
585
+ for (const dk of deps) {
586
+ fwd.add(dk);
587
+ let set = this.reverseIndex.get(dk);
588
+ if (!set) {
589
+ set = /* @__PURE__ */ new Set();
590
+ this.reverseIndex.set(dk, set);
591
+ }
592
+ set.add(key);
593
+ }
594
+ if (fwd.size > 0) this.forwardIndex.set(key, fwd);
595
+ };
596
+ return fn(ctx, register);
597
+ }
598
+ /**
599
+ * looks up which item keys are affected by an update event.
600
+ * for route events, checks route-target deps for both the new and previous entity targets.
601
+ */
602
+ getAffectedKeys(event) {
603
+ if (event.target === "entity") return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;
604
+ let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));
605
+ if (event.target === "route") {
606
+ if ("after" in event && event.after.type === "entity") affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);
607
+ if ("before" in event && event.before.type === "entity") affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);
608
+ }
609
+ return affected ?? EMPTY_KEYS;
610
+ }
611
+ /** removes all recorded deps for a single item (called on eviction) */
612
+ removeItem(key) {
613
+ this.clearItem(key);
614
+ }
615
+ /** drops all recorded deps — used when clearing the entire cache */
616
+ clear() {
617
+ this.reverseIndex.clear();
618
+ this.forwardIndex.clear();
619
+ }
620
+ /**
621
+ * removes index entries for any item key NOT present in `keys`.
622
+ * called after a full re-fetch to prune refs from items that were deleted upstream.
623
+ */
624
+ retainOnly(keys) {
625
+ for (const key of this.forwardIndex.keys()) if (!keys.has(key)) this.clearItem(key);
626
+ }
637
627
  };
638
-
639
- // src/collection.ts
628
+ //#endregion
629
+ //#region src/collection.ts
640
630
  function fetchCollection(source, client, ids) {
641
- return (0, import_client3.collectAsync)(
642
- (0, import_client3.mapAsync)(
643
- client.subscribe((0, import_client3.createSourceSubscription)(source), { ids }),
644
- (r) => r.source
645
- )
646
- );
631
+ return (0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe((0, _contello_client.createSourceSubscription)(source), { ids }), (r) => r.source));
647
632
  }
648
633
  function createCollection(source, options, client, updates$, resolver, refreshByTtl) {
649
- const opts = options ?? {};
650
- const mapFn = opts.map ?? ((item) => item);
651
- const _def = {
652
- name: opts.name ?? source.__model,
653
- model: source.__model,
654
- cache: {
655
- ttl: resolveTtl(opts.cache?.ttl),
656
- eviction: opts.cache?.eviction ?? "refresh"
657
- }
658
- };
659
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
660
- const channel = createRefreshChannel(opts.onRefresh);
661
- const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh("ttl") });
662
- let loaded = false;
663
- const projected = new import_projected2.ProjectedMap({
664
- key: (item) => item.id,
665
- values: (ids) => wrap(
666
- `collection:${_def.name}`,
667
- () => (0, import_projected2.maybeThen)(
668
- fetchCollection(source, client, ids),
669
- (rawItems) => Promise.all(
670
- rawItems.map(
671
- (item) => Promise.resolve(
672
- dependencyCollector.createContext(
673
- (ref, register) => (0, import_projected2.maybeThen)(mapFn(item, ref), (mapped) => {
674
- register(mapped.id);
675
- return mapped;
676
- })
677
- )
678
- )
679
- )
680
- ).then((items) => {
681
- if (ids === void 0) {
682
- dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
683
- if (!loaded) {
684
- loaded = true;
685
- ttl.mark();
686
- opts.onLoad?.(items.map((item) => item.id));
687
- }
688
- } else {
689
- const returnedIds = new Set(items.map((item) => item.id));
690
- for (const id of ids) {
691
- if (!returnedIds.has(id)) {
692
- dependencyCollector.removeItem(id);
693
- }
694
- }
695
- }
696
- return items;
697
- })
698
- )
699
- ),
700
- sort: opts.sort
701
- });
702
- function emit(ids, kind) {
703
- channel.emit({ ids, kind });
704
- }
705
- function runFullRefresh(kind) {
706
- refreshByTtl.enqueue(
707
- () => (0, import_client3.runWithBackoff)(
708
- () => projected.refresh().then((map) => {
709
- emit([...map.keys()], kind);
710
- ttl.mark();
711
- })
712
- )
713
- );
714
- }
715
- function runPartialRefresh(refreshIds, deletedIds) {
716
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
717
- if (refreshIds.length === 0) {
718
- emit(changedIds, "upstream-update");
719
- return;
720
- }
721
- void (0, import_client3.runWithBackoff)(
722
- () => projected.refresh(refreshIds).then(() => {
723
- emit(changedIds, "upstream-update");
724
- })
725
- );
726
- }
727
- const unsubUpdates = updates$.subscribe((batch) => {
728
- if (!loaded) {
729
- return;
730
- }
731
- const ownEvents = batch.entity.get(_def.model) ?? [];
732
- const deleted = [];
733
- const upserted = /* @__PURE__ */ new Set();
734
- for (const event of ownEvents) {
735
- if (event.mutation === "delete") {
736
- deleted.push(event.id);
737
- } else {
738
- upserted.add(event.id);
739
- }
740
- }
741
- const depAffected = /* @__PURE__ */ new Set();
742
- for (const event of batch.events) {
743
- for (const id of dependencyCollector.getAffectedKeys(event)) {
744
- depAffected.add(id);
745
- }
746
- }
747
- if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {
748
- return;
749
- }
750
- if (_def.cache.eviction === "clear") {
751
- dependencyCollector.clear();
752
- projected.clear();
753
- return;
754
- }
755
- for (const id of deleted) {
756
- dependencyCollector.removeItem(id);
757
- }
758
- if (deleted.length > 0) {
759
- projected.delete(deleted);
760
- }
761
- const refreshIds = /* @__PURE__ */ new Set([...upserted, ...depAffected]);
762
- for (const id of deleted) {
763
- refreshIds.delete(id);
764
- }
765
- runPartialRefresh([...refreshIds], deleted);
766
- });
767
- const instance = {
768
- name: _def.name,
769
- refresh$: channel.stream$,
770
- get(idOrIds) {
771
- return projected.get(idOrIds);
772
- },
773
- getAll() {
774
- return projected.getAll();
775
- },
776
- refresh() {
777
- runFullRefresh("on-demand");
778
- },
779
- async load() {
780
- if (!loaded) {
781
- await projected.getAllAsMap();
782
- }
783
- }
784
- };
785
- return {
786
- instance,
787
- destroy() {
788
- unsubUpdates();
789
- ttl.clear();
790
- channel.complete();
791
- }
792
- };
634
+ const opts = options ?? {};
635
+ const mapFn = opts.map ?? ((item) => item);
636
+ const _def = {
637
+ name: opts.name ?? source.__model,
638
+ model: source.__model,
639
+ cache: {
640
+ ttl: resolveTtl(opts.cache?.ttl),
641
+ eviction: opts.cache?.eviction ?? "refresh"
642
+ }
643
+ };
644
+ const dependencyCollector = new DependencyCollector(_def.model, resolver);
645
+ const channel = createRefreshChannel(opts.onRefresh);
646
+ const ttl = createTtlOrchestrator({
647
+ ttl: _def.cache.ttl,
648
+ run: () => runFullRefresh("ttl")
649
+ });
650
+ let loaded = false;
651
+ const projected$7 = new projected.ProjectedMap({
652
+ key: (item) => item.id,
653
+ values: (ids) => wrap(`collection:${_def.name}`, () => (0, projected.maybeThen)(fetchCollection(source, client, ids), async (rawItems) => {
654
+ const items = await Promise.all(rawItems.map((item) => Promise.resolve(dependencyCollector.createContext((ref, register) => (0, projected.maybeThen)(mapFn(item, ref), (mapped) => {
655
+ register(mapped.id);
656
+ return mapped;
657
+ })))));
658
+ if (ids === void 0) {
659
+ dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
660
+ if (!loaded) {
661
+ loaded = true;
662
+ ttl.mark();
663
+ opts.onLoad?.(items.map((item) => item.id));
664
+ }
665
+ } else {
666
+ const returnedIds = new Set(items.map((item) => item.id));
667
+ for (const id of ids) if (!returnedIds.has(id)) dependencyCollector.removeItem(id);
668
+ }
669
+ return items;
670
+ })),
671
+ sort: opts.sort
672
+ });
673
+ function emit(ids, kind) {
674
+ channel.emit({
675
+ ids,
676
+ kind
677
+ });
678
+ }
679
+ function runFullRefresh(kind) {
680
+ refreshByTtl.enqueue(() => (0, _contello_client.runWithBackoff)(async () => {
681
+ emit((await projected$7.refresh()).keys().toArray(), kind);
682
+ ttl.mark();
683
+ }));
684
+ }
685
+ function runPartialRefresh(refreshIds, deletedIds) {
686
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
687
+ if (refreshIds.length === 0) {
688
+ emit(changedIds, "upstream-update");
689
+ return;
690
+ }
691
+ (0, _contello_client.runWithBackoff)(async () => {
692
+ await projected$7.refresh(refreshIds);
693
+ emit(changedIds, "upstream-update");
694
+ });
695
+ }
696
+ const unsubUpdates = updates$.subscribe((batch) => {
697
+ if (!loaded) return;
698
+ const ownEvents = batch.entity.get(_def.model) ?? [];
699
+ const deleted = [];
700
+ const upserted = /* @__PURE__ */ new Set();
701
+ for (const event of ownEvents) if (event.mutation === "delete") deleted.push(event.id);
702
+ else upserted.add(event.id);
703
+ const depAffected = /* @__PURE__ */ new Set();
704
+ for (const event of batch.events) for (const id of dependencyCollector.getAffectedKeys(event)) depAffected.add(id);
705
+ if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) return;
706
+ if (_def.cache.eviction === "clear") {
707
+ dependencyCollector.clear();
708
+ projected$7.clear();
709
+ return;
710
+ }
711
+ for (const id of deleted) dependencyCollector.removeItem(id);
712
+ if (deleted.length > 0) projected$7.delete(deleted);
713
+ const refreshIds = upserted.union(depAffected);
714
+ for (const id of deleted) refreshIds.delete(id);
715
+ runPartialRefresh([...refreshIds], deleted);
716
+ });
717
+ return {
718
+ instance: {
719
+ name: _def.name,
720
+ refresh$: channel.stream$,
721
+ get(idOrIds) {
722
+ return projected$7.get(idOrIds);
723
+ },
724
+ getAll() {
725
+ return projected$7.getAll();
726
+ },
727
+ refresh() {
728
+ runFullRefresh("on-demand");
729
+ },
730
+ async load() {
731
+ if (!loaded) await projected$7.getAllAsMap();
732
+ }
733
+ },
734
+ destroy() {
735
+ unsubUpdates();
736
+ ttl.clear();
737
+ channel.complete();
738
+ }
739
+ };
793
740
  }
794
741
  function createCollectionSync(source, options, client, updates$, resolver, refreshByTtl) {
795
- const { instance: base, destroy } = createCollection(
796
- source,
797
- options,
798
- client,
799
- updates$,
800
- resolver,
801
- refreshByTtl
802
- );
803
- function assertSync(value, method) {
804
- if (value instanceof Promise) {
805
- throw new TypeError(`collection "${base.name}".${method}() is not initialized yet \u2014 call collection.load() first`);
806
- }
807
- return value;
808
- }
809
- return {
810
- instance: {
811
- ...base,
812
- get(idOrIds) {
813
- return assertSync(base.get(idOrIds), "get");
814
- },
815
- getAll() {
816
- return assertSync(base.getAll(), "getAll");
817
- }
818
- },
819
- destroy
820
- };
742
+ const { instance: base, destroy } = createCollection(source, options, client, updates$, resolver, refreshByTtl);
743
+ function assertSync(value, method) {
744
+ if (value instanceof Promise) throw new TypeError(`collection "${base.name}".${method}() is not initialized yet — call collection.load() first`);
745
+ return value;
746
+ }
747
+ return {
748
+ instance: {
749
+ ...base,
750
+ get(idOrIds) {
751
+ return assertSync(base.get(idOrIds), "get");
752
+ },
753
+ getAll() {
754
+ return assertSync(base.getAll(), "getAll");
755
+ }
756
+ },
757
+ destroy
758
+ };
821
759
  }
822
-
823
- // src/i18n.ts
824
- var import_client4 = require("@contello/client");
825
- var import_projected3 = require("projected");
760
+ //#endregion
761
+ //#region src/i18n.ts
826
762
  function toGqlMessageInput(msg) {
827
- return {
828
- token: msg.token,
829
- example: msg.example,
830
- description: msg.description,
831
- variables: msg.variables?.map((v) => ({ name: v.name, description: v.description, example: v.example })),
832
- translations: msg.translations?.map((t) => ({ language: t.language, message: t.message })),
833
- initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message }))
834
- };
763
+ return {
764
+ token: msg.token,
765
+ example: msg.example,
766
+ description: msg.description,
767
+ variables: msg.variables?.map((v) => ({
768
+ name: v.name,
769
+ description: v.description,
770
+ example: v.example
771
+ })),
772
+ translations: msg.translations?.map((t) => ({
773
+ language: t.language,
774
+ message: t.message
775
+ })),
776
+ initialTranslations: msg.initialTranslations?.map((t) => ({
777
+ language: t.language,
778
+ message: t.message
779
+ }))
780
+ };
835
781
  }
836
782
  function createI18nMessagesCollection(def, client, updates$, refreshByTtl) {
837
- const channel = createRefreshChannel(def.onRefresh);
838
- const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });
839
- let loaded = false;
840
- const i18nSourceDoc = (0, import_client4.createSourceSubscription)(schema.sources.storeI18nMessage);
841
- const projected = new import_projected3.ProjectedMap({
842
- key: (msg) => msg.id,
843
- values: (ids) => wrap(
844
- `i18n:${def.collection}`,
845
- () => (0, import_client4.collectAsync)(
846
- (0, import_client4.mapAsync)(
847
- client.subscribe(i18nSourceDoc, {
848
- collection: def.collection,
849
- ids
850
- }),
851
- (data) => data.source
852
- )
853
- ).then((msgs) => {
854
- const items = msgs.map((msg) => ({
855
- id: msg.id,
856
- token: msg.token,
857
- translations: new Map(msg.translations.map((t) => [t.language, t.value]))
858
- }));
859
- if (ids === void 0 && !loaded) {
860
- loaded = true;
861
- ttl.mark();
862
- }
863
- return items;
864
- })
865
- )
866
- });
867
- function emit(ids, kind) {
868
- channel.emit({ ids, kind });
869
- }
870
- function emitWithCurrentIds(kind) {
871
- (0, import_projected3.maybeThen)(projected.getAll(), (msgs) => {
872
- emit(
873
- msgs.map((m) => m.id),
874
- kind
875
- );
876
- });
877
- }
878
- function runTtlRefresh() {
879
- refreshByTtl.enqueue(
880
- () => (0, import_client4.runWithBackoff)(() => projected.refresh()).then(() => {
881
- emitWithCurrentIds("ttl");
882
- ttl.mark();
883
- })
884
- );
885
- }
886
- const scheduleRefresh = createRefresher(
887
- () => projected.refresh(),
888
- (kind) => {
889
- emitWithCurrentIds(kind);
890
- ttl.mark();
891
- },
892
- () => {
893
- }
894
- );
895
- function runPartialRefresh(upsertedIds, deletedIds) {
896
- const changedIds = [.../* @__PURE__ */ new Set([...upsertedIds, ...deletedIds])];
897
- if (changedIds.length === 0) {
898
- return;
899
- }
900
- if (upsertedIds.length === 0) {
901
- emit(changedIds, "upstream-update");
902
- return;
903
- }
904
- void (0, import_client4.runWithBackoff)(
905
- () => projected.refresh(upsertedIds).then(() => {
906
- emit(changedIds, "upstream-update");
907
- })
908
- );
909
- }
910
- const unsubUpdates = updates$.subscribe((batch) => {
911
- if (!loaded) {
912
- return;
913
- }
914
- if (batch.i18nMessage.length === 0) {
915
- return;
916
- }
917
- const deleted = [];
918
- const upserted = /* @__PURE__ */ new Set();
919
- for (const event of batch.i18nMessage) {
920
- if (event.mutation === "delete") {
921
- deleted.push(event.id);
922
- } else {
923
- upserted.add(event.id);
924
- }
925
- }
926
- if (deleted.length > 0) {
927
- projected.delete(deleted);
928
- }
929
- runPartialRefresh([...upserted], deleted);
930
- });
931
- return {
932
- refresh$: channel.stream$,
933
- get(idOrIds) {
934
- return projected.get(idOrIds);
935
- },
936
- getAll() {
937
- return projected.getAll();
938
- },
939
- register(messages) {
940
- return wrap(
941
- `i18n-register:${def.collection}`,
942
- () => client.execute(storeRegisterI18nMessagesDocument, {
943
- collection: def.collection,
944
- messages: messages.map((message) => toGqlMessageInput(message))
945
- }).then(() => {
946
- })
947
- );
948
- },
949
- refresh() {
950
- scheduleRefresh("on-demand");
951
- },
952
- destroy() {
953
- unsubUpdates();
954
- ttl.clear();
955
- channel.complete();
956
- }
957
- };
783
+ const channel = createRefreshChannel(def.onRefresh);
784
+ const ttl = createTtlOrchestrator({
785
+ ttl: resolveTtl(def.cache?.ttl),
786
+ run: () => runTtlRefresh()
787
+ });
788
+ let loaded = false;
789
+ const i18nSourceDoc = (0, _contello_client.createSourceSubscription)(schema.sources.storeI18nMessage);
790
+ const projected$6 = new projected.ProjectedMap({
791
+ key: (msg) => msg.id,
792
+ values: (ids) => wrap(`i18n:${def.collection}`, async () => {
793
+ const items = (await (0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe(i18nSourceDoc, {
794
+ collection: def.collection,
795
+ ids
796
+ }), (data) => data.source))).map((msg) => ({
797
+ id: msg.id,
798
+ token: msg.token,
799
+ translations: new Map(msg.translations.map((t) => [t.language, t.value]))
800
+ }));
801
+ if (ids === void 0 && !loaded) {
802
+ loaded = true;
803
+ ttl.mark();
804
+ }
805
+ return items;
806
+ })
807
+ });
808
+ function emit(ids, kind) {
809
+ channel.emit({
810
+ ids,
811
+ kind
812
+ });
813
+ }
814
+ function emitWithCurrentIds(kind) {
815
+ (0, projected.maybeThen)(projected$6.getAll(), (msgs) => {
816
+ emit(msgs.map((m) => m.id), kind);
817
+ });
818
+ }
819
+ function runTtlRefresh() {
820
+ refreshByTtl.enqueue(async () => {
821
+ await (0, _contello_client.runWithBackoff)(() => projected$6.refresh());
822
+ emitWithCurrentIds("ttl");
823
+ ttl.mark();
824
+ });
825
+ }
826
+ const scheduleRefresh = createRefresher(() => projected$6.refresh(), (kind) => {
827
+ emitWithCurrentIds(kind);
828
+ ttl.mark();
829
+ }, () => {});
830
+ function runPartialRefresh(upsertedIds, deletedIds) {
831
+ const changedIds = [.../* @__PURE__ */ new Set([...upsertedIds, ...deletedIds])];
832
+ if (changedIds.length === 0) return;
833
+ if (upsertedIds.length === 0) {
834
+ emit(changedIds, "upstream-update");
835
+ return;
836
+ }
837
+ (0, _contello_client.runWithBackoff)(async () => {
838
+ await projected$6.refresh(upsertedIds);
839
+ emit(changedIds, "upstream-update");
840
+ });
841
+ }
842
+ const unsubUpdates = updates$.subscribe((batch) => {
843
+ if (!loaded) return;
844
+ if (batch.i18nMessage.length === 0) return;
845
+ const deleted = [];
846
+ const upserted = /* @__PURE__ */ new Set();
847
+ for (const event of batch.i18nMessage) if (event.mutation === "delete") deleted.push(event.id);
848
+ else upserted.add(event.id);
849
+ if (deleted.length > 0) projected$6.delete(deleted);
850
+ runPartialRefresh([...upserted], deleted);
851
+ });
852
+ return {
853
+ refresh$: channel.stream$,
854
+ get(idOrIds) {
855
+ return projected$6.get(idOrIds);
856
+ },
857
+ getAll() {
858
+ return projected$6.getAll();
859
+ },
860
+ register(messages) {
861
+ return wrap(`i18n-register:${def.collection}`, async () => {
862
+ await client.execute(storeRegisterI18nMessagesDocument, {
863
+ collection: def.collection,
864
+ messages: messages.map((message) => toGqlMessageInput(message))
865
+ });
866
+ });
867
+ },
868
+ refresh() {
869
+ scheduleRefresh("on-demand");
870
+ },
871
+ destroy() {
872
+ unsubUpdates();
873
+ ttl.clear();
874
+ channel.complete();
875
+ }
876
+ };
958
877
  }
959
-
960
- // src/lazy-assets.ts
961
- var import_client5 = require("@contello/client");
962
- var import_projected4 = require("projected");
963
-
964
- // src/lru.ts
965
- var import_lru_cache = require("lru-cache");
878
+ //#endregion
879
+ //#region src/lru.ts
966
880
  function createLruCache(options) {
967
- const { max, ttl, onEvict: dispose } = options;
968
- const lru = new import_lru_cache.LRUCache({
969
- max,
970
- ...ttl !== void 0 && { ttl, ttlAutopurge: false },
971
- ...dispose !== void 0 && { dispose }
972
- });
973
- return {
974
- has: (key) => lru.has(key),
975
- get: (key) => lru.get(key),
976
- set: (key, value) => {
977
- lru.set(key, value);
978
- },
979
- delete: (key) => {
980
- lru.delete(key);
981
- },
982
- clear: () => {
983
- lru.clear();
984
- },
985
- keys: () => [...lru.keys()]
986
- };
881
+ const { max, ttl, onEvict: dispose } = options;
882
+ const lru = new lru_cache.LRUCache({
883
+ max,
884
+ ...ttl !== void 0 && {
885
+ ttl,
886
+ ttlAutopurge: false
887
+ },
888
+ ...dispose !== void 0 && { dispose }
889
+ });
890
+ return {
891
+ has: (key) => lru.has(key),
892
+ get: (key) => lru.get(key),
893
+ set: (key, value) => {
894
+ lru.set(key, value);
895
+ },
896
+ delete: (key) => {
897
+ lru.delete(key);
898
+ },
899
+ clear: () => {
900
+ lru.clear();
901
+ },
902
+ keys: () => lru.keys().toArray()
903
+ };
987
904
  }
988
-
989
- // src/lazy-assets.ts
990
- function mapFile2(raw) {
991
- return {
992
- uid: raw.uid,
993
- mimeType: raw.mimeType,
994
- metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : void 0
995
- };
905
+ //#endregion
906
+ //#region src/lazy-assets.ts
907
+ function mapFile(raw) {
908
+ return {
909
+ uid: raw.uid,
910
+ mimeType: raw.mimeType,
911
+ metadata: raw.metadata ? {
912
+ width: raw.metadata.width,
913
+ height: raw.metadata.height
914
+ } : void 0
915
+ };
996
916
  }
997
- function mapAsset2(raw) {
998
- return {
999
- id: raw.id,
1000
- original: mapFile2(raw.original),
1001
- preview: raw.preview ? mapFile2(raw.preview) : void 0,
1002
- optimized: raw.optimized.map((file) => mapFile2(file))
1003
- };
917
+ function mapAsset(raw) {
918
+ return {
919
+ id: raw.id,
920
+ original: mapFile(raw.original),
921
+ preview: raw.preview ? mapFile(raw.preview) : void 0,
922
+ optimized: raw.optimized.map((file) => mapFile(file))
923
+ };
1004
924
  }
1005
925
  function createLazyAssetsCollection(def, client, updates$) {
1006
- const _def = {
1007
- cache: {
1008
- max: def?.cache?.max ?? DEFAULT_LRU_MAX,
1009
- ttl: resolveTtl(def?.cache?.ttl)
1010
- }
1011
- };
1012
- const cache = createLruCache({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: void 0 });
1013
- const assetsSourceDoc = (0, import_client5.createSourceSubscription)(schema.sources.storeAsset);
1014
- const projected = new import_projected4.ProjectedLazyMap({
1015
- key: (asset) => asset.id,
1016
- values: (ids) => wrap(
1017
- "assets",
1018
- () => (0, import_client5.collectAsync)(
1019
- (0, import_client5.mapAsync)(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
1020
- ).then((rawItems) => rawItems.map((item) => mapAsset2(item)))
1021
- ),
1022
- cache
1023
- });
1024
- const channel = createRefreshChannel(def?.onRefresh);
1025
- function emit(ids, kind) {
1026
- channel.emit({ ids, kind });
1027
- }
1028
- let lastRefreshKeys = [];
1029
- const scheduleRefresh = createRefresher(
1030
- async () => {
1031
- lastRefreshKeys = cache.keys();
1032
- if (lastRefreshKeys.length === 0) {
1033
- return;
1034
- }
1035
- await projected.refresh(lastRefreshKeys);
1036
- },
1037
- (kind) => {
1038
- if (lastRefreshKeys.length > 0) {
1039
- emit(lastRefreshKeys, kind);
1040
- }
1041
- },
1042
- () => {
1043
- }
1044
- );
1045
- const unsubUpdates = updates$.subscribe((batch) => {
1046
- if (batch.asset.length === 0) return;
1047
- for (const event of batch.asset) {
1048
- projected.delete(event.id);
1049
- }
1050
- emit(
1051
- batch.asset.map((e) => e.id),
1052
- "upstream-update"
1053
- );
1054
- });
1055
- return {
1056
- instance: {
1057
- refresh$: channel.stream$,
1058
- get(idOrIds) {
1059
- return projected.get(idOrIds);
1060
- },
1061
- upload(data, meta, options) {
1062
- return client.upload(data, meta, options);
1063
- },
1064
- download(fileId) {
1065
- return client.download(fileId);
1066
- },
1067
- proxyHls(path, signal) {
1068
- return client.proxyHls(path, signal);
1069
- },
1070
- refresh() {
1071
- scheduleRefresh("on-demand");
1072
- },
1073
- clear() {
1074
- projected.clear();
1075
- }
1076
- },
1077
- destroy() {
1078
- unsubUpdates();
1079
- channel.complete();
1080
- }
1081
- };
926
+ const _def = { cache: {
927
+ max: def?.cache?.max ?? 1e3,
928
+ ttl: resolveTtl(def?.cache?.ttl)
929
+ } };
930
+ const cache = createLruCache({
931
+ max: _def.cache.max,
932
+ ttl: _def.cache.ttl,
933
+ onEvict: void 0
934
+ });
935
+ const assetsSourceDoc = (0, _contello_client.createSourceSubscription)(schema.sources.storeAsset);
936
+ const projected$5 = new projected.ProjectedLazyMap({
937
+ key: (asset) => asset.id,
938
+ values: (ids) => wrap("assets", async () => {
939
+ return (await (0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source))).map((item) => mapAsset(item));
940
+ }),
941
+ cache
942
+ });
943
+ const channel = createRefreshChannel(def?.onRefresh);
944
+ function emit(ids, kind) {
945
+ channel.emit({
946
+ ids,
947
+ kind
948
+ });
949
+ }
950
+ let lastRefreshKeys = [];
951
+ const scheduleRefresh = createRefresher(async () => {
952
+ lastRefreshKeys = cache.keys();
953
+ if (lastRefreshKeys.length === 0) return;
954
+ await projected$5.refresh(lastRefreshKeys);
955
+ }, (kind) => {
956
+ if (lastRefreshKeys.length > 0) emit(lastRefreshKeys, kind);
957
+ }, () => {});
958
+ const unsubUpdates = updates$.subscribe((batch) => {
959
+ if (batch.asset.length === 0) return;
960
+ for (const event of batch.asset) projected$5.delete(event.id);
961
+ emit(batch.asset.map((e) => e.id), "upstream-update");
962
+ });
963
+ return {
964
+ instance: {
965
+ refresh$: channel.stream$,
966
+ get(idOrIds) {
967
+ return projected$5.get(idOrIds);
968
+ },
969
+ upload(data, meta, options) {
970
+ return client.upload(data, meta, options);
971
+ },
972
+ download(fileId) {
973
+ return client.download(fileId);
974
+ },
975
+ proxyHls(path, signal) {
976
+ return client.proxyHls(path, signal);
977
+ },
978
+ refresh() {
979
+ scheduleRefresh("on-demand");
980
+ },
981
+ clear() {
982
+ projected$5.clear();
983
+ }
984
+ },
985
+ destroy() {
986
+ unsubUpdates();
987
+ channel.complete();
988
+ }
989
+ };
1082
990
  }
1083
-
1084
- // src/lazy-collection.ts
1085
- var import_client6 = require("@contello/client");
1086
- var import_projected5 = require("projected");
991
+ //#endregion
992
+ //#region src/lazy-collection.ts
1087
993
  function createLazyCollection(source, options, client, updates$, resolver) {
1088
- const opts = options ?? {};
1089
- const mapFn = opts.map ?? ((item) => item);
1090
- const _def = {
1091
- name: opts.name ?? source.__model,
1092
- model: source.__model,
1093
- cache: {
1094
- max: opts.cache?.max ?? DEFAULT_LRU_MAX,
1095
- ttl: resolveTtl(opts.cache?.ttl)
1096
- }
1097
- };
1098
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
1099
- const cache = createLruCache({
1100
- max: _def.cache.max,
1101
- ttl: _def.cache.ttl,
1102
- onEvict: (_value, key) => dependencyCollector.removeItem(key)
1103
- });
1104
- const projected = new import_projected5.ProjectedLazyMap({
1105
- key: (item) => item.id,
1106
- values: (keys) => wrap(
1107
- `lazy-collection:${_def.name}`,
1108
- () => (0, import_projected5.maybeThen)(
1109
- (0, import_client6.collectAsync)(
1110
- (0, import_client6.mapAsync)(
1111
- client.subscribe((0, import_client6.createSourceSubscription)(source), {
1112
- ids: keys
1113
- }),
1114
- (r) => r.source
1115
- )
1116
- ),
1117
- (rawItems) => Promise.all(
1118
- rawItems.map(
1119
- (item) => Promise.resolve(
1120
- dependencyCollector.createContext(
1121
- (ref, register) => (0, import_projected5.maybeThen)(mapFn(item, ref), (mapped) => {
1122
- register(mapped.id);
1123
- return mapped;
1124
- })
1125
- )
1126
- )
1127
- )
1128
- )
1129
- )
1130
- ),
1131
- cache
1132
- });
1133
- const refresh$ = (0, import_client6.createAsyncIterableSubject)();
1134
- function emit(ids, kind) {
1135
- const event = { ids, kind };
1136
- refresh$.next(event);
1137
- opts.onRefresh?.(event);
1138
- }
1139
- let lastRefreshKeys = [];
1140
- const scheduleRefresh = createRefresher(
1141
- async () => {
1142
- lastRefreshKeys = cache.keys();
1143
- if (lastRefreshKeys.length === 0) {
1144
- return;
1145
- }
1146
- await projected.refresh(lastRefreshKeys);
1147
- },
1148
- (kind) => {
1149
- if (lastRefreshKeys.length > 0) {
1150
- emit(lastRefreshKeys, kind);
1151
- }
1152
- },
1153
- () => {
1154
- }
1155
- );
1156
- const unsubUpdates = updates$.subscribe((batch) => {
1157
- const evicted = /* @__PURE__ */ new Set();
1158
- const ownModelEvents = batch.entity.get(_def.model);
1159
- if (ownModelEvents) {
1160
- for (const event of ownModelEvents) {
1161
- evicted.add(event.id);
1162
- }
1163
- }
1164
- for (const event of batch.events) {
1165
- for (const key of dependencyCollector.getAffectedKeys(event)) {
1166
- evicted.add(key);
1167
- }
1168
- }
1169
- if (evicted.size > 0) {
1170
- for (const key of evicted) {
1171
- dependencyCollector.removeItem(key);
1172
- projected.delete(key);
1173
- }
1174
- emit([...evicted], "upstream-update");
1175
- }
1176
- });
1177
- return {
1178
- instance: {
1179
- name: _def.name,
1180
- refresh$,
1181
- get(idOrIds) {
1182
- return projected.get(idOrIds);
1183
- },
1184
- refresh() {
1185
- scheduleRefresh("on-demand");
1186
- },
1187
- clear() {
1188
- dependencyCollector.clear();
1189
- projected.clear();
1190
- }
1191
- },
1192
- destroy() {
1193
- unsubUpdates();
1194
- refresh$.complete();
1195
- }
1196
- };
994
+ const opts = options ?? {};
995
+ const mapFn = opts.map ?? ((item) => item);
996
+ const _def = {
997
+ name: opts.name ?? source.__model,
998
+ model: source.__model,
999
+ cache: {
1000
+ max: opts.cache?.max ?? 1e3,
1001
+ ttl: resolveTtl(opts.cache?.ttl)
1002
+ }
1003
+ };
1004
+ const dependencyCollector = new DependencyCollector(_def.model, resolver);
1005
+ const cache = createLruCache({
1006
+ max: _def.cache.max,
1007
+ ttl: _def.cache.ttl,
1008
+ onEvict: (_value, key) => dependencyCollector.removeItem(key)
1009
+ });
1010
+ const projected$4 = new projected.ProjectedLazyMap({
1011
+ key: (item) => item.id,
1012
+ values: (keys) => wrap(`lazy-collection:${_def.name}`, () => (0, projected.maybeThen)((0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe((0, _contello_client.createSourceSubscription)(source), { ids: keys }), (r) => r.source)), (rawItems) => Promise.all(rawItems.map((item) => Promise.resolve(dependencyCollector.createContext((ref, register) => (0, projected.maybeThen)(mapFn(item, ref), (mapped) => {
1013
+ register(mapped.id);
1014
+ return mapped;
1015
+ }))))))),
1016
+ cache
1017
+ });
1018
+ const refresh$ = (0, _contello_client.createAsyncIterableSubject)();
1019
+ function emit(ids, kind) {
1020
+ const event = {
1021
+ ids,
1022
+ kind
1023
+ };
1024
+ refresh$.next(event);
1025
+ opts.onRefresh?.(event);
1026
+ }
1027
+ let lastRefreshKeys = [];
1028
+ const scheduleRefresh = createRefresher(async () => {
1029
+ lastRefreshKeys = cache.keys();
1030
+ if (lastRefreshKeys.length === 0) return;
1031
+ await projected$4.refresh(lastRefreshKeys);
1032
+ }, (kind) => {
1033
+ if (lastRefreshKeys.length > 0) emit(lastRefreshKeys, kind);
1034
+ }, () => {});
1035
+ const unsubUpdates = updates$.subscribe((batch) => {
1036
+ const evicted = /* @__PURE__ */ new Set();
1037
+ const ownModelEvents = batch.entity.get(_def.model);
1038
+ if (ownModelEvents) for (const event of ownModelEvents) evicted.add(event.id);
1039
+ for (const event of batch.events) for (const key of dependencyCollector.getAffectedKeys(event)) evicted.add(key);
1040
+ if (evicted.size > 0) {
1041
+ for (const key of evicted) {
1042
+ dependencyCollector.removeItem(key);
1043
+ projected$4.delete(key);
1044
+ }
1045
+ emit([...evicted], "upstream-update");
1046
+ }
1047
+ });
1048
+ return {
1049
+ instance: {
1050
+ name: _def.name,
1051
+ refresh$,
1052
+ get(idOrIds) {
1053
+ return projected$4.get(idOrIds);
1054
+ },
1055
+ refresh() {
1056
+ scheduleRefresh("on-demand");
1057
+ },
1058
+ clear() {
1059
+ dependencyCollector.clear();
1060
+ projected$4.clear();
1061
+ }
1062
+ },
1063
+ destroy() {
1064
+ unsubUpdates();
1065
+ refresh$.complete();
1066
+ }
1067
+ };
1197
1068
  }
1198
-
1199
- // src/lazy-routes.ts
1200
- var import_client7 = require("@contello/client");
1201
- var import_projected6 = require("projected");
1202
-
1203
- // src/routes-mapping.ts
1069
+ //#endregion
1070
+ //#region src/routes-mapping.ts
1204
1071
  function mapRoute(raw, resolver) {
1205
- const base = {
1206
- id: raw.id,
1207
- path: raw.path,
1208
- customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value }))
1209
- };
1210
- switch (raw.target.__typename) {
1211
- case "ContelloRouteTargetRedirect": {
1212
- return {
1213
- ...base,
1214
- type: "redirect",
1215
- location: raw.target.location,
1216
- status: raw.target.responseCode
1217
- };
1218
- }
1219
- case "ContelloRouteTargetText": {
1220
- return {
1221
- ...base,
1222
- type: "text",
1223
- content: raw.target.content,
1224
- mimeType: raw.target.mimeType
1225
- };
1226
- }
1227
- case "ContelloRouteTargetAsset": {
1228
- return {
1229
- ...base,
1230
- type: "asset",
1231
- assetId: raw.target.asset.id,
1232
- fileId: raw.target.asset.original.uid,
1233
- contentDisposition: raw.target.contentDisposition === "INLINE" ? "inline" : "attachment",
1234
- mimeType: raw.target.asset.original.mimeType
1235
- };
1236
- }
1237
- case "ContelloRouteTargetEntity": {
1238
- if (!raw.target.entity) {
1239
- return void 0;
1240
- }
1241
- const entityType = raw.target.entity.__typename;
1242
- return {
1243
- ...base,
1244
- type: "entity",
1245
- model: resolver.resolveModel(entityType),
1246
- entityType,
1247
- entityId: raw.target.entity.id
1248
- };
1249
- }
1250
- default: {
1251
- return void 0;
1252
- }
1253
- }
1072
+ const base = {
1073
+ id: raw.id,
1074
+ path: raw.path,
1075
+ customHeaders: raw.customHeaders.map((h) => ({
1076
+ name: h.name,
1077
+ value: h.value
1078
+ }))
1079
+ };
1080
+ switch (raw.target.__typename) {
1081
+ case "ContelloRouteTargetRedirect": return {
1082
+ ...base,
1083
+ type: "redirect",
1084
+ location: raw.target.location,
1085
+ status: raw.target.responseCode
1086
+ };
1087
+ case "ContelloRouteTargetText": return {
1088
+ ...base,
1089
+ type: "text",
1090
+ content: raw.target.content,
1091
+ mimeType: raw.target.mimeType
1092
+ };
1093
+ case "ContelloRouteTargetAsset": return {
1094
+ ...base,
1095
+ type: "asset",
1096
+ assetId: raw.target.asset.id,
1097
+ fileId: raw.target.asset.original.uid,
1098
+ contentDisposition: raw.target.contentDisposition === "INLINE" ? "inline" : "attachment",
1099
+ mimeType: raw.target.asset.original.mimeType
1100
+ };
1101
+ case "ContelloRouteTargetEntity": {
1102
+ if (!raw.target.entity) return;
1103
+ const entityType = raw.target.entity.__typename;
1104
+ return {
1105
+ ...base,
1106
+ type: "entity",
1107
+ model: resolver.resolveModel(entityType),
1108
+ entityType,
1109
+ entityId: raw.target.entity.id
1110
+ };
1111
+ }
1112
+ default: return;
1113
+ }
1254
1114
  }
1255
-
1256
- // src/lazy-routes.ts
1257
- var ID_PREFIX = "1\0";
1258
- var PATH_PREFIX = "2\0";
1259
- var CACHE_KEY = /* @__PURE__ */ Symbol("cacheKey");
1115
+ //#endregion
1116
+ //#region src/lazy-routes.ts
1117
+ const ID_PREFIX = "1\0";
1118
+ const PATH_PREFIX = "2\0";
1119
+ const CACHE_KEY = Symbol("cacheKey");
1260
1120
  function collectRoutes(rawItems, keyFn, resolver) {
1261
- return rawItems.reduce((acc, raw) => {
1262
- const mapped = mapRoute(raw, resolver);
1263
- if (mapped) {
1264
- mapped[CACHE_KEY] = keyFn(mapped);
1265
- acc.push(mapped);
1266
- }
1267
- return acc;
1268
- }, []);
1121
+ return rawItems.reduce((acc, raw) => {
1122
+ const mapped = mapRoute(raw, resolver);
1123
+ if (mapped) {
1124
+ mapped[CACHE_KEY] = keyFn(mapped);
1125
+ acc.push(mapped);
1126
+ }
1127
+ return acc;
1128
+ }, []);
1269
1129
  }
1130
+ /**
1131
+ * cache wrapper that presents a unified `ID_PREFIX + id` / `PATH_PREFIX + path` key space
1132
+ * to ProjectedLazyMap while storing entries in the underlying LRU under ID_PREFIX keys only.
1133
+ *
1134
+ * path -> id resolution is handled internally via a pathToId map kept in sync with the LRU
1135
+ * (populated on set, cleared on natural LRU eviction via onEvict, and on explicit delete).
1136
+ */
1270
1137
  function createRoutesCache(max, ttl) {
1271
- const pathToId = /* @__PURE__ */ new Map();
1272
- const idToPath = /* @__PURE__ */ new Map();
1273
- const lru = createLruCache({
1274
- max,
1275
- ttl,
1276
- onEvict: (route) => {
1277
- pathToId.delete(route.path);
1278
- idToPath.delete(route.id);
1279
- }
1280
- });
1281
- function resolveKey(key) {
1282
- if (key.startsWith(PATH_PREFIX)) {
1283
- const id = pathToId.get(key.slice(2));
1284
- if (id) {
1285
- return ID_PREFIX + id;
1286
- }
1287
- return key;
1288
- }
1289
- return key;
1290
- }
1291
- return {
1292
- has: (key) => lru.has(resolveKey(key)),
1293
- get: (key) => lru.get(resolveKey(key)),
1294
- set: (_key, value) => {
1295
- const previousPath = idToPath.get(value.id);
1296
- if (previousPath !== void 0 && previousPath !== value.path) {
1297
- pathToId.delete(previousPath);
1298
- }
1299
- pathToId.set(value.path, value.id);
1300
- idToPath.set(value.id, value.path);
1301
- lru.set(ID_PREFIX + value.id, value);
1302
- },
1303
- delete: (key) => {
1304
- const resolved = resolveKey(key);
1305
- const value = lru.get(resolved);
1306
- if (value) {
1307
- pathToId.delete(value.path);
1308
- idToPath.delete(value.id);
1309
- }
1310
- lru.delete(resolved);
1311
- },
1312
- clear: () => {
1313
- pathToId.clear();
1314
- idToPath.clear();
1315
- lru.clear();
1316
- },
1317
- keys: () => lru.keys()
1318
- };
1138
+ const pathToId = /* @__PURE__ */ new Map();
1139
+ const idToPath = /* @__PURE__ */ new Map();
1140
+ const lru = createLruCache({
1141
+ max,
1142
+ ttl,
1143
+ onEvict: (route) => {
1144
+ pathToId.delete(route.path);
1145
+ idToPath.delete(route.id);
1146
+ }
1147
+ });
1148
+ function resolveKey(key) {
1149
+ if (key.startsWith(PATH_PREFIX)) {
1150
+ const id = pathToId.get(key.slice(2));
1151
+ if (id) return ID_PREFIX + id;
1152
+ return key;
1153
+ }
1154
+ return key;
1155
+ }
1156
+ return {
1157
+ has: (key) => lru.has(resolveKey(key)),
1158
+ get: (key) => lru.get(resolveKey(key)),
1159
+ set: (_key, value) => {
1160
+ const previousPath = idToPath.get(value.id);
1161
+ if (previousPath !== void 0 && previousPath !== value.path) pathToId.delete(previousPath);
1162
+ pathToId.set(value.path, value.id);
1163
+ idToPath.set(value.id, value.path);
1164
+ lru.set(ID_PREFIX + value.id, value);
1165
+ },
1166
+ delete: (key) => {
1167
+ const resolved = resolveKey(key);
1168
+ const value = lru.get(resolved);
1169
+ if (value) {
1170
+ pathToId.delete(value.path);
1171
+ idToPath.delete(value.id);
1172
+ }
1173
+ lru.delete(resolved);
1174
+ },
1175
+ clear: () => {
1176
+ pathToId.clear();
1177
+ idToPath.clear();
1178
+ lru.clear();
1179
+ },
1180
+ keys: () => lru.keys()
1181
+ };
1319
1182
  }
1320
1183
  function createLazyRoutesCollection(def, client, updates$, resolver) {
1321
- const _def = {
1322
- cache: {
1323
- max: def?.cache?.max ?? DEFAULT_LRU_MAX,
1324
- ttl: resolveTtl(def?.cache?.ttl)
1325
- }
1326
- };
1327
- const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);
1328
- const routesSourceDoc = (0, import_client7.createSourceSubscription)(schema.sources.storeRoute);
1329
- function fetchRoutes(vars) {
1330
- return (0, import_client7.collectAsync)(
1331
- (0, import_client7.mapAsync)(client.subscribe(routesSourceDoc, vars), (data) => data.source)
1332
- );
1333
- }
1334
- const projected = new import_projected6.ProjectedLazyMap({
1335
- key: (route) => route[CACHE_KEY] ?? ID_PREFIX + route.id,
1336
- values: (prefixedKeys) => wrap("routes", () => {
1337
- const ids = [];
1338
- const paths = [];
1339
- for (const key of prefixedKeys) {
1340
- const value = key.slice(2);
1341
- if (key.startsWith(ID_PREFIX)) {
1342
- ids.push(value);
1343
- } else {
1344
- paths.push(value);
1345
- }
1346
- }
1347
- return Promise.all([
1348
- ids.length > 0 ? fetchRoutes({ ids }).then((raw) => collectRoutes(raw, (r) => ID_PREFIX + r.id, resolver)) : Promise.resolve([]),
1349
- paths.length > 0 ? fetchRoutes({ paths }).then((raw) => collectRoutes(raw, (r) => PATH_PREFIX + r.path, resolver)) : Promise.resolve([])
1350
- ]).then(([byIds, byPaths]) => [...byIds, ...byPaths]);
1351
- }),
1352
- cache
1353
- });
1354
- const channel = createRefreshChannel(def?.onRefresh);
1355
- function emit(ids, kind) {
1356
- channel.emit({ ids, kind });
1357
- }
1358
- let lastRefreshKeys = [];
1359
- const scheduleRefresh = createRefresher(
1360
- async () => {
1361
- lastRefreshKeys = cache.keys();
1362
- if (lastRefreshKeys.length === 0) {
1363
- return;
1364
- }
1365
- await projected.refresh(lastRefreshKeys);
1366
- },
1367
- (kind) => {
1368
- if (lastRefreshKeys.length > 0) {
1369
- emit(
1370
- lastRefreshKeys.map((key) => key.slice(2)),
1371
- kind
1372
- );
1373
- }
1374
- },
1375
- () => {
1376
- }
1377
- );
1378
- const unsubUpdates = updates$.subscribe((batch) => {
1379
- const evicted = [];
1380
- for (const event of batch.route) {
1381
- const idKey = ID_PREFIX + event.id;
1382
- if (event.mutation === "delete") {
1383
- cache.delete(idKey);
1384
- evicted.push(event.id);
1385
- } else {
1386
- if (cache.has(idKey)) {
1387
- cache.set(idKey, event.after);
1388
- }
1389
- evicted.push(event.after.path);
1390
- }
1391
- }
1392
- if (evicted.length > 0) {
1393
- emit(evicted, "upstream-update");
1394
- }
1395
- });
1396
- return {
1397
- instance: {
1398
- refresh$: channel.stream$,
1399
- get(idOrIds) {
1400
- if (Array.isArray(idOrIds)) {
1401
- return projected.get(idOrIds.map((id) => ID_PREFIX + id));
1402
- }
1403
- return projected.get(ID_PREFIX + idOrIds);
1404
- },
1405
- getByPath(pathOrPaths) {
1406
- if (Array.isArray(pathOrPaths)) {
1407
- return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));
1408
- }
1409
- return projected.get(PATH_PREFIX + pathOrPaths);
1410
- },
1411
- refresh() {
1412
- scheduleRefresh("on-demand");
1413
- },
1414
- clear() {
1415
- projected.clear();
1416
- }
1417
- },
1418
- destroy() {
1419
- unsubUpdates();
1420
- channel.complete();
1421
- }
1422
- };
1184
+ const _def = { cache: {
1185
+ max: def?.cache?.max ?? 1e3,
1186
+ ttl: resolveTtl(def?.cache?.ttl)
1187
+ } };
1188
+ const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);
1189
+ const routesSourceDoc = (0, _contello_client.createSourceSubscription)(schema.sources.storeRoute);
1190
+ function fetchRoutes(vars) {
1191
+ return (0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe(routesSourceDoc, vars), (data) => data.source));
1192
+ }
1193
+ const projected$3 = new projected.ProjectedLazyMap({
1194
+ key: (route) => route[CACHE_KEY] ?? ID_PREFIX + route.id,
1195
+ values: (prefixedKeys) => wrap("routes", async () => {
1196
+ const ids = [];
1197
+ const paths = [];
1198
+ for (const key of prefixedKeys) {
1199
+ const value = key.slice(2);
1200
+ if (key.startsWith(ID_PREFIX)) ids.push(value);
1201
+ else paths.push(value);
1202
+ }
1203
+ const [rawByIds, rawByPaths] = await Promise.all([ids.length > 0 ? fetchRoutes({ ids }) : Promise.resolve([]), paths.length > 0 ? fetchRoutes({ paths }) : Promise.resolve([])]);
1204
+ const byIds = collectRoutes(rawByIds, (r) => ID_PREFIX + r.id, resolver);
1205
+ const byPaths = collectRoutes(rawByPaths, (r) => PATH_PREFIX + r.path, resolver);
1206
+ return [...byIds, ...byPaths];
1207
+ }),
1208
+ cache
1209
+ });
1210
+ const channel = createRefreshChannel(def?.onRefresh);
1211
+ function emit(ids, kind) {
1212
+ channel.emit({
1213
+ ids,
1214
+ kind
1215
+ });
1216
+ }
1217
+ let lastRefreshKeys = [];
1218
+ const scheduleRefresh = createRefresher(async () => {
1219
+ lastRefreshKeys = cache.keys();
1220
+ if (lastRefreshKeys.length === 0) return;
1221
+ await projected$3.refresh(lastRefreshKeys);
1222
+ }, (kind) => {
1223
+ if (lastRefreshKeys.length > 0) emit(lastRefreshKeys.map((key) => key.slice(2)), kind);
1224
+ }, () => {});
1225
+ const unsubUpdates = updates$.subscribe((batch) => {
1226
+ const evicted = [];
1227
+ for (const event of batch.route) {
1228
+ const idKey = ID_PREFIX + event.id;
1229
+ if (event.mutation === "delete") {
1230
+ cache.delete(idKey);
1231
+ evicted.push(event.id);
1232
+ } else {
1233
+ if (cache.has(idKey)) cache.set(idKey, event.after);
1234
+ evicted.push(event.after.path);
1235
+ }
1236
+ }
1237
+ if (evicted.length > 0) emit(evicted, "upstream-update");
1238
+ });
1239
+ return {
1240
+ instance: {
1241
+ refresh$: channel.stream$,
1242
+ get(idOrIds) {
1243
+ if (Array.isArray(idOrIds)) return projected$3.get(idOrIds.map((id) => ID_PREFIX + id));
1244
+ return projected$3.get(ID_PREFIX + idOrIds);
1245
+ },
1246
+ getByPath(pathOrPaths) {
1247
+ if (Array.isArray(pathOrPaths)) return projected$3.get(pathOrPaths.map((p) => PATH_PREFIX + p));
1248
+ return projected$3.get(PATH_PREFIX + pathOrPaths);
1249
+ },
1250
+ refresh() {
1251
+ scheduleRefresh("on-demand");
1252
+ },
1253
+ clear() {
1254
+ projected$3.clear();
1255
+ }
1256
+ },
1257
+ destroy() {
1258
+ unsubUpdates();
1259
+ channel.complete();
1260
+ }
1261
+ };
1423
1262
  }
1424
-
1425
- // src/model-resolver.ts
1263
+ //#endregion
1264
+ //#region src/model-resolver.ts
1426
1265
  var ModelResolver = class {
1427
- _typeNames;
1428
- _toModel;
1429
- _toTypeName;
1430
- constructor(models2) {
1431
- const toModel = /* @__PURE__ */ new Map();
1432
- const toTypeName = /* @__PURE__ */ new Map();
1433
- let typeNames;
1434
- if (models2) {
1435
- typeNames = /* @__PURE__ */ new Set();
1436
- for (const [model, typeName] of Object.entries(models2)) {
1437
- toModel.set(typeName, model);
1438
- toTypeName.set(model, typeName);
1439
- typeNames.add(typeName);
1440
- }
1441
- }
1442
- this._typeNames = typeNames;
1443
- this._toModel = toModel;
1444
- this._toTypeName = toTypeName;
1445
- }
1446
- hasTypeName(typeName) {
1447
- return !this._typeNames || this._typeNames.has(typeName);
1448
- }
1449
- getModel(typeName) {
1450
- return this._toModel.get(typeName);
1451
- }
1452
- getTypeName(model) {
1453
- return this._toTypeName.get(model) ?? model;
1454
- }
1455
- hasModel(model) {
1456
- return this._toTypeName.size === 0 || this._toTypeName.has(model);
1457
- }
1458
- resolveModel(typeName) {
1459
- return this._toModel.get(typeName) ?? typeName;
1460
- }
1266
+ _typeNames;
1267
+ _toModel;
1268
+ _toTypeName;
1269
+ constructor(models) {
1270
+ const toModel = /* @__PURE__ */ new Map();
1271
+ const toTypeName = /* @__PURE__ */ new Map();
1272
+ let typeNames;
1273
+ if (models) {
1274
+ typeNames = /* @__PURE__ */ new Set();
1275
+ for (const [model, typeName] of Object.entries(models)) {
1276
+ toModel.set(typeName, model);
1277
+ toTypeName.set(model, typeName);
1278
+ typeNames.add(typeName);
1279
+ }
1280
+ }
1281
+ this._typeNames = typeNames;
1282
+ this._toModel = toModel;
1283
+ this._toTypeName = toTypeName;
1284
+ }
1285
+ hasTypeName(typeName) {
1286
+ return !this._typeNames || this._typeNames.has(typeName);
1287
+ }
1288
+ getModel(typeName) {
1289
+ return this._toModel.get(typeName);
1290
+ }
1291
+ getTypeName(model) {
1292
+ return this._toTypeName.get(model) ?? model;
1293
+ }
1294
+ hasModel(model) {
1295
+ return this._toTypeName.size === 0 || this._toTypeName.has(model);
1296
+ }
1297
+ resolveModel(typeName) {
1298
+ return this._toModel.get(typeName) ?? typeName;
1299
+ }
1461
1300
  };
1462
-
1463
- // src/routes.ts
1464
- var import_client8 = require("@contello/client");
1465
- var import_projected7 = require("projected");
1301
+ //#endregion
1302
+ //#region src/routes.ts
1466
1303
  function createRoutesCollection(options, client, updates$, resolver, refreshByTtl) {
1467
- const opts = options ?? {};
1468
- const cache = {
1469
- ttl: resolveTtl(opts.cache?.ttl),
1470
- eviction: opts.cache?.eviction ?? "refresh"
1471
- };
1472
- const channel = createRefreshChannel(opts.onRefresh);
1473
- const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
1474
- const pathById = /* @__PURE__ */ new Map();
1475
- const idByPath = /* @__PURE__ */ new Map();
1476
- let loaded = false;
1477
- const routesSourceDoc = (0, import_client8.createSourceSubscription)(schema.sources.storeRoute);
1478
- const projected = new import_projected7.ProjectedMap({
1479
- key: (route) => route.id,
1480
- values: (ids) => wrap(
1481
- "routes",
1482
- () => (0, import_client8.collectAsync)(
1483
- (0, import_client8.mapAsync)(client.subscribe(routesSourceDoc, { ids }), (data) => data.source)
1484
- ).then((rawItems) => {
1485
- const items = rawItems.reduce((acc, raw) => {
1486
- const mapped = mapRoute(raw, resolver);
1487
- if (mapped) {
1488
- acc.push(mapped);
1489
- }
1490
- return acc;
1491
- }, []);
1492
- if (ids === void 0) {
1493
- pathById.clear();
1494
- idByPath.clear();
1495
- for (const r of items) {
1496
- pathById.set(r.id, r.path);
1497
- idByPath.set(r.path, r.id);
1498
- }
1499
- if (!loaded) {
1500
- loaded = true;
1501
- ttl.mark();
1502
- opts.onLoad?.(items.map((r) => r.id));
1503
- }
1504
- } else {
1505
- const returnedIds = new Set(items.map((r) => r.id));
1506
- for (const id of ids) {
1507
- if (!returnedIds.has(id)) {
1508
- const oldPath = pathById.get(id);
1509
- if (oldPath !== void 0) {
1510
- idByPath.delete(oldPath);
1511
- pathById.delete(id);
1512
- }
1513
- }
1514
- }
1515
- for (const r of items) {
1516
- const oldPath = pathById.get(r.id);
1517
- if (oldPath !== void 0 && oldPath !== r.path) {
1518
- idByPath.delete(oldPath);
1519
- }
1520
- pathById.set(r.id, r.path);
1521
- idByPath.set(r.path, r.id);
1522
- }
1523
- }
1524
- return items;
1525
- })
1526
- )
1527
- });
1528
- function emit(ids, kind) {
1529
- channel.emit({ ids, kind });
1530
- }
1531
- function runFullRefresh(kind) {
1532
- refreshByTtl.enqueue(
1533
- () => (0, import_client8.runWithBackoff)(
1534
- () => projected.refresh().then((map) => {
1535
- emit([...map.keys()], kind);
1536
- ttl.mark();
1537
- })
1538
- )
1539
- );
1540
- }
1541
- function runPartialRefresh(refreshIds, deletedIds) {
1542
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
1543
- if (refreshIds.length === 0) {
1544
- emit(changedIds, "upstream-update");
1545
- return;
1546
- }
1547
- void (0, import_client8.runWithBackoff)(
1548
- () => projected.refresh(refreshIds).then(() => {
1549
- emit(changedIds, "upstream-update");
1550
- })
1551
- );
1552
- }
1553
- const unsubUpdates = updates$.subscribe((batch) => {
1554
- if (!loaded || batch.route.length === 0) {
1555
- return;
1556
- }
1557
- const deleted = [];
1558
- const upserted = /* @__PURE__ */ new Set();
1559
- for (const event of batch.route) {
1560
- if (event.mutation === "delete") {
1561
- deleted.push(event.id);
1562
- } else {
1563
- upserted.add(event.id);
1564
- }
1565
- }
1566
- if (cache.eviction === "clear") {
1567
- pathById.clear();
1568
- idByPath.clear();
1569
- projected.clear();
1570
- return;
1571
- }
1572
- for (const id of deleted) {
1573
- const oldPath = pathById.get(id);
1574
- if (oldPath !== void 0) {
1575
- idByPath.delete(oldPath);
1576
- pathById.delete(id);
1577
- }
1578
- }
1579
- if (deleted.length > 0) {
1580
- projected.delete(deleted);
1581
- }
1582
- runPartialRefresh([...upserted], deleted);
1583
- });
1584
- function getByIdSingle(id) {
1585
- return projected.get(id);
1586
- }
1587
- function getByIds(ids) {
1588
- return projected.get(ids);
1589
- }
1590
- function lookupByPathSingle(path) {
1591
- return (0, import_projected7.maybeThen)(ensureLoaded(), () => {
1592
- const id = idByPath.get(path);
1593
- return id === void 0 ? void 0 : projected.get(id);
1594
- });
1595
- }
1596
- function lookupByPaths(paths) {
1597
- return (0, import_projected7.maybeThen)(ensureLoaded(), () => {
1598
- const ids = [];
1599
- for (const p of paths) {
1600
- const id = idByPath.get(p);
1601
- if (id !== void 0) {
1602
- ids.push(id);
1603
- }
1604
- }
1605
- return projected.get(ids);
1606
- });
1607
- }
1608
- function ensureLoaded() {
1609
- if (loaded) {
1610
- return void 0;
1611
- }
1612
- return (0, import_projected7.maybeThen)(projected.getAllAsMap(), () => {
1613
- });
1614
- }
1615
- const instance = {
1616
- refresh$: channel.stream$,
1617
- async load() {
1618
- if (!loaded) {
1619
- await projected.getAllAsMap();
1620
- }
1621
- },
1622
- get(idOrIds) {
1623
- return typeof idOrIds === "string" ? getByIdSingle(idOrIds) : getByIds(idOrIds);
1624
- },
1625
- getByPath(pathOrPaths) {
1626
- return typeof pathOrPaths === "string" ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);
1627
- },
1628
- refresh() {
1629
- runFullRefresh("on-demand");
1630
- }
1631
- };
1632
- return {
1633
- instance,
1634
- destroy() {
1635
- unsubUpdates();
1636
- ttl.clear();
1637
- channel.complete();
1638
- }
1639
- };
1304
+ const opts = options ?? {};
1305
+ const cache = {
1306
+ ttl: resolveTtl(opts.cache?.ttl),
1307
+ eviction: opts.cache?.eviction ?? "refresh"
1308
+ };
1309
+ const channel = createRefreshChannel(opts.onRefresh);
1310
+ const ttl = createTtlOrchestrator({
1311
+ ttl: cache.ttl,
1312
+ run: () => runFullRefresh("ttl")
1313
+ });
1314
+ const pathById = /* @__PURE__ */ new Map();
1315
+ const idByPath = /* @__PURE__ */ new Map();
1316
+ let loaded = false;
1317
+ const routesSourceDoc = (0, _contello_client.createSourceSubscription)(schema.sources.storeRoute);
1318
+ const projected$2 = new projected.ProjectedMap({
1319
+ key: (route) => route.id,
1320
+ values: (ids) => wrap("routes", async () => {
1321
+ const items = (await (0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe(routesSourceDoc, { ids }), (data) => data.source))).reduce((acc, raw) => {
1322
+ const mapped = mapRoute(raw, resolver);
1323
+ if (mapped) acc.push(mapped);
1324
+ return acc;
1325
+ }, []);
1326
+ if (ids === void 0) {
1327
+ pathById.clear();
1328
+ idByPath.clear();
1329
+ for (const r of items) {
1330
+ pathById.set(r.id, r.path);
1331
+ idByPath.set(r.path, r.id);
1332
+ }
1333
+ if (!loaded) {
1334
+ loaded = true;
1335
+ ttl.mark();
1336
+ opts.onLoad?.(items.map((r) => r.id));
1337
+ }
1338
+ } else {
1339
+ const returnedIds = new Set(items.map((r) => r.id));
1340
+ for (const id of ids) {
1341
+ if (returnedIds.has(id)) continue;
1342
+ const oldPath = pathById.get(id);
1343
+ if (oldPath !== void 0) {
1344
+ idByPath.delete(oldPath);
1345
+ pathById.delete(id);
1346
+ }
1347
+ }
1348
+ for (const r of items) {
1349
+ const oldPath = pathById.get(r.id);
1350
+ if (oldPath !== void 0 && oldPath !== r.path) idByPath.delete(oldPath);
1351
+ pathById.set(r.id, r.path);
1352
+ idByPath.set(r.path, r.id);
1353
+ }
1354
+ }
1355
+ return items;
1356
+ })
1357
+ });
1358
+ function emit(ids, kind) {
1359
+ channel.emit({
1360
+ ids,
1361
+ kind
1362
+ });
1363
+ }
1364
+ function runFullRefresh(kind) {
1365
+ refreshByTtl.enqueue(() => (0, _contello_client.runWithBackoff)(async () => {
1366
+ emit((await projected$2.refresh()).keys().toArray(), kind);
1367
+ ttl.mark();
1368
+ }));
1369
+ }
1370
+ function runPartialRefresh(refreshIds, deletedIds) {
1371
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
1372
+ if (refreshIds.length === 0) {
1373
+ emit(changedIds, "upstream-update");
1374
+ return;
1375
+ }
1376
+ (0, _contello_client.runWithBackoff)(async () => {
1377
+ await projected$2.refresh(refreshIds);
1378
+ emit(changedIds, "upstream-update");
1379
+ });
1380
+ }
1381
+ const unsubUpdates = updates$.subscribe((batch) => {
1382
+ if (!loaded || batch.route.length === 0) return;
1383
+ const deleted = [];
1384
+ const upserted = /* @__PURE__ */ new Set();
1385
+ for (const event of batch.route) if (event.mutation === "delete") deleted.push(event.id);
1386
+ else upserted.add(event.id);
1387
+ if (cache.eviction === "clear") {
1388
+ pathById.clear();
1389
+ idByPath.clear();
1390
+ projected$2.clear();
1391
+ return;
1392
+ }
1393
+ for (const id of deleted) {
1394
+ const oldPath = pathById.get(id);
1395
+ if (oldPath !== void 0) {
1396
+ idByPath.delete(oldPath);
1397
+ pathById.delete(id);
1398
+ }
1399
+ }
1400
+ if (deleted.length > 0) projected$2.delete(deleted);
1401
+ runPartialRefresh([...upserted], deleted);
1402
+ });
1403
+ function getByIdSingle(id) {
1404
+ return projected$2.get(id);
1405
+ }
1406
+ function getByIds(ids) {
1407
+ return projected$2.get(ids);
1408
+ }
1409
+ function lookupByPathSingle(path) {
1410
+ return (0, projected.maybeThen)(ensureLoaded(), () => {
1411
+ const id = idByPath.get(path);
1412
+ return id === void 0 ? void 0 : projected$2.get(id);
1413
+ });
1414
+ }
1415
+ function lookupByPaths(paths) {
1416
+ return (0, projected.maybeThen)(ensureLoaded(), () => {
1417
+ const ids = [];
1418
+ for (const p of paths) {
1419
+ const id = idByPath.get(p);
1420
+ if (id !== void 0) ids.push(id);
1421
+ }
1422
+ return projected$2.get(ids);
1423
+ });
1424
+ }
1425
+ function ensureLoaded() {
1426
+ if (loaded) return;
1427
+ return (0, projected.maybeThen)(projected$2.getAllAsMap(), () => {});
1428
+ }
1429
+ return {
1430
+ instance: {
1431
+ refresh$: channel.stream$,
1432
+ async load() {
1433
+ if (!loaded) await projected$2.getAllAsMap();
1434
+ },
1435
+ get(idOrIds) {
1436
+ return typeof idOrIds === "string" ? getByIdSingle(idOrIds) : getByIds(idOrIds);
1437
+ },
1438
+ getByPath(pathOrPaths) {
1439
+ return typeof pathOrPaths === "string" ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);
1440
+ },
1441
+ refresh() {
1442
+ runFullRefresh("on-demand");
1443
+ }
1444
+ },
1445
+ destroy() {
1446
+ unsubUpdates();
1447
+ ttl.clear();
1448
+ channel.complete();
1449
+ }
1450
+ };
1640
1451
  }
1641
1452
  function createRoutesSyncCollection(options, client, updates$, resolver, refreshByTtl) {
1642
- const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);
1643
- function assertSync(value, method) {
1644
- if (value instanceof Promise) {
1645
- throw new TypeError(`routes.${method}() is not initialized yet \u2014 call routes.load() first`);
1646
- }
1647
- return value;
1648
- }
1649
- return {
1650
- instance: {
1651
- ...base,
1652
- get(idOrIds) {
1653
- return assertSync(base.get(idOrIds), "get");
1654
- },
1655
- getByPath(pathOrPaths) {
1656
- return assertSync(base.getByPath(pathOrPaths), "getByPath");
1657
- }
1658
- },
1659
- destroy
1660
- };
1453
+ const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);
1454
+ function assertSync(value, method) {
1455
+ if (value instanceof Promise) throw new TypeError(`routes.${method}() is not initialized yet — call routes.load() first`);
1456
+ return value;
1457
+ }
1458
+ return {
1459
+ instance: {
1460
+ ...base,
1461
+ get(idOrIds) {
1462
+ return assertSync(base.get(idOrIds), "get");
1463
+ },
1464
+ getByPath(pathOrPaths) {
1465
+ return assertSync(base.getByPath(pathOrPaths), "getByPath");
1466
+ }
1467
+ },
1468
+ destroy
1469
+ };
1661
1470
  }
1662
-
1663
- // src/singleton.ts
1664
- var import_client9 = require("@contello/client");
1665
- var import_projected8 = require("projected");
1471
+ //#endregion
1472
+ //#region src/singleton.ts
1666
1473
  function createSingleton(source, options, client, updates$, resolver, refreshByTtl) {
1667
- const opts = options ?? {};
1668
- const mapFn = opts.map ?? ((item) => item);
1669
- const _def = {
1670
- name: opts.name ?? source.__model,
1671
- model: source.__model,
1672
- cache: {
1673
- ttl: resolveTtl(opts.cache?.ttl),
1674
- eviction: opts.cache?.eviction ?? "refresh"
1675
- }
1676
- };
1677
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
1678
- const itemKey = `singleton:${_def.name}`;
1679
- const channel = createRefreshChannel(opts.onRefresh);
1680
- const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });
1681
- let loaded = false;
1682
- const projected = new import_projected8.ProjectedValue({
1683
- value: () => wrap(
1684
- `singleton:${_def.name}`,
1685
- () => (0, import_projected8.maybeThen)(
1686
- (0, import_client9.firstAsync)(
1687
- (0, import_client9.mapAsync)(
1688
- client.subscribe((0, import_client9.createSourceSubscription)(source)),
1689
- (r) => r.source
1690
- )
1691
- ),
1692
- (raw) => dependencyCollector.createContext(
1693
- (ref, register) => (0, import_projected8.maybeThen)(mapFn(raw, ref), (mapped) => {
1694
- register(itemKey);
1695
- if (!loaded) {
1696
- loaded = true;
1697
- ttl.mark();
1698
- opts.onLoad?.();
1699
- }
1700
- return mapped;
1701
- })
1702
- )
1703
- )
1704
- )
1705
- });
1706
- function emit(kind) {
1707
- channel.emit({ kind });
1708
- }
1709
- function runTtlRefresh() {
1710
- refreshByTtl.enqueue(
1711
- () => (0, import_client9.runWithBackoff)(() => projected.refresh()).then(() => {
1712
- emit("ttl");
1713
- ttl.mark();
1714
- })
1715
- );
1716
- }
1717
- const scheduleRefresh = createRefresher(
1718
- () => projected.refresh(),
1719
- (kind) => {
1720
- emit(kind);
1721
- ttl.mark();
1722
- },
1723
- () => {
1724
- }
1725
- );
1726
- const unsubUpdates = updates$.subscribe((batch) => {
1727
- if (!loaded) {
1728
- return;
1729
- }
1730
- const hasOwnModel = batch.entity.has(_def.model);
1731
- const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);
1732
- if (!hasOwnModel && !hasAffectedRefs) {
1733
- return;
1734
- }
1735
- if (_def.cache.eviction === "clear") {
1736
- dependencyCollector.clear();
1737
- projected.clear();
1738
- return;
1739
- }
1740
- scheduleRefresh("upstream-update");
1741
- });
1742
- return {
1743
- instance: {
1744
- name: _def.name,
1745
- refresh$: channel.stream$,
1746
- get() {
1747
- return projected.get();
1748
- },
1749
- refresh() {
1750
- scheduleRefresh("on-demand");
1751
- },
1752
- async load() {
1753
- if (!loaded) {
1754
- await projected.get();
1755
- }
1756
- }
1757
- },
1758
- destroy() {
1759
- unsubUpdates();
1760
- ttl.clear();
1761
- channel.complete();
1762
- }
1763
- };
1474
+ const opts = options ?? {};
1475
+ const mapFn = opts.map ?? ((item) => item);
1476
+ const _def = {
1477
+ name: opts.name ?? source.__model,
1478
+ model: source.__model,
1479
+ cache: {
1480
+ ttl: resolveTtl(opts.cache?.ttl),
1481
+ eviction: opts.cache?.eviction ?? "refresh"
1482
+ }
1483
+ };
1484
+ const dependencyCollector = new DependencyCollector(_def.model, resolver);
1485
+ const itemKey = `singleton:${_def.name}`;
1486
+ const channel = createRefreshChannel(opts.onRefresh);
1487
+ const ttl = createTtlOrchestrator({
1488
+ ttl: _def.cache.ttl,
1489
+ run: () => runTtlRefresh()
1490
+ });
1491
+ let loaded = false;
1492
+ const projected$1 = new projected.ProjectedValue({ value: () => wrap(`singleton:${_def.name}`, () => (0, projected.maybeThen)((0, _contello_client.firstAsync)((0, _contello_client.mapAsync)(client.subscribe((0, _contello_client.createSourceSubscription)(source)), (r) => r.source)), (raw) => dependencyCollector.createContext((ref, register) => (0, projected.maybeThen)(mapFn(raw, ref), (mapped) => {
1493
+ register(itemKey);
1494
+ if (!loaded) {
1495
+ loaded = true;
1496
+ ttl.mark();
1497
+ opts.onLoad?.();
1498
+ }
1499
+ return mapped;
1500
+ })))) });
1501
+ function emit(kind) {
1502
+ channel.emit({ kind });
1503
+ }
1504
+ function runTtlRefresh() {
1505
+ refreshByTtl.enqueue(async () => {
1506
+ await (0, _contello_client.runWithBackoff)(() => projected$1.refresh());
1507
+ emit("ttl");
1508
+ ttl.mark();
1509
+ });
1510
+ }
1511
+ const scheduleRefresh = createRefresher(() => projected$1.refresh(), (kind) => {
1512
+ emit(kind);
1513
+ ttl.mark();
1514
+ }, () => {});
1515
+ const unsubUpdates = updates$.subscribe((batch) => {
1516
+ if (!loaded) return;
1517
+ const hasOwnModel = batch.entity.has(_def.model);
1518
+ const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);
1519
+ if (!hasOwnModel && !hasAffectedRefs) return;
1520
+ if (_def.cache.eviction === "clear") {
1521
+ dependencyCollector.clear();
1522
+ projected$1.clear();
1523
+ return;
1524
+ }
1525
+ scheduleRefresh("upstream-update");
1526
+ });
1527
+ return {
1528
+ instance: {
1529
+ name: _def.name,
1530
+ refresh$: channel.stream$,
1531
+ get() {
1532
+ return projected$1.get();
1533
+ },
1534
+ refresh() {
1535
+ scheduleRefresh("on-demand");
1536
+ },
1537
+ async load() {
1538
+ if (!loaded) await projected$1.get();
1539
+ }
1540
+ },
1541
+ destroy() {
1542
+ unsubUpdates();
1543
+ ttl.clear();
1544
+ channel.complete();
1545
+ }
1546
+ };
1764
1547
  }
1765
1548
  function createSingletonSync(source, options, client, updates$, resolver, refreshByTtl) {
1766
- const { instance: base, destroy } = createSingleton(
1767
- source,
1768
- options,
1769
- client,
1770
- updates$,
1771
- resolver,
1772
- refreshByTtl
1773
- );
1774
- return {
1775
- instance: {
1776
- ...base,
1777
- get() {
1778
- const result = base.get();
1779
- if (result instanceof Promise) {
1780
- throw new TypeError(`singleton "${base.name}" is not initialized yet \u2014 call singleton.load() first`);
1781
- }
1782
- return result;
1783
- }
1784
- },
1785
- destroy
1786
- };
1549
+ const { instance: base, destroy } = createSingleton(source, options, client, updates$, resolver, refreshByTtl);
1550
+ return {
1551
+ instance: {
1552
+ ...base,
1553
+ get() {
1554
+ const result = base.get();
1555
+ if (result instanceof Promise) throw new TypeError(`singleton "${base.name}" is not initialized yet — call singleton.load() first`);
1556
+ return result;
1557
+ }
1558
+ },
1559
+ destroy
1560
+ };
1787
1561
  }
1788
-
1789
- // src/watcher.ts
1790
- var import_client10 = require("@contello/client");
1562
+ //#endregion
1563
+ //#region src/watcher.ts
1791
1564
  function addRouteByModel(map, entityType, event) {
1792
- let list = map.get(entityType);
1793
- if (!list) {
1794
- list = [];
1795
- map.set(entityType, list);
1796
- }
1797
- list.push(event);
1565
+ let list = map.get(entityType);
1566
+ if (!list) {
1567
+ list = [];
1568
+ map.set(entityType, list);
1569
+ }
1570
+ list.push(event);
1571
+ }
1572
+ function addEventToBatch(batch, event) {
1573
+ switch (event.target) {
1574
+ case "route":
1575
+ batch.route.push(event);
1576
+ if ("after" in event && event.after.type === "entity") addRouteByModel(batch.routeByEntityModel, event.after.model, event);
1577
+ if ("before" in event && event.before.type === "entity") addRouteByModel(batch.routeByEntityModel, event.before.model, event);
1578
+ break;
1579
+ case "asset":
1580
+ batch.asset.push(event);
1581
+ break;
1582
+ case "i18nMessage":
1583
+ batch.i18nMessage.push(event);
1584
+ break;
1585
+ case "entity": {
1586
+ let list = batch.entity.get(event.model);
1587
+ if (!list) {
1588
+ list = [];
1589
+ batch.entity.set(event.model, list);
1590
+ }
1591
+ list.push(event);
1592
+ break;
1593
+ }
1594
+ }
1798
1595
  }
1799
1596
  function createUpdateBatch(events) {
1800
- const route = [];
1801
- const asset = [];
1802
- const i18nMessage = [];
1803
- const entity = /* @__PURE__ */ new Map();
1804
- const routeByEntityModel = /* @__PURE__ */ new Map();
1805
- for (const event of events) {
1806
- switch (event.target) {
1807
- case "route": {
1808
- route.push(event);
1809
- if ("after" in event && event.after.type === "entity") {
1810
- addRouteByModel(routeByEntityModel, event.after.model, event);
1811
- }
1812
- if ("before" in event && event.before.type === "entity") {
1813
- addRouteByModel(routeByEntityModel, event.before.model, event);
1814
- }
1815
- break;
1816
- }
1817
- case "asset": {
1818
- asset.push(event);
1819
- break;
1820
- }
1821
- case "i18nMessage": {
1822
- i18nMessage.push(event);
1823
- break;
1824
- }
1825
- case "entity": {
1826
- let list = entity.get(event.model);
1827
- if (!list) {
1828
- list = [];
1829
- entity.set(event.model, list);
1830
- }
1831
- list.push(event);
1832
- break;
1833
- }
1834
- }
1835
- }
1836
- return { events, route, asset, i18nMessage, entity, routeByEntityModel };
1597
+ const batch = {
1598
+ route: [],
1599
+ asset: [],
1600
+ i18nMessage: [],
1601
+ entity: /* @__PURE__ */ new Map(),
1602
+ routeByEntityModel: /* @__PURE__ */ new Map()
1603
+ };
1604
+ for (const event of events) addEventToBatch(batch, event);
1605
+ return {
1606
+ events,
1607
+ route: batch.route,
1608
+ asset: batch.asset,
1609
+ i18nMessage: batch.i18nMessage,
1610
+ entity: batch.entity,
1611
+ routeByEntityModel: batch.routeByEntityModel
1612
+ };
1837
1613
  }
1838
1614
  function castMutationType(type) {
1839
- switch (type) {
1840
- case "CREATE": {
1841
- return "create";
1842
- }
1843
- case "UPDATE": {
1844
- return "update";
1845
- }
1846
- case "DELETE": {
1847
- return "delete";
1848
- }
1849
- }
1615
+ switch (type) {
1616
+ case "CREATE": return "create";
1617
+ case "UPDATE": return "update";
1618
+ case "DELETE": return "delete";
1619
+ }
1850
1620
  }
1851
1621
  function mapEvent(raw, resolver) {
1852
- const mutation = castMutationType(raw.mutation.type);
1853
- const target = raw.target;
1854
- const { id, __typename } = target;
1855
- switch (__typename) {
1856
- case "ContelloRoute": {
1857
- if (mutation === "delete") {
1858
- return { id, mutation: "delete", target: "route" };
1859
- }
1860
- const after = mapRoute(target, resolver);
1861
- if (!after) {
1862
- return void 0;
1863
- }
1864
- if (mutation === "create") {
1865
- return { id, mutation, target: "route", after };
1866
- }
1867
- const before = raw.prev?.__typename === "ContelloRoute" ? mapRoute(raw.prev, resolver) ?? void 0 : void 0;
1868
- if (!before) {
1869
- return void 0;
1870
- }
1871
- return { id, mutation, target: "route", after, before };
1872
- }
1873
- case "ContelloAsset": {
1874
- return { id, mutation, target: "asset" };
1875
- }
1876
- case "ContelloI18nMessage": {
1877
- return { id, mutation, target: "i18nMessage", token: target.token };
1878
- }
1879
- default: {
1880
- if (!__typename || !resolver.hasTypeName(__typename)) {
1881
- return void 0;
1882
- }
1883
- return { id, mutation, target: "entity", model: resolver.resolveModel(__typename) };
1884
- }
1885
- }
1622
+ const mutation = castMutationType(raw.mutation.type);
1623
+ const target = raw.target;
1624
+ const { id, __typename } = target;
1625
+ switch (__typename) {
1626
+ case "ContelloRoute": {
1627
+ if (mutation === "delete") return {
1628
+ id,
1629
+ mutation: "delete",
1630
+ target: "route"
1631
+ };
1632
+ const after = mapRoute(target, resolver);
1633
+ if (!after) return;
1634
+ if (mutation === "create") return {
1635
+ id,
1636
+ mutation,
1637
+ target: "route",
1638
+ after
1639
+ };
1640
+ const before = raw.prev?.__typename === "ContelloRoute" ? mapRoute(raw.prev, resolver) ?? void 0 : void 0;
1641
+ if (!before) return;
1642
+ return {
1643
+ id,
1644
+ mutation,
1645
+ target: "route",
1646
+ after,
1647
+ before
1648
+ };
1649
+ }
1650
+ case "ContelloAsset": return {
1651
+ id,
1652
+ mutation,
1653
+ target: "asset"
1654
+ };
1655
+ case "ContelloI18nMessage": return {
1656
+ id,
1657
+ mutation,
1658
+ target: "i18nMessage",
1659
+ token: target.token
1660
+ };
1661
+ default:
1662
+ if (!__typename || !resolver.hasTypeName(__typename)) return;
1663
+ return {
1664
+ id,
1665
+ mutation,
1666
+ target: "entity",
1667
+ model: resolver.resolveModel(__typename)
1668
+ };
1669
+ }
1886
1670
  }
1887
1671
  function safeMapEvent(raw, resolver) {
1888
- try {
1889
- return mapEvent(raw, resolver);
1890
- } catch {
1891
- return void 0;
1892
- }
1672
+ try {
1673
+ return mapEvent(raw, resolver);
1674
+ } catch {
1675
+ return;
1676
+ }
1893
1677
  }
1894
1678
  function createInternalWatcher(client, resolver) {
1895
- const updates$ = (0, import_client10.createAsyncIterableSubject)();
1896
- let controller;
1897
- return {
1898
- updates$,
1899
- start() {
1900
- if (controller) {
1901
- return;
1902
- }
1903
- controller = new AbortController();
1904
- const signal = controller.signal;
1905
- wrap("watcher:start", () => {
1906
- void (async () => {
1907
- const source = (0, import_client10.asyncKeepalive)(
1908
- () => client.subscribe(storeWatchUpdatesDocument),
1909
- signal
1910
- );
1911
- const events = (0, import_client10.mapAsync)(
1912
- source,
1913
- (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => safeMapEvent(e, resolver)).filter((e) => e !== void 0)
1914
- );
1915
- for await (const list of events) {
1916
- if (signal.aborted) {
1917
- return;
1918
- }
1919
- if (list.length === 0) {
1920
- continue;
1921
- }
1922
- try {
1923
- updates$.next(createUpdateBatch(list));
1924
- } catch {
1925
- }
1926
- }
1927
- })().catch(() => {
1928
- });
1929
- });
1930
- },
1931
- stop() {
1932
- controller?.abort();
1933
- controller = void 0;
1934
- updates$.complete();
1935
- }
1936
- };
1679
+ const updates$ = (0, _contello_client.createAsyncIterableSubject)();
1680
+ let controller;
1681
+ return {
1682
+ updates$,
1683
+ start() {
1684
+ if (controller) return;
1685
+ controller = new AbortController();
1686
+ const signal = controller.signal;
1687
+ wrap("watcher:start", () => {
1688
+ (async () => {
1689
+ const events = (0, _contello_client.mapAsync)((0, _contello_client.asyncKeepalive)(() => client.subscribe(storeWatchUpdatesDocument), signal), (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => safeMapEvent(e, resolver)).filter((e) => e !== void 0));
1690
+ for await (const list of events) {
1691
+ if (signal.aborted) return;
1692
+ if (list.length === 0) continue;
1693
+ try {
1694
+ updates$.next(createUpdateBatch(list));
1695
+ } catch {}
1696
+ }
1697
+ })().catch(() => {});
1698
+ });
1699
+ },
1700
+ stop() {
1701
+ controller?.abort();
1702
+ controller = void 0;
1703
+ updates$.complete();
1704
+ }
1705
+ };
1937
1706
  }
1938
-
1939
- // src/store.ts
1707
+ //#endregion
1708
+ //#region src/store.ts
1940
1709
  var Store = class {
1941
- _client;
1942
- _resolver;
1943
- _watcher;
1944
- _schema;
1945
- _cleanups = [];
1946
- _refreshByTtl = createRefreshByTtlQueue();
1947
- /**
1948
- * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1949
- * each iteration starts an independent fan-out from the shared source.
1950
- */
1951
- updates$;
1952
- constructor(options) {
1953
- const { url, project, token, schema: schema2 } = options;
1954
- this._schema = schema2;
1955
- this._client = (0, import_client11.createContelloClient)({
1956
- url,
1957
- project,
1958
- token,
1959
- schema: schema2,
1960
- connections: options.connections,
1961
- onConnected: options.onConnected,
1962
- onReconnecting: options.onReconnecting,
1963
- onError: options.onError,
1964
- connectionEvents: options.connectionEvents
1965
- });
1966
- this._resolver = new ModelResolver(schema2?.models);
1967
- this._watcher = createInternalWatcher(this._client, this._resolver);
1968
- this.updates$ = this._watcher.updates$;
1969
- this.ping = () => this._client.ping();
1970
- }
1971
- get client() {
1972
- return this._client;
1973
- }
1974
- async init() {
1975
- await wrap("store:init", () => this._client.init());
1976
- this._watcher.start();
1977
- }
1978
- async destroy() {
1979
- for (const fn of this._cleanups.splice(0)) {
1980
- try {
1981
- fn();
1982
- } catch {
1983
- }
1984
- }
1985
- this._watcher.stop();
1986
- await wrap("store:destroy", () => this._client.destroy());
1987
- }
1988
- /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */
1989
- _resolveSource(sourceOrKey) {
1990
- if (typeof sourceOrKey !== "string") {
1991
- return sourceOrKey;
1992
- }
1993
- const sources2 = this._schema?.sources;
1994
- const source = sources2?.[sourceOrKey];
1995
- if (!source) {
1996
- throw new Error(`@contello/store: no source named "${sourceOrKey}" in schema.sources`);
1997
- }
1998
- return source;
1999
- }
2000
- // --- singleton ---
2001
- defineSingleton(sourceOrKey, options) {
2002
- const source = this._resolveSource(sourceOrKey);
2003
- const { instance, destroy } = createSingleton(
2004
- source,
2005
- options,
2006
- this._client,
2007
- this._watcher.updates$,
2008
- this._resolver,
2009
- this._refreshByTtl
2010
- );
2011
- this._cleanups.push(destroy);
2012
- return instance;
2013
- }
2014
- defineSingletonSync(sourceOrKey, options) {
2015
- const source = this._resolveSource(sourceOrKey);
2016
- const { instance, destroy } = createSingletonSync(
2017
- source,
2018
- options,
2019
- this._client,
2020
- this._watcher.updates$,
2021
- this._resolver,
2022
- this._refreshByTtl
2023
- );
2024
- this._cleanups.push(destroy);
2025
- return instance;
2026
- }
2027
- // --- collection ---
2028
- defineCollection(sourceOrKey, options) {
2029
- const source = this._resolveSource(sourceOrKey);
2030
- const { instance, destroy } = createCollection(
2031
- source,
2032
- options,
2033
- this._client,
2034
- this._watcher.updates$,
2035
- this._resolver,
2036
- this._refreshByTtl
2037
- );
2038
- this._cleanups.push(destroy);
2039
- return instance;
2040
- }
2041
- defineCollectionSync(sourceOrKey, options) {
2042
- const source = this._resolveSource(sourceOrKey);
2043
- const { instance, destroy } = createCollectionSync(
2044
- source,
2045
- options,
2046
- this._client,
2047
- this._watcher.updates$,
2048
- this._resolver,
2049
- this._refreshByTtl
2050
- );
2051
- this._cleanups.push(destroy);
2052
- return instance;
2053
- }
2054
- // --- lazy collection ---
2055
- defineLazyCollection(sourceOrKey, options) {
2056
- const source = this._resolveSource(sourceOrKey);
2057
- const { instance, destroy } = createLazyCollection(
2058
- source,
2059
- options,
2060
- this._client,
2061
- this._watcher.updates$,
2062
- this._resolver
2063
- );
2064
- this._cleanups.push(destroy);
2065
- return instance;
2066
- }
2067
- // --- assets / routes / i18n (no source — built-ins) ---
2068
- // --- assets ---
2069
- defineAssets(options) {
2070
- const { instance, destroy } = createAssetsCollection(
2071
- options,
2072
- this._client,
2073
- this._watcher.updates$,
2074
- this._refreshByTtl
2075
- );
2076
- this._cleanups.push(destroy);
2077
- return instance;
2078
- }
2079
- defineAssetsSync(options) {
2080
- const { instance, destroy } = createAssetsSyncCollection(
2081
- options,
2082
- this._client,
2083
- this._watcher.updates$,
2084
- this._refreshByTtl
2085
- );
2086
- this._cleanups.push(destroy);
2087
- return instance;
2088
- }
2089
- defineLazyAssets(options) {
2090
- const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);
2091
- this._cleanups.push(destroy);
2092
- return instance;
2093
- }
2094
- // --- routes ---
2095
- defineRoutes(options) {
2096
- const { instance, destroy } = createRoutesCollection(
2097
- options,
2098
- this._client,
2099
- this._watcher.updates$,
2100
- this._resolver,
2101
- this._refreshByTtl
2102
- );
2103
- this._cleanups.push(destroy);
2104
- return instance;
2105
- }
2106
- defineRoutesSync(options) {
2107
- const { instance, destroy } = createRoutesSyncCollection(
2108
- options,
2109
- this._client,
2110
- this._watcher.updates$,
2111
- this._resolver,
2112
- this._refreshByTtl
2113
- );
2114
- this._cleanups.push(destroy);
2115
- return instance;
2116
- }
2117
- defineLazyRoutes(options) {
2118
- const { instance, destroy } = createLazyRoutesCollection(
2119
- options,
2120
- this._client,
2121
- this._watcher.updates$,
2122
- this._resolver
2123
- );
2124
- this._cleanups.push(destroy);
2125
- return instance;
2126
- }
2127
- defineI18nMessages(def) {
2128
- const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);
2129
- this._cleanups.push(result.destroy);
2130
- return result;
2131
- }
2132
- ping;
1710
+ _client;
1711
+ _resolver;
1712
+ _watcher;
1713
+ _schema;
1714
+ _cleanups = [];
1715
+ _refreshByTtl = createRefreshByTtlQueue();
1716
+ /**
1717
+ * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1718
+ * each iteration starts an independent fan-out from the shared source.
1719
+ */
1720
+ updates$;
1721
+ ping;
1722
+ constructor(options) {
1723
+ const { url, project, token, schema } = options;
1724
+ this._schema = schema;
1725
+ this._client = (0, _contello_client.createContelloClient)({
1726
+ url,
1727
+ project,
1728
+ token,
1729
+ schema,
1730
+ connections: options.connections,
1731
+ onConnected: options.onConnected,
1732
+ onReconnecting: options.onReconnecting,
1733
+ onError: options.onError,
1734
+ connectionEvents: options.connectionEvents
1735
+ });
1736
+ this._resolver = new ModelResolver(schema?.models);
1737
+ this._watcher = createInternalWatcher(this._client, this._resolver);
1738
+ this.updates$ = this._watcher.updates$;
1739
+ this.ping = () => this._client.ping();
1740
+ }
1741
+ /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */
1742
+ _resolveSource(sourceOrKey) {
1743
+ if (typeof sourceOrKey !== "string") return sourceOrKey;
1744
+ const source = (this._schema?.sources)?.[sourceOrKey];
1745
+ if (!source) throw new Error(`@contello/store: no source named "${sourceOrKey}" in schema.sources`);
1746
+ return source;
1747
+ }
1748
+ get client() {
1749
+ return this._client;
1750
+ }
1751
+ async init() {
1752
+ await wrap("store:init", () => this._client.init());
1753
+ this._watcher.start();
1754
+ }
1755
+ async destroy() {
1756
+ for (const fn of this._cleanups.splice(0)) try {
1757
+ fn();
1758
+ } catch {}
1759
+ this._watcher.stop();
1760
+ await wrap("store:destroy", () => this._client.destroy());
1761
+ }
1762
+ defineSingleton(sourceOrKey, options) {
1763
+ const { instance, destroy } = createSingleton(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1764
+ this._cleanups.push(destroy);
1765
+ return instance;
1766
+ }
1767
+ defineSingletonSync(sourceOrKey, options) {
1768
+ const { instance, destroy } = createSingletonSync(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1769
+ this._cleanups.push(destroy);
1770
+ return instance;
1771
+ }
1772
+ defineCollection(sourceOrKey, options) {
1773
+ const { instance, destroy } = createCollection(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1774
+ this._cleanups.push(destroy);
1775
+ return instance;
1776
+ }
1777
+ defineCollectionSync(sourceOrKey, options) {
1778
+ const { instance, destroy } = createCollectionSync(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1779
+ this._cleanups.push(destroy);
1780
+ return instance;
1781
+ }
1782
+ defineLazyCollection(sourceOrKey, options) {
1783
+ const { instance, destroy } = createLazyCollection(this._resolveSource(sourceOrKey), options, this._client, this._watcher.updates$, this._resolver);
1784
+ this._cleanups.push(destroy);
1785
+ return instance;
1786
+ }
1787
+ defineAssets(options) {
1788
+ const { instance, destroy } = createAssetsCollection(options, this._client, this._watcher.updates$, this._refreshByTtl);
1789
+ this._cleanups.push(destroy);
1790
+ return instance;
1791
+ }
1792
+ defineAssetsSync(options) {
1793
+ const { instance, destroy } = createAssetsSyncCollection(options, this._client, this._watcher.updates$, this._refreshByTtl);
1794
+ this._cleanups.push(destroy);
1795
+ return instance;
1796
+ }
1797
+ defineLazyAssets(options) {
1798
+ const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);
1799
+ this._cleanups.push(destroy);
1800
+ return instance;
1801
+ }
1802
+ defineRoutes(options) {
1803
+ const { instance, destroy } = createRoutesCollection(options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1804
+ this._cleanups.push(destroy);
1805
+ return instance;
1806
+ }
1807
+ defineRoutesSync(options) {
1808
+ const { instance, destroy } = createRoutesSyncCollection(options, this._client, this._watcher.updates$, this._resolver, this._refreshByTtl);
1809
+ this._cleanups.push(destroy);
1810
+ return instance;
1811
+ }
1812
+ defineLazyRoutes(options) {
1813
+ const { instance, destroy } = createLazyRoutesCollection(options, this._client, this._watcher.updates$, this._resolver);
1814
+ this._cleanups.push(destroy);
1815
+ return instance;
1816
+ }
1817
+ defineI18nMessages(def) {
1818
+ const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);
1819
+ this._cleanups.push(result.destroy);
1820
+ return result;
1821
+ }
2133
1822
  };
2134
1823
  function createStore(options) {
2135
- return new Store(options);
1824
+ return new Store(options);
2136
1825
  }
2137
-
2138
- // src/index.ts
2139
- var import_projected9 = require("projected");
2140
- // Annotate the CommonJS export names for ESM import in node:
2141
- 0 && (module.exports = {
2142
- Store,
2143
- createStore,
2144
- maybeCatch,
2145
- maybeThen
1826
+ //#endregion
1827
+ exports.Store = Store;
1828
+ exports.createStore = createStore;
1829
+ Object.defineProperty(exports, "maybeCatch", {
1830
+ enumerable: true,
1831
+ get: function() {
1832
+ return projected.maybeCatch;
1833
+ }
1834
+ });
1835
+ Object.defineProperty(exports, "maybeThen", {
1836
+ enumerable: true,
1837
+ get: function() {
1838
+ return projected.maybeThen;
1839
+ }
2146
1840
  });