@ember-data/request-utils 5.6.0-alpha.5 → 5.6.0-beta.1

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.
Files changed (30) hide show
  1. package/addon-main.cjs +1 -1
  2. package/dist/deprecation-support.js +9 -8
  3. package/dist/handlers.js +1 -141
  4. package/dist/index.js +6 -909
  5. package/dist/string.js +1 -2
  6. package/package.json +5 -11
  7. package/unstable-preview-types/deprecation-support.d.ts +2 -2
  8. package/unstable-preview-types/handlers.d.ts +8 -8
  9. package/unstable-preview-types/index.d.ts +10 -649
  10. package/unstable-preview-types/string.d.ts +13 -14
  11. package/dist/deprecation-support.js.map +0 -1
  12. package/dist/handlers.js.map +0 -1
  13. package/dist/index.js.map +0 -1
  14. package/dist/inflect-SV-gOUrZ.js +0 -267
  15. package/dist/inflect-SV-gOUrZ.js.map +0 -1
  16. package/dist/string.js.map +0 -1
  17. package/dist/transform-BixPrO0I.js +0 -173
  18. package/dist/transform-BixPrO0I.js.map +0 -1
  19. package/unstable-preview-types/-private/handlers/auto-compress.d.ts +0 -155
  20. package/unstable-preview-types/-private/handlers/auto-compress.d.ts.map +0 -1
  21. package/unstable-preview-types/-private/string/inflect.d.ts +0 -107
  22. package/unstable-preview-types/-private/string/inflect.d.ts.map +0 -1
  23. package/unstable-preview-types/-private/string/inflections.d.ts +0 -12
  24. package/unstable-preview-types/-private/string/inflections.d.ts.map +0 -1
  25. package/unstable-preview-types/-private/string/transform.d.ts +0 -102
  26. package/unstable-preview-types/-private/string/transform.d.ts.map +0 -1
  27. package/unstable-preview-types/deprecation-support.d.ts.map +0 -1
  28. package/unstable-preview-types/handlers.d.ts.map +0 -1
  29. package/unstable-preview-types/index.d.ts.map +0 -1
  30. package/unstable-preview-types/string.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { deprecate } from '@ember/debug';
2
- import { getOrSetGlobal } from '@warp-drive/core/types/-private';
3
- import { L as LRUCache } from "./transform-BixPrO0I.js";
4
- import { macroCondition, getGlobalConfig } from '@embroider/macros';
2
+ import { DefaultCachePolicy } from '@warp-drive/core/store';
3
+ export { DefaultCachePolicy as CachePolicy, parseCacheControl } from '@warp-drive/core/store';
4
+ export * from '@warp-drive/utilities';
5
5
 
6
6
  /**
7
7
  * Simple utility function to assist in url building,
@@ -41,912 +41,8 @@ import { macroCondition, getGlobalConfig } from '@embroider/macros';
41
41
  * @module
42
42
  * @public
43
43
  */
44
- // prevents the final constructed object from needing to add
45
- // host and namespace which are provided by the final consuming
46
- // class to the prototype which can result in overwrite errors
47
- const CONFIG = getOrSetGlobal('CONFIG', {
48
- host: '',
49
- namespace: ''
50
- });
51
44
 
