@contello/store 2.1.1 → 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,1915 +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
479
+ //#endregion
480
+ //#region src/dependency-collector.ts
481
+ const EMPTY_KEYS = /* @__PURE__ */ new Set();
485
482
  function createDependencyKey(target, id) {
486
- return `${target}\0${id}`;
483
+ return `${target}\0${id}`;
487
484
  }
488
485
  function createEntityDependencyKey(typename, id) {
489
- return `entity\0${typename}\0${id}`;
486
+ return `entity\0${typename}\0${id}`;
490
487
  }
491
488
  function createRouteTargetKey(typename, id) {
492
- return `routeTarget\0${typename}\0${id}`;
489
+ return `routeTarget\0${typename}\0${id}`;
493
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
+ */
494
509
  var DependencyCollector = class {
495
- constructor(model, resolver) {
496
- this.model = model;
497
- this.resolver = resolver;
498
- }
499
- /** dep key -> item keys that declared a dependency on it */
500
- reverseIndex = /* @__PURE__ */ new Map();
501
- /** item key -> dep keys it currently declares */
502
- forwardIndex = /* @__PURE__ */ new Map();
503
- /**
504
- * creates a scoped MapperContext for one item and runs `fn` with it.
505
- * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function
506
- * that must be called once the item key is known — it writes all declared deps into the index.
507
- * returns whatever `fn` returns, preserving MaybePromise semantics.
508
- */
509
- createContext(fn) {
510
- const deps = [];
511
- const ctx = {
512
- track: (obj) => {
513
- if (!obj.id) {
514
- throw new Error(`track(): object with __typename "${obj.__typename}" has no "id" field`);
515
- }
516
- switch (obj.__typename) {
517
- case "ContelloAsset": {
518
- deps.push(createDependencyKey("asset", obj.id));
519
- break;
520
- }
521
- case "ContelloRoute": {
522
- deps.push(createDependencyKey("route", obj.id));
523
- break;
524
- }
525
- default: {
526
- const model = this.resolver.getModel(obj.__typename);
527
- if (!model) {
528
- throw new Error(
529
- `track(): unexpected __typename "${obj.__typename}" \u2014 expected ContelloAsset, ContelloRoute, or a known entity model`
530
- );
531
- }
532
- deps.push(createEntityDependencyKey(model, obj.id));
533
- }
534
- }
535
- },
536
- trackEntity: (model, id) => {
537
- this.warnIfUnknownModel(model);
538
- deps.push(createEntityDependencyKey(model, id));
539
- },
540
- trackAsset: (id) => deps.push(createDependencyKey("asset", id)),
541
- trackRoute: (id) => deps.push(createDependencyKey("route", id))
542
- };
543
- const register = (key) => {
544
- this.clearItem(key);
545
- deps.push(createRouteTargetKey(this.model, String(key)));
546
- const fwd = /* @__PURE__ */ new Set();
547
- for (const dk of deps) {
548
- fwd.add(dk);
549
- let set = this.reverseIndex.get(dk);
550
- if (!set) {
551
- set = /* @__PURE__ */ new Set();
552
- this.reverseIndex.set(dk, set);
553
- }
554
- set.add(key);
555
- }
556
- if (fwd.size > 0) {
557
- this.forwardIndex.set(key, fwd);
558
- }
559
- };
560
- return fn(ctx, register);
561
- }
562
- /**
563
- * looks up which item keys are affected by an update event.
564
- * for route events, checks route-target deps for both the new and previous entity targets.
565
- */
566
- getAffectedKeys(event) {
567
- if (event.target === "entity") {
568
- return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? /* @__PURE__ */ new Set();
569
- }
570
- let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));
571
- if (event.target === "route") {
572
- if ("after" in event && event.after.type === "entity") {
573
- affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);
574
- }
575
- if ("before" in event && event.before.type === "entity") {
576
- affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);
577
- }
578
- }
579
- return affected ?? /* @__PURE__ */ new Set();
580
- }
581
- mergeRouteTargetKeys(existing, entityType, entityId) {
582
- const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));
583
- if (!items) {
584
- return existing;
585
- }
586
- return existing ? /* @__PURE__ */ new Set([...existing, ...items]) : items;
587
- }
588
- /** removes all recorded deps for a single item (called on eviction) */
589
- removeItem(key) {
590
- this.clearItem(key);
591
- }
592
- /** drops all recorded deps — used when clearing the entire cache */
593
- clear() {
594
- this.reverseIndex.clear();
595
- this.forwardIndex.clear();
596
- }
597
- /**
598
- * removes index entries for any item key NOT present in `keys`.
599
- * called after a full re-fetch to prune refs from items that were deleted upstream.
600
- */
601
- retainOnly(keys) {
602
- for (const key of this.forwardIndex.keys()) {
603
- if (!keys.has(key)) {
604
- this.clearItem(key);
605
- }
606
- }
607
- }
608
- warnIfUnknownModel(model) {
609
- if (!this.resolver.hasModel(model)) {
610
- console.warn(
611
- `[contello/store] tracking model "${model}" which is not in models \u2014 updates for this model will be ignored`
612
- );
613
- }
614
- }
615
- /**
616
- * removes all index entries for one item key.
617
- * cleans up the forward entry and removes the item from every reverse set it appeared in.
618
- * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.
619
- */
620
- clearItem(key) {
621
- const existingDeps = this.forwardIndex.get(key);
622
- if (!existingDeps) {
623
- return;
624
- }
625
- for (const dk of existingDeps) {
626
- const set = this.reverseIndex.get(dk);
627
- if (set) {
628
- set.delete(key);
629
- if (set.size === 0) {
630
- this.reverseIndex.delete(dk);
631
- }
632
- }
633
- }
634
- this.forwardIndex.delete(key);
635
- }
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
+ }
636
627
  };
637
-
638
- // src/collection.ts
628
+ //#endregion
629
+ //#region src/collection.ts
639
630
  function fetchCollection(source, client, ids) {
640
- return (0, import_client3.collectAsync)(
641
- (0, import_client3.mapAsync)(
642
- client.subscribe((0, import_client3.createSourceSubscription)(source), { ids }),
643
- (r) => r.source
644
- )
645
- );
631
+ return (0, _contello_client.collectAsync)((0, _contello_client.mapAsync)(client.subscribe((0, _contello_client.createSourceSubscription)(source), { ids }), (r) => r.source));
646
632
  }
647
633
  function createCollection(source, options, client, updates$, resolver, refreshByTtl) {
648
- const opts = options ?? {};
649
- const mapFn = opts.map ?? ((item) => item);
650
- const _def = {
651
- name: opts.name ?? source.__model,
652
- model: source.__model,
653
- cache: {
654
- ttl: resolveTtl(opts.cache?.ttl),
655
- eviction: opts.cache?.eviction ?? "refresh"
656
- }
657
- };
658
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
659
- const channel = createRefreshChannel(opts.onRefresh);
660
- const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh("ttl") });
661
- let loaded = false;
662
- const projected = new import_projected2.ProjectedMap({
663
- key: (item) => item.id,
664
- values: (ids) => wrap(
665
- `collection:${_def.name}`,
666
- () => (0, import_projected2.maybeThen)(
667
- fetchCollection(source, client, ids),
668
- (rawItems) => Promise.all(
669
- rawItems.map(
670
- (item) => Promise.resolve(
671
- dependencyCollector.createContext(
672
- (ref, register) => (0, import_projected2.maybeThen)(mapFn(item, ref), (mapped) => {
673
- register(mapped.id);
674
- return mapped;
675
- })
676
- )
677
- )
678
- )
679
- ).then((items) => {
680
- if (ids === void 0) {
681
- dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
682
- if (!loaded) {
683
- loaded = true;
684
- ttl.mark();
685
- opts.onLoad?.(items.map((item) => item.id));
686
- }
687
- } else {
688
- const returnedIds = new Set(items.map((item) => item.id));
689
- for (const id of ids) {
690
- if (!returnedIds.has(id)) {
691
- dependencyCollector.removeItem(id);
692
- }
693
- }
694
- }
695
- return items;
696
- })
697
- )
698
- ),
699
- sort: opts.sort
700
- });
701
- function emit(ids, kind) {
702
- channel.emit({ ids, kind });
703
- }
704
- function runFullRefresh(kind) {
705
- refreshByTtl.enqueue(
706
- () => (0, import_client3.runWithBackoff)(
707
- () => projected.refresh().then((map) => {
708
- emit([...map.keys()], kind);
709
- ttl.mark();
710
- })
711
- )
712
- );
713
- }
714
- function runPartialRefresh(refreshIds, deletedIds) {
715
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
716
- if (refreshIds.length === 0) {
717
- emit(changedIds, "upstream-update");
718
- return;
719
- }
720
- void (0, import_client3.runWithBackoff)(
721
- () => projected.refresh(refreshIds).then(() => {
722
- emit(changedIds, "upstream-update");
723
- })
724
- );
725
- }
726
- const unsubUpdates = updates$.subscribe((batch) => {
727
- if (!loaded) {
728
- return;
729
- }
730
- const ownEvents = batch.entity.get(_def.model) ?? [];
731
- const deleted = [];
732
- const upserted = /* @__PURE__ */ new Set();
733
- for (const event of ownEvents) {
734
- if (event.mutation === "delete") {
735
- deleted.push(event.id);
736
- } else {
737
- upserted.add(event.id);
738
- }
739
- }
740
- const depAffected = /* @__PURE__ */ new Set();
741
- for (const event of batch.events) {
742
- for (const id of dependencyCollector.getAffectedKeys(event)) {
743
- depAffected.add(id);
744
- }
745
- }
746
- if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {
747
- return;
748
- }
749
- if (_def.cache.eviction === "clear") {
750
- dependencyCollector.clear();
751
- projected.clear();
752
- return;
753
- }
754
- for (const id of deleted) {
755
- dependencyCollector.removeItem(id);
756
- }
757
- if (deleted.length > 0) {
758
- projected.delete(deleted);
759
- }
760
- const refreshIds = /* @__PURE__ */ new Set([...upserted, ...depAffected]);
761
- for (const id of deleted) {
762
- refreshIds.delete(id);
763
- }
764
- runPartialRefresh([...refreshIds], deleted);
765
- });
766
- const instance = {
767
- name: _def.name,
768
- refresh$: channel.stream$,
769
- get(idOrIds) {
770
- return projected.get(idOrIds);
771
- },
772
- getAll() {
773
- return projected.getAll();
774
- },
775
- refresh() {
776
- runFullRefresh("on-demand");
777
- },
778
- async load() {
779
- if (!loaded) {
780
- await projected.getAllAsMap();
781
- }
782
- }
783
- };
784
- return {
785
- instance,
786
- destroy() {
787
- unsubUpdates();
788
- ttl.clear();
789
- channel.complete();
790
- }
791
- };
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
+ };
792
740
  }
793
741
  function createCollectionSync(source, options, client, updates$, resolver, refreshByTtl) {
794
- const { instance: base, destroy } = createCollection(
795
- source,
796
- options,
797
- client,
798
- updates$,
799
- resolver,
800
- refreshByTtl
801
- );
802
- function assertSync(value, method) {
803
- if (value instanceof Promise) {
804
- throw new TypeError(`collection "${base.name}".${method}() is not initialized yet \u2014 call collection.load() first`);
805
- }
806
- return value;
807
- }
808
- return {
809
- instance: {
810
- ...base,
811
- get(idOrIds) {
812
- return assertSync(base.get(idOrIds), "get");
813
- },
814
- getAll() {
815
- return assertSync(base.getAll(), "getAll");
816
- }
817
- },
818
- destroy
819
- };
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
+ };
820
759
  }
821
-
822
- // src/i18n.ts
823
- var import_client4 = require("@contello/client");
824
- var import_projected3 = require("projected");
760
+ //#endregion
761
+ //#region src/i18n.ts
825
762
  function toGqlMessageInput(msg) {
826
- return {
827
- token: msg.token,
828
- example: msg.example,
829
- description: msg.description,
830
- variables: msg.variables?.map((v) => ({ name: v.name, description: v.description, example: v.example })),
831
- translations: msg.translations?.map((t) => ({ language: t.language, message: t.message })),
832
- initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message }))
833
- };
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
+ };
834
781
  }
835
782
  function createI18nMessagesCollection(def, client, updates$, refreshByTtl) {
836
- const channel = createRefreshChannel(def.onRefresh);
837
- const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });
838
- let loaded = false;
839
- const i18nSourceDoc = (0, import_client4.createSourceSubscription)(schema.sources.storeI18nMessage);
840
- const projected = new import_projected3.ProjectedMap({
841
- key: (msg) => msg.id,
842
- values: (ids) => wrap(
843
- `i18n:${def.collection}`,
844
- () => (0, import_client4.collectAsync)(
845
- (0, import_client4.mapAsync)(
846
- client.subscribe(i18nSourceDoc, {
847
- collection: def.collection,
848
- ids
849
- }),
850
- (data) => data.source
851
- )
852
- ).then((msgs) => {
853
- const items = msgs.map((msg) => ({
854
- id: msg.id,
855
- token: msg.token,
856
- translations: new Map(msg.translations.map((t) => [t.language, t.value]))
857
- }));
858
- if (ids === void 0 && !loaded) {
859
- loaded = true;
860
- ttl.mark();
861
- }
862
- return items;
863
- })
864
- )
865
- });
866
- function emit(ids, kind) {
867
- channel.emit({ ids, kind });
868
- }
869
- function emitWithCurrentIds(kind) {
870
- (0, import_projected3.maybeThen)(projected.getAll(), (msgs) => {
871
- emit(
872
- msgs.map((m) => m.id),
873
- kind
874
- );
875
- });
876
- }
877
- function runTtlRefresh() {
878
- refreshByTtl.enqueue(
879
- () => (0, import_client4.runWithBackoff)(() => projected.refresh()).then(() => {
880
- emitWithCurrentIds("ttl");
881
- ttl.mark();
882
- })
883
- );
884
- }
885
- const scheduleRefresh = createRefresher(
886
- () => projected.refresh(),
887
- (kind) => {
888
- emitWithCurrentIds(kind);
889
- ttl.mark();
890
- },
891
- () => {
892
- }
893
- );
894
- function runPartialRefresh(upsertedIds, deletedIds) {
895
- const changedIds = [.../* @__PURE__ */ new Set([...upsertedIds, ...deletedIds])];
896
- if (changedIds.length === 0) {
897
- return;
898
- }
899
- if (upsertedIds.length === 0) {
900
- emit(changedIds, "upstream-update");
901
- return;
902
- }
903
- void (0, import_client4.runWithBackoff)(
904
- () => projected.refresh(upsertedIds).then(() => {
905
- emit(changedIds, "upstream-update");
906
- })
907
- );
908
- }
909
- const unsubUpdates = updates$.subscribe((batch) => {
910
- if (!loaded) {
911
- return;
912
- }
913
- if (batch.i18nMessage.length === 0) {
914
- return;
915
- }
916
- const deleted = [];
917
- const upserted = /* @__PURE__ */ new Set();
918
- for (const event of batch.i18nMessage) {
919
- if (event.mutation === "delete") {
920
- deleted.push(event.id);
921
- } else {
922
- upserted.add(event.id);
923
- }
924
- }
925
- if (deleted.length > 0) {
926
- projected.delete(deleted);
927
- }
928
- runPartialRefresh([...upserted], deleted);
929
- });
930
- return {
931
- refresh$: channel.stream$,
932
- get(idOrIds) {
933
- return projected.get(idOrIds);
934
- },
935
- getAll() {
936
- return projected.getAll();
937
- },
938
- register(messages) {
939
- return wrap(
940
- `i18n-register:${def.collection}`,
941
- () => client.execute(storeRegisterI18nMessagesDocument, {
942
- collection: def.collection,
943
- messages: messages.map((message) => toGqlMessageInput(message))
944
- }).then(() => {
945
- })
946
- );
947
- },
948
- refresh() {
949
- scheduleRefresh("on-demand");
950
- },
951
- destroy() {
952
- unsubUpdates();
953
- ttl.clear();
954
- channel.complete();
955
- }
956
- };
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
+ };
957
877
  }
958
-
959
- // src/lazy-assets.ts
960
- var import_client5 = require("@contello/client");
961
- var import_projected4 = require("projected");
962
-
963
- // src/lru.ts
964
- var import_lru_cache = require("lru-cache");
878
+ //#endregion
879
+ //#region src/lru.ts
965
880
  function createLruCache(options) {
966
- const { max, ttl, onEvict: dispose } = options;
967
- const lru = new import_lru_cache.LRUCache({
968
- max,
969
- ...ttl !== void 0 && { ttl, ttlAutopurge: false },
970
- ...dispose !== void 0 && { dispose }
971
- });
972
- return {
973
- has: (key) => lru.has(key),
974
- get: (key) => lru.get(key),
975
- set: (key, value) => {
976
- lru.set(key, value);
977
- },
978
- delete: (key) => {
979
- lru.delete(key);
980
- },
981
- clear: () => {
982
- lru.clear();
983
- },
984
- keys: () => [...lru.keys()]
985
- };
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
+ };
986
904
  }
987
-
988
- // src/lazy-assets.ts
989
- function mapFile2(raw) {
990
- return {
991
- uid: raw.uid,
992
- mimeType: raw.mimeType,
993
- metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : void 0
994
- };
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
+ };
995
916
  }
996
- function mapAsset2(raw) {
997
- return {
998
- id: raw.id,
999
- original: mapFile2(raw.original),
1000
- preview: raw.preview ? mapFile2(raw.preview) : void 0,
1001
- optimized: raw.optimized.map((file) => mapFile2(file))
1002
- };
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
+ };
1003
924
  }
1004
925
  function createLazyAssetsCollection(def, client, updates$) {
1005
- const _def = {
1006
- cache: {
1007
- max: def?.cache?.max ?? DEFAULT_LRU_MAX,
1008
- ttl: resolveTtl(def?.cache?.ttl)
1009
- }
1010
- };
1011
- const cache = createLruCache({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: void 0 });
1012
- const assetsSourceDoc = (0, import_client5.createSourceSubscription)(schema.sources.storeAsset);
1013
- const projected = new import_projected4.ProjectedLazyMap({
1014
- key: (asset) => asset.id,
1015
- values: (ids) => wrap(
1016
- "assets",
1017
- () => (0, import_client5.collectAsync)(
1018
- (0, import_client5.mapAsync)(client.subscribe(assetsSourceDoc, { ids }), (data) => data.source)
1019
- ).then((rawItems) => rawItems.map((item) => mapAsset2(item)))
1020
- ),
1021
- cache
1022
- });
1023
- const channel = createRefreshChannel(def?.onRefresh);
1024
- function emit(ids, kind) {
1025
- channel.emit({ ids, kind });
1026
- }
1027
- let lastRefreshKeys = [];
1028
- const scheduleRefresh = createRefresher(
1029
- async () => {
1030
- lastRefreshKeys = cache.keys();
1031
- if (lastRefreshKeys.length === 0) {
1032
- return;
1033
- }
1034
- await projected.refresh(lastRefreshKeys);
1035
- },
1036
- (kind) => {
1037
- if (lastRefreshKeys.length > 0) {
1038
- emit(lastRefreshKeys, kind);
1039
- }
1040
- },
1041
- () => {
1042
- }
1043
- );
1044
- const unsubUpdates = updates$.subscribe((batch) => {
1045
- if (batch.asset.length === 0) return;
1046
- for (const event of batch.asset) {
1047
- projected.delete(event.id);
1048
- }
1049
- emit(
1050
- batch.asset.map((e) => e.id),
1051
- "upstream-update"
1052
- );
1053
- });
1054
- return {
1055
- instance: {
1056
- refresh$: channel.stream$,
1057
- get(idOrIds) {
1058
- return projected.get(idOrIds);
1059
- },
1060
- upload(data, meta, options) {
1061
- return client.upload(data, meta, options);
1062
- },
1063
- download(fileId) {
1064
- return client.download(fileId);
1065
- },
1066
- proxyHls(path, signal) {
1067
- return client.proxyHls(path, signal);
1068
- },
1069
- refresh() {
1070
- scheduleRefresh("on-demand");
1071
- },
1072
- clear() {
1073
- projected.clear();
1074
- }
1075
- },
1076
- destroy() {
1077
- unsubUpdates();
1078
- channel.complete();
1079
- }
1080
- };
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
+ };
1081
990
  }
1082
-
1083
- // src/lazy-collection.ts
1084
- var import_client6 = require("@contello/client");
1085
- var import_projected5 = require("projected");
991
+ //#endregion
992
+ //#region src/lazy-collection.ts
1086
993
  function createLazyCollection(source, options, client, updates$, resolver) {
1087
- const opts = options ?? {};
1088
- const mapFn = opts.map ?? ((item) => item);
1089
- const _def = {
1090
- name: opts.name ?? source.__model,
1091
- model: source.__model,
1092
- cache: {
1093
- max: opts.cache?.max ?? DEFAULT_LRU_MAX,
1094
- ttl: resolveTtl(opts.cache?.ttl)
1095
- }
1096
- };
1097
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
1098
- const cache = createLruCache({
1099
- max: _def.cache.max,
1100
- ttl: _def.cache.ttl,
1101
- onEvict: (_value, key) => dependencyCollector.removeItem(key)
1102
- });
1103
- const projected = new import_projected5.ProjectedLazyMap({
1104
- key: (item) => item.id,
1105
- values: (keys) => wrap(
1106
- `lazy-collection:${_def.name}`,
1107
- () => (0, import_projected5.maybeThen)(
1108
- (0, import_client6.collectAsync)(
1109
- (0, import_client6.mapAsync)(
1110
- client.subscribe((0, import_client6.createSourceSubscription)(source), {
1111
- ids: keys
1112
- }),
1113
- (r) => r.source
1114
- )
1115
- ),
1116
- (rawItems) => Promise.all(
1117
- rawItems.map(
1118
- (item) => Promise.resolve(
1119
- dependencyCollector.createContext(
1120
- (ref, register) => (0, import_projected5.maybeThen)(mapFn(item, ref), (mapped) => {
1121
- register(mapped.id);
1122
- return mapped;
1123
- })
1124
- )
1125
- )
1126
- )
1127
- )
1128
- )
1129
- ),
1130
- cache
1131
- });
1132
- const refresh$ = (0, import_client6.createAsyncIterableSubject)();
1133
- function emit(ids, kind) {
1134
- const event = { ids, kind };
1135
- refresh$.next(event);
1136
- opts.onRefresh?.(event);
1137
- }
1138
- let lastRefreshKeys = [];
1139
- const scheduleRefresh = createRefresher(
1140
- async () => {
1141
- lastRefreshKeys = cache.keys();
1142
- if (lastRefreshKeys.length === 0) {
1143
- return;
1144
- }
1145
- await projected.refresh(lastRefreshKeys);
1146
- },
1147
- (kind) => {
1148
- if (lastRefreshKeys.length > 0) {
1149
- emit(lastRefreshKeys, kind);
1150
- }
1151
- },
1152
- () => {
1153
- }
1154
- );
1155
- const unsubUpdates = updates$.subscribe((batch) => {
1156
- const evicted = /* @__PURE__ */ new Set();
1157
- const ownModelEvents = batch.entity.get(_def.model);
1158
- if (ownModelEvents) {
1159
- for (const event of ownModelEvents) {
1160
- evicted.add(event.id);
1161
- }
1162
- }
1163
- for (const event of batch.events) {
1164
- for (const key of dependencyCollector.getAffectedKeys(event)) {
1165
- evicted.add(key);
1166
- }
1167
- }
1168
- if (evicted.size > 0) {
1169
- for (const key of evicted) {
1170
- dependencyCollector.removeItem(key);
1171
- projected.delete(key);
1172
- }
1173
- emit([...evicted], "upstream-update");
1174
- }
1175
- });
1176
- return {
1177
- instance: {
1178
- name: _def.name,
1179
- refresh$,
1180
- get(idOrIds) {
1181
- return projected.get(idOrIds);
1182
- },
1183
- refresh() {
1184
- scheduleRefresh("on-demand");
1185
- },
1186
- clear() {
1187
- dependencyCollector.clear();
1188
- projected.clear();
1189
- }
1190
- },
1191
- destroy() {
1192
- unsubUpdates();
1193
- refresh$.complete();
1194
- }
1195
- };
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
+ };
1196
1068
  }
1197
-
1198
- // src/lazy-routes.ts
1199
- var import_client7 = require("@contello/client");
1200
- var import_projected6 = require("projected");
1201
-
1202
- // src/routes-mapping.ts
1069
+ //#endregion
1070
+ //#region src/routes-mapping.ts
1203
1071
  function mapRoute(raw, resolver) {
1204
- const base = {
1205
- id: raw.id,
1206
- path: raw.path,
1207
- customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value }))
1208
- };
1209
- switch (raw.target.__typename) {
1210
- case "ContelloRouteTargetRedirect": {
1211
- return {
1212
- ...base,
1213
- type: "redirect",
1214
- location: raw.target.location,
1215
- status: raw.target.responseCode
1216
- };
1217
- }
1218
- case "ContelloRouteTargetText": {
1219
- return {
1220
- ...base,
1221
- type: "text",
1222
- content: raw.target.content,
1223
- mimeType: raw.target.mimeType
1224
- };
1225
- }
1226
- case "ContelloRouteTargetAsset": {
1227
- return {
1228
- ...base,
1229
- type: "asset",
1230
- assetId: raw.target.asset.id,
1231
- fileId: raw.target.asset.original.uid,
1232
- contentDisposition: raw.target.contentDisposition === "INLINE" ? "inline" : "attachment",
1233
- mimeType: raw.target.asset.original.mimeType
1234
- };
1235
- }
1236
- case "ContelloRouteTargetEntity": {
1237
- if (!raw.target.entity) {
1238
- return void 0;
1239
- }
1240
- const entityType = raw.target.entity.__typename;
1241
- return {
1242
- ...base,
1243
- type: "entity",
1244
- model: resolver.resolveModel(entityType),
1245
- entityType,
1246
- entityId: raw.target.entity.id
1247
- };
1248
- }
1249
- default: {
1250
- return void 0;
1251
- }
1252
- }
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
+ }
1253
1114
  }
1254
-
1255
- // src/lazy-routes.ts
1256
- var ID_PREFIX = "1\0";
1257
- var PATH_PREFIX = "2\0";
1258
- 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");
1259
1120
  function collectRoutes(rawItems, keyFn, resolver) {
1260
- return rawItems.reduce((acc, raw) => {
1261
- const mapped = mapRoute(raw, resolver);
1262
- if (mapped) {
1263
- mapped[CACHE_KEY] = keyFn(mapped);
1264
- acc.push(mapped);
1265
- }
1266
- return acc;
1267
- }, []);
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
+ }, []);
1268
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
+ */
1269
1137
  function createRoutesCache(max, ttl) {
1270
- const pathToId = /* @__PURE__ */ new Map();
1271
- const lru = createLruCache({
1272
- max,
1273
- ttl,
1274
- onEvict: (route) => {
1275
- pathToId.delete(route.path);
1276
- }
1277
- });
1278
- function resolveKey(key) {
1279
- if (key.startsWith(PATH_PREFIX)) {
1280
- const id = pathToId.get(key.slice(2));
1281
- if (id) {
1282
- return ID_PREFIX + id;
1283
- }
1284
- return key;
1285
- }
1286
- return key;
1287
- }
1288
- return {
1289
- has: (key) => lru.has(resolveKey(key)),
1290
- get: (key) => lru.get(resolveKey(key)),
1291
- set: (_key, value) => {
1292
- pathToId.set(value.path, value.id);
1293
- lru.set(ID_PREFIX + value.id, value);
1294
- },
1295
- delete: (key) => {
1296
- const resolved = resolveKey(key);
1297
- const value = lru.get(resolved);
1298
- if (value) {
1299
- pathToId.delete(value.path);
1300
- }
1301
- lru.delete(resolved);
1302
- },
1303
- clear: () => {
1304
- pathToId.clear();
1305
- lru.clear();
1306
- },
1307
- keys: () => lru.keys()
1308
- };
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
+ };
1309
1182
  }
1310
1183
  function createLazyRoutesCollection(def, client, updates$, resolver) {
1311
- const _def = {
1312
- cache: {
1313
- max: def?.cache?.max ?? DEFAULT_LRU_MAX,
1314
- ttl: resolveTtl(def?.cache?.ttl)
1315
- }
1316
- };
1317
- const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);
1318
- const routesSourceDoc = (0, import_client7.createSourceSubscription)(schema.sources.storeRoute);
1319
- function fetchRoutes(vars) {
1320
- return (0, import_client7.collectAsync)(
1321
- (0, import_client7.mapAsync)(client.subscribe(routesSourceDoc, vars), (data) => data.source)
1322
- );
1323
- }
1324
- const projected = new import_projected6.ProjectedLazyMap({
1325
- key: (route) => route[CACHE_KEY] ?? ID_PREFIX + route.id,
1326
- values: (prefixedKeys) => wrap("routes", () => {
1327
- const ids = [];
1328
- const paths = [];
1329
- for (const key of prefixedKeys) {
1330
- const value = key.slice(2);
1331
- if (key.startsWith(ID_PREFIX)) {
1332
- ids.push(value);
1333
- } else {
1334
- paths.push(value);
1335
- }
1336
- }
1337
- return Promise.all([
1338
- ids.length > 0 ? fetchRoutes({ ids }).then((raw) => collectRoutes(raw, (r) => ID_PREFIX + r.id, resolver)) : Promise.resolve([]),
1339
- paths.length > 0 ? fetchRoutes({ paths }).then((raw) => collectRoutes(raw, (r) => PATH_PREFIX + r.path, resolver)) : Promise.resolve([])
1340
- ]).then(([byIds, byPaths]) => [...byIds, ...byPaths]);
1341
- }),
1342
- cache
1343
- });
1344
- const channel = createRefreshChannel(def?.onRefresh);
1345
- function emit(ids, kind) {
1346
- channel.emit({ ids, kind });
1347
- }
1348
- let lastRefreshKeys = [];
1349
- const scheduleRefresh = createRefresher(
1350
- async () => {
1351
- lastRefreshKeys = cache.keys();
1352
- if (lastRefreshKeys.length === 0) {
1353
- return;
1354
- }
1355
- await projected.refresh(lastRefreshKeys);
1356
- },
1357
- (kind) => {
1358
- if (lastRefreshKeys.length > 0) {
1359
- emit(
1360
- lastRefreshKeys.map((key) => key.slice(2)),
1361
- kind
1362
- );
1363
- }
1364
- },
1365
- () => {
1366
- }
1367
- );
1368
- const unsubUpdates = updates$.subscribe((batch) => {
1369
- const evicted = [];
1370
- for (const event of batch.route) {
1371
- const idKey = ID_PREFIX + event.id;
1372
- if (event.mutation === "delete") {
1373
- cache.delete(idKey);
1374
- evicted.push(event.id);
1375
- } else {
1376
- if (cache.has(idKey)) {
1377
- cache.set(idKey, event.after);
1378
- }
1379
- evicted.push(event.after.path);
1380
- }
1381
- }
1382
- if (evicted.length > 0) {
1383
- emit(evicted, "upstream-update");
1384
- }
1385
- });
1386
- return {
1387
- instance: {
1388
- refresh$: channel.stream$,
1389
- get(idOrIds) {
1390
- if (Array.isArray(idOrIds)) {
1391
- return projected.get(idOrIds.map((id) => ID_PREFIX + id));
1392
- }
1393
- return projected.get(ID_PREFIX + idOrIds);
1394
- },
1395
- getByPath(pathOrPaths) {
1396
- if (Array.isArray(pathOrPaths)) {
1397
- return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));
1398
- }
1399
- return projected.get(PATH_PREFIX + pathOrPaths);
1400
- },
1401
- refresh() {
1402
- scheduleRefresh("on-demand");
1403
- },
1404
- clear() {
1405
- projected.clear();
1406
- }
1407
- },
1408
- destroy() {
1409
- unsubUpdates();
1410
- channel.complete();
1411
- }
1412
- };
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
+ };
1413
1262
  }
1414
-
1415
- // src/model-resolver.ts
1263
+ //#endregion
1264
+ //#region src/model-resolver.ts
1416
1265
  var ModelResolver = class {
1417
- _typeNames;
1418
- _toModel;
1419
- _toTypeName;
1420
- constructor(models2) {
1421
- const toModel = /* @__PURE__ */ new Map();
1422
- const toTypeName = /* @__PURE__ */ new Map();
1423
- let typeNames;
1424
- if (models2) {
1425
- typeNames = /* @__PURE__ */ new Set();
1426
- for (const [model, typeName] of Object.entries(models2)) {
1427
- toModel.set(typeName, model);
1428
- toTypeName.set(model, typeName);
1429
- typeNames.add(typeName);
1430
- }
1431
- }
1432
- this._typeNames = typeNames;
1433
- this._toModel = toModel;
1434
- this._toTypeName = toTypeName;
1435
- }
1436
- hasTypeName(typeName) {
1437
- return !this._typeNames || this._typeNames.has(typeName);
1438
- }
1439
- getModel(typeName) {
1440
- return this._toModel.get(typeName);
1441
- }
1442
- getTypeName(model) {
1443
- return this._toTypeName.get(model) ?? model;
1444
- }
1445
- hasModel(model) {
1446
- return this._toTypeName.size === 0 || this._toTypeName.has(model);
1447
- }
1448
- resolveModel(typeName) {
1449
- return this._toModel.get(typeName) ?? typeName;
1450
- }
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
+ }
1451
1300
  };
1452
-
1453
- // src/routes.ts
1454
- var import_client8 = require("@contello/client");
1455
- var import_projected7 = require("projected");
1301
+ //#endregion
1302
+ //#region src/routes.ts
1456
1303
  function createRoutesCollection(options, client, updates$, resolver, refreshByTtl) {
1457
- const opts = options ?? {};
1458
- const cache = {
1459
- ttl: resolveTtl(opts.cache?.ttl),
1460
- eviction: opts.cache?.eviction ?? "refresh"
1461
- };
1462
- const channel = createRefreshChannel(opts.onRefresh);
1463
- const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh("ttl") });
1464
- const pathById = /* @__PURE__ */ new Map();
1465
- const idByPath = /* @__PURE__ */ new Map();
1466
- let loaded = false;
1467
- const routesSourceDoc = (0, import_client8.createSourceSubscription)(schema.sources.storeRoute);
1468
- const projected = new import_projected7.ProjectedMap({
1469
- key: (route) => route.id,
1470
- values: (ids) => wrap(
1471
- "routes",
1472
- () => (0, import_client8.collectAsync)(
1473
- (0, import_client8.mapAsync)(client.subscribe(routesSourceDoc, { ids }), (data) => data.source)
1474
- ).then((rawItems) => {
1475
- const items = rawItems.reduce((acc, raw) => {
1476
- const mapped = mapRoute(raw, resolver);
1477
- if (mapped) {
1478
- acc.push(mapped);
1479
- }
1480
- return acc;
1481
- }, []);
1482
- if (ids === void 0) {
1483
- pathById.clear();
1484
- idByPath.clear();
1485
- for (const r of items) {
1486
- pathById.set(r.id, r.path);
1487
- idByPath.set(r.path, r.id);
1488
- }
1489
- if (!loaded) {
1490
- loaded = true;
1491
- ttl.mark();
1492
- opts.onLoad?.(items.map((r) => r.id));
1493
- }
1494
- } else {
1495
- const returnedIds = new Set(items.map((r) => r.id));
1496
- for (const id of ids) {
1497
- if (!returnedIds.has(id)) {
1498
- const oldPath = pathById.get(id);
1499
- if (oldPath !== void 0) {
1500
- idByPath.delete(oldPath);
1501
- pathById.delete(id);
1502
- }
1503
- }
1504
- }
1505
- for (const r of items) {
1506
- const oldPath = pathById.get(r.id);
1507
- if (oldPath !== void 0 && oldPath !== r.path) {
1508
- idByPath.delete(oldPath);
1509
- }
1510
- pathById.set(r.id, r.path);
1511
- idByPath.set(r.path, r.id);
1512
- }
1513
- }
1514
- return items;
1515
- })
1516
- )
1517
- });
1518
- function emit(ids, kind) {
1519
- channel.emit({ ids, kind });
1520
- }
1521
- function runFullRefresh(kind) {
1522
- refreshByTtl.enqueue(
1523
- () => (0, import_client8.runWithBackoff)(
1524
- () => projected.refresh().then((map) => {
1525
- emit([...map.keys()], kind);
1526
- ttl.mark();
1527
- })
1528
- )
1529
- );
1530
- }
1531
- function runPartialRefresh(refreshIds, deletedIds) {
1532
- const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
1533
- if (refreshIds.length === 0) {
1534
- emit(changedIds, "upstream-update");
1535
- return;
1536
- }
1537
- void (0, import_client8.runWithBackoff)(
1538
- () => projected.refresh(refreshIds).then(() => {
1539
- emit(changedIds, "upstream-update");
1540
- })
1541
- );
1542
- }
1543
- const unsubUpdates = updates$.subscribe((batch) => {
1544
- if (!loaded || batch.route.length === 0) {
1545
- return;
1546
- }
1547
- const deleted = [];
1548
- const upserted = /* @__PURE__ */ new Set();
1549
- for (const event of batch.route) {
1550
- if (event.mutation === "delete") {
1551
- deleted.push(event.id);
1552
- } else {
1553
- upserted.add(event.id);
1554
- }
1555
- }
1556
- if (cache.eviction === "clear") {
1557
- pathById.clear();
1558
- idByPath.clear();
1559
- projected.clear();
1560
- return;
1561
- }
1562
- for (const id of deleted) {
1563
- const oldPath = pathById.get(id);
1564
- if (oldPath !== void 0) {
1565
- idByPath.delete(oldPath);
1566
- pathById.delete(id);
1567
- }
1568
- }
1569
- if (deleted.length > 0) {
1570
- projected.delete(deleted);
1571
- }
1572
- runPartialRefresh([...upserted], deleted);
1573
- });
1574
- function getByIdSingle(id) {
1575
- return projected.get(id);
1576
- }
1577
- function getByIds(ids) {
1578
- return projected.get(ids);
1579
- }
1580
- function lookupByPathSingle(path) {
1581
- return (0, import_projected7.maybeThen)(ensureLoaded(), () => {
1582
- const id = idByPath.get(path);
1583
- return id === void 0 ? void 0 : projected.get(id);
1584
- });
1585
- }
1586
- function lookupByPaths(paths) {
1587
- return (0, import_projected7.maybeThen)(ensureLoaded(), () => {
1588
- const ids = [];
1589
- for (const p of paths) {
1590
- const id = idByPath.get(p);
1591
- if (id !== void 0) {
1592
- ids.push(id);
1593
- }
1594
- }
1595
- return projected.get(ids);
1596
- });
1597
- }
1598
- function ensureLoaded() {
1599
- if (loaded) {
1600
- return void 0;
1601
- }
1602
- return (0, import_projected7.maybeThen)(projected.getAllAsMap(), () => {
1603
- });
1604
- }
1605
- const instance = {
1606
- refresh$: channel.stream$,
1607
- async load() {
1608
- if (!loaded) {
1609
- await projected.getAllAsMap();
1610
- }
1611
- },
1612
- get(idOrIds) {
1613
- return typeof idOrIds === "string" ? getByIdSingle(idOrIds) : getByIds(idOrIds);
1614
- },
1615
- getByPath(pathOrPaths) {
1616
- return typeof pathOrPaths === "string" ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);
1617
- },
1618
- refresh() {
1619
- runFullRefresh("on-demand");
1620
- }
1621
- };
1622
- return {
1623
- instance,
1624
- destroy() {
1625
- unsubUpdates();
1626
- ttl.clear();
1627
- channel.complete();
1628
- }
1629
- };
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
+ };
1630
1451
  }
1631
1452
  function createRoutesSyncCollection(options, client, updates$, resolver, refreshByTtl) {
1632
- const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);
1633
- function assertSync(value, method) {
1634
- if (value instanceof Promise) {
1635
- throw new TypeError(`routes.${method}() is not initialized yet \u2014 call routes.load() first`);
1636
- }
1637
- return value;
1638
- }
1639
- return {
1640
- instance: {
1641
- ...base,
1642
- get(idOrIds) {
1643
- return assertSync(base.get(idOrIds), "get");
1644
- },
1645
- getByPath(pathOrPaths) {
1646
- return assertSync(base.getByPath(pathOrPaths), "getByPath");
1647
- }
1648
- },
1649
- destroy
1650
- };
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
+ };
1651
1470
  }
1652
-
1653
- // src/singleton.ts
1654
- var import_client9 = require("@contello/client");
1655
- var import_projected8 = require("projected");
1471
+ //#endregion
1472
+ //#region src/singleton.ts
1656
1473
  function createSingleton(source, options, client, updates$, resolver, refreshByTtl) {
1657
- const opts = options ?? {};
1658
- const mapFn = opts.map ?? ((item) => item);
1659
- const _def = {
1660
- name: opts.name ?? source.__model,
1661
- model: source.__model,
1662
- cache: {
1663
- ttl: resolveTtl(opts.cache?.ttl),
1664
- eviction: opts.cache?.eviction ?? "refresh"
1665
- }
1666
- };
1667
- const dependencyCollector = new DependencyCollector(_def.model, resolver);
1668
- const itemKey = `singleton:${_def.name}`;
1669
- const channel = createRefreshChannel(opts.onRefresh);
1670
- const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });
1671
- let loaded = false;
1672
- const projected = new import_projected8.ProjectedValue({
1673
- value: () => wrap(
1674
- `singleton:${_def.name}`,
1675
- () => (0, import_projected8.maybeThen)(
1676
- (0, import_client9.firstAsync)(
1677
- (0, import_client9.mapAsync)(
1678
- client.subscribe((0, import_client9.createSourceSubscription)(source)),
1679
- (r) => r.source
1680
- )
1681
- ),
1682
- (raw) => dependencyCollector.createContext(
1683
- (ref, register) => (0, import_projected8.maybeThen)(mapFn(raw, ref), (mapped) => {
1684
- register(itemKey);
1685
- if (!loaded) {
1686
- loaded = true;
1687
- ttl.mark();
1688
- opts.onLoad?.();
1689
- }
1690
- return mapped;
1691
- })
1692
- )
1693
- )
1694
- )
1695
- });
1696
- function emit(kind) {
1697
- channel.emit({ kind });
1698
- }
1699
- function runTtlRefresh() {
1700
- refreshByTtl.enqueue(
1701
- () => (0, import_client9.runWithBackoff)(() => projected.refresh()).then(() => {
1702
- emit("ttl");
1703
- ttl.mark();
1704
- })
1705
- );
1706
- }
1707
- const scheduleRefresh = createRefresher(
1708
- () => projected.refresh(),
1709
- (kind) => {
1710
- emit(kind);
1711
- ttl.mark();
1712
- },
1713
- () => {
1714
- }
1715
- );
1716
- const unsubUpdates = updates$.subscribe((batch) => {
1717
- if (!loaded) {
1718
- return;
1719
- }
1720
- const hasOwnModel = batch.entity.has(_def.model);
1721
- const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);
1722
- if (!hasOwnModel && !hasAffectedRefs) {
1723
- return;
1724
- }
1725
- if (_def.cache.eviction === "clear") {
1726
- dependencyCollector.clear();
1727
- projected.clear();
1728
- return;
1729
- }
1730
- scheduleRefresh("upstream-update");
1731
- });
1732
- return {
1733
- instance: {
1734
- name: _def.name,
1735
- refresh$: channel.stream$,
1736
- get() {
1737
- return projected.get();
1738
- },
1739
- refresh() {
1740
- scheduleRefresh("on-demand");
1741
- },
1742
- async load() {
1743
- if (!loaded) {
1744
- await projected.get();
1745
- }
1746
- }
1747
- },
1748
- destroy() {
1749
- unsubUpdates();
1750
- ttl.clear();
1751
- channel.complete();
1752
- }
1753
- };
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
+ };
1754
1547
  }
1755
1548
  function createSingletonSync(source, options, client, updates$, resolver, refreshByTtl) {
1756
- const { instance: base, destroy } = createSingleton(
1757
- source,
1758
- options,
1759
- client,
1760
- updates$,
1761
- resolver,
1762
- refreshByTtl
1763
- );
1764
- return {
1765
- instance: {
1766
- ...base,
1767
- get() {
1768
- const result = base.get();
1769
- if (result instanceof Promise) {
1770
- throw new TypeError(`singleton "${base.name}" is not initialized yet \u2014 call singleton.load() first`);
1771
- }
1772
- return result;
1773
- }
1774
- },
1775
- destroy
1776
- };
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
+ };
1777
1561
  }
1778
-
1779
- // src/watcher.ts
1780
- var import_client10 = require("@contello/client");
1562
+ //#endregion
1563
+ //#region src/watcher.ts
1781
1564
  function addRouteByModel(map, entityType, event) {
1782
- let list = map.get(entityType);
1783
- if (!list) {
1784
- list = [];
1785
- map.set(entityType, list);
1786
- }
1787
- 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
+ }
1788
1595
  }
1789
1596
  function createUpdateBatch(events) {
1790
- const route = [];
1791
- const asset = [];
1792
- const i18nMessage = [];
1793
- const entity = /* @__PURE__ */ new Map();
1794
- const routeByEntityModel = /* @__PURE__ */ new Map();
1795
- for (const event of events) {
1796
- switch (event.target) {
1797
- case "route": {
1798
- route.push(event);
1799
- if ("after" in event && event.after.type === "entity") {
1800
- addRouteByModel(routeByEntityModel, event.after.model, event);
1801
- }
1802
- if ("before" in event && event.before.type === "entity") {
1803
- addRouteByModel(routeByEntityModel, event.before.model, event);
1804
- }
1805
- break;
1806
- }
1807
- case "asset": {
1808
- asset.push(event);
1809
- break;
1810
- }
1811
- case "i18nMessage": {
1812
- i18nMessage.push(event);
1813
- break;
1814
- }
1815
- case "entity": {
1816
- let list = entity.get(event.model);
1817
- if (!list) {
1818
- list = [];
1819
- entity.set(event.model, list);
1820
- }
1821
- list.push(event);
1822
- break;
1823
- }
1824
- }
1825
- }
1826
- 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
+ };
1827
1613
  }
1828
1614
  function castMutationType(type) {
1829
- switch (type) {
1830
- case "CREATE": {
1831
- return "create";
1832
- }
1833
- case "UPDATE": {
1834
- return "update";
1835
- }
1836
- case "DELETE": {
1837
- return "delete";
1838
- }
1839
- }
1615
+ switch (type) {
1616
+ case "CREATE": return "create";
1617
+ case "UPDATE": return "update";
1618
+ case "DELETE": return "delete";
1619
+ }
1840
1620
  }
1841
1621
  function mapEvent(raw, resolver) {
1842
- const mutation = castMutationType(raw.mutation.type);
1843
- const target = raw.target;
1844
- const { id, __typename } = target;
1845
- switch (__typename) {
1846
- case "ContelloRoute": {
1847
- if (mutation === "delete") {
1848
- return { id, mutation: "delete", target: "route" };
1849
- }
1850
- const after = mapRoute(target, resolver);
1851
- if (!after) {
1852
- return void 0;
1853
- }
1854
- if (mutation === "create") {
1855
- return { id, mutation, target: "route", after };
1856
- }
1857
- const before = raw.prev?.__typename === "ContelloRoute" ? mapRoute(raw.prev, resolver) ?? void 0 : void 0;
1858
- if (!before) {
1859
- return void 0;
1860
- }
1861
- return { id, mutation, target: "route", after, before };
1862
- }
1863
- case "ContelloAsset": {
1864
- return { id, mutation, target: "asset" };
1865
- }
1866
- case "ContelloI18nMessage": {
1867
- return { id, mutation, target: "i18nMessage", token: target.token };
1868
- }
1869
- default: {
1870
- if (!__typename || !resolver.hasTypeName(__typename)) {
1871
- return void 0;
1872
- }
1873
- return { id, mutation, target: "entity", model: resolver.resolveModel(__typename) };
1874
- }
1875
- }
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
+ }
1670
+ }
1671
+ function safeMapEvent(raw, resolver) {
1672
+ try {
1673
+ return mapEvent(raw, resolver);
1674
+ } catch {
1675
+ return;
1676
+ }
1876
1677
  }
1877
1678
  function createInternalWatcher(client, resolver) {
1878
- const updates$ = (0, import_client10.createAsyncIterableSubject)();
1879
- let controller;
1880
- return {
1881
- updates$,
1882
- start() {
1883
- if (controller) {
1884
- return;
1885
- }
1886
- controller = new AbortController();
1887
- const signal = controller.signal;
1888
- wrap("watcher:start", () => {
1889
- void (async () => {
1890
- const source = (0, import_client10.asyncKeepalive)(
1891
- () => client.subscribe(storeWatchUpdatesDocument),
1892
- signal
1893
- );
1894
- const events = (0, import_client10.mapAsync)(
1895
- source,
1896
- (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => mapEvent(e, resolver)).filter((e) => e !== void 0)
1897
- );
1898
- for await (const list of events) {
1899
- if (signal.aborted) {
1900
- return;
1901
- }
1902
- if (list.length === 0) {
1903
- continue;
1904
- }
1905
- updates$.next(createUpdateBatch(list));
1906
- }
1907
- })();
1908
- });
1909
- },
1910
- stop() {
1911
- controller?.abort();
1912
- controller = void 0;
1913
- updates$.complete();
1914
- }
1915
- };
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
+ };
1916
1706
  }
1917
-
1918
- // src/store.ts
1707
+ //#endregion
1708
+ //#region src/store.ts
1919
1709
  var Store = class {
1920
- _client;
1921
- _resolver;
1922
- _watcher;
1923
- _schema;
1924
- _cleanups = [];
1925
- _refreshByTtl = createRefreshByTtlQueue();
1926
- /**
1927
- * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1928
- * each iteration starts an independent fan-out from the shared source.
1929
- */
1930
- updates$;
1931
- constructor(options) {
1932
- const { url, project, token, schema: schema2 } = options;
1933
- this._schema = schema2;
1934
- this._client = (0, import_client11.createContelloClient)({
1935
- url,
1936
- project,
1937
- token,
1938
- schema: schema2,
1939
- connections: options.connections,
1940
- onConnected: options.onConnected,
1941
- onReconnecting: options.onReconnecting,
1942
- onError: options.onError,
1943
- connectionEvents: options.connectionEvents
1944
- });
1945
- this._resolver = new ModelResolver(schema2?.models);
1946
- this._watcher = createInternalWatcher(this._client, this._resolver);
1947
- this.updates$ = this._watcher.updates$;
1948
- this.ping = () => this._client.ping();
1949
- }
1950
- get client() {
1951
- return this._client;
1952
- }
1953
- async init() {
1954
- await wrap("store:init", () => this._client.init());
1955
- this._watcher.start();
1956
- }
1957
- async destroy() {
1958
- for (const fn of this._cleanups.splice(0)) {
1959
- try {
1960
- fn();
1961
- } catch {
1962
- }
1963
- }
1964
- this._watcher.stop();
1965
- await wrap("store:destroy", () => this._client.destroy());
1966
- }
1967
- /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */
1968
- _resolveSource(sourceOrKey) {
1969
- if (typeof sourceOrKey !== "string") {
1970
- return sourceOrKey;
1971
- }
1972
- const sources2 = this._schema?.sources;
1973
- const source = sources2?.[sourceOrKey];
1974
- if (!source) {
1975
- throw new Error(`@contello/store: no source named "${sourceOrKey}" in schema.sources`);
1976
- }
1977
- return source;
1978
- }
1979
- // --- singleton ---
1980
- defineSingleton(sourceOrKey, options) {
1981
- const source = this._resolveSource(sourceOrKey);
1982
- const { instance, destroy } = createSingleton(
1983
- source,
1984
- options,
1985
- this._client,
1986
- this._watcher.updates$,
1987
- this._resolver,
1988
- this._refreshByTtl
1989
- );
1990
- this._cleanups.push(destroy);
1991
- return instance;
1992
- }
1993
- defineSingletonSync(sourceOrKey, options) {
1994
- const source = this._resolveSource(sourceOrKey);
1995
- const { instance, destroy } = createSingletonSync(
1996
- source,
1997
- options,
1998
- this._client,
1999
- this._watcher.updates$,
2000
- this._resolver,
2001
- this._refreshByTtl
2002
- );
2003
- this._cleanups.push(destroy);
2004
- return instance;
2005
- }
2006
- // --- collection ---
2007
- defineCollection(sourceOrKey, options) {
2008
- const source = this._resolveSource(sourceOrKey);
2009
- const { instance, destroy } = createCollection(
2010
- source,
2011
- options,
2012
- this._client,
2013
- this._watcher.updates$,
2014
- this._resolver,
2015
- this._refreshByTtl
2016
- );
2017
- this._cleanups.push(destroy);
2018
- return instance;
2019
- }
2020
- defineCollectionSync(sourceOrKey, options) {
2021
- const source = this._resolveSource(sourceOrKey);
2022
- const { instance, destroy } = createCollectionSync(
2023
- source,
2024
- options,
2025
- this._client,
2026
- this._watcher.updates$,
2027
- this._resolver,
2028
- this._refreshByTtl
2029
- );
2030
- this._cleanups.push(destroy);
2031
- return instance;
2032
- }
2033
- // --- lazy collection ---
2034
- defineLazyCollection(sourceOrKey, options) {
2035
- const source = this._resolveSource(sourceOrKey);
2036
- const { instance, destroy } = createLazyCollection(
2037
- source,
2038
- options,
2039
- this._client,
2040
- this._watcher.updates$,
2041
- this._resolver
2042
- );
2043
- this._cleanups.push(destroy);
2044
- return instance;
2045
- }
2046
- // --- assets / routes / i18n (no source — built-ins) ---
2047
- // --- assets ---
2048
- defineAssets(options) {
2049
- const { instance, destroy } = createAssetsCollection(
2050
- options,
2051
- this._client,
2052
- this._watcher.updates$,
2053
- this._refreshByTtl
2054
- );
2055
- this._cleanups.push(destroy);
2056
- return instance;
2057
- }
2058
- defineAssetsSync(options) {
2059
- const { instance, destroy } = createAssetsSyncCollection(
2060
- options,
2061
- this._client,
2062
- this._watcher.updates$,
2063
- this._refreshByTtl
2064
- );
2065
- this._cleanups.push(destroy);
2066
- return instance;
2067
- }
2068
- defineLazyAssets(options) {
2069
- const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);
2070
- this._cleanups.push(destroy);
2071
- return instance;
2072
- }
2073
- // --- routes ---
2074
- defineRoutes(options) {
2075
- const { instance, destroy } = createRoutesCollection(
2076
- options,
2077
- this._client,
2078
- this._watcher.updates$,
2079
- this._resolver,
2080
- this._refreshByTtl
2081
- );
2082
- this._cleanups.push(destroy);
2083
- return instance;
2084
- }
2085
- defineRoutesSync(options) {
2086
- const { instance, destroy } = createRoutesSyncCollection(
2087
- options,
2088
- this._client,
2089
- this._watcher.updates$,
2090
- this._resolver,
2091
- this._refreshByTtl
2092
- );
2093
- this._cleanups.push(destroy);
2094
- return instance;
2095
- }
2096
- defineLazyRoutes(options) {
2097
- const { instance, destroy } = createLazyRoutesCollection(
2098
- options,
2099
- this._client,
2100
- this._watcher.updates$,
2101
- this._resolver
2102
- );
2103
- this._cleanups.push(destroy);
2104
- return instance;
2105
- }
2106
- defineI18nMessages(def) {
2107
- const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);
2108
- this._cleanups.push(result.destroy);
2109
- return result;
2110
- }
2111
- 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
+ }
2112
1822
  };
2113
1823
  function createStore(options) {
2114
- return new Store(options);
1824
+ return new Store(options);
2115
1825
  }
2116
-
2117
- // src/index.ts
2118
- var import_projected9 = require("projected");
2119
- // Annotate the CommonJS export names for ESM import in node:
2120
- 0 && (module.exports = {
2121
- Store,
2122
- createStore,
2123
- maybeCatch,
2124
- 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
+ }
2125
1840
  });