@itd-api/cache 0.0.2 → 0.2.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.js CHANGED
@@ -1,720 +1,839 @@
1
- import { LRUCache } from 'lru-cache';
2
-
3
- // src/errors.ts
1
+ import { NotificationUpdateType, isBuiltInOperationId } from "itd-api";
2
+ import { LRUCache } from "lru-cache";
3
+ //#region src/errors.ts
4
+ /** Ошибка настройки или использования плагина кэша. */
4
5
  var CacheError = class extends Error {
5
- name = "CacheError";
6
+ name = "CacheError";
6
7
  };
7
-
8
- // src/key.ts
9
- var OMITTED_FIELDS = /* @__PURE__ */ new Set([
10
- "method",
11
- "path",
12
- "service",
13
- "baseUrl",
14
- "query",
15
- "body",
16
- "headers",
17
- "raw",
18
- "skipAuth",
19
- "signal",
20
- "timeout",
21
- "retry",
22
- "skipQueue",
23
- "skipAuthRefresh",
24
- "cache"
8
+ //#endregion
9
+ //#region src/key.ts
10
+ const OMITTED_FIELDS = /* @__PURE__ */ new Set([
11
+ "method",
12
+ "operationId",
13
+ "path",
14
+ "service",
15
+ "baseUrl",
16
+ "query",
17
+ "body",
18
+ "headers",
19
+ "raw",
20
+ "skipAuth",
21
+ "signal",
22
+ "timeout",
23
+ "retry",
24
+ "retrySafety",
25
+ "skipQueue",
26
+ "skipAuthRefresh",
27
+ "extensions"
25
28
  ]);
29
+ /** Строка query в том же порядке и с теми же правилами, что использует itd-api. */
26
30
  function queryKey(query) {
27
- if (!query) return "";
28
- const search = new URLSearchParams();
29
- for (const [key, value] of Object.entries(query)) {
30
- if (value === void 0 || value === null) continue;
31
- if (Array.isArray(value)) {
32
- for (const item of value) search.append(key, String(item));
33
- } else {
34
- search.append(key, String(value));
35
- }
36
- }
37
- return search.toString();
31
+ if (!query) return "";
32
+ const search = new URLSearchParams();
33
+ for (const [key, value] of Object.entries(query)) {
34
+ if (value === void 0 || value === null) continue;
35
+ if (Array.isArray(value)) for (const item of value) search.append(key, String(item));
36
+ else search.append(key, String(value));
37
+ }
38
+ return search.toString();
38
39
  }
39
- function buildCacheKey(route, request) {
40
- const extras = {};
41
- for (const [key, value] of Object.entries(request)) {
42
- if (!OMITTED_FIELDS.has(key) && value !== void 0) extras[key] = value;
43
- }
44
- try {
45
- return JSON.stringify({
46
- route,
47
- method: request.method.toUpperCase(),
48
- service: request.service ?? null,
49
- baseUrl: request.baseUrl ?? null,
50
- path: request.path,
51
- query: queryKey(request.query),
52
- body: request.body ?? null,
53
- raw: request.raw ?? false,
54
- skipAuth: request.skipAuth ?? null,
55
- extras
56
- });
57
- } catch {
58
- return void 0;
59
- }
40
+ /**
41
+ * Собирает ключ из значений, влияющих на адрес, тело или разобранный ответ.
42
+ *
43
+ * Заголовки и транспортные опции намеренно не входят. Если тело либо опция другого
44
+ * плагина не сериализуются как JSON, запрос выполняется без кэша.
45
+ */
46
+ function buildCacheKey(operation, request) {
47
+ const extras = {};
48
+ for (const [key, value] of Object.entries(request)) if (!OMITTED_FIELDS.has(key) && value !== void 0) extras[key] = value;
49
+ const { cache: _cacheMode, ...extensions } = request.extensions ?? {};
50
+ if (Object.keys(extensions).length > 0) extras.extensions = extensions;
51
+ try {
52
+ return JSON.stringify({
53
+ operation,
54
+ method: request.method.toUpperCase(),
55
+ service: request.service ?? null,
56
+ baseUrl: request.baseUrl ?? null,
57
+ path: request.path,
58
+ query: queryKey(request.query),
59
+ body: request.body ?? null,
60
+ raw: request.raw ?? false,
61
+ skipAuth: request.skipAuth ?? null,
62
+ extras
63
+ });
64
+ } catch {
65
+ return;
66
+ }
60
67
  }
61
-
62
- // src/mutations.ts
63
- var POST_CONTENT = [
64
- "posts.list",
65
- "posts.get",
66
- "posts.byUser",
67
- "posts.likedByUser",
68
- "posts.comments",
69
- "posts.stats",
70
- "comments.replies",
71
- "hashtags.search",
72
- "hashtags.trending",
73
- "hashtags.posts",
74
- "search.all",
75
- "users.me",
76
- "users.get",
77
- "users.pins"
78
- ];
79
- var POST_REACTIONS = [
80
- "posts.list",
81
- "posts.get",
82
- "posts.byUser",
83
- "posts.likedByUser",
84
- "posts.stats",
85
- "hashtags.posts",
86
- "search.all"
87
- ];
88
- var COMMENTS = [
89
- "posts.list",
90
- "posts.get",
91
- "posts.comments",
92
- "posts.stats",
93
- "comments.replies",
94
- "hashtags.posts",
95
- "search.all"
68
+ //#endregion
69
+ //#region src/operations.ts
70
+ function freezeOperations(operations) {
71
+ for (const operation of operations) Object.freeze(operation);
72
+ return Object.freeze(operations);
73
+ }
74
+ /** Читающие операции, которые можно кэшировать. */
75
+ const CACHE_OPERATIONS = freezeOperations([
76
+ {
77
+ id: "auth.sessions",
78
+ category: "auth"
79
+ },
80
+ {
81
+ id: "users.me",
82
+ category: "users"
83
+ },
84
+ {
85
+ id: "users.checkUsername",
86
+ category: "users"
87
+ },
88
+ {
89
+ id: "users.search",
90
+ category: "users"
91
+ },
92
+ {
93
+ id: "users.whoToFollow",
94
+ category: "users"
95
+ },
96
+ {
97
+ id: "users.topClans",
98
+ category: "users"
99
+ },
100
+ {
101
+ id: "users.followers",
102
+ category: "users"
103
+ },
104
+ {
105
+ id: "users.following",
106
+ category: "users"
107
+ },
108
+ {
109
+ id: "users.blocked",
110
+ category: "users"
111
+ },
112
+ {
113
+ id: "users.getPrivacy",
114
+ category: "users"
115
+ },
116
+ {
117
+ id: "users.pins",
118
+ category: "users"
119
+ },
120
+ {
121
+ id: "users.followStatus",
122
+ category: "users"
123
+ },
124
+ {
125
+ id: "users.get",
126
+ category: "users"
127
+ },
128
+ {
129
+ id: "posts.list",
130
+ category: "posts"
131
+ },
132
+ {
133
+ id: "posts.likedByUser",
134
+ category: "posts"
135
+ },
136
+ {
137
+ id: "posts.byUser",
138
+ category: "posts"
139
+ },
140
+ {
141
+ id: "posts.comments",
142
+ category: "posts"
143
+ },
144
+ {
145
+ id: "posts.stats",
146
+ category: "posts"
147
+ },
148
+ {
149
+ id: "posts.get",
150
+ category: "posts"
151
+ },
152
+ {
153
+ id: "comments.replies",
154
+ category: "comments"
155
+ },
156
+ {
157
+ id: "notifications.list",
158
+ category: "notifications"
159
+ },
160
+ {
161
+ id: "notifications.count",
162
+ category: "notifications"
163
+ },
164
+ {
165
+ id: "notifications.getSettings",
166
+ category: "notifications"
167
+ },
168
+ {
169
+ id: "hashtags.search",
170
+ category: "hashtags"
171
+ },
172
+ {
173
+ id: "hashtags.trending",
174
+ category: "hashtags"
175
+ },
176
+ {
177
+ id: "hashtags.posts",
178
+ category: "hashtags"
179
+ },
180
+ {
181
+ id: "search.all",
182
+ category: "search"
183
+ },
184
+ {
185
+ id: "files.get",
186
+ category: "files"
187
+ },
188
+ {
189
+ id: "subscription.status",
190
+ category: "subscription"
191
+ },
192
+ {
193
+ id: "subscription.methods",
194
+ category: "subscription"
195
+ },
196
+ {
197
+ id: "verification.status",
198
+ category: "verification"
199
+ },
200
+ {
201
+ id: "platform.changelog",
202
+ category: "platform"
203
+ },
204
+ {
205
+ id: "platform.announcements",
206
+ category: "platform"
207
+ },
208
+ {
209
+ id: "platform.portal",
210
+ category: "platform"
211
+ },
212
+ {
213
+ id: "status.get",
214
+ category: "platform"
215
+ }
216
+ ]);
217
+ const OPERATIONS = new Map(CACHE_OPERATIONS.map((operation) => [operation.id, operation]));
218
+ /** Проверяет публичное имя кэшируемой операции. */
219
+ function isCacheOperationId(value) {
220
+ return OPERATIONS.has(value);
221
+ }
222
+ /** Находит читающую операцию по стабильному семантическому ID. */
223
+ function cacheOperation(operationId) {
224
+ return OPERATIONS.get(operationId);
225
+ }
226
+ //#endregion
227
+ //#region src/policy.ts
228
+ /** Виды политики кэша, объявляемой в метаданных операции. */
229
+ const CachePolicyKind = Object.freeze({
230
+ Query: "query",
231
+ Mutation: "mutation"
232
+ });
233
+ /** Области изоляции данных кэша. */
234
+ const CachePolicyScope = Object.freeze({
235
+ Account: "account",
236
+ Session: "session"
237
+ });
238
+ /** Способы инвалидации кэша после мутации. */
239
+ const CacheInvalidation = Object.freeze({ All: "all" });
240
+ //#endregion
241
+ //#region src/mutations.ts
242
+ const POST_CONTENT = [
243
+ "posts.list",
244
+ "posts.get",
245
+ "posts.byUser",
246
+ "posts.likedByUser",
247
+ "posts.comments",
248
+ "posts.stats",
249
+ "comments.replies",
250
+ "hashtags.search",
251
+ "hashtags.trending",
252
+ "hashtags.posts",
253
+ "search.all",
254
+ "users.me",
255
+ "users.get",
256
+ "users.pins"
96
257
  ];
97
- var PROFILE = [
98
- "users.me",
99
- "users.get",
100
- "users.checkUsername",
101
- "users.search",
102
- "users.whoToFollow",
103
- "users.topClans",
104
- "users.followers",
105
- "users.following",
106
- "users.blocked",
107
- "users.getPrivacy",
108
- "users.pins",
109
- "users.followStatus",
110
- "posts.list",
111
- "posts.get",
112
- "posts.byUser",
113
- "posts.likedByUser",
114
- "posts.comments",
115
- "comments.replies",
116
- "hashtags.posts",
117
- "search.all"
258
+ const POST_REACTIONS = [
259
+ "posts.list",
260
+ "posts.get",
261
+ "posts.byUser",
262
+ "posts.likedByUser",
263
+ "posts.stats",
264
+ "hashtags.posts",
265
+ "search.all"
118
266
  ];
119
- var FOLLOWING = [
120
- "users.me",
121
- "users.get",
122
- "users.search",
123
- "users.whoToFollow",
124
- "users.followers",
125
- "users.following",
126
- "users.followStatus",
127
- "posts.list",
128
- "posts.byUser",
129
- "search.all"
267
+ const COMMENTS = [
268
+ "posts.list",
269
+ "posts.get",
270
+ "posts.comments",
271
+ "posts.stats",
272
+ "comments.replies",
273
+ "hashtags.posts",
274
+ "search.all"
130
275
  ];
131
- var BLOCKS = [
132
- "users.me",
133
- "users.get",
134
- "users.search",
135
- "users.whoToFollow",
136
- "users.followers",
137
- "users.following",
138
- "users.blocked",
139
- "users.followStatus",
140
- "posts.list",
141
- "search.all"
276
+ const PROFILE = [
277
+ "users.me",
278
+ "users.get",
279
+ "users.checkUsername",
280
+ "users.search",
281
+ "users.whoToFollow",
282
+ "users.topClans",
283
+ "users.followers",
284
+ "users.following",
285
+ "users.blocked",
286
+ "users.getPrivacy",
287
+ "users.pins",
288
+ "users.followStatus",
289
+ "posts.list",
290
+ "posts.get",
291
+ "posts.byUser",
292
+ "posts.likedByUser",
293
+ "posts.comments",
294
+ "comments.replies",
295
+ "hashtags.posts",
296
+ "search.all"
142
297
  ];
143
- var PINS = [
144
- "users.me",
145
- "users.get",
146
- "users.pins",
147
- "posts.list",
148
- "posts.get",
149
- "posts.byUser"
298
+ const FOLLOWING = [
299
+ "users.me",
300
+ "users.get",
301
+ "users.search",
302
+ "users.whoToFollow",
303
+ "users.followers",
304
+ "users.following",
305
+ "users.followStatus",
306
+ "posts.list",
307
+ "posts.byUser",
308
+ "search.all"
150
309
  ];
151
- var NOTIFICATIONS = [
152
- "notifications.list",
153
- "notifications.count"
310
+ const BLOCKS = [
311
+ "users.me",
312
+ "users.get",
313
+ "users.search",
314
+ "users.whoToFollow",
315
+ "users.followers",
316
+ "users.following",
317
+ "users.blocked",
318
+ "users.followStatus",
319
+ "posts.list",
320
+ "search.all"
154
321
  ];
155
- var SUBSCRIPTION = [
156
- "subscription.status",
157
- "subscription.methods"
322
+ const PINS = [
323
+ "users.me",
324
+ "users.get",
325
+ "users.pins",
326
+ "posts.list",
327
+ "posts.get",
328
+ "posts.byUser"
158
329
  ];
159
- var NOTHING = [];
160
- var CACHE_MUTATIONS = Object.freeze([
161
- // Авторизация и сессии.
162
- { method: "POST", path: /^\/api\/v1\/auth\/refresh$/, invalidates: NOTHING },
163
- { method: "POST", path: /^\/api\/v1\/auth\/resend-otp$/, invalidates: NOTHING },
164
- { method: "POST", path: /^\/api\/v1\/auth\/forgot-password$/, invalidates: NOTHING },
165
- { method: "POST", path: /^\/api\/v1\/auth\/sign-up$/, invalidates: "all" },
166
- { method: "POST", path: /^\/api\/v1\/auth\/sign-in$/, invalidates: "all" },
167
- { method: "POST", path: /^\/api\/v1\/auth\/verify-otp$/, invalidates: "all" },
168
- { method: "POST", path: /^\/api\/v1\/auth\/logout$/, invalidates: "all" },
169
- { method: "POST", path: /^\/api\/v1\/auth\/reset-password$/, invalidates: "all" },
170
- { method: "POST", path: /^\/api\/v1\/auth\/change-password$/, invalidates: "all" },
171
- {
172
- method: "DELETE",
173
- path: /^\/api\/v1\/auth\/sessions(?:\/[^/]+)?$/,
174
- invalidates: ["auth.sessions"],
175
- scope: "account"
176
- },
177
- // Посты и комментарии.
178
- { method: "POST", path: /^\/api\/posts$/, invalidates: POST_CONTENT },
179
- { method: "PUT", path: /^\/api\/posts\/[^/]+$/, invalidates: POST_CONTENT },
180
- { method: "DELETE", path: /^\/api\/posts\/[^/]+$/, invalidates: POST_CONTENT },
181
- { method: "POST", path: /^\/api\/posts\/[^/]+\/restore$/, invalidates: POST_CONTENT },
182
- { method: "POST", path: /^\/api\/posts\/[^/]+\/like$/, invalidates: POST_REACTIONS },
183
- { method: "DELETE", path: /^\/api\/posts\/[^/]+\/like$/, invalidates: POST_REACTIONS },
184
- { method: "POST", path: /^\/api\/posts\/[^/]+\/repost$/, invalidates: POST_CONTENT },
185
- { method: "DELETE", path: /^\/api\/posts\/[^/]+\/repost$/, invalidates: POST_CONTENT },
186
- { method: "POST", path: /^\/api\/posts\/[^/]+\/pin$/, invalidates: PINS },
187
- { method: "DELETE", path: /^\/api\/posts\/[^/]+\/pin$/, invalidates: PINS },
188
- { method: "POST", path: /^\/api\/posts\/[^/]+\/poll\/vote$/, invalidates: POST_REACTIONS },
189
- { method: "POST", path: /^\/api\/posts\/[^/]+\/comments$/, invalidates: COMMENTS },
190
- { method: "POST", path: /^\/api\/comments\/[^/]+\/replies$/, invalidates: COMMENTS },
191
- { method: "PATCH", path: /^\/api\/comments\/[^/]+$/, invalidates: COMMENTS },
192
- { method: "DELETE", path: /^\/api\/comments\/[^/]+$/, invalidates: COMMENTS },
193
- { method: "POST", path: /^\/api\/comments\/[^/]+\/restore$/, invalidates: COMMENTS },
194
- { method: "POST", path: /^\/api\/comments\/[^/]+\/like$/, invalidates: COMMENTS },
195
- { method: "DELETE", path: /^\/api\/comments\/[^/]+\/like$/, invalidates: COMMENTS },
196
- // Профиль и связи между пользователями.
197
- { method: "PUT", path: /^\/api\/users\/me$/, invalidates: PROFILE },
198
- { method: "DELETE", path: /^\/api\/users\/me$/, invalidates: PROFILE },
199
- { method: "POST", path: /^\/api\/users\/me\/restore$/, invalidates: PROFILE },
200
- { method: "POST", path: /^\/api\/users\/profile$/, invalidates: PROFILE },
201
- { method: "POST", path: /^\/api\/users\/[^/]+\/follow$/, invalidates: FOLLOWING },
202
- { method: "DELETE", path: /^\/api\/users\/[^/]+\/follow$/, invalidates: FOLLOWING },
203
- { method: "POST", path: /^\/api\/users\/[^/]+\/block$/, invalidates: BLOCKS },
204
- { method: "DELETE", path: /^\/api\/users\/[^/]+\/block$/, invalidates: BLOCKS },
205
- {
206
- method: "PUT",
207
- path: /^\/api\/users\/me\/privacy$/,
208
- invalidates: ["users.me", "users.get", "users.getPrivacy"]
209
- },
210
- { method: "PUT", path: /^\/api\/users\/me\/pin$/, invalidates: PINS },
211
- { method: "DELETE", path: /^\/api\/users\/me\/pin$/, invalidates: PINS },
212
- // Уведомления.
213
- {
214
- method: "POST",
215
- path: /^\/api\/notifications\/(?:[^/]+\/read|read-batch|read-all)$/,
216
- invalidates: NOTIFICATIONS,
217
- scope: "account"
218
- },
219
- {
220
- method: "PUT",
221
- path: /^\/api\/notifications\/settings$/,
222
- invalidates: ["notifications.getSettings"],
223
- scope: "account"
224
- },
225
- // Файлы и настройки аккаунта.
226
- { method: "POST", path: /^\/api\/files\/upload$/, invalidates: NOTHING },
227
- {
228
- method: "DELETE",
229
- path: /^\/api\/files\/[^/]+$/,
230
- invalidates: ["files.get", ...POST_CONTENT]
231
- },
232
- {
233
- method: "POST",
234
- path: /^\/api\/verification\/submit$/,
235
- invalidates: ["verification.status"],
236
- scope: "account"
237
- },
238
- {
239
- method: "POST",
240
- path: /^\/api\/v1\/subscription\/pay$/,
241
- invalidates: SUBSCRIPTION,
242
- scope: "account"
243
- },
244
- {
245
- method: "POST",
246
- path: /^\/api\/v1\/subscription\/auto-renewal$/,
247
- invalidates: SUBSCRIPTION,
248
- scope: "account"
249
- },
250
- {
251
- method: "POST",
252
- path: /^\/api\/v1\/subscription\/bind-card$/,
253
- invalidates: SUBSCRIPTION,
254
- scope: "account"
255
- },
256
- {
257
- method: "POST",
258
- path: /^\/api\/v1\/subscription\/methods\/[^/]+\/default$/,
259
- invalidates: SUBSCRIPTION,
260
- scope: "account"
261
- },
262
- {
263
- method: "DELETE",
264
- path: /^\/api\/v1\/subscription\/methods\/[^/]+$/,
265
- invalidates: SUBSCRIPTION,
266
- scope: "account"
267
- },
268
- // Эти запросы не меняют ни один доступный для кэширования ответ.
269
- { method: "POST", path: /^\/api\/reports$/, invalidates: NOTHING },
270
- { method: "POST", path: /^\/api\/v1\/[ix]$/, invalidates: NOTHING }
330
+ const NOTIFICATIONS = ["notifications.list", "notifications.count"];
331
+ const SUBSCRIPTION = ["subscription.status", "subscription.methods"];
332
+ const NOTHING = [];
333
+ /**
334
+ * Известные изменяющие запросы и читающие операции, чьи ответы они могут изменить.
335
+ *
336
+ * Каталог намеренно консервативен: лучше удалить несколько связанных списков, чем оставить
337
+ * персонализированное поле или вложенный объект устаревшим.
338
+ */
339
+ const CACHE_MUTATIONS = Object.freeze([
340
+ {
341
+ operationId: "auth.refresh",
342
+ invalidates: NOTHING
343
+ },
344
+ {
345
+ operationId: "auth.resendOtp",
346
+ invalidates: NOTHING
347
+ },
348
+ {
349
+ operationId: "auth.forgotPassword",
350
+ invalidates: NOTHING
351
+ },
352
+ {
353
+ operationId: "auth.signUp",
354
+ invalidates: CacheInvalidation.All
355
+ },
356
+ {
357
+ operationId: "auth.signIn",
358
+ invalidates: CacheInvalidation.All
359
+ },
360
+ {
361
+ operationId: "auth.verifyOtp",
362
+ invalidates: CacheInvalidation.All
363
+ },
364
+ {
365
+ operationId: "auth.logout",
366
+ invalidates: CacheInvalidation.All
367
+ },
368
+ {
369
+ operationId: "auth.resetPassword",
370
+ invalidates: CacheInvalidation.All
371
+ },
372
+ {
373
+ operationId: "auth.changePassword",
374
+ invalidates: CacheInvalidation.All
375
+ },
376
+ {
377
+ operationId: "auth.revokeSession",
378
+ invalidates: ["auth.sessions"],
379
+ scope: CachePolicyScope.Account
380
+ },
381
+ {
382
+ operationId: "auth.revokeOtherSessions",
383
+ invalidates: ["auth.sessions"],
384
+ scope: CachePolicyScope.Account
385
+ },
386
+ {
387
+ operationId: "posts.create",
388
+ invalidates: POST_CONTENT
389
+ },
390
+ {
391
+ operationId: "posts.update",
392
+ invalidates: POST_CONTENT
393
+ },
394
+ {
395
+ operationId: "posts.remove",
396
+ invalidates: POST_CONTENT
397
+ },
398
+ {
399
+ operationId: "posts.restore",
400
+ invalidates: POST_CONTENT
401
+ },
402
+ {
403
+ operationId: "posts.like",
404
+ invalidates: POST_REACTIONS
405
+ },
406
+ {
407
+ operationId: "posts.unlike",
408
+ invalidates: POST_REACTIONS
409
+ },
410
+ {
411
+ operationId: "posts.repost",
412
+ invalidates: POST_CONTENT
413
+ },
414
+ {
415
+ operationId: "posts.unrepost",
416
+ invalidates: POST_CONTENT
417
+ },
418
+ {
419
+ operationId: "posts.pin",
420
+ invalidates: PINS
421
+ },
422
+ {
423
+ operationId: "posts.unpin",
424
+ invalidates: PINS
425
+ },
426
+ {
427
+ operationId: "posts.vote",
428
+ invalidates: POST_REACTIONS
429
+ },
430
+ {
431
+ operationId: "posts.comment",
432
+ invalidates: COMMENTS
433
+ },
434
+ {
435
+ operationId: "comments.reply",
436
+ invalidates: COMMENTS
437
+ },
438
+ {
439
+ operationId: "comments.update",
440
+ invalidates: COMMENTS
441
+ },
442
+ {
443
+ operationId: "comments.remove",
444
+ invalidates: COMMENTS
445
+ },
446
+ {
447
+ operationId: "comments.restore",
448
+ invalidates: COMMENTS
449
+ },
450
+ {
451
+ operationId: "comments.like",
452
+ invalidates: COMMENTS
453
+ },
454
+ {
455
+ operationId: "comments.unlike",
456
+ invalidates: COMMENTS
457
+ },
458
+ {
459
+ operationId: "users.updateMe",
460
+ invalidates: PROFILE
461
+ },
462
+ {
463
+ operationId: "users.deactivate",
464
+ invalidates: PROFILE
465
+ },
466
+ {
467
+ operationId: "users.restore",
468
+ invalidates: PROFILE
469
+ },
470
+ {
471
+ operationId: "users.createProfile",
472
+ invalidates: PROFILE
473
+ },
474
+ {
475
+ operationId: "users.follow",
476
+ invalidates: FOLLOWING
477
+ },
478
+ {
479
+ operationId: "users.unfollow",
480
+ invalidates: FOLLOWING
481
+ },
482
+ {
483
+ operationId: "users.block",
484
+ invalidates: BLOCKS
485
+ },
486
+ {
487
+ operationId: "users.unblock",
488
+ invalidates: BLOCKS
489
+ },
490
+ {
491
+ operationId: "users.updatePrivacy",
492
+ invalidates: [
493
+ "users.me",
494
+ "users.get",
495
+ "users.getPrivacy"
496
+ ]
497
+ },
498
+ {
499
+ operationId: "users.setPin",
500
+ invalidates: PINS
501
+ },
502
+ {
503
+ operationId: "users.removePin",
504
+ invalidates: PINS
505
+ },
506
+ {
507
+ operationId: "notifications.markRead",
508
+ invalidates: NOTIFICATIONS,
509
+ scope: CachePolicyScope.Account
510
+ },
511
+ {
512
+ operationId: "notifications.markReadBatch",
513
+ invalidates: NOTIFICATIONS,
514
+ scope: CachePolicyScope.Account
515
+ },
516
+ {
517
+ operationId: "notifications.markAllRead",
518
+ invalidates: NOTIFICATIONS,
519
+ scope: CachePolicyScope.Account
520
+ },
521
+ {
522
+ operationId: "notifications.updateSettings",
523
+ invalidates: ["notifications.getSettings"],
524
+ scope: CachePolicyScope.Account
525
+ },
526
+ {
527
+ operationId: "files.upload",
528
+ invalidates: NOTHING
529
+ },
530
+ {
531
+ operationId: "files.remove",
532
+ invalidates: ["files.get", ...POST_CONTENT]
533
+ },
534
+ {
535
+ operationId: "verification.submit",
536
+ invalidates: ["verification.status"],
537
+ scope: CachePolicyScope.Account
538
+ },
539
+ {
540
+ operationId: "subscription.pay",
541
+ invalidates: SUBSCRIPTION,
542
+ scope: CachePolicyScope.Account
543
+ },
544
+ {
545
+ operationId: "subscription.setAutoRenewal",
546
+ invalidates: SUBSCRIPTION,
547
+ scope: CachePolicyScope.Account
548
+ },
549
+ {
550
+ operationId: "subscription.bindCard",
551
+ invalidates: SUBSCRIPTION,
552
+ scope: CachePolicyScope.Account
553
+ },
554
+ {
555
+ operationId: "subscription.setDefaultMethod",
556
+ invalidates: SUBSCRIPTION,
557
+ scope: CachePolicyScope.Account
558
+ },
559
+ {
560
+ operationId: "subscription.removeMethod",
561
+ invalidates: SUBSCRIPTION,
562
+ scope: CachePolicyScope.Account
563
+ },
564
+ {
565
+ operationId: "reports.create",
566
+ invalidates: NOTHING
567
+ },
568
+ {
569
+ operationId: "telemetry.dwell",
570
+ invalidates: NOTHING
571
+ },
572
+ {
573
+ operationId: "telemetry.interaction",
574
+ invalidates: NOTHING
575
+ }
271
576
  ]);
272
- function cacheMutation(method, path) {
273
- const normalized = method.toUpperCase();
274
- return CACHE_MUTATIONS.find(
275
- (mutation) => mutation.method === normalized && mutation.path.test(path)
276
- );
577
+ for (const mutation of CACHE_MUTATIONS) {
578
+ Object.freeze(mutation.invalidates);
579
+ Object.freeze(mutation);
277
580
  }
278
-
279
- // src/routes.ts
280
- var CACHE_ROUTES = Object.freeze([
281
- { id: "auth.sessions", category: "auth", method: "GET", path: /^\/api\/v1\/auth\/sessions$/ },
282
- { id: "users.me", category: "users", method: "GET", path: /^\/api\/users\/me$/ },
283
- {
284
- id: "users.checkUsername",
285
- category: "users",
286
- method: "GET",
287
- path: /^\/api\/users\/check-username$/
288
- },
289
- { id: "users.search", category: "users", method: "GET", path: /^\/api\/users\/search$/ },
290
- {
291
- id: "users.whoToFollow",
292
- category: "users",
293
- method: "GET",
294
- path: /^\/api\/users\/suggestions\/who-to-follow$/
295
- },
296
- {
297
- id: "users.topClans",
298
- category: "users",
299
- method: "GET",
300
- path: /^\/api\/users\/stats\/top-clans$/
301
- },
302
- {
303
- id: "users.followers",
304
- category: "users",
305
- method: "GET",
306
- path: /^\/api\/users\/[^/]+\/followers$/
307
- },
308
- {
309
- id: "users.following",
310
- category: "users",
311
- method: "GET",
312
- path: /^\/api\/users\/[^/]+\/following$/
313
- },
314
- {
315
- id: "users.blocked",
316
- category: "users",
317
- method: "GET",
318
- path: /^\/api\/users\/me\/blocked$/
319
- },
320
- {
321
- id: "users.getPrivacy",
322
- category: "users",
323
- method: "GET",
324
- path: /^\/api\/users\/me\/privacy$/
325
- },
326
- { id: "users.pins", category: "users", method: "GET", path: /^\/api\/users\/me\/pins$/ },
327
- {
328
- id: "users.followStatus",
329
- category: "users",
330
- method: "POST",
331
- path: /^\/api\/users\/follow-status$/
332
- },
333
- { id: "users.get", category: "users", method: "GET", path: /^\/api\/users\/[^/]+$/ },
334
- { id: "posts.list", category: "posts", method: "GET", path: /^\/api\/posts$/ },
335
- {
336
- id: "posts.likedByUser",
337
- category: "posts",
338
- method: "GET",
339
- path: /^\/api\/posts\/user\/[^/]+\/liked$/
340
- },
341
- {
342
- id: "posts.byUser",
343
- category: "posts",
344
- method: "GET",
345
- path: /^\/api\/posts\/user\/[^/]+$/
346
- },
347
- {
348
- id: "posts.comments",
349
- category: "posts",
350
- method: "GET",
351
- path: /^\/api\/posts\/[^/]+\/comments$/
352
- },
353
- { id: "posts.stats", category: "posts", method: "POST", path: /^\/api\/posts\/stats$/ },
354
- { id: "posts.get", category: "posts", method: "GET", path: /^\/api\/posts\/[^/]+$/ },
355
- {
356
- id: "comments.replies",
357
- category: "comments",
358
- method: "GET",
359
- path: /^\/api\/comments\/[^/]+\/replies$/
360
- },
361
- {
362
- id: "notifications.list",
363
- category: "notifications",
364
- method: "GET",
365
- path: /^\/api\/notifications\/$/
366
- },
367
- {
368
- id: "notifications.count",
369
- category: "notifications",
370
- method: "GET",
371
- path: /^\/api\/notifications\/count$/
372
- },
373
- {
374
- id: "notifications.getSettings",
375
- category: "notifications",
376
- method: "GET",
377
- path: /^\/api\/notifications\/settings$/
378
- },
379
- {
380
- id: "hashtags.search",
381
- category: "hashtags",
382
- method: "GET",
383
- path: /^\/api\/hashtags$/
384
- },
385
- {
386
- id: "hashtags.trending",
387
- category: "hashtags",
388
- method: "GET",
389
- path: /^\/api\/hashtags\/trending$/
390
- },
391
- {
392
- id: "hashtags.posts",
393
- category: "hashtags",
394
- method: "GET",
395
- path: /^\/api\/hashtags\/[^/]+\/posts$/
396
- },
397
- { id: "search.all", category: "search", method: "GET", path: /^\/api\/search$/ },
398
- { id: "files.get", category: "files", method: "GET", path: /^\/api\/files\/[^/]+$/ },
399
- {
400
- id: "subscription.status",
401
- category: "subscription",
402
- method: "GET",
403
- path: /^\/api\/v1\/subscription\/$/
404
- },
405
- {
406
- id: "subscription.methods",
407
- category: "subscription",
408
- method: "GET",
409
- path: /^\/api\/v1\/subscription\/methods$/
410
- },
411
- {
412
- id: "verification.status",
413
- category: "verification",
414
- method: "GET",
415
- path: /^\/api\/verification\/status$/
416
- },
417
- {
418
- id: "platform.changelog",
419
- category: "platform",
420
- method: "GET",
421
- path: /^\/api\/platform\/changelog$/
422
- },
423
- {
424
- id: "platform.announcements",
425
- category: "platform",
426
- method: "GET",
427
- path: /^\/api\/platform\/announcements$/
428
- },
429
- { id: "platform.portal", category: "platform", method: "GET", path: /^\/api\/v1\/portal$/ },
430
- { id: "platform.status", category: "platform", method: "GET", path: /^\/api\/status$/ }
431
- ]);
432
- var ROUTE_IDS = new Set(CACHE_ROUTES.map((route) => route.id));
433
- function isCacheRouteId(value) {
434
- return ROUTE_IDS.has(value);
435
- }
436
- function cacheRoute(method, path) {
437
- const normalized = method.toUpperCase();
438
- return CACHE_ROUTES.find((route) => route.method === normalized && route.path.test(path));
581
+ const MUTATIONS = new Map(CACHE_MUTATIONS.map((mutation) => [mutation.operationId, mutation]));
582
+ /** Находит известную мутацию по стабильному семантическому ID. */
583
+ function cacheMutation(operationId) {
584
+ return MUTATIONS.get(operationId);
439
585
  }
440
-
441
- // src/plugin.ts
442
- var CacheModes = Object.freeze({
443
- /** Отдать свежий кэш, иначе выполнить запрос и сохранить ответ. */
444
- Default: "default",
445
- /** Пропустить сохранённое значение, выполнить запрос и перезаписать кэш. */
446
- Reload: "reload",
447
- /** Не читать и не писать кэш для этого запроса. */
448
- NoStore: "no-store"
586
+ //#endregion
587
+ //#region src/plugin.ts
588
+ /** Режимы кэширования отдельного запроса. */
589
+ const CacheModes = Object.freeze({
590
+ /** Отдать свежий кэш, иначе выполнить запрос и сохранить ответ. */
591
+ Default: "default",
592
+ /** Пропустить сохранённое значение, выполнить запрос и перезаписать кэш. */
593
+ Reload: "reload",
594
+ /** Не читать и не писать кэш для этого запроса. */
595
+ NoStore: "no-store"
449
596
  });
450
- var DEFAULT_MAX_ENTRIES = 500;
451
- var CACHE_MODES = new Set(Object.values(CacheModes));
597
+ const DEFAULT_MAX_ENTRIES = 500;
598
+ const CACHE_MODES = new Set(Object.values(CacheModes));
452
599
  function assertPositive(value, name, integer = false) {
453
- if (!Number.isFinite(value) || value <= 0 || integer && !Number.isInteger(value)) {
454
- throw new CacheError(
455
- `${name} \u0434\u043E\u043B\u0436\u0435\u043D \u0431\u044B\u0442\u044C ${integer ? "\u0446\u0435\u043B\u044B\u043C " : ""}\u043F\u043E\u043B\u043E\u0436\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u043C \u0447\u0438\u0441\u043B\u043E\u043C, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E: ${value}`
456
- );
457
- }
600
+ if (!Number.isFinite(value) || value <= 0 || integer && !Number.isInteger(value)) throw new CacheError(`${name} должен быть ${integer ? "целым " : ""}положительным числом, получено: ${value}`);
458
601
  }
459
602
  function resolveOptions(options) {
460
- if (!options || typeof options !== "object") {
461
- throw new CacheError("cache() \u043F\u0440\u0438\u043D\u0438\u043C\u0430\u0435\u0442 \u043E\u0431\u044A\u0435\u043A\u0442 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043A");
462
- }
463
- assertPositive(options.ttl, "cache.ttl");
464
- if (!Array.isArray(options.routes) || options.routes.length === 0) {
465
- throw new CacheError("cache.routes \u0434\u043E\u043B\u0436\u0435\u043D \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C \u0445\u043E\u0442\u044F \u0431\u044B \u043E\u0434\u0438\u043D \u043C\u0430\u0440\u0448\u0440\u0443\u0442");
466
- }
467
- const routes = /* @__PURE__ */ new Set();
468
- for (const route of options.routes) {
469
- if (typeof route !== "string" || !isCacheRouteId(route)) {
470
- throw new CacheError(`\u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u043C\u0430\u0440\u0448\u0440\u0443\u0442 \u043A\u044D\u0448\u0430: ${JSON.stringify(route)}`);
471
- }
472
- routes.add(route);
473
- }
474
- const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
475
- assertPositive(maxEntries, "cache.maxEntries", true);
476
- const deduplicate = options.deduplicate ?? true;
477
- if (typeof deduplicate !== "boolean") {
478
- throw new CacheError(`cache.deduplicate \u0434\u043E\u043B\u0436\u0435\u043D \u0431\u044B\u0442\u044C boolean, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E: ${deduplicate}`);
479
- }
480
- return { ttl: options.ttl, routes, maxEntries, deduplicate };
603
+ if (!options || typeof options !== "object") throw new CacheError("cache() принимает объект настроек");
604
+ assertPositive(options.ttl, "cache.ttl");
605
+ if (!Array.isArray(options.operations) || options.operations.length === 0) throw new CacheError("cache.operations должен содержать хотя бы одну операцию");
606
+ const operations = /* @__PURE__ */ new Set();
607
+ for (const operation of options.operations) {
608
+ if (typeof operation !== "string" || isBuiltInOperationId(operation) && !isCacheOperationId(operation)) throw new CacheError(`Неизвестная операция кэша: ${JSON.stringify(operation)}`);
609
+ operations.add(operation);
610
+ }
611
+ const maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
612
+ assertPositive(maxEntries, "cache.maxEntries", true);
613
+ const deduplicate = options.deduplicate ?? true;
614
+ if (typeof deduplicate !== "boolean") throw new CacheError(`cache.deduplicate должен быть boolean, получено: ${deduplicate}`);
615
+ return {
616
+ ttl: options.ttl,
617
+ operations,
618
+ maxEntries,
619
+ deduplicate
620
+ };
481
621
  }
482
622
  function cloneValue(value) {
483
- try {
484
- return { cacheable: true, value: structuredClone(value) };
485
- } catch {
486
- return { cacheable: false, value };
487
- }
623
+ try {
624
+ return {
625
+ cacheable: true,
626
+ value: structuredClone(value)
627
+ };
628
+ } catch {
629
+ return {
630
+ cacheable: false,
631
+ value
632
+ };
633
+ }
488
634
  }
489
635
  function cacheMode(request) {
490
- const mode = request.cache ?? CacheModes.Default;
491
- if (!CACHE_MODES.has(mode)) {
492
- throw new CacheError(
493
- `cache \u0434\u043E\u043B\u0436\u0435\u043D \u0431\u044B\u0442\u044C '${CacheModes.Default}', '${CacheModes.Reload}' \u0438\u043B\u0438 '${CacheModes.NoStore}', \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E: ${String(mode)}`
494
- );
495
- }
496
- return mode;
636
+ const mode = request.extensions?.cache ?? CacheModes.Default;
637
+ if (!CACHE_MODES.has(mode)) throw new CacheError(`cache должен быть '${CacheModes.Default}', '${CacheModes.Reload}' или '${CacheModes.NoStore}', получено: ${String(mode)}`);
638
+ return mode;
497
639
  }
640
+ /** Создаёт TTL/LRU-кэш нормализованных результатов itd-api. */
498
641
  function cache(options) {
499
- const config = resolveOptions(options);
500
- const values = new LRUCache({
501
- max: config.maxEntries,
502
- ttl: config.ttl,
503
- updateAgeOnGet: false,
504
- allowStale: false
505
- });
506
- const pending = /* @__PURE__ */ new Map();
507
- const routeGenerations = /* @__PURE__ */ new Map();
508
- const scopeGenerations = /* @__PURE__ */ new Map();
509
- const scopeRouteGenerations = /* @__PURE__ */ new Map();
510
- const keyStates = /* @__PURE__ */ new Map();
511
- let generation = 0;
512
- let installationSequence = 0;
513
- const scopeRouteKey = (accountScope, route) => JSON.stringify([accountScope, route]);
514
- const clear = () => {
515
- generation += 1;
516
- values.clear();
517
- pending.clear();
518
- };
519
- const invalidate = (...routes) => {
520
- if (routes.length === 0) return;
521
- const selected = /* @__PURE__ */ new Set();
522
- for (const route of routes) {
523
- if (!isCacheRouteId(route)) {
524
- throw new CacheError(`\u041D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u044B\u0439 \u043C\u0430\u0440\u0448\u0440\u0443\u0442 \u043A\u044D\u0448\u0430: ${JSON.stringify(route)}`);
525
- }
526
- selected.add(route);
527
- routeGenerations.set(route, (routeGenerations.get(route) ?? 0) + 1);
528
- }
529
- for (const [key, entry] of values.entries()) {
530
- if (selected.has(entry.route)) values.delete(key);
531
- }
532
- for (const [key, entry] of pending) {
533
- if (selected.has(entry.route)) pending.delete(key);
534
- }
535
- };
536
- const clearScope = (accountScope) => {
537
- scopeGenerations.set(accountScope, (scopeGenerations.get(accountScope) ?? 0) + 1);
538
- for (const [key, entry] of values.entries()) {
539
- if (entry.accountScope === accountScope) values.delete(key);
540
- }
541
- for (const [key, entry] of pending) {
542
- if (entry.accountScope === accountScope) pending.delete(key);
543
- }
544
- };
545
- const invalidateScope = (accountScope, routes) => {
546
- if (routes.length === 0) return;
547
- const selected = new Set(routes);
548
- for (const route of selected) {
549
- const key = scopeRouteKey(accountScope, route);
550
- scopeRouteGenerations.set(key, (scopeRouteGenerations.get(key) ?? 0) + 1);
551
- }
552
- for (const [key, entry] of values.entries()) {
553
- if (entry.accountScope === accountScope && selected.has(entry.route)) values.delete(key);
554
- }
555
- for (const [key, entry] of pending) {
556
- if (entry.accountScope === accountScope && selected.has(entry.route)) pending.delete(key);
557
- }
558
- };
559
- const applyMutation = (accountScope, mutation) => {
560
- if (mutation.invalidates === "all") {
561
- clearScope(accountScope);
562
- } else if (mutation.scope === "account") {
563
- invalidateScope(accountScope, mutation.invalidates);
564
- } else {
565
- invalidate(...mutation.invalidates);
566
- }
567
- };
568
- const createTransformer = (installation, baseUrl, getAuthIdentity, getAuthScope) => {
569
- const fallbackAuthScope = JSON.stringify([baseUrl, `installation:${installation}`]);
570
- const resolveIdentity = async () => {
571
- const identity = await getAuthIdentity?.();
572
- const accountScope = identity?.userId ? JSON.stringify([baseUrl, identity.userId]) : getAuthScope ? JSON.stringify([baseUrl, getAuthScope()]) : fallbackAuthScope;
573
- const sessionScope = identity?.userId && identity.sessionId ? JSON.stringify([baseUrl, identity.userId, identity.sessionId]) : JSON.stringify([
574
- accountScope,
575
- getAuthScope ? getAuthScope() : `installation:${installation}`
576
- ]);
577
- return { accountScope, sessionScope };
578
- };
579
- return async (rawRequest, next) => {
580
- const request = rawRequest;
581
- const route = cacheRoute(request.method, request.path);
582
- const method = request.method.toUpperCase();
583
- const isRead = route !== void 0 || method === "GET" || method === "HEAD";
584
- if (!isRead) {
585
- const mutation = cacheMutation(method, request.path);
586
- const startedIdentity = mutation ? await resolveIdentity() : void 0;
587
- const result = await next(request);
588
- if (mutation && startedIdentity) {
589
- applyMutation(startedIdentity.accountScope, mutation);
590
- const currentIdentity = await resolveIdentity();
591
- if (currentIdentity.accountScope !== startedIdentity.accountScope && (mutation.invalidates === "all" || mutation.scope === "account")) {
592
- applyMutation(currentIdentity.accountScope, mutation);
593
- }
594
- } else {
595
- clear();
596
- }
597
- return result;
598
- }
599
- if (!route || !config.routes.has(route.id)) return next(request);
600
- const mode = cacheMode(request);
601
- if (mode === CacheModes.NoStore) return next(request);
602
- const unscopedKey = buildCacheKey(route.id, request);
603
- if (unscopedKey === void 0) return next(request);
604
- const identity = await resolveIdentity();
605
- const scope = route.id === "auth.sessions" ? identity.sessionScope : identity.accountScope;
606
- const key = JSON.stringify([scope, unscopedKey]);
607
- if (mode === CacheModes.Reload) {
608
- const state = keyStates.get(key) ?? {
609
- active: 0,
610
- generation: 0
611
- };
612
- state.generation += 1;
613
- keyStates.set(key, state);
614
- values.delete(key);
615
- pending.delete(key);
616
- }
617
- if (mode === CacheModes.Default) {
618
- const hit = values.get(key);
619
- if (hit) {
620
- const cloned = cloneValue(hit.value);
621
- if (cloned.cacheable) return cloned.value;
622
- values.delete(key);
623
- }
624
- const existing = pending.get(key);
625
- if (config.deduplicate && request.signal === void 0 && request.timeout === void 0 && existing) {
626
- const loaded = await existing.promise;
627
- return cloneValue(loaded.value).value;
628
- }
629
- }
630
- const startedGeneration = generation;
631
- const startedScopeGeneration = scopeGenerations.get(identity.accountScope) ?? 0;
632
- const startedRouteGeneration = routeGenerations.get(route.id) ?? 0;
633
- const scopedRouteKey = scopeRouteKey(identity.accountScope, route.id);
634
- const startedScopeRouteGeneration = scopeRouteGenerations.get(scopedRouteKey) ?? 0;
635
- const keyState = keyStates.get(key) ?? {
636
- active: 0,
637
- generation: 0
638
- };
639
- keyState.active += 1;
640
- keyStates.set(key, keyState);
641
- const startedKeyGeneration = keyState.generation;
642
- const load = (async () => {
643
- try {
644
- const result = await next(request);
645
- const stored = cloneValue(result);
646
- const currentIdentity = await resolveIdentity();
647
- const currentScope = route.id === "auth.sessions" ? currentIdentity.sessionScope : currentIdentity.accountScope;
648
- if (stored.cacheable && currentScope === scope && generation === startedGeneration && (scopeGenerations.get(identity.accountScope) ?? 0) === startedScopeGeneration && (routeGenerations.get(route.id) ?? 0) === startedRouteGeneration && (scopeRouteGenerations.get(scopedRouteKey) ?? 0) === startedScopeRouteGeneration && keyState.generation === startedKeyGeneration) {
649
- values.set(key, {
650
- accountScope: identity.accountScope,
651
- route: route.id,
652
- value: stored.value
653
- });
654
- }
655
- return { cacheable: stored.cacheable, value: result };
656
- } finally {
657
- keyState.active -= 1;
658
- if (keyState.active === 0 && keyStates.get(key) === keyState) keyStates.delete(key);
659
- }
660
- })();
661
- const mayDeduplicate = mode === CacheModes.Default && config.deduplicate && request.signal === void 0 && request.timeout === void 0;
662
- const entry = {
663
- accountScope: identity.accountScope,
664
- route: route.id,
665
- promise: load
666
- };
667
- if (mayDeduplicate) pending.set(key, entry);
668
- try {
669
- const loaded = await load;
670
- return loaded.value;
671
- } finally {
672
- if (pending.get(key) === entry) pending.delete(key);
673
- }
674
- };
675
- };
676
- return {
677
- name: "cache",
678
- optionKeys: ["cache"],
679
- get size() {
680
- values.purgeStale();
681
- return values.size;
682
- },
683
- clear,
684
- invalidate,
685
- attachRealtime(stream) {
686
- if (!stream || typeof stream.on !== "function") {
687
- throw new CacheError("attachRealtime() \u043F\u0440\u0438\u043D\u0438\u043C\u0430\u0435\u0442 \u043F\u043E\u0442\u043E\u043A \u0438\u0437 itd.realtime()");
688
- }
689
- const invalidateStream = (...routes) => {
690
- const identity = typeof stream.getAuthIdentity === "function" ? stream.getAuthIdentity() : void 0;
691
- const streamBaseUrl = typeof stream.baseUrl === "string" && stream.baseUrl.length > 0 ? stream.baseUrl : void 0;
692
- const legacyScope = typeof stream.getAuthScope === "function" ? stream.getAuthScope() : void 0;
693
- const accountScope = identity?.userId && streamBaseUrl ? JSON.stringify([streamBaseUrl, identity.userId]) : legacyScope !== void 0 && streamBaseUrl ? JSON.stringify([streamBaseUrl, legacyScope]) : void 0;
694
- if (accountScope === void 0) invalidate(...routes);
695
- else invalidateScope(accountScope, routes);
696
- };
697
- invalidateStream("notifications.list", "notifications.count");
698
- const offNotification = stream.on(
699
- "notification",
700
- () => invalidateStream("notifications.list", "notifications.count")
701
- );
702
- const offUnreadCount = stream.on(
703
- "unreadCount",
704
- () => invalidateStream("notifications.count")
705
- );
706
- return () => {
707
- offNotification();
708
- offUnreadCount();
709
- };
710
- },
711
- install({ use, baseUrl, getAuthIdentity, getAuthScope }) {
712
- installationSequence += 1;
713
- use(createTransformer(installationSequence, baseUrl, getAuthIdentity, getAuthScope));
714
- }
715
- };
642
+ const config = resolveOptions(options);
643
+ const values = new LRUCache({
644
+ max: config.maxEntries,
645
+ ttl: config.ttl,
646
+ updateAgeOnGet: false,
647
+ allowStale: false
648
+ });
649
+ const pending = /* @__PURE__ */ new Map();
650
+ const operationGenerations = /* @__PURE__ */ new Map();
651
+ const scopeGenerations = /* @__PURE__ */ new Map();
652
+ const scopeOperationGenerations = /* @__PURE__ */ new Map();
653
+ const keyStates = /* @__PURE__ */ new Map();
654
+ let generation = 0;
655
+ let installationSequence = 0;
656
+ const scopeOperationKey = (accountScope, operation) => JSON.stringify([accountScope, operation]);
657
+ const clear = () => {
658
+ generation += 1;
659
+ values.clear();
660
+ pending.clear();
661
+ };
662
+ const invalidate = (...operations) => {
663
+ if (operations.length === 0) return;
664
+ const selected = /* @__PURE__ */ new Set();
665
+ for (const operation of operations) {
666
+ if (typeof operation !== "string") throw new CacheError(`Неизвестная операция кэша: ${JSON.stringify(operation)}`);
667
+ const operationId = operation;
668
+ selected.add(operationId);
669
+ operationGenerations.set(operationId, (operationGenerations.get(operationId) ?? 0) + 1);
670
+ }
671
+ for (const [key, entry] of values.entries()) if (selected.has(entry.operation)) values.delete(key);
672
+ for (const [key, entry] of pending) if (selected.has(entry.operation)) pending.delete(key);
673
+ };
674
+ const clearScope = (accountScope) => {
675
+ scopeGenerations.set(accountScope, (scopeGenerations.get(accountScope) ?? 0) + 1);
676
+ for (const [key, entry] of values.entries()) if (entry.accountScope === accountScope) values.delete(key);
677
+ for (const [key, entry] of pending) if (entry.accountScope === accountScope) pending.delete(key);
678
+ };
679
+ const invalidateScope = (accountScope, operations) => {
680
+ if (operations.length === 0) return;
681
+ const selected = new Set(operations);
682
+ for (const operation of selected) {
683
+ const key = scopeOperationKey(accountScope, operation);
684
+ scopeOperationGenerations.set(key, (scopeOperationGenerations.get(key) ?? 0) + 1);
685
+ }
686
+ for (const [key, entry] of values.entries()) if (entry.accountScope === accountScope && selected.has(entry.operation)) values.delete(key);
687
+ for (const [key, entry] of pending) if (entry.accountScope === accountScope && selected.has(entry.operation)) pending.delete(key);
688
+ };
689
+ const applyMutation = (accountScope, mutation) => {
690
+ if (mutation.invalidates === CacheInvalidation.All) clearScope(accountScope);
691
+ else if (mutation.scope === CachePolicyScope.Account) invalidateScope(accountScope, mutation.invalidates);
692
+ else invalidate(...mutation.invalidates);
693
+ };
694
+ const invalidateNotificationStream = (stream, ...operations) => {
695
+ const identity = stream.getAuthIdentity();
696
+ const streamBaseUrl = stream.baseUrl;
697
+ const legacyScope = stream.getAuthScope();
698
+ const accountScope = identity?.userId ? JSON.stringify([streamBaseUrl, identity.userId]) : legacyScope !== void 0 ? JSON.stringify([streamBaseUrl, legacyScope]) : void 0;
699
+ if (accountScope === void 0) invalidate(...operations);
700
+ else invalidateScope(accountScope, operations);
701
+ };
702
+ const notificationMiddleware = async (context, next) => {
703
+ if (context.update.type === NotificationUpdateType.Notification) invalidateNotificationStream(context.stream, "notifications.list", "notifications.count");
704
+ else if (context.update.type === NotificationUpdateType.UnreadCount) invalidateNotificationStream(context.stream, "notifications.count");
705
+ await next();
706
+ };
707
+ const createTransformer = (installation, baseUrl, getAuthIdentity, getAuthScope, getOperation) => {
708
+ const fallbackAuthScope = JSON.stringify([baseUrl, `installation:${installation}`]);
709
+ const resolveIdentity = async () => {
710
+ const identity = await getAuthIdentity?.();
711
+ const accountScope = identity?.userId ? JSON.stringify([baseUrl, identity.userId]) : getAuthScope ? JSON.stringify([baseUrl, getAuthScope()]) : fallbackAuthScope;
712
+ return {
713
+ accountScope,
714
+ sessionScope: identity?.userId && identity.sessionId ? JSON.stringify([
715
+ baseUrl,
716
+ identity.userId,
717
+ identity.sessionId
718
+ ]) : JSON.stringify([accountScope, getAuthScope ? getAuthScope() : `installation:${installation}`])
719
+ };
720
+ };
721
+ return async (request, next) => {
722
+ const policy = getOperation(request.operationId)?.annotations?.cache;
723
+ const operation = cacheOperation(request.operationId) ?? (policy?.kind === CachePolicyKind.Query ? {
724
+ id: request.operationId,
725
+ category: request.operationId.split(".", 1)[0] ?? "feature"
726
+ } : void 0);
727
+ const method = request.method.toUpperCase();
728
+ if (!(policy !== void 0 ? policy.kind === CachePolicyKind.Query : operation !== void 0 || method === "GET" || method === "HEAD")) {
729
+ const mutation = cacheMutation(request.operationId) ?? (policy?.kind === CachePolicyKind.Mutation ? {
730
+ operationId: request.operationId,
731
+ invalidates: policy.invalidates,
732
+ ...policy.scope === void 0 ? {} : { scope: policy.scope }
733
+ } : void 0);
734
+ const startedIdentity = mutation ? await resolveIdentity() : void 0;
735
+ const result = await next(request);
736
+ if (mutation && startedIdentity) {
737
+ applyMutation(startedIdentity.accountScope, mutation);
738
+ const currentIdentity = await resolveIdentity();
739
+ if (currentIdentity.accountScope !== startedIdentity.accountScope && (mutation.invalidates === CacheInvalidation.All || mutation.scope === CachePolicyScope.Account)) applyMutation(currentIdentity.accountScope, mutation);
740
+ } else clear();
741
+ return result;
742
+ }
743
+ if (!operation || !config.operations.has(operation.id)) return next(request);
744
+ const mode = cacheMode(request);
745
+ if (mode === CacheModes.NoStore) return next(request);
746
+ const unscopedKey = buildCacheKey(operation.id, request);
747
+ if (unscopedKey === void 0) return next(request);
748
+ const identity = await resolveIdentity();
749
+ const scope = operation.id === "auth.sessions" || policy?.kind === CachePolicyKind.Query && policy.scope === CachePolicyScope.Session ? identity.sessionScope : identity.accountScope;
750
+ const key = JSON.stringify([scope, unscopedKey]);
751
+ if (mode === CacheModes.Reload) {
752
+ const state = keyStates.get(key) ?? {
753
+ active: 0,
754
+ generation: 0
755
+ };
756
+ state.generation += 1;
757
+ keyStates.set(key, state);
758
+ values.delete(key);
759
+ pending.delete(key);
760
+ }
761
+ if (mode === CacheModes.Default) {
762
+ const hit = values.get(key);
763
+ if (hit) {
764
+ const cloned = cloneValue(hit.value);
765
+ if (cloned.cacheable) return cloned.value;
766
+ values.delete(key);
767
+ }
768
+ const existing = pending.get(key);
769
+ if (config.deduplicate && request.signal === void 0 && request.timeout === void 0 && existing) return cloneValue((await existing.promise).value).value;
770
+ }
771
+ const startedGeneration = generation;
772
+ const startedScopeGeneration = scopeGenerations.get(identity.accountScope) ?? 0;
773
+ const startedOperationGeneration = operationGenerations.get(operation.id) ?? 0;
774
+ const scopedOperationKey = scopeOperationKey(identity.accountScope, operation.id);
775
+ const startedScopeOperationGeneration = scopeOperationGenerations.get(scopedOperationKey) ?? 0;
776
+ const keyState = keyStates.get(key) ?? {
777
+ active: 0,
778
+ generation: 0
779
+ };
780
+ keyState.active += 1;
781
+ keyStates.set(key, keyState);
782
+ const startedKeyGeneration = keyState.generation;
783
+ const load = (async () => {
784
+ try {
785
+ const result = await next(request);
786
+ const stored = cloneValue(result);
787
+ const currentIdentity = await resolveIdentity();
788
+ const currentScope = operation.id === "auth.sessions" || policy?.kind === CachePolicyKind.Query && policy.scope === CachePolicyScope.Session ? currentIdentity.sessionScope : currentIdentity.accountScope;
789
+ if (stored.cacheable && currentScope === scope && generation === startedGeneration && (scopeGenerations.get(identity.accountScope) ?? 0) === startedScopeGeneration && (operationGenerations.get(operation.id) ?? 0) === startedOperationGeneration && (scopeOperationGenerations.get(scopedOperationKey) ?? 0) === startedScopeOperationGeneration && keyState.generation === startedKeyGeneration) values.set(key, {
790
+ accountScope: identity.accountScope,
791
+ operation: operation.id,
792
+ value: stored.value
793
+ });
794
+ return {
795
+ cacheable: stored.cacheable,
796
+ value: result
797
+ };
798
+ } finally {
799
+ keyState.active -= 1;
800
+ if (keyState.active === 0 && keyStates.get(key) === keyState) keyStates.delete(key);
801
+ }
802
+ })();
803
+ const mayDeduplicate = mode === CacheModes.Default && config.deduplicate && request.signal === void 0 && request.timeout === void 0;
804
+ const entry = {
805
+ accountScope: identity.accountScope,
806
+ operation: operation.id,
807
+ promise: load
808
+ };
809
+ if (mayDeduplicate) pending.set(key, entry);
810
+ try {
811
+ return (await load).value;
812
+ } finally {
813
+ if (pending.get(key) === entry) pending.delete(key);
814
+ }
815
+ };
816
+ };
817
+ return {
818
+ name: "cache",
819
+ get size() {
820
+ values.purgeStale();
821
+ return values.size;
822
+ },
823
+ clear,
824
+ invalidate,
825
+ attachNotificationEvents(stream) {
826
+ if (!stream || typeof stream.use !== "function" || typeof stream.getAuthIdentity !== "function" || typeof stream.getAuthScope !== "function" || typeof stream.baseUrl !== "string") throw new CacheError("attachNotificationEvents() принимает канал itd.notifications.events");
827
+ invalidateNotificationStream(stream, "notifications.list", "notifications.count");
828
+ return stream.use(notificationMiddleware);
829
+ },
830
+ install({ operations, baseUrl, getAuthIdentity, getAuthScope }) {
831
+ installationSequence += 1;
832
+ operations.use(createTransformer(installationSequence, baseUrl, getAuthIdentity, getAuthScope, operations.get));
833
+ }
834
+ };
716
835
  }
836
+ //#endregion
837
+ export { CACHE_OPERATIONS, CacheError, CacheInvalidation, CacheModes, CachePolicyKind, CachePolicyScope, buildCacheKey, cache, cacheOperation, isCacheOperationId };
717
838
 
718
- export { CACHE_ROUTES, CacheError, CacheModes, buildCacheKey, cache, cacheRoute, isCacheRouteId };
719
- //# sourceMappingURL=index.js.map
720
839
  //# sourceMappingURL=index.js.map