52
- /**
53
- * Sets the global configuration for `buildBaseURL`
54
- * for host and namespace values for the application.
55
- *
56
- * These values may still be overridden by passing
57
- * them to buildBaseURL directly.
58
- *
59
- * This method may be called as many times as needed.
60
- * host values of `''` or `'/'` are equivalent.
61
- *
62
- * Except for the value of `/` as host, host should not
63
- * end with `/`.
64
- *
65
- * namespace should not start or end with a `/`.
66
- *
67
- * ```ts
68
- * type BuildURLConfig = {
69
- * host: string;
70
- * namespace: string'
71
- * }
72
- * ```
73
- *
74
- * Example:
75
- *
76
- * ```ts
77
- * import { setBuildURLConfig } from '@ember-data/request-utils';
78
- *
79
- * setBuildURLConfig({
80
- * host: 'https://api.example.com',
81
- * namespace: 'api/v1'
82
- * });
83
- * ```
84
- *
85
- * @public
86
- * @param {BuildURLConfig} config
87
- * @return {void}
88
- */
89
- function setBuildURLConfig(config) {
90
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
91
- if (!test) {
92
- throw new Error(`setBuildURLConfig: You must pass a config object`);
93
- }
94
- })(config) : {};
95
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
96
- if (!test) {
97
- throw new Error(`setBuildURLConfig: You must pass a config object with a 'host' or 'namespace' property`);
98
- }
99
- })('host' in config || 'namespace' in config) : {};
100
- CONFIG.host = config.host || '';
101
- CONFIG.namespace = config.namespace || '';
102
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
103
- if (!test) {
104
- throw new Error(`buildBaseURL: host must NOT end with '/', received '${CONFIG.host}'`);
105
- }
106
- })(CONFIG.host === '/' || !CONFIG.host.endsWith('/')) : {};
107
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
108
- if (!test) {
109
- throw new Error(`buildBaseURL: namespace must NOT start with '/', received '${CONFIG.namespace}'`);
110
- }
111
- })(!CONFIG.namespace.startsWith('/')) : {};
112
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
113
- if (!test) {
114
- throw new Error(`buildBaseURL: namespace must NOT end with '/', received '${CONFIG.namespace}'`);
115
- }
116
- })(!CONFIG.namespace.endsWith('/')) : {};
117
- }
118
- const OPERATIONS_WITH_PRIMARY_RECORDS = new Set(['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord']);
119
- function isOperationWithPrimaryRecord(options) {
120
- return 'op' in options && OPERATIONS_WITH_PRIMARY_RECORDS.has(options.op);
121
- }
122
- function hasResourcePath(options) {
123
- return 'resourcePath' in options && typeof options.resourcePath === 'string' && options.resourcePath.length > 0;
124
- }
125
- function resourcePathForType(options) {
126
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
127
- if (!test) {
128
- throw new Error(`resourcePathForType: You must pass a valid op as part of options`);
129
- }
130
- })('op' in options && typeof options.op === 'string') : {};
131
- return options.op === 'findMany' ? options.identifiers[0].type : options.identifier.type;
132
- }
133
-
134
- /**
135
- * Builds a URL for a request based on the provided options.
136
- * Does not include support for building query params (see `buildQueryParams`)
137
- * so that it may be composed cleanly with other query-params strategies.
138
- *
139
- * Usage:
140
- *
141
- * ```ts
142
- * import { buildBaseURL } from '@ember-data/request-utils';
143
- *
144
- * const url = buildBaseURL({
145
- * host: 'https://api.example.com',
146
- * namespace: 'api/v1',
147
- * resourcePath: 'emberDevelopers',
148
- * op: 'query',
149
- * identifier: { type: 'ember-developer' }
150
- * });
151
- *
152
- * // => 'https://api.example.com/api/v1/emberDevelopers'
153
- * ```
154
- *
155
- * On the surface this may seem like a lot of work to do something simple, but
156
- * it is designed to be composable with other utilities and interfaces that the
157
- * average product engineer will never need to see or use.
158
- *
159
- * A few notes:
160
- *
161
- * - `resourcePath` is optional, but if it is not provided, `identifier.type` will be used.
162
- * - `host` and `namespace` are optional, but if they are not provided, the values globally
163
- * configured via `setBuildURLConfig` will be used.
164
- * - `op` is required and must be one of the following:
165
- * - 'findRecord' 'query' 'findMany' 'findRelatedCollection' 'findRelatedRecord'` 'createRecord' 'updateRecord' 'deleteRecord'
166
- * - Depending on the value of `op`, `identifier` or `identifiers` will be required.
167
- *
168
- * @public
169
- * @param urlOptions
170
- * @return {String}
171
- */
172
- function buildBaseURL(urlOptions) {
173
- const options = Object.assign({
174
- host: CONFIG.host,
175
- namespace: CONFIG.namespace
176
- }, urlOptions);
177
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
178
- if (!test) {
179
- throw new Error(`buildBaseURL: You must pass \`op\` as part of options`);
180
- }
181
- })(hasResourcePath(options) || typeof options.op === 'string' && options.op.length > 0) : {};
182
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
183
- if (!test) {
184
- throw new Error(`buildBaseURL: You must pass \`identifier\` as part of options`);
185
- }
186
- })(hasResourcePath(options) || options.op === 'findMany' || options.identifier && typeof options.identifier === 'object') : {};
187
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
188
- if (!test) {
189
- throw new Error(`buildBaseURL: You must pass \`identifiers\` as part of options`);
190
- }
191
- })(hasResourcePath(options) || options.op !== 'findMany' || options.identifiers && Array.isArray(options.identifiers) && options.identifiers.length > 0 && options.identifiers.every(i => i && typeof i === 'object')) : {};
192
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
193
- if (!test) {
194
- throw new Error(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'id'`);
195
- }
196
- })(hasResourcePath(options) || !isOperationWithPrimaryRecord(options) || typeof options.identifier.id === 'string' && options.identifier.id.length > 0) : {};
197
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
198
- if (!test) {
199
- throw new Error(`buildBaseURL: You must pass \`identifiers\` as part of options`);
200
- }
201
- })(hasResourcePath(options) || options.op !== 'findMany' || options.identifiers.every(i => typeof i.id === 'string' && i.id.length > 0)) : {};
202
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
203
- if (!test) {
204
- throw new Error(`buildBaseURL: You must pass valid \`identifier\` as part of options, expected 'type'`);
205
- }
206
- })(hasResourcePath(options) || options.op === 'findMany' || typeof options.identifier.type === 'string' && options.identifier.type.length > 0) : {};
207
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
208
- if (!test) {
209
- throw new Error(`buildBaseURL: You must pass valid \`identifiers\` as part of options, expected 'type'`);
210
- }
211
- })(hasResourcePath(options) || options.op !== 'findMany' || typeof options.identifiers[0].type === 'string' && options.identifiers[0].type.length > 0) : {};
212
-
213
- // prettier-ignore
214
- const idPath = isOperationWithPrimaryRecord(options) ? encodeURIComponent(options.identifier.id) : '';
215
- const resourcePath = options.resourcePath || resourcePathForType(options);
216
- const {
217
- host,
218
- namespace
219
- } = options;
220
- const fieldPath = 'fieldPath' in options ? options.fieldPath : '';
221
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
222
- if (!test) {
223
- throw new Error(`buildBaseURL: You tried to build a url for a ${String('op' in options ? options.op + ' ' : '')}request to ${resourcePath} but resourcePath must be set or op must be one of "${['findRecord', 'findRelatedRecord', 'findRelatedCollection', 'updateRecord', 'deleteRecord', 'createRecord', 'query', 'findMany'].join('","')}".`);
224
- }
225
- })(hasResourcePath(options) || ['findRecord', 'query', 'findMany', 'findRelatedCollection', 'findRelatedRecord', 'createRecord', 'updateRecord', 'deleteRecord'].includes(options.op)) : {};
226
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
227
- if (!test) {
228
- throw new Error(`buildBaseURL: host must NOT end with '/', received '${host}'`);
229
- }
230
- })(host === '/' || !host.endsWith('/')) : {};
231
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
232
- if (!test) {
233
- throw new Error(`buildBaseURL: namespace must NOT start with '/', received '${namespace}'`);
234
- }
235
- })(!namespace.startsWith('/')) : {};
236
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
237
- if (!test) {
238
- throw new Error(`buildBaseURL: namespace must NOT end with '/', received '${namespace}'`);
239
- }
240
- })(!namespace.endsWith('/')) : {};
241
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
242
- if (!test) {
243
- throw new Error(`buildBaseURL: resourcePath must NOT start with '/', received '${resourcePath}'`);
244
- }
245
- })(!resourcePath.startsWith('/')) : {};
246
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
247
- if (!test) {
248
- throw new Error(`buildBaseURL: resourcePath must NOT end with '/', received '${resourcePath}'`);
249
- }
250
- })(!resourcePath.endsWith('/')) : {};
251
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
252
- if (!test) {
253
- throw new Error(`buildBaseURL: fieldPath must NOT start with '/', received '${fieldPath}'`);
254
- }
255
- })(!fieldPath.startsWith('/')) : {};
256
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
257
- if (!test) {
258
- throw new Error(`buildBaseURL: fieldPath must NOT end with '/', received '${fieldPath}'`);
259
- }
260
- })(!fieldPath.endsWith('/')) : {};
261
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
262
- if (!test) {
263
- throw new Error(`buildBaseURL: idPath must NOT start with '/', received '${idPath}'`);
264
- }
265
- })(!idPath.startsWith('/')) : {};
266
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
267
- if (!test) {
268
- throw new Error(`buildBaseURL: idPath must NOT end with '/', received '${idPath}'`);
269
- }
270
- })(!idPath.endsWith('/')) : {};
271
- const hasHost = host !== '' && host !== '/';
272
- const url = [hasHost ? host : '', namespace, resourcePath, idPath, fieldPath].filter(Boolean).join('/');
273
- return hasHost ? url : `/${url}`;
274
- }
275
- const DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS = {
276
- arrayFormat: 'comma'
277
- };
278
- function handleInclude(include) {
279
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
280
- if (!test) {
281
- throw new Error(`Expected include to be a string or array, got ${typeof include}`);
282
- }
283
- })(typeof include === 'string' || Array.isArray(include)) : {};
284
- return typeof include === 'string' ? include.split(',') : include;
285
- }
286
-
287
- /**
288
- * filter out keys of an object that have falsy values or point to empty arrays
289
- * returning a new object with only those keys that have truthy values / non-empty arrays
290
- *
291
- * @public
292
- * @param {Record<string, Serializable>} source object to filter keys with empty values from
293
- * @return {Record<string, Serializable>} A new object with the keys that contained empty values removed
294
- */
295
- function filterEmpty(source) {
296
- const result = {};
297
- for (const key in source) {
298
- const value = source[key];
299
- // Allow `0` and `false` but filter falsy values that indicate "empty"
300
- if (value !== undefined && value !== null && value !== '') {
301
- if (!Array.isArray(value) || value.length > 0) {
302
- result[key] = source[key];
303
- }
304
- }
305
- }
306
- return result;
307
- }
308
-
309
- /**
310
- * Sorts query params by both key and value returning a new URLSearchParams
311
- * object with the keys inserted in sorted order.
312
- *
313
- * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
314
- *
315
- * Options:
316
- * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
317
- *
318
- * 'bracket': appends [] to the key for every value e.g. `&ids[]=1&ids[]=2`
319
- * 'indices': appends [i] to the key for every value e.g. `&ids[0]=1&ids[1]=2`
320
- * 'repeat': appends the key for every value e.g. `&ids=1&ids=2`
321
- * 'comma' (default): appends the key once with a comma separated list of values e.g. `&ids=1,2`
322
- *
323
- * @public
324
- * @param {URLSearchParams | object} params
325
- * @param {Object} options
326
- * @return {URLSearchParams} A URLSearchParams with keys inserted in sorted order
327
- */
328
- function sortQueryParams(params, options) {
329
- const opts = Object.assign({}, DEFAULT_QUERY_PARAMS_SERIALIZATION_OPTIONS, options);
330
- const paramsIsObject = !(params instanceof URLSearchParams);
331
- const urlParams = new URLSearchParams();
332
- const dictionaryParams = paramsIsObject ? params : {};
333
- if (!paramsIsObject) {
334
- params.forEach((value, key) => {
335
- const hasExisting = key in dictionaryParams;
336
- if (!hasExisting) {
337
- dictionaryParams[key] = value;
338
- } else {
339
- const existingValue = dictionaryParams[key];
340
- if (Array.isArray(existingValue)) {
341
- existingValue.push(value);
342
- } else {
343
- dictionaryParams[key] = [existingValue, value];
344
- }
345
- }
346
- });
347
- }
348
- if ('include' in dictionaryParams) {
349
- dictionaryParams.include = handleInclude(dictionaryParams.include);
350
- }
351
- const sortedKeys = Object.keys(dictionaryParams).sort();
352
- sortedKeys.forEach(key => {
353
- const value = dictionaryParams[key];
354
- if (Array.isArray(value)) {
355
- value.sort();
356
- switch (opts.arrayFormat) {
357
- case 'indices':
358
- value.forEach((v, i) => {
359
- urlParams.append(`${key}[${i}]`, String(v));
360
- });
361
- return;
362
- case 'bracket':
363
- value.forEach(v => {
364
- urlParams.append(`${key}[]`, String(v));
365
- });
366
- return;
367
- case 'repeat':
368
- value.forEach(v => {
369
- urlParams.append(key, String(v));
370
- });
371
- return;
372
- case 'comma':
373
- default:
374
- urlParams.append(key, value.join(','));
375
- return;
376
- }
377
- } else {
378
- urlParams.append(key, String(value));
379
- }
380
- });
381
- return urlParams;
382
- }
383
-
384
- /**
385
- * Sorts query params by both key and value, returning a query params string
386
- *
387
- * Treats `included` specially, splicing it into an array if it is a string and sorting the array.
388
- *
389
- * Options:
390
- * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'
391
- *
392
- * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`
393
- * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`
394
- * 'repeat': appends the key for every value e.g. `ids=1&ids=2`
395
- * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`
396
- *
397
- * @public
398
- * @param {URLSearchParams | Object} params
399
- * @param {Object} [options]
400
- * @return {String} A sorted query params string without the leading `?`
401
- */
402
- function buildQueryParams(params, options) {
403
- return sortQueryParams(params, options).toString();
404
- }
405
- const NUMERIC_KEYS = new Set(['max-age', 's-maxage', 'stale-if-error', 'stale-while-revalidate']);
406
-
407
- /**
408
- * Parses a string Cache-Control header value into an object with the following structure:
409
- *
410
- * ```ts
411
- * interface CacheControlValue {
412
- * immutable?: boolean;
413
- * 'max-age'?: number;
414
- * 'must-revalidate'?: boolean;
415
- * 'must-understand'?: boolean;
416
- * 'no-cache'?: boolean;
417
- * 'no-store'?: boolean;
418
- * 'no-transform'?: boolean;
419
- * 'only-if-cached'?: boolean;
420
- * private?: boolean;
421
- * 'proxy-revalidate'?: boolean;
422
- * public?: boolean;
423
- * 's-maxage'?: number;
424
- * 'stale-if-error'?: number;
425
- * 'stale-while-revalidate'?: number;
426
- * }
427
- * ```
428
- * @public
429
- * @param {String} header
430
- * @return {CacheControlValue}
431
- */
432
- function parseCacheControl(header) {
433
- return CACHE_CONTROL_CACHE.get(header);
434
- }
435
- const CACHE_CONTROL_CACHE = new LRUCache(header => {
436
- let key = '';
437
- let value = '';
438
- let isParsingKey = true;
439
- const cacheControlValue = {};
440
- for (let i = 0; i < header.length; i++) {
441
- const char = header.charAt(i);
442
- if (char === ',') {
443
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
444
- if (!test) {
445
- throw new Error(`Invalid Cache-Control value, expected a value`);
446
- }
447
- })(!isParsingKey || !NUMERIC_KEYS.has(key)) : {};
448
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
449
- if (!test) {
450
- throw new Error(`Invalid Cache-Control value, expected a value after "=" but got ","`);
451
- }
452
- })(i === 0 || header.charAt(i - 1) !== '=') : {};
453
- isParsingKey = true;
454
- // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
455
- cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
456
- key = '';
457
- value = '';
458
- continue;
459
- } else if (char === '=') {
460
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
461
- if (!test) {
462
- throw new Error(`Invalid Cache-Control value, expected a value after "="`);
463
- }
464
- })(i + 1 !== header.length) : {};
465
- isParsingKey = false;
466
- } else if (char === ' ' || char === `\t` || char === `\n`) {
467
- continue;
468
- } else if (isParsingKey) {
469
- key += char;
470
- } else {
471
- value += char;
472
- }
473
- if (i === header.length - 1) {
474
- // @ts-expect-error TS incorrectly thinks that optional keys must have a type that includes undefined
475
- cacheControlValue[key] = NUMERIC_KEYS.has(key) ? parseCacheControlValue(value) : true;
476
- }
477
- }
478
- return cacheControlValue;
479
- }, 200);
480
- function parseCacheControlValue(stringToParse) {
481
- const parsedValue = Number.parseInt(stringToParse);
482
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
483
- if (!test) {
484
- throw new Error(`Invalid Cache-Control value, expected a number but got - ${stringToParse}`);
485
- }
486
- })(!Number.isNaN(parsedValue)) : {};
487
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
488
- if (!test) {
489
- throw new Error(`Invalid Cache-Control value, expected a number greater than 0 but got - ${stringToParse}`);
490
- }
491
- })(parsedValue >= 0) : {};
492
- if (Number.isNaN(parsedValue) || parsedValue < 0) {
493
- return 0;
494
- }
495
- return parsedValue;
496
- }
497
- function isExpired(identifier, request, config) {
498
- const {
499
- constraints
500
- } = config;
501
- if (constraints?.isExpired) {
502
- const result = constraints.isExpired(request);
503
- if (result !== null) {
504
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
505
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
506
- // eslint-disable-next-line no-console
507
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because constraints.isExpired returned ${result}`);
508
- }
509
- }
510
- return result;
511
- }
512
- }
513
- const {
514
- headers
515
- } = request.response;
516
- if (!headers) {
517
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
518
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
519
- // eslint-disable-next-line no-console
520
- console.log(`CachePolicy: ${identifier.lid} is EXPIRED because no headers were provided`);
521
- }
522
- }
523
-
524
- // if we have no headers then both the headers based expiration
525
- // and the time based expiration will be considered expired
526
- return true;
527
- }
528
-
529
- // check for X-WarpDrive-Expires
530
- const now = Date.now();
531
- const date = headers.get('Date');
532
- if (constraints?.headers) {
533
- if (constraints.headers['X-WarpDrive-Expires']) {
534
- const xWarpDriveExpires = headers.get('X-WarpDrive-Expires');
535
- if (xWarpDriveExpires) {
536
- const expirationTime = new Date(xWarpDriveExpires).getTime();
537
- const result = now >= expirationTime;
538
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
539
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
540
- // eslint-disable-next-line no-console
541
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the time set by X-WarpDrive-Expires header is ${result ? 'in the past' : 'in the future'}`);
542
- }
543
- }
544
- return result;
545
- }
546
- }
547
-
548
- // check for Cache-Control
549
- if (constraints.headers['Cache-Control']) {
550
- const cacheControl = headers.get('Cache-Control');
551
- const age = headers.get('Age');
552
- if (cacheControl && age && date) {
553
- const cacheControlValue = parseCacheControl(cacheControl);
554
-
555
- // max-age and s-maxage are stored in
556
- const maxAge = cacheControlValue['max-age'] || cacheControlValue['s-maxage'];
557
- if (maxAge) {
558
- // age is stored in seconds
559
- const ageValue = parseInt(age, 10);
560
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
561
- if (!test) {
562
- throw new Error(`Invalid Cache-Control value, expected a number but got - ${age}`);
563
- }
564
- })(!Number.isNaN(ageValue)) : {};
565
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
566
- if (!test) {
567
- throw new Error(`Invalid Cache-Control value, expected a number greater than 0 but got - ${age}`);
568
- }
569
- })(ageValue >= 0) : {};
570
- if (!Number.isNaN(ageValue) && ageValue >= 0) {
571
- const dateValue = new Date(date).getTime();
572
- const expirationTime = dateValue + (maxAge - ageValue) * 1000;
573
- const result = now >= expirationTime;
574
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
575
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
576
- // eslint-disable-next-line no-console
577
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the time set by Cache-Control header is ${result ? 'in the past' : 'in the future'}`);
578
- }
579
- }
580
- return result;
581
- }
582
- }
583
- }
584
- }
585
-
586
- // check for Expires
587
- if (constraints.headers.Expires) {
588
- const expires = headers.get('Expires');
589
- if (expires) {
590
- const expirationTime = new Date(expires).getTime();
591
- const result = now >= expirationTime;
592
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
593
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
594
- // eslint-disable-next-line no-console
595
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the time set by Expires header is ${result ? 'in the past' : 'in the future'}`);
596
- }
597
- }
598
- return result;
599
- }
600
- }
601
- }
602
-
603
- // check for Date
604
- if (!date) {
605
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
606
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
607
- // eslint-disable-next-line no-console
608
- console.log(`CachePolicy: ${identifier.lid} is EXPIRED because no Date header was provided`);
609
- }
610
- }
611
- return true;
612
- }
613
- let expirationTime = config.apiCacheHardExpires;
614
- if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
615
- if (!config.disableTestOptimization) {
616
- expirationTime = config.apiCacheSoftExpires;
617
- }
618
- }
619
- const time = new Date(date).getTime();
620
- const deadline = time + expirationTime;
621
- const result = now >= deadline;
622
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
623
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
624
- // eslint-disable-next-line no-console
625
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'EXPIRED' : 'NOT expired'} because the apiCacheHardExpires time since the response's Date header is ${result ? 'in the past' : 'in the future'}`);
626
- }
627
- }
628
- return result;
629
- }
630
-
631
- /**
632
- * The configuration options for the CachePolicy
633
- * provided by `@ember-data/request-utils`.
634
- *
635
- * ```ts
636
- * import { CachePolicy } from '@ember-data/request-utils';
637
- *
638
- * new CachePolicy({
639
- * // ... PolicyConfig Settings ... //
640
- * });
641
- * ```
642
- *
643
- */
644
-
645
- /**
646
- * A basic CachePolicy that can be added to the Store service.
647
- *
648
- * Determines staleness based on time since the request was last received from the API
649
- * using the `date` header.
650
- *
651
- * Determines expiration based on configured constraints as well as a time based
652
- * expiration strategy based on the `date` header.
653
- *
654
- * In order expiration is determined by:
655
- *
656
- * - Is explicitly invalidated
657
- * - ↳ (if null) isExpired function \<IF Constraint Active>
658
- * - ↳ (if null) X-WarpDrive-Expires header \<IF Constraint Active>
659
- * - ↳ (if null) Cache-Control header \<IF Constraint Active>
660
- * - ↳ (if null) Expires header \<IF Constraint Active>
661
- * - ↳ (if null) Date header + apiCacheHardExpires \< current time
662
- *
663
- * Invalidates any request for which `cacheOptions.types` was provided when a createRecord
664
- * request for that type is successful.
665
- *
666
- * For this to work, the `createRecord` request must include the `cacheOptions.types` array
667
- * with the types that should be invalidated, or its request should specify the identifiers
668
- * of the records that are being created via `records`. Providing both is valid.
669
- *
670
- * > [!NOTE]
671
- * > only requests that had specified `cacheOptions.types` and occurred prior to the
672
- * > createRecord request will be invalidated. This means that a given request should always
673
- * > specify the types that would invalidate it to opt into this behavior. Abstracting this
674
- * > behavior via builders is recommended to ensure consistency.
675
- *
676
- * This allows the Store's CacheHandler to determine if a request is expired and
677
- * should be refetched upon next request.
678
- *
679
- * The `Fetch` handler provided by `@ember-data/request/fetch` will automatically
680
- * add the `date` header to responses if it is not present.
681
- *
682
- * > [!NOTE]
683
- * > Date headers do not have millisecond precision, so expiration times should
684
- * > generally be larger than 1000ms.
685
- *
686
- * Usage:
687
- *
688
- * ```ts
689
- * import { CachePolicy } from '@ember-data/request-utils';
690
- * import DataStore from '@ember-data/store';
691
- *
692
- * // ...
693
- *
694
- * export class Store extends DataStore {
695
- * constructor(args) {
696
- * super(args);
697
- * this.lifetimes = new CachePolicy({ apiCacheSoftExpires: 30_000, apiCacheHardExpires: 60_000 });
698
- * }
699
- * }
700
- * ```
701
- *
702
- * In Testing environments, the `apiCacheSoftExpires` will always be `false`
703
- * and `apiCacheHardExpires` will use the `apiCacheSoftExpires` value.
704
- *
705
- * This helps reduce flakiness and produce predictably rendered results in test suites.
706
- *
707
- * Requests that specifically set `cacheOptions.backgroundReload = true` will
708
- * still be background reloaded in tests.
709
- *
710
- * This behavior can be opted out of by setting `disableTestOptimization = true`
711
- * in the policy config.
712
- *
713
- * @class CachePolicy
714
- * @public
715
- */
716
- class CachePolicy {
717
- _getStore(store) {
718
- let set = this._stores.get(store);
719
- if (!set) {
720
- set = {
721
- invalidated: new Set(),
722
- types: new Map()
723
- };
724
- this._stores.set(store, set);
725
- }
726
- return set;
727
- }
728
- constructor(config) {
729
- this._stores = new WeakMap();
730
- const _config = arguments.length === 1 ? config : arguments[1];
731
- deprecate(`Passing a Store to the CachePolicy is deprecated, please pass only a config instead.`, arguments.length === 1, {
732
- id: 'ember-data:request-utils:lifetimes-service-store-arg',
733
- since: {
734
- enabled: '5.4',
735
- available: '4.13'
736
- },
737
- for: '@ember-data/request-utils',
738
- until: '6.0'
739
- });
740
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
741
- if (!test) {
742
- throw new Error(`You must pass a config to the CachePolicy`);
743
- }
744
- })(_config) : {};
745
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
746
- if (!test) {
747
- throw new Error(`You must pass a apiCacheSoftExpires to the CachePolicy`);
748
- }
749
- })(typeof _config.apiCacheSoftExpires === 'number') : {};
750
- macroCondition(getGlobalConfig().WarpDrive.env.DEBUG) ? (test => {
751
- if (!test) {
752
- throw new Error(`You must pass a apiCacheHardExpires to the CachePolicy`);
753
- }
754
- })(typeof _config.apiCacheHardExpires === 'number') : {};
755
- this.config = _config;
756
- }
757
-
758
- /**
759
- * Invalidate a request by its identifier for a given store instance.
760
- *
761
- * While the store argument may seem redundant, the CachePolicy
762
- * is designed to be shared across multiple stores / forks
763
- * of the store.
764
- *
765
- * ```ts
766
- * store.lifetimes.invalidateRequest(store, identifier);
767
- * ```
768
- *
769
- * @public
770
- * @param {StableDocumentIdentifier} identifier
771
- * @param {Store} store
772
- */
773
- invalidateRequest(identifier, store) {
774
- this._getStore(store).invalidated.add(identifier);
775
- }
776
-
777
- /**
778
- * Invalidate all requests associated to a specific type
779
- * for a given store instance.
780
- *
781
- * While the store argument may seem redundant, the CachePolicy
782
- * is designed to be shared across multiple stores / forks
783
- * of the store.
784
- *
785
- * This invalidation is done automatically when using this service
786
- * for both the CacheHandler and the LegacyNetworkHandler.
787
- *
788
- * ```ts
789
- * store.lifetimes.invalidateRequestsForType(store, 'person');
790
- * ```
791
- *
792
- * @public
793
- * @param {String} type
794
- * @param {Store} store
795
- */
796
- invalidateRequestsForType(type, store) {
797
- const storeCache = this._getStore(store);
798
- const set = storeCache.types.get(type);
799
- const notifications = store.notifications;
800
- if (set) {
801
- // TODO batch notifications
802
- set.forEach(id => {
803
- storeCache.invalidated.add(id);
804
- notifications.notify(id, 'invalidated');
805
- });
806
- }
807
- }
808
-
809
- /**
810
- * Invoked when a request has been fulfilled from the configured request handlers.
811
- * This is invoked by the CacheHandler for both foreground and background requests
812
- * once the cache has been updated.
813
- *
814
- * Note, this is invoked by the CacheHandler regardless of whether
815
- * the request has a cache-key.
816
- *
817
- * This method should not be invoked directly by consumers.
818
- *
819
- * @public
820
- * @param {ImmutableRequestInfo} request
821
- * @param {ImmutableResponse} response
822
- * @param {Store} store
823
- * @param {StableDocumentIdentifier | null} identifier
824
- * @return {void}
825
- */
826
- didRequest(request, response, identifier, store) {
827
- // if this is a successful createRecord request, invalidate the cacheKey for the type
828
- if (request.op === 'createRecord') {
829
- const statusNumber = response?.status ?? 0;
830
- if (statusNumber >= 200 && statusNumber < 400) {
831
- const types = new Set(request.records?.map(r => r.type));
832
- const additionalTypes = request.cacheOptions?.types;
833
- additionalTypes?.forEach(type => {
834
- types.add(type);
835
- });
836
- types.forEach(type => {
837
- this.invalidateRequestsForType(type, store);
838
- });
839
- }
840
-
841
- // add this document's cacheKey to a map for all associated types
842
- // it is recommended to only use this for queries
843
- } else if (identifier && request.cacheOptions?.types?.length) {
844
- const storeCache = this._getStore(store);
845
- request.cacheOptions?.types.forEach(type => {
846
- const set = storeCache.types.get(type);
847
- if (set) {
848
- set.add(identifier);
849
- storeCache.invalidated.delete(identifier);
850
- } else {
851
- storeCache.types.set(type, new Set([identifier]));
852
- }
853
- });
854
- }
855
- }
856
-
857
- /**
858
- * Invoked to determine if the request may be fulfilled from cache
859
- * if possible.
860
- *
861
- * Note, this is only invoked by the CacheHandler if the request has
862
- * a cache-key.
863
- *
864
- * If no cache entry is found or the entry is hard expired,
865
- * the request will be fulfilled from the configured request handlers
866
- * and the cache will be updated before returning the response.
867
- *
868
- * @public
869
- * @param {StableDocumentIdentifier} identifier
870
- * @param {Store} store
871
- * @return {Boolean} true if the request is considered hard expired
872
- */
873
- isHardExpired(identifier, store) {
874
- // if we are explicitly invalidated, we are hard expired
875
- const storeCache = this._getStore(store);
876
- if (storeCache.invalidated.has(identifier)) {
877
- return true;
878
- }
879
- const cache = store.cache;
880
- const cached = cache.peekRequest(identifier);
881
- if (!cached?.response) {
882
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
883
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
884
- // eslint-disable-next-line no-console
885
- console.log(`CachePolicy: ${identifier.lid} is EXPIRED because no cache entry was found`);
886
- }
887
- }
888
- return true;
889
- }
890
- return isExpired(identifier, cached, this.config);
891
- }
892
-
893
- /**
894
- * Invoked if `isHardExpired` is false to determine if the request
895
- * should be update behind the scenes if cache data is already available.
896
- *
897
- * Note, this is only invoked by the CacheHandler if the request has
898
- * a cache-key.
899
- *
900
- * If true, the request will be fulfilled from cache while a backgrounded
901
- * request is made to update the cache via the configured request handlers.
902
- *
903
- * @public
904
- * @param {StableDocumentIdentifier} identifier
905
- * @param {Store} store
906
- * @return {Boolean} true if the request is considered soft expired
907
- */
908
- isSoftExpired(identifier, store) {
909
- if (macroCondition(getGlobalConfig().WarpDrive.env.TESTING)) {
910
- if (!this.config.disableTestOptimization) {
911
- return false;
912
- }
913
- }
914
- const cache = store.cache;
915
- const cached = cache.peekRequest(identifier);
916
- if (cached?.response) {
917
- const date = cached.response.headers.get('date');
918
- if (!date) {
919
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
920
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
921
- // eslint-disable-next-line no-console
922
- console.log(`CachePolicy: ${identifier.lid} is STALE because no date header was found`);
923
- }
924
- }
925
- return true;
926
- } else {
927
- const time = new Date(date).getTime();
928
- const now = Date.now();
929
- const deadline = time + this.config.apiCacheSoftExpires;
930
- const result = now >= deadline;
931
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
932
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
933
- // eslint-disable-next-line no-console
934
- console.log(`CachePolicy: ${identifier.lid} is ${result ? 'STALE' : 'NOT stale'}. Expiration time: ${deadline}, now: ${now}`);
935
- }
936
- }
937
- return result;
938
- }
939
- }
940
- if (macroCondition(getGlobalConfig().WarpDrive.activeLogging.LOG_CACHE_POLICY)) {
941
- if (getGlobalConfig().WarpDrive.debug.LOG_CACHE_POLICY || globalThis.getWarpDriveRuntimeConfig().debug.LOG_CACHE_POLICY) {
942
- // eslint-disable-next-line no-console
943
- console.log(`CachePolicy: ${identifier.lid} is STALE because no cache entry was found`);
944
- }
945
- }
946
- return true;
947
- }
948
- }
949
- class LifetimesService extends CachePolicy {
45
+ class LifetimesService extends DefaultCachePolicy {
950
46
  constructor(config) {
951
47
  deprecate(`\`import { LifetimesService } from '@ember-data/request-utils';\` is deprecated, please use \`import { CachePolicy } from '@ember-data/request-utils';\` instead.`, false, {
952
48
  id: 'ember-data:deprecate-lifetimes-service-import',
@@ -960,4 +56,5 @@ class LifetimesService extends CachePolicy {
960
56
  super(config);
961
57
  }
962
58
  }
963
- export { CachePolicy, LifetimesService, buildBaseURL, buildQueryParams, filterEmpty, parseCacheControl, setBuildURLConfig, sortQueryParams };
59
+
60
+ export { LifetimesService };