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