@itd-api/cache 0.0.2 → 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,720 +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: "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 }
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 CacheModes = Object.freeze({
443
- /** Отдать свежий кэш, иначе выполнить запрос и сохранить ответ. */
444
- Default: "default",
445
- /** Пропустить сохранённое значение, выполнить запрос и перезаписать кэш. */
446
- Reload: "reload",
447
- /** Не читать и не писать кэш для этого запроса. */
448
- NoStore: "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"
449
581
  });
450
- var DEFAULT_MAX_ENTRIES = 500;
451
- var CACHE_MODES = new Set(Object.values(CacheModes));
582
+ const DEFAULT_MAX_ENTRIES = 500;
583
+ const CACHE_MODES = new Set(Object.values(CacheModes));
452
584
  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
- }
585
+ if (!Number.isFinite(value) || value <= 0 || integer && !Number.isInteger(value)) throw new CacheError(`${name} должен быть ${integer ? "целым " : ""}положительным числом, получено: ${value}`);
458
586
  }
459
587
  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 };
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
+ };
481
606
  }
482
607
  function cloneValue(value) {
483
- try {
484
- return { cacheable: true, value: structuredClone(value) };
485
- } catch {
486
- return { cacheable: false, value };
487
- }
608
+ try {
609
+ return {
610
+ cacheable: true,
611
+ value: structuredClone(value)
612
+ };
613
+ } catch {
614
+ return {
615
+ cacheable: false,
616
+ value
617
+ };
618
+ }
488
619
  }
489
620
  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;
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;
497
624
  }
625
+ /** Создаёт TTL/LRU-кэш разобранных ответов itd-api. */
498
626
  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
- };
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
+ };
716
811
  }
812
+ //#endregion
813
+ export { CACHE_OPERATIONS, CacheError, CacheModes, buildCacheKey, cache, cacheOperation, isCacheOperationId };
717
814
 
718
- export { CACHE_ROUTES, CacheError, CacheModes, buildCacheKey, cache, cacheRoute, isCacheRouteId };
719
- //# sourceMappingURL=index.js.map
720
815
  //# sourceMappingURL=index.js.map