@envelop/response-cache 2.4.0-alpha-c0cc559.0 → 2.4.0-alpha-e9434aa.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/index.js DELETED
@@ -1,422 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- const LRU = _interopDefault(require('lru-cache'));
8
- const core = require('@envelop/core');
9
- const utils = require('@graphql-tools/utils');
10
- const graphql = require('graphql');
11
- const jsonStableStringify = _interopDefault(require('fast-json-stable-stringify'));
12
-
13
- const createInMemoryCache = (params) => {
14
- var _a;
15
- const buildEntityId = (_a = params === null || params === void 0 ? void 0 : params.buildEntityId) !== null && _a !== void 0 ? _a : defaultBuildEntityId;
16
- const cachedResponses = new LRU({
17
- max: params === null || params === void 0 ? void 0 : params.max,
18
- stale: false,
19
- noDisposeOnSet: true,
20
- dispose(responseId) {
21
- purgeResponse(responseId, false);
22
- },
23
- });
24
- const entityToResponseIds = new Map();
25
- const responseIdToEntityIds = new Map();
26
- function purgeResponse(responseId, shouldRemove = true) {
27
- var _a;
28
- const entityIds = responseIdToEntityIds.get(responseId);
29
- // get entities related to the response
30
- if (entityIds !== undefined) {
31
- for (const entityId of entityIds) {
32
- // remove the response mapping from the entity
33
- (_a = entityToResponseIds.get(entityId)) === null || _a === void 0 ? void 0 : _a.delete(responseId);
34
- }
35
- // remove all the entity mappings from the response
36
- responseIdToEntityIds.delete(responseId);
37
- }
38
- if (shouldRemove) {
39
- // remove the response from the cache
40
- cachedResponses.del(responseId);
41
- }
42
- }
43
- function purgeEntity(entity) {
44
- const responseIds = entityToResponseIds.get(entity);
45
- if (responseIds !== undefined) {
46
- for (const responseId of responseIds) {
47
- purgeResponse(responseId);
48
- }
49
- }
50
- }
51
- return {
52
- set(responseId, result, collectedEntities, ttl) {
53
- cachedResponses.set(responseId, result, ttl);
54
- const entityIds = new Set();
55
- responseIdToEntityIds.set(responseId, entityIds);
56
- for (const { typename, id } of collectedEntities) {
57
- let operationIds = entityToResponseIds.get(typename);
58
- if (operationIds == null) {
59
- operationIds = new Set();
60
- entityToResponseIds.set(typename, operationIds);
61
- }
62
- // typename => operation
63
- operationIds.add(responseId);
64
- // operation => typename
65
- entityIds.add(typename);
66
- if (id !== undefined) {
67
- const entityId = buildEntityId(typename, id);
68
- let responseIds = entityToResponseIds.get(entityId);
69
- if (responseIds == null) {
70
- responseIds = new Set();
71
- entityToResponseIds.set(entityId, responseIds);
72
- }
73
- // typename:id => operation
74
- responseIds.add(responseId);
75
- // operation => typename:id
76
- entityIds.add(entityId);
77
- }
78
- }
79
- },
80
- get(responseId) {
81
- var _a;
82
- return (_a = cachedResponses.get(responseId)) !== null && _a !== void 0 ? _a : null;
83
- },
84
- invalidate(entitiesToRemove) {
85
- for (const { typename, id } of entitiesToRemove) {
86
- purgeEntity(id != null ? buildEntityId(typename, id) : typename);
87
- }
88
- },
89
- };
90
- };
91
- const defaultBuildEntityId = (typename, id) => `${typename}:${id}`;
92
-
93
- const webCrypto = globalThis.crypto;
94
- const sha256Browser = (bytes) => {
95
- const hash = webCrypto.subtle.digest({ name: 'SHA-256' }, bytes);
96
- return new Promise((resolve, reject) => {
97
- Promise.resolve(hash)
98
- .then(function (result) {
99
- resolve(new Uint8Array(result));
100
- })
101
- .catch(function (error) {
102
- reject(error);
103
- });
104
- });
105
- };
106
- let nodeCrypto;
107
- if (typeof window === 'undefined' && !webCrypto) {
108
- // Indirect eval'd require/import to guarantee no side-effects in module scope
109
- // (optimization for minifier)
110
- try {
111
- // eslint-disable-next-line no-new-func
112
- nodeCrypto = Promise.resolve(new Function('require', 'return require("crypto")')(require));
113
- }
114
- catch (_error) {
115
- try {
116
- // eslint-disable-next-line no-new-func
117
- nodeCrypto = new Function('return import("crypto")')();
118
- }
119
- catch (_error) { }
120
- }
121
- }
122
- const hashSHA256 = async (text) => {
123
- // Node.js support
124
- if (nodeCrypto) {
125
- return nodeCrypto.then(crypto => crypto.createHash('sha256').update(text).digest('hex'));
126
- }
127
- else if (webCrypto) {
128
- let buf;
129
- if (typeof TextEncoder !== 'undefined') {
130
- buf = new TextEncoder().encode(text);
131
- }
132
- else {
133
- buf = new Uint8Array(text.length);
134
- for (let i = 0, l = text.length; i < l; i++) {
135
- // NOTE: We assume that the input GraphQL Query only uses UTF-8 at most
136
- // since GraphQL mostly consists of ASCII, this is completely fine
137
- buf[i] = text.charCodeAt(i);
138
- }
139
- }
140
- const out = await sha256Browser(buf);
141
- let hash = '';
142
- for (let i = 0, l = out.length; i < l; i++) {
143
- const hex = out[i].toString(16);
144
- hash += '00'.slice(0, Math.max(0, 2 - hex.length)) + hex;
145
- }
146
- return hash;
147
- }
148
- if (process.env.NODE_ENV !== 'production') {
149
- // eslint-disable-next-line no-console
150
- console.warn('[@envelop/response-cache]: The Node Crypto and Web Crypto APIs are not available.\n' +
151
- 'This is an unexpected error. Please report it by filing a GitHub Issue.');
152
- }
153
- return Promise.resolve('');
154
- };
155
-
156
- const contextSymbol = Symbol('responseCache');
157
- const rawDocumentStringSymbol = Symbol('rawDocumentString');
158
- /**
159
- * Default function used for building the response cache key.
160
- * It is exported here for advanced use-cases. E.g. if you want to short circuit and serve responses from the cache on a global level in order to completely by-pass the GraphQL flow.
161
- */
162
- const defaultBuildResponseCacheKey = params => {
163
- var _a, _b, _c;
164
- return hashSHA256([
165
- params.documentString,
166
- (_a = params.operationName) !== null && _a !== void 0 ? _a : '',
167
- jsonStableStringify((_b = params.variableValues) !== null && _b !== void 0 ? _b : {}),
168
- (_c = params.sessionId) !== null && _c !== void 0 ? _c : '',
169
- ].join('|'));
170
- };
171
- /**
172
- * Default function used to check if the result should be cached.
173
- *
174
- * It is exported here for advanced use-cases. E.g. if you want to choose if
175
- * results with certain error types should be cached.
176
- *
177
- * By default, results with errors (unexpected, EnvelopError, or GraphQLError) are not cached.
178
- */
179
- const defaultShouldCacheResult = (params) => {
180
- if (params.result.errors) {
181
- // eslint-disable-next-line no-console
182
- console.warn('[useResponseCache] Failed to cache due to errors');
183
- return false;
184
- }
185
- return true;
186
- };
187
- const defaultGetDocumentStringFromContext = context => context[rawDocumentStringSymbol];
188
- function useResponseCache({ cache = createInMemoryCache(), ttl: globalTtl = Infinity, session = () => null, enabled, ignoredTypes = [], ttlPerType = {}, ttlPerSchemaCoordinate = {}, idFields = ['id'], invalidateViaMutation = true, buildResponseCacheKey = defaultBuildResponseCacheKey, getDocumentStringFromContext = defaultGetDocumentStringFromContext, shouldCacheResult = defaultShouldCacheResult,
189
- // eslint-disable-next-line dot-notation
190
- includeExtensionMetadata = typeof process !== 'undefined' ? process.env['NODE_ENV'] === 'development' : false, } = {}) {
191
- const appliedTransform = Symbol('responseCache.appliedTransform');
192
- const ignoredTypesMap = new Set(ignoredTypes);
193
- // never cache Introspections
194
- ttlPerSchemaCoordinate = { 'Query.__schema': 0, ...ttlPerSchemaCoordinate };
195
- return {
196
- onSchemaChange({ schema, replaceSchema }) {
197
- var _a;
198
- // @ts-expect-error See https://github.com/graphql/graphql-js/pull/3511 - remove this comments once merged
199
- if (((_a = schema.extensions) === null || _a === void 0 ? void 0 : _a[appliedTransform]) === true) {
200
- return;
201
- }
202
- const patchedSchema = applyResponseCacheLogic(schema, idFields);
203
- patchedSchema.extensions = {
204
- ...patchedSchema.extensions,
205
- [appliedTransform]: true,
206
- };
207
- replaceSchema(patchedSchema);
208
- },
209
- onParse(parseCtx) {
210
- return function onParseEnd(ctx) {
211
- if (ctx.result && 'kind' in ctx.result) {
212
- const source = parseCtx.params.source;
213
- const rawDocumentString = typeof source === 'string' ? source : source.body;
214
- ctx.extendContext({
215
- [rawDocumentStringSymbol]: rawDocumentString,
216
- });
217
- }
218
- };
219
- },
220
- async onExecute(ctx) {
221
- var _a;
222
- const identifier = new Map();
223
- const types = new Set();
224
- const context = {
225
- identifier,
226
- types,
227
- currentTtl: undefined,
228
- ttlPerType,
229
- ignoredTypesMap,
230
- skip: false,
231
- };
232
- ctx.extendContext({
233
- [contextSymbol]: context,
234
- });
235
- if (isMutation(ctx.args.document)) {
236
- if (invalidateViaMutation === false) {
237
- return;
238
- }
239
- return {
240
- onExecuteDone({ result, setResult }) {
241
- if (core.isAsyncIterable(result)) {
242
- // eslint-disable-next-line no-console
243
- console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
244
- return;
245
- }
246
- cache.invalidate(context.identifier.values());
247
- if (includeExtensionMetadata) {
248
- setResult({
249
- ...result,
250
- extensions: {
251
- ...result.extensions,
252
- responseCache: {
253
- invalidatedEntities: Array.from(context.identifier.values()),
254
- },
255
- },
256
- });
257
- }
258
- },
259
- };
260
- }
261
- else {
262
- const documentString = getDocumentStringFromContext(ctx.args.contextValue);
263
- if (documentString != null) {
264
- const operationId = await buildResponseCacheKey({
265
- documentString,
266
- variableValues: ctx.args.variableValues,
267
- operationName: ctx.args.operationName,
268
- sessionId: session(ctx.args.contextValue),
269
- });
270
- if (((_a = enabled === null || enabled === void 0 ? void 0 : enabled(ctx.args.contextValue)) !== null && _a !== void 0 ? _a : true) === true) {
271
- const cachedResponse = await cache.get(operationId);
272
- if (cachedResponse != null) {
273
- if (includeExtensionMetadata) {
274
- ctx.setResultAndStopExecution({
275
- ...cachedResponse,
276
- extensions: {
277
- responseCache: {
278
- hit: true,
279
- },
280
- },
281
- });
282
- }
283
- else {
284
- ctx.setResultAndStopExecution(cachedResponse);
285
- }
286
- return;
287
- }
288
- }
289
- if (ttlPerSchemaCoordinate) {
290
- const typeInfo = new graphql.TypeInfo(ctx.args.schema);
291
- graphql.visit(ctx.args.document, graphql.visitWithTypeInfo(typeInfo, {
292
- Field(fieldNode) {
293
- const parentType = typeInfo.getParentType();
294
- if (parentType) {
295
- const schemaCoordinate = `${parentType.name}.${fieldNode.name.value}`;
296
- const maybeTtl = ttlPerSchemaCoordinate[schemaCoordinate];
297
- if (maybeTtl !== undefined) {
298
- context.currentTtl = calculateTtl(maybeTtl, context.currentTtl);
299
- }
300
- }
301
- },
302
- }));
303
- }
304
- return {
305
- onExecuteDone({ result, setResult }) {
306
- var _a;
307
- if (core.isAsyncIterable(result)) {
308
- // eslint-disable-next-line no-console
309
- console.warn('[useResponseCache] AsyncIterable returned from execute is currently unsupported.');
310
- return;
311
- }
312
- if (context.skip) {
313
- return;
314
- }
315
- if (!shouldCacheResult({ result })) {
316
- return;
317
- }
318
- // we only use the global ttl if no currentTtl has been determined.
319
- const finalTtl = (_a = context.currentTtl) !== null && _a !== void 0 ? _a : globalTtl;
320
- if (finalTtl === 0) {
321
- if (includeExtensionMetadata) {
322
- setResult({
323
- ...result,
324
- extensions: {
325
- responseCache: {
326
- hit: false,
327
- didCache: false,
328
- },
329
- },
330
- });
331
- }
332
- return;
333
- }
334
- cache.set(operationId, result, identifier.values(), finalTtl);
335
- if (includeExtensionMetadata) {
336
- setResult({
337
- ...result,
338
- extensions: {
339
- responseCache: {
340
- hit: false,
341
- didCache: true,
342
- ttl: finalTtl,
343
- },
344
- },
345
- });
346
- }
347
- },
348
- };
349
- }
350
- else {
351
- // eslint-disable-next-line no-console
352
- console.warn(`[useResponseCache] Failed extracting document string from the context. The response will not be cached or served from the cache. ` +
353
- `If you are overriding the 'parse' behavior make sure to pass a custom 'getDocumentStringFromContext' function for getting the document string, which is required for building the response cache key.`);
354
- return undefined;
355
- }
356
- }
357
- },
358
- };
359
- }
360
- function isOperationDefinition(node) {
361
- return (node === null || node === void 0 ? void 0 : node.kind) === 'OperationDefinition';
362
- }
363
- function calculateTtl(typeTtl, currentTtl) {
364
- if (typeof currentTtl === 'number') {
365
- return Math.min(currentTtl, typeTtl);
366
- }
367
- return typeTtl;
368
- }
369
- function isMutation(doc) {
370
- return doc.definitions.find(isOperationDefinition).operation === 'mutation';
371
- }
372
- function runWith(input, callback) {
373
- if (input instanceof Promise) {
374
- input.then(callback, () => undefined);
375
- }
376
- else {
377
- callback(input);
378
- }
379
- }
380
- function applyResponseCacheLogic(schema, idFieldNames) {
381
- return utils.mapSchema(schema, {
382
- [utils.MapperKind.OBJECT_FIELD](fieldConfig, fieldName, typename) {
383
- if (idFieldNames.includes(fieldName)) {
384
- return {
385
- ...fieldConfig,
386
- resolve(src, args, context, info) {
387
- var _a;
388
- const result = ((_a = fieldConfig.resolve) !== null && _a !== void 0 ? _a : graphql.defaultFieldResolver)(src, args, context, info);
389
- runWith(result, (id) => {
390
- const ctx = context[contextSymbol];
391
- if (ctx !== undefined) {
392
- if (ctx.ignoredTypesMap.has(typename)) {
393
- ctx.skip = true;
394
- }
395
- if (ctx.skip === true) {
396
- ctx.skip = true;
397
- return;
398
- }
399
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
400
- // @ts-ignore TODO: investigate what to do if id is something unexpected
401
- ctx.identifier.set(`${typename}:${id}`, { typename, id });
402
- ctx.types.add(typename);
403
- if (typename in ctx.ttlPerType) {
404
- ctx.currentTtl = calculateTtl(ctx.ttlPerType[typename], ctx.currentTtl);
405
- }
406
- }
407
- });
408
- return result;
409
- },
410
- };
411
- }
412
- return fieldConfig;
413
- },
414
- });
415
- }
416
-
417
- exports.createInMemoryCache = createInMemoryCache;
418
- exports.defaultBuildEntityId = defaultBuildEntityId;
419
- exports.defaultBuildResponseCacheKey = defaultBuildResponseCacheKey;
420
- exports.defaultGetDocumentStringFromContext = defaultGetDocumentStringFromContext;
421
- exports.defaultShouldCacheResult = defaultShouldCacheResult;
422
- exports.useResponseCache = useResponseCache;