@contello/store 3.0.0 → 3.1.0

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