@warp-drive-mirror/utilities 5.9.0-alpha.21 → 5.9.0-alpha.23

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.
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- //#region ../../node_modules/.pnpm/@warp-d_f6d5a2b6297864aac1090915a29560e9/node_modules/@warp-drive-mirror/core/dist/utils/string.js
2
+ //#region ../../node_modules/.pnpm/@warp-d_5e1563e0e582c8365bb74466d3761d6d/node_modules/@warp-drive-mirror/core/dist/utils/string.js
3
3
  const DEFAULT_MAX_CACHE_SIZE = 1e4;
4
4
  /**
5
5
  * An LRUCache implementation with upsert semantics.
@@ -1 +1 @@
1
- {"version":3,"file":"string.cjs","names":["DEFAULT_MAX_CACHE_SIZE","LRUCache","constructor","doWork","size","state","Map","get","key","value","delete","set","newValue","k","clear","STRING_DASHERIZE_REGEXP","STRING_DECAMELIZE_REGEXP","STRING_DASHERIZE_CACHE","replace","toLowerCase","dasherize","str","internalDasherize","LRUCache","defaultRules","capitalize","BLANK_REGEX","LAST_WORD_DASHED_REGEX","LAST_WORD_CAMELIZED_REGEX","CAMELIZED_REGEX","SINGULARS","word","_singularize","PLURALS","_pluralize","UNCOUNTABLE","Set","uncountable","IRREGULAR","Map","INVERSE_IRREGULAR","SINGULAR_RULES","singular","reverse","PLURAL_RULES","plurals","add","toLowerCase","loadUncountable","uncountables","forEach","irregular","single","plur","set","loadIrregular","irregularPairs","pair","clear","resetToDefaults","clearRules","v","singularize","get","pluralize","unshiftMap","map","rules","entries","rule","plural","regex","string","has","delete","inflect","typeRules","irregulars","isBlank","test","lowercase","wordSplit","exec","lastWord","isCamelized","substitution","match","replace","RegExp"],"sources":["../../../node_modules/.pnpm/@warp-d_f6d5a2b6297864aac1090915a29560e9/node_modules/@warp-drive-mirror/core/dist/utils/string.js","../src/-private/string/inflections.ts","../src/-private/string/transform.ts","../src/-private/string/inflect.ts"],"sourcesContent":["import { DEBUG } from '@warp-drive-mirror/core/build-config/env';\n\nconst DEFAULT_MAX_CACHE_SIZE = 10_000;\n\n/**\n * An LRUCache implementation with upsert semantics.\n *\n * This implementation is *not* generic, but focuses on\n * performance tuning for the string transformation cases\n * where the key maps to the value very simply.\n *\n * It takes a work function that should generate a new value\n * for a given key when called. It will be called when the key\n * is not found in the cache.\n *\n * It keeps track of the number of hits, misses, and ejections\n * in DEBUG envs, which is useful for tuning the cache size.\n *\n * This is an internal utility class for use by this module\n * and by `@warp-drive-mirror/utilities/string`. It is not intended\n * for use outside of these modules at this time.\n *\n * @private\n */\nexport class LRUCache<T, V> {\n declare size: number;\n declare state: Map<T, V>;\n declare doWork: (k: T) => V;\n\n // debug stats\n declare _hits: number;\n declare _misses: number;\n declare _ejected: number;\n\n constructor(doWork: (k: T) => V, size?: number) {\n this.size = size || DEFAULT_MAX_CACHE_SIZE;\n this.state = new Map();\n this.doWork = doWork;\n\n if (DEBUG) {\n this._hits = 0;\n this._misses = 0;\n this._ejected = 0;\n }\n }\n\n get(key: T): V {\n const value = this.state.get(key);\n if (value) {\n if (DEBUG) {\n this._hits++;\n }\n this.state.delete(key);\n this.state.set(key, value);\n return value;\n }\n if (DEBUG) {\n this._misses++;\n }\n\n const newValue = this.doWork(key);\n this.set(key, newValue);\n return newValue;\n }\n\n set(key: T, value: V): void {\n if (this.state.size === this.size) {\n for (const [k] of this.state) {\n if (DEBUG) {\n this._ejected++;\n }\n this.state.delete(k);\n break;\n }\n }\n this.state.set(key, value);\n }\n\n clear(): void {\n this.state.clear();\n if (DEBUG) {\n this._hits = 0;\n this._misses = 0;\n this._ejected = 0;\n }\n }\n}\n\nconst STRING_DASHERIZE_REGEXP = /[ _]/g;\nconst STRING_DECAMELIZE_REGEXP = /([a-z\\d])([A-Z])/g;\n/**\n * The {@link LRUCache} backing {@link dasherize}, keyed by the original\n * (un-dasherized) string.\n *\n * @private\n */\nexport const STRING_DASHERIZE_CACHE: LRUCache<string, string> = new LRUCache<string, string>((key: string) =>\n key.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase().replace(STRING_DASHERIZE_REGEXP, '-')\n);\n\n/**\n * This is an internal utility function that converts a string\n * to a dasherized format. Library consumers should use the\n * re-exported version from `@warp-drive-mirror/utilities/string` instead.\n *\n * This version is only in this location to support a deprecated\n * behavior in the core package and will be removed in a future.\n *\n * @private\n */\nexport function dasherize(str: string): string {\n return STRING_DASHERIZE_CACHE.get(str);\n}\n","export type RulesArray = Array<[RegExp, string]>;\ntype DefaultRulesType = {\n plurals: RulesArray;\n singular: RulesArray;\n irregularPairs: Array<[string, string]>;\n uncountable: string[];\n};\n\nexport const defaultRules: DefaultRulesType = {\n plurals: [\n [/$/, 's'],\n [/s$/i, 's'],\n [/^(ax|test)is$/i, '$1es'],\n [/(octop|vir)us$/i, '$1i'],\n [/(octop|vir)i$/i, '$1i'],\n [/(alias|status|bonus)$/i, '$1es'],\n [/(tu|bu)s$/i, '$1ses'],\n [/(buffal|tomat)o$/i, '$1oes'],\n [/([ti])um$/i, '$1a'],\n [/([ti])a$/i, '$1a'],\n [/sis$/i, 'ses'],\n [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],\n [/(hive)$/i, '$1s'],\n [/([^aeiouy]|qu)y$/i, '$1ies'],\n [/(x|ch|ss|sh)$/i, '$1es'],\n [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],\n [/^(m|l)ouse$/i, '$1ice'],\n [/^(m|l)ice$/i, '$1ice'],\n [/^(ox)$/i, '$1en'],\n [/^(oxen)$/i, '$1'],\n [/(quiz)$/i, '$1zes'],\n ],\n\n singular: [\n [/s$/i, ''],\n [/(ss)$/i, '$1'],\n [/(n)ews$/i, '$1ews'],\n [/([ti])a$/i, '$1um'],\n [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'],\n [/(^analy)(sis|ses)$/i, '$1sis'],\n [/([^f])ves$/i, '$1fe'],\n [/(hive)s$/i, '$1'],\n [/(tive)s$/i, '$1'],\n [/([lr])ves$/i, '$1f'],\n [/([^aeiouy]|qu)ies$/i, '$1y'],\n [/(s)eries$/i, '$1eries'],\n [/(m)ovies$/i, '$1ovie'],\n [/(x|ch|ss|sh)es$/i, '$1'],\n [/^(m|l)ice$/i, '$1ouse'],\n [/(tus|bus)(es)?$/i, '$1'],\n [/(o)es$/i, '$1'],\n [/(shoe)s$/i, '$1'],\n [/(cris|test)(is|es)$/i, '$1is'],\n [/^(a)x[ie]s$/i, '$1xis'],\n [/(octop|vir)(us|i)$/i, '$1us'],\n [/(alias|status|bonus)(es)?$/i, '$1'],\n [/^(ox)en/i, '$1'],\n [/(vert|ind)ices$/i, '$1ex'],\n [/(matr)ices$/i, '$1ix'],\n [/(quiz)zes$/i, '$1'],\n [/(database)s$/i, '$1'],\n ],\n\n irregularPairs: [\n ['person', 'people'],\n ['man', 'men'],\n ['child', 'children'],\n ['sex', 'sexes'],\n ['move', 'moves'],\n ['cow', 'kine'],\n ['zombie', 'zombies'],\n ],\n\n uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police'],\n};\n","import { dasherize as internalDasherize, LRUCache, STRING_DASHERIZE_CACHE } from '@warp-drive-mirror/core/utils/string';\n\n// eslint-disable-next-line no-useless-escape\nconst STRING_CAMELIZE_REGEXP_1 = /(\\-|\\_|\\.|\\s)+(.)?/g;\nconst STRING_CAMELIZE_REGEXP_2 = /(^|\\/)([A-Z])/g;\nconst CAMELIZE_CACHE = new LRUCache<string, string>((key: string) =>\n key\n .replace(STRING_CAMELIZE_REGEXP_1, (_match, _separator, chr: string | null) => (chr ? chr.toUpperCase() : ''))\n .replace(STRING_CAMELIZE_REGEXP_2, (match /*, separator, chr */) => match.toLowerCase())\n);\n\nconst STRING_UNDERSCORE_REGEXP_1 = /([a-z\\d])([A-Z]+)/g;\n// eslint-disable-next-line no-useless-escape\nconst STRING_UNDERSCORE_REGEXP_2 = /\\-|\\s+/g;\nconst UNDERSCORE_CACHE = new LRUCache<string, string>((str: string) =>\n str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase()\n);\n\nconst STRING_CAPITALIZE_REGEXP = /(^|\\/)([a-z\\u00C0-\\u024F])/g;\nconst CAPITALIZE_CACHE = new LRUCache<string, string>((str: string) =>\n str.replace(STRING_CAPITALIZE_REGEXP, (match /*, separator, chr */) => match.toUpperCase())\n);\n\n/**\n * Replaces underscores, spaces, or camelCase with dashes.\n *\n * ```js\n * import { dasherize } from '@warp-drive-mirror/utilities/string';\n *\n * dasherize('innerHTML'); // 'inner-html'\n * dasherize('action_name'); // 'action-name'\n * dasherize('css-class-name'); // 'css-class-name'\n * dasherize('my favorite items'); // 'my-favorite-items'\n * dasherize('privateDocs/ownerInvoice'; // 'private-docs/owner-invoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport const dasherize: (str: string) => string = internalDasherize;\n\n/**\n * Returns the lowerCamelCase form of a string.\n *\n * ```js\n * import { camelize } from '@warp-drive-mirror/utilities/string';\n *\n * camelize('innerHTML'); // 'innerHTML'\n * camelize('action_name'); // 'actionName'\n * camelize('css-class-name'); // 'cssClassName'\n * camelize('my favorite items'); // 'myFavoriteItems'\n * camelize('My Favorite Items'); // 'myFavoriteItems'\n * camelize('private-docs/owner-invoice'); // 'privateDocs/ownerInvoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport function camelize(str: string): string {\n return CAMELIZE_CACHE.get(str);\n}\n\n/**\n * Returns the lower\\_case\\_and\\_underscored form of a string.\n *\n * ```js\n * import { underscore } from '@warp-drive-mirror/utilities/string';\n *\n * underscore('innerHTML'); // 'inner_html'\n * underscore('action_name'); // 'action_name'\n * underscore('css-class-name'); // 'css_class_name'\n * underscore('my favorite items'); // 'my_favorite_items'\n * underscore('privateDocs/ownerInvoice'); // 'private_docs/owner_invoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport function underscore(str: string): string {\n return UNDERSCORE_CACHE.get(str);\n}\n\n/**\n * Returns the Capitalized form of a string\n *\n * ```js\n * import { capitalize } from '@warp-drive-mirror/utilities/string';\n *\n * capitalize('innerHTML') // 'InnerHTML'\n * capitalize('action_name') // 'Action_name'\n * capitalize('css-class-name') // 'Css-class-name'\n * capitalize('my favorite items') // 'My favorite items'\n * capitalize('privateDocs/ownerInvoice'); // 'PrivateDocs/ownerInvoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport function capitalize(str: string): string {\n return CAPITALIZE_CACHE.get(str);\n}\n\n/**\n * Sets the maximum size of the LRUCache for all string transformation functions.\n * The default size is 10,000.\n *\n * @public\n * @since 4.13.0\n */\nexport function setMaxLRUCacheSize(size: number): void {\n CAMELIZE_CACHE.size = size;\n UNDERSCORE_CACHE.size = size;\n CAPITALIZE_CACHE.size = size;\n STRING_DASHERIZE_CACHE.size = size;\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { LRUCache } from '@warp-drive-mirror/core/utils/string';\n\nimport { defaultRules } from './inflections.ts';\nimport { capitalize } from './transform.ts';\n\nconst BLANK_REGEX = /^\\s*$/;\nconst LAST_WORD_DASHED_REGEX = /([\\w/-]+[_/\\s-])([a-z\\d]+$)/;\nconst LAST_WORD_CAMELIZED_REGEX = /([\\w/\\s-]+)([A-Z][a-z\\d]*$)/;\nconst CAMELIZED_REGEX = /[A-Z][a-z\\d]*$/;\n\nconst SINGULARS = new LRUCache<string, string>((word: string) => {\n return _singularize(word);\n});\nconst PLURALS = new LRUCache<string, string>((word: string) => {\n return _pluralize(word);\n});\nconst UNCOUNTABLE = new Set(defaultRules.uncountable);\nconst IRREGULAR: Map<string, string> = new Map();\nconst INVERSE_IRREGULAR: Map<string, string> = new Map();\nconst SINGULAR_RULES = new Map(defaultRules.singular.reverse());\nconst PLURAL_RULES = new Map(defaultRules.plurals.reverse());\n\n/**\n * Marks a word as uncountable. Uncountable words are not pluralized\n * or singularized.\n *\n * @public\n * @since 4.13.0\n */\nexport function uncountable(word: string): void {\n UNCOUNTABLE.add(word.toLowerCase());\n}\n\n/**\n * Marks a list of words as uncountable. Uncountable words are not pluralized\n * or singularized.\n *\n * @public\n * @since 4.13.0\n */\nexport function loadUncountable(uncountables: string[]): void {\n uncountables.forEach((word) => {\n uncountable(word);\n });\n}\n\n/**\n * Marks a word as irregular. Irregular words have unique\n * pluralization and singularization rules.\n *\n * @public\n * @since 4.13.0\n */\nexport function irregular(single: string, plur: string): void {\n //pluralizing\n IRREGULAR.set(single.toLowerCase(), plur);\n IRREGULAR.set(plur.toLowerCase(), plur);\n\n //singularizing\n INVERSE_IRREGULAR.set(plur.toLowerCase(), single);\n INVERSE_IRREGULAR.set(single.toLowerCase(), single);\n}\n\n/**\n * Marks a list of word pairs as irregular. Irregular words have unique\n * pluralization and singularization rules.\n *\n * @public\n * @since 4.13.0\n */\nexport function loadIrregular(irregularPairs: Array<[string, string]>): void {\n irregularPairs.forEach((pair) => {\n //pluralizing\n IRREGULAR.set(pair[0].toLowerCase(), pair[1]);\n IRREGULAR.set(pair[1].toLowerCase(), pair[1]);\n\n //singularizing\n INVERSE_IRREGULAR.set(pair[1].toLowerCase(), pair[0]);\n INVERSE_IRREGULAR.set(pair[0].toLowerCase(), pair[0]);\n });\n}\nloadIrregular(defaultRules.irregularPairs);\n\n/**\n * Clears the caches for singularize and pluralize.\n *\n * @public\n * @since 4.13.0\n */\nexport function clear(): void {\n SINGULARS.clear();\n PLURALS.clear();\n}\n\n/**\n * Resets the inflection rules to the defaults.\n *\n * @public\n * @since 4.13.0\n */\nexport function resetToDefaults(): void {\n clearRules();\n defaultRules.uncountable.forEach((v) => UNCOUNTABLE.add(v));\n defaultRules.singular.forEach((v) => SINGULAR_RULES.set(v[0], v[1]));\n defaultRules.plurals.forEach((v) => PLURAL_RULES.set(v[0], v[1]));\n loadIrregular(defaultRules.irregularPairs);\n}\n\n/**\n * Clears all inflection rules\n * and resets the caches for singularize and pluralize.\n *\n * @public\n * @since 4.13.0\n */\nexport function clearRules(): void {\n SINGULARS.clear();\n PLURALS.clear();\n UNCOUNTABLE.clear();\n IRREGULAR.clear();\n INVERSE_IRREGULAR.clear();\n SINGULAR_RULES.clear();\n PLURAL_RULES.clear();\n}\n\n/**\n * Singularizes a word.\n *\n * @public\n * @since 4.13.0\n */\nexport function singularize(word: string): string {\n assert(`singularize expects to receive a non-empty string`, typeof word === 'string' && word.length > 0);\n if (!word) return '';\n return SINGULARS.get(word);\n}\n\n/**\n * Pluralizes a word.\n *\n * @public\n * @since 4.13.0\n */\nexport function pluralize(word: string): string {\n assert(`pluralize expects to receive a non-empty string`, typeof word === 'string' && word.length > 0);\n if (!word) return '';\n return PLURALS.get(word);\n}\n\nfunction unshiftMap<K, V>(v: [K, V], map: Map<K, V>) {\n // reorder\n const rules = [v, ...map.entries()];\n map.clear();\n rules.forEach((rule) => {\n map.set(rule[0], rule[1]);\n });\n}\n\n/**\n * Adds a pluralization rule.\n *\n * @public\n * @since 4.13.0\n */\nexport function plural(regex: RegExp, string: string): void {\n // rule requires reordering if exists, so remove it first\n if (PLURAL_RULES.has(regex)) {\n PLURAL_RULES.delete(regex);\n }\n\n // reorder\n unshiftMap([regex, string], PLURAL_RULES);\n}\n\n/**\n * Adds a singularization rule.\n *\n * @public\n * @since 4.13.0\n */\nexport function singular(regex: RegExp, string: string): void {\n // rule requires reordering if exists, so remove it first\n if (SINGULAR_RULES.has(regex)) {\n SINGULAR_RULES.delete(regex);\n }\n\n // reorder\n unshiftMap([regex, string], SINGULAR_RULES);\n}\n\nfunction _pluralize(word: string) {\n return inflect(word, PLURAL_RULES, IRREGULAR);\n}\n\nfunction _singularize(word: string) {\n return inflect(word, SINGULAR_RULES, INVERSE_IRREGULAR);\n}\n\nfunction inflect(word: string, typeRules: Map<RegExp, string>, irregulars: Map<string, string>) {\n // empty strings\n const isBlank = !word || BLANK_REGEX.test(word);\n if (isBlank) {\n return word;\n }\n\n // basic uncountables\n const lowercase = word.toLowerCase();\n if (UNCOUNTABLE.has(lowercase)) {\n return word;\n }\n\n // adv uncountables\n const wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word);\n const lastWord = wordSplit ? wordSplit[2].toLowerCase() : null;\n if (lastWord && UNCOUNTABLE.has(lastWord)) {\n return word;\n }\n\n // handle irregulars\n const isCamelized = CAMELIZED_REGEX.test(word);\n for (let [rule, substitution] of irregulars) {\n if (lowercase.match(rule + '$')) {\n if (isCamelized && lastWord && irregulars.has(lastWord)) {\n substitution = capitalize(substitution);\n rule = capitalize(rule);\n }\n\n return word.replace(new RegExp(rule, 'i'), substitution);\n }\n }\n\n // do the actual inflection\n for (const [rule, substitution] of typeRules) {\n if (rule.test(word)) {\n return word.replace(rule, substitution);\n }\n }\n\n return word;\n}\n"],"x_google_ignoreList":[0],"mappings":";;AAEA,MAAMA,yBAAyB;;;;;;;;;;;;;;;;;;;;;AAsB/B,IAAaC,WAAb,MAA4B;CAU1BC,YAAYC,QAAqBC,MAAe;EAC9C,KAAKA,OAAOA,QAAQJ;EACpB,KAAKK,wBAAQ,IAAIC,IAAI;EACrB,KAAKH,SAASA;CAOhB;CAEAI,IAAIC,KAAW;EACb,MAAMC,QAAQ,KAAKJ,MAAME,IAAIC,GAAG;EAChC,IAAIC,OAAO;GAIT,KAAKJ,MAAMK,OAAOF,GAAG;GACrB,KAAKH,MAAMM,IAAIH,KAAKC,KAAK;GACzB,OAAOA;EACT;EAKA,MAAMG,WAAW,KAAKT,OAAOK,GAAG;EAChC,KAAKG,IAAIH,KAAKI,QAAQ;EACtB,OAAOA;CACT;CAEAD,IAAIH,KAAQC,OAAgB;EAC1B,IAAI,KAAKJ,MAAMD,SAAS,KAAKA,MAC3B,KAAK,MAAM,CAACS,MAAM,KAAKR,OAAO;GAI5B,KAAKA,MAAMK,OAAOG,CAAC;GACnB;EACF;EAEF,KAAKR,MAAMM,IAAIH,KAAKC,KAAK;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AAMjB,OAAO,GAAG,GAAG;EAC/B,IAAIe,eAAeD,YAAYN,WAAWJ,IAAIU,QAAQ,GAAG;GACvDE,eAAe5D,WAAW4D,YAAY;GACtChB,OAAO5C,WAAW4C,IAAI;EACxB;EAEA,OAAOtC,KAAKwD,QAAQ,IAAIC,OAAOnB,MAAM,GAAG,GAAGgB,YAAY;CACzD;CAIF,KAAK,MAAM,CAAChB,MAAMgB,iBAAiBT,WACjC,IAAIP,KAAKU,KAAKhD,IAAI,GAChB,OAAOA,KAAKwD,QAAQlB,MAAMgB,YAAY;CAI1C,OAAOtD;AACT"}
1
+ {"version":3,"file":"string.cjs","names":["DEFAULT_MAX_CACHE_SIZE","LRUCache","constructor","doWork","size","state","Map","get","key","value","delete","set","newValue","k","clear","STRING_DASHERIZE_REGEXP","STRING_DECAMELIZE_REGEXP","STRING_DASHERIZE_CACHE","replace","toLowerCase","dasherize","str","internalDasherize","LRUCache","defaultRules","capitalize","BLANK_REGEX","LAST_WORD_DASHED_REGEX","LAST_WORD_CAMELIZED_REGEX","CAMELIZED_REGEX","SINGULARS","word","_singularize","PLURALS","_pluralize","UNCOUNTABLE","Set","uncountable","IRREGULAR","Map","INVERSE_IRREGULAR","SINGULAR_RULES","singular","reverse","PLURAL_RULES","plurals","add","toLowerCase","loadUncountable","uncountables","forEach","irregular","single","plur","set","loadIrregular","irregularPairs","pair","clear","resetToDefaults","clearRules","v","singularize","get","pluralize","unshiftMap","map","rules","entries","rule","plural","regex","string","has","delete","inflect","typeRules","irregulars","isBlank","test","lowercase","wordSplit","exec","lastWord","isCamelized","substitution","match","replace","RegExp"],"sources":["../../../node_modules/.pnpm/@warp-d_5e1563e0e582c8365bb74466d3761d6d/node_modules/@warp-drive-mirror/core/dist/utils/string.js","../src/-private/string/inflections.ts","../src/-private/string/transform.ts","../src/-private/string/inflect.ts"],"sourcesContent":["import { DEBUG } from '@warp-drive-mirror/core/build-config/env';\n\nconst DEFAULT_MAX_CACHE_SIZE = 10_000;\n\n/**\n * An LRUCache implementation with upsert semantics.\n *\n * This implementation is *not* generic, but focuses on\n * performance tuning for the string transformation cases\n * where the key maps to the value very simply.\n *\n * It takes a work function that should generate a new value\n * for a given key when called. It will be called when the key\n * is not found in the cache.\n *\n * It keeps track of the number of hits, misses, and ejections\n * in DEBUG envs, which is useful for tuning the cache size.\n *\n * This is an internal utility class for use by this module\n * and by `@warp-drive-mirror/utilities/string`. It is not intended\n * for use outside of these modules at this time.\n *\n * @private\n */\nexport class LRUCache<T, V> {\n declare size: number;\n declare state: Map<T, V>;\n declare doWork: (k: T) => V;\n\n // debug stats\n declare _hits: number;\n declare _misses: number;\n declare _ejected: number;\n\n constructor(doWork: (k: T) => V, size?: number) {\n this.size = size || DEFAULT_MAX_CACHE_SIZE;\n this.state = new Map();\n this.doWork = doWork;\n\n if (DEBUG) {\n this._hits = 0;\n this._misses = 0;\n this._ejected = 0;\n }\n }\n\n get(key: T): V {\n const value = this.state.get(key);\n if (value) {\n if (DEBUG) {\n this._hits++;\n }\n this.state.delete(key);\n this.state.set(key, value);\n return value;\n }\n if (DEBUG) {\n this._misses++;\n }\n\n const newValue = this.doWork(key);\n this.set(key, newValue);\n return newValue;\n }\n\n set(key: T, value: V): void {\n if (this.state.size === this.size) {\n for (const [k] of this.state) {\n if (DEBUG) {\n this._ejected++;\n }\n this.state.delete(k);\n break;\n }\n }\n this.state.set(key, value);\n }\n\n clear(): void {\n this.state.clear();\n if (DEBUG) {\n this._hits = 0;\n this._misses = 0;\n this._ejected = 0;\n }\n }\n}\n\nconst STRING_DASHERIZE_REGEXP = /[ _]/g;\nconst STRING_DECAMELIZE_REGEXP = /([a-z\\d])([A-Z])/g;\n/**\n * The {@link LRUCache} backing {@link dasherize}, keyed by the original\n * (un-dasherized) string.\n *\n * @private\n */\nexport const STRING_DASHERIZE_CACHE: LRUCache<string, string> = new LRUCache<string, string>((key: string) =>\n key.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase().replace(STRING_DASHERIZE_REGEXP, '-')\n);\n\n/**\n * This is an internal utility function that converts a string\n * to a dasherized format. Library consumers should use the\n * re-exported version from `@warp-drive-mirror/utilities/string` instead.\n *\n * This version is only in this location to support a deprecated\n * behavior in the core package and will be removed in a future.\n *\n * @private\n */\nexport function dasherize(str: string): string {\n return STRING_DASHERIZE_CACHE.get(str);\n}\n","export type RulesArray = Array<[RegExp, string]>;\ntype DefaultRulesType = {\n plurals: RulesArray;\n singular: RulesArray;\n irregularPairs: Array<[string, string]>;\n uncountable: string[];\n};\n\nexport const defaultRules: DefaultRulesType = {\n plurals: [\n [/$/, 's'],\n [/s$/i, 's'],\n [/^(ax|test)is$/i, '$1es'],\n [/(octop|vir)us$/i, '$1i'],\n [/(octop|vir)i$/i, '$1i'],\n [/(alias|status|bonus)$/i, '$1es'],\n [/(tu|bu)s$/i, '$1ses'],\n [/(buffal|tomat)o$/i, '$1oes'],\n [/([ti])um$/i, '$1a'],\n [/([ti])a$/i, '$1a'],\n [/sis$/i, 'ses'],\n [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],\n [/(hive)$/i, '$1s'],\n [/([^aeiouy]|qu)y$/i, '$1ies'],\n [/(x|ch|ss|sh)$/i, '$1es'],\n [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],\n [/^(m|l)ouse$/i, '$1ice'],\n [/^(m|l)ice$/i, '$1ice'],\n [/^(ox)$/i, '$1en'],\n [/^(oxen)$/i, '$1'],\n [/(quiz)$/i, '$1zes'],\n ],\n\n singular: [\n [/s$/i, ''],\n [/(ss)$/i, '$1'],\n [/(n)ews$/i, '$1ews'],\n [/([ti])a$/i, '$1um'],\n [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'],\n [/(^analy)(sis|ses)$/i, '$1sis'],\n [/([^f])ves$/i, '$1fe'],\n [/(hive)s$/i, '$1'],\n [/(tive)s$/i, '$1'],\n [/([lr])ves$/i, '$1f'],\n [/([^aeiouy]|qu)ies$/i, '$1y'],\n [/(s)eries$/i, '$1eries'],\n [/(m)ovies$/i, '$1ovie'],\n [/(x|ch|ss|sh)es$/i, '$1'],\n [/^(m|l)ice$/i, '$1ouse'],\n [/(tus|bus)(es)?$/i, '$1'],\n [/(o)es$/i, '$1'],\n [/(shoe)s$/i, '$1'],\n [/(cris|test)(is|es)$/i, '$1is'],\n [/^(a)x[ie]s$/i, '$1xis'],\n [/(octop|vir)(us|i)$/i, '$1us'],\n [/(alias|status|bonus)(es)?$/i, '$1'],\n [/^(ox)en/i, '$1'],\n [/(vert|ind)ices$/i, '$1ex'],\n [/(matr)ices$/i, '$1ix'],\n [/(quiz)zes$/i, '$1'],\n [/(database)s$/i, '$1'],\n ],\n\n irregularPairs: [\n ['person', 'people'],\n ['man', 'men'],\n ['child', 'children'],\n ['sex', 'sexes'],\n ['move', 'moves'],\n ['cow', 'kine'],\n ['zombie', 'zombies'],\n ],\n\n uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police'],\n};\n","import { dasherize as internalDasherize, LRUCache, STRING_DASHERIZE_CACHE } from '@warp-drive-mirror/core/utils/string';\n\n// eslint-disable-next-line no-useless-escape\nconst STRING_CAMELIZE_REGEXP_1 = /(\\-|\\_|\\.|\\s)+(.)?/g;\nconst STRING_CAMELIZE_REGEXP_2 = /(^|\\/)([A-Z])/g;\nconst CAMELIZE_CACHE = new LRUCache<string, string>((key: string) =>\n key\n .replace(STRING_CAMELIZE_REGEXP_1, (_match, _separator, chr: string | null) => (chr ? chr.toUpperCase() : ''))\n .replace(STRING_CAMELIZE_REGEXP_2, (match /*, separator, chr */) => match.toLowerCase())\n);\n\nconst STRING_UNDERSCORE_REGEXP_1 = /([a-z\\d])([A-Z]+)/g;\n// eslint-disable-next-line no-useless-escape\nconst STRING_UNDERSCORE_REGEXP_2 = /\\-|\\s+/g;\nconst UNDERSCORE_CACHE = new LRUCache<string, string>((str: string) =>\n str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2').replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase()\n);\n\nconst STRING_CAPITALIZE_REGEXP = /(^|\\/)([a-z\\u00C0-\\u024F])/g;\nconst CAPITALIZE_CACHE = new LRUCache<string, string>((str: string) =>\n str.replace(STRING_CAPITALIZE_REGEXP, (match /*, separator, chr */) => match.toUpperCase())\n);\n\n/**\n * Replaces underscores, spaces, or camelCase with dashes.\n *\n * ```js\n * import { dasherize } from '@warp-drive-mirror/utilities/string';\n *\n * dasherize('innerHTML'); // 'inner-html'\n * dasherize('action_name'); // 'action-name'\n * dasherize('css-class-name'); // 'css-class-name'\n * dasherize('my favorite items'); // 'my-favorite-items'\n * dasherize('privateDocs/ownerInvoice'; // 'private-docs/owner-invoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport const dasherize: (str: string) => string = internalDasherize;\n\n/**\n * Returns the lowerCamelCase form of a string.\n *\n * ```js\n * import { camelize } from '@warp-drive-mirror/utilities/string';\n *\n * camelize('innerHTML'); // 'innerHTML'\n * camelize('action_name'); // 'actionName'\n * camelize('css-class-name'); // 'cssClassName'\n * camelize('my favorite items'); // 'myFavoriteItems'\n * camelize('My Favorite Items'); // 'myFavoriteItems'\n * camelize('private-docs/owner-invoice'); // 'privateDocs/ownerInvoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport function camelize(str: string): string {\n return CAMELIZE_CACHE.get(str);\n}\n\n/**\n * Returns the lower\\_case\\_and\\_underscored form of a string.\n *\n * ```js\n * import { underscore } from '@warp-drive-mirror/utilities/string';\n *\n * underscore('innerHTML'); // 'inner_html'\n * underscore('action_name'); // 'action_name'\n * underscore('css-class-name'); // 'css_class_name'\n * underscore('my favorite items'); // 'my_favorite_items'\n * underscore('privateDocs/ownerInvoice'); // 'private_docs/owner_invoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport function underscore(str: string): string {\n return UNDERSCORE_CACHE.get(str);\n}\n\n/**\n * Returns the Capitalized form of a string\n *\n * ```js\n * import { capitalize } from '@warp-drive-mirror/utilities/string';\n *\n * capitalize('innerHTML') // 'InnerHTML'\n * capitalize('action_name') // 'Action_name'\n * capitalize('css-class-name') // 'Css-class-name'\n * capitalize('my favorite items') // 'My favorite items'\n * capitalize('privateDocs/ownerInvoice'); // 'PrivateDocs/ownerInvoice'\n * ```\n *\n * @public\n * @since 4.13.0\n */\nexport function capitalize(str: string): string {\n return CAPITALIZE_CACHE.get(str);\n}\n\n/**\n * Sets the maximum size of the LRUCache for all string transformation functions.\n * The default size is 10,000.\n *\n * @public\n * @since 4.13.0\n */\nexport function setMaxLRUCacheSize(size: number): void {\n CAMELIZE_CACHE.size = size;\n UNDERSCORE_CACHE.size = size;\n CAPITALIZE_CACHE.size = size;\n STRING_DASHERIZE_CACHE.size = size;\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport { LRUCache } from '@warp-drive-mirror/core/utils/string';\n\nimport { defaultRules } from './inflections.ts';\nimport { capitalize } from './transform.ts';\n\nconst BLANK_REGEX = /^\\s*$/;\nconst LAST_WORD_DASHED_REGEX = /([\\w/-]+[_/\\s-])([a-z\\d]+$)/;\nconst LAST_WORD_CAMELIZED_REGEX = /([\\w/\\s-]+)([A-Z][a-z\\d]*$)/;\nconst CAMELIZED_REGEX = /[A-Z][a-z\\d]*$/;\n\nconst SINGULARS = new LRUCache<string, string>((word: string) => {\n return _singularize(word);\n});\nconst PLURALS = new LRUCache<string, string>((word: string) => {\n return _pluralize(word);\n});\nconst UNCOUNTABLE = new Set(defaultRules.uncountable);\nconst IRREGULAR: Map<string, string> = new Map();\nconst INVERSE_IRREGULAR: Map<string, string> = new Map();\nconst SINGULAR_RULES = new Map(defaultRules.singular.reverse());\nconst PLURAL_RULES = new Map(defaultRules.plurals.reverse());\n\n/**\n * Marks a word as uncountable. Uncountable words are not pluralized\n * or singularized.\n *\n * @public\n * @since 4.13.0\n */\nexport function uncountable(word: string): void {\n UNCOUNTABLE.add(word.toLowerCase());\n}\n\n/**\n * Marks a list of words as uncountable. Uncountable words are not pluralized\n * or singularized.\n *\n * @public\n * @since 4.13.0\n */\nexport function loadUncountable(uncountables: string[]): void {\n uncountables.forEach((word) => {\n uncountable(word);\n });\n}\n\n/**\n * Marks a word as irregular. Irregular words have unique\n * pluralization and singularization rules.\n *\n * @public\n * @since 4.13.0\n */\nexport function irregular(single: string, plur: string): void {\n //pluralizing\n IRREGULAR.set(single.toLowerCase(), plur);\n IRREGULAR.set(plur.toLowerCase(), plur);\n\n //singularizing\n INVERSE_IRREGULAR.set(plur.toLowerCase(), single);\n INVERSE_IRREGULAR.set(single.toLowerCase(), single);\n}\n\n/**\n * Marks a list of word pairs as irregular. Irregular words have unique\n * pluralization and singularization rules.\n *\n * @public\n * @since 4.13.0\n */\nexport function loadIrregular(irregularPairs: Array<[string, string]>): void {\n irregularPairs.forEach((pair) => {\n //pluralizing\n IRREGULAR.set(pair[0].toLowerCase(), pair[1]);\n IRREGULAR.set(pair[1].toLowerCase(), pair[1]);\n\n //singularizing\n INVERSE_IRREGULAR.set(pair[1].toLowerCase(), pair[0]);\n INVERSE_IRREGULAR.set(pair[0].toLowerCase(), pair[0]);\n });\n}\nloadIrregular(defaultRules.irregularPairs);\n\n/**\n * Clears the caches for singularize and pluralize.\n *\n * @public\n * @since 4.13.0\n */\nexport function clear(): void {\n SINGULARS.clear();\n PLURALS.clear();\n}\n\n/**\n * Resets the inflection rules to the defaults.\n *\n * @public\n * @since 4.13.0\n */\nexport function resetToDefaults(): void {\n clearRules();\n defaultRules.uncountable.forEach((v) => UNCOUNTABLE.add(v));\n defaultRules.singular.forEach((v) => SINGULAR_RULES.set(v[0], v[1]));\n defaultRules.plurals.forEach((v) => PLURAL_RULES.set(v[0], v[1]));\n loadIrregular(defaultRules.irregularPairs);\n}\n\n/**\n * Clears all inflection rules\n * and resets the caches for singularize and pluralize.\n *\n * @public\n * @since 4.13.0\n */\nexport function clearRules(): void {\n SINGULARS.clear();\n PLURALS.clear();\n UNCOUNTABLE.clear();\n IRREGULAR.clear();\n INVERSE_IRREGULAR.clear();\n SINGULAR_RULES.clear();\n PLURAL_RULES.clear();\n}\n\n/**\n * Singularizes a word.\n *\n * @public\n * @since 4.13.0\n */\nexport function singularize(word: string): string {\n assert(`singularize expects to receive a non-empty string`, typeof word === 'string' && word.length > 0);\n if (!word) return '';\n return SINGULARS.get(word);\n}\n\n/**\n * Pluralizes a word.\n *\n * @public\n * @since 4.13.0\n */\nexport function pluralize(word: string): string {\n assert(`pluralize expects to receive a non-empty string`, typeof word === 'string' && word.length > 0);\n if (!word) return '';\n return PLURALS.get(word);\n}\n\nfunction unshiftMap<K, V>(v: [K, V], map: Map<K, V>) {\n // reorder\n const rules = [v, ...map.entries()];\n map.clear();\n rules.forEach((rule) => {\n map.set(rule[0], rule[1]);\n });\n}\n\n/**\n * Adds a pluralization rule.\n *\n * @public\n * @since 4.13.0\n */\nexport function plural(regex: RegExp, string: string): void {\n // rule requires reordering if exists, so remove it first\n if (PLURAL_RULES.has(regex)) {\n PLURAL_RULES.delete(regex);\n }\n\n // reorder\n unshiftMap([regex, string], PLURAL_RULES);\n}\n\n/**\n * Adds a singularization rule.\n *\n * @public\n * @since 4.13.0\n */\nexport function singular(regex: RegExp, string: string): void {\n // rule requires reordering if exists, so remove it first\n if (SINGULAR_RULES.has(regex)) {\n SINGULAR_RULES.delete(regex);\n }\n\n // reorder\n unshiftMap([regex, string], SINGULAR_RULES);\n}\n\nfunction _pluralize(word: string) {\n return inflect(word, PLURAL_RULES, IRREGULAR);\n}\n\nfunction _singularize(word: string) {\n return inflect(word, SINGULAR_RULES, INVERSE_IRREGULAR);\n}\n\nfunction inflect(word: string, typeRules: Map<RegExp, string>, irregulars: Map<string, string>) {\n // empty strings\n const isBlank = !word || BLANK_REGEX.test(word);\n if (isBlank) {\n return word;\n }\n\n // basic uncountables\n const lowercase = word.toLowerCase();\n if (UNCOUNTABLE.has(lowercase)) {\n return word;\n }\n\n // adv uncountables\n const wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word);\n const lastWord = wordSplit ? wordSplit[2].toLowerCase() : null;\n if (lastWord && UNCOUNTABLE.has(lastWord)) {\n return word;\n }\n\n // handle irregulars\n const isCamelized = CAMELIZED_REGEX.test(word);\n for (let [rule, substitution] of irregulars) {\n if (lowercase.match(rule + '$')) {\n if (isCamelized && lastWord && irregulars.has(lastWord)) {\n substitution = capitalize(substitution);\n rule = capitalize(rule);\n }\n\n return word.replace(new RegExp(rule, 'i'), substitution);\n }\n }\n\n // do the actual inflection\n for (const [rule, substitution] of typeRules) {\n if (rule.test(word)) {\n return word.replace(rule, substitution);\n }\n }\n\n return word;\n}\n"],"x_google_ignoreList":[0],"mappings":";;AAEA,MAAMA,yBAAyB;;;;;;;;;;;;;;;;;;;;;AAsB/B,IAAaC,WAAb,MAA4B;CAU1BC,YAAYC,QAAqBC,MAAe;EAC9C,KAAKA,OAAOA,QAAQJ;EACpB,KAAKK,wBAAQ,IAAIC,IAAI;EACrB,KAAKH,SAASA;CAOhB;CAEAI,IAAIC,KAAW;EACb,MAAMC,QAAQ,KAAKJ,MAAME,IAAIC,GAAG;EAChC,IAAIC,OAAO;GAIT,KAAKJ,MAAMK,OAAOF,GAAG;GACrB,KAAKH,MAAMM,IAAIH,KAAKC,KAAK;GACzB,OAAOA;EACT;EAKA,MAAMG,WAAW,KAAKT,OAAOK,GAAG;EAChC,KAAKG,IAAIH,KAAKI,QAAQ;EACtB,OAAOA;CACT;CAEAD,IAAIH,KAAQC,OAAgB;EAC1B,IAAI,KAAKJ,MAAMD,SAAS,KAAKA,MAC3B,KAAK,MAAM,CAACS,MAAM,KAAKR,OAAO;GAI5B,KAAKA,MAAMK,OAAOG,CAAC;GACnB;EACF;EAEF,KAAKR,MAAMM,IAAIH,KAAKC,KAAK;CAC3B;CAEAK,QAAc;EACZ,KAAKT,MAAMS,MAAM;CAMnB;AACF;AAEA,MAAMC,0BAA0B;AAChC,MAAMC,2BA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,WAAW4D,YAAY;GACtChB,OAAO5C,WAAW4C,IAAI;EACxB;EAEA,OAAOtC,KAAKwD,QAAQ,IAAIC,OAAOnB,MAAM,GAAG,GAAGgB,YAAY;CACzD;CAIF,KAAK,MAAM,CAAChB,MAAMgB,iBAAiBT,WACjC,IAAIP,KAAKU,KAAKhD,IAAI,GAChB,OAAOA,KAAKwD,QAAQlB,MAAMgB,YAAY;CAI1C,OAAOtD;AACT"}
@@ -3,7 +3,6 @@ import { ReactiveDataDocument } from "@warp-drive-mirror/core/reactive";
3
3
  import { TypeFromInstance, TypedRecordInstance } from "@warp-drive-mirror/core/types/record";
4
4
  import { ConstrainedRequestOptions, CreateRequestOptions, DeleteRequestOptions, FindRecordOptions, FindRecordRequestOptions, PostQueryRequestOptions, QueryRequestOptions, RemotelyAccessibleIdentifier, UpdateRequestOptions } from "@warp-drive-mirror/core/types/request";
5
5
  import { QueryParamsSource } from "@warp-drive-mirror/core/types/params";
6
- import { ReactiveDataDocument as ReactiveDataDocument$1 } from "@warp-drive-mirror/core/reactive.js";
7
6
  import { Cache } from "@warp-drive-mirror/core/types/cache";
8
7
  import { ResourceKey } from "@warp-drive-mirror/core/types/identifier";
9
8
  import { Value } from "@warp-drive-mirror/core/types/json/raw";
@@ -359,7 +358,7 @@ declare function createRecord(record: unknown, options?: ConstrainedRequestOptio
359
358
  */
360
359
  declare function updateRecord<T extends TypedRecordInstance, RT extends TypedRecordInstance = T>(record: T, options?: ConstrainedRequestOptions & {
361
360
  patch?: boolean;
362
- }): UpdateRequestOptions<ReactiveDataDocument$1<RT>, T>;
361
+ }): UpdateRequestOptions<ReactiveDataDocument<RT>, T>;
363
362
  declare function updateRecord(record: unknown, options?: ConstrainedRequestOptions & {
364
363
  patch?: boolean;
365
364
  }): UpdateRequestOptions;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json-api.d.ts","names":[],"sources":["../src/-private/json-api/find-record.ts","../src/-private/json-api/query.ts","../src/-private/json-api/save-record.ts","../src/-private/json-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AAqB,qBAAqB,KAAK;iBAClC,aACd,iBACA,UAAU;EAA8B;IACvC;;;KC5PE,0BAA0B;KAEnB;EAEN;EACA;EACA,aAAa,eAAe;EAC5B,gBAAgB,eAAe;;EAG/B;EACA;EACA;EACA,aAAa,eAAe;EAC5B,gBAAgB,eAAe;;;;;;;;;;;;;;;;;iBAkBrB,mBACd,OAAO,OACP,aAAa;;;;EAKb,MAAM;;iBAEQ,mBACd,OAAO,OACP,aAAa;;;;EAKb,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqGQ,eACd,OAAO,OACP,YAAY;;;;EAMZ,MAAM;;;;UC/JS,sBAAsB;EACrC;IACE;;;EAGF;IACE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDY,kBAAkB,QAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"json-api.js","names":["recordIdentifierFor","buildBaseURL","pluralize","copyForwardUrlOptions","ACCEPT_HEADER_VALUE","macroCondition","getGlobalConfig","isExisting","identifier","id","type","deleteRecord","record","options","WarpDrive","env","DEBUG","test","Error","urlOptions","op","resourcePath","url","headers","Headers","append","method","data","records","createRecord","updateRecord","patch","patchRecord","opts","serializeResources","cache","identifiers","data","Array","isArray","map","identifier","_serializeResource","fixRef","id","lid","type","fixRelData","rel","ref","record","structuredClone","peek","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","test","Error","String","relationships","key","Object","keys","relationship","length","serializePatch","hasChangedAttrs","attrsChanges","changedAttrs","attributes","forEach","change","newVal","undefined","changedRelationships","size","diff","localState"],"sources":["../src/-private/json-api/-utils.ts","../src/-private/json-api/find-record.ts","../src/-private/json-api/query.ts","../src/-private/json-api/save-record.ts","../src/-private/json-api/serialize.ts"],"sourcesContent":["import type { QueryParamsSource } from '@warp-drive-mirror/core/types/params';\n\nimport type { BuildURLConfig } from '../../index.ts';\nimport { buildQueryParams as buildParams, setBuildURLConfig as setConfig } from '../../index.ts';\n\nexport interface JSONAPIConfig extends BuildURLConfig {\n profiles?: {\n pagination?: string;\n [key: string]: string | undefined;\n };\n extensions?: {\n atomic?: string;\n [key: string]: string | undefined;\n };\n}\n\nconst JsonApiAccept = 'application/vnd.api+json';\nconst DEFAULT_CONFIG: JSONAPIConfig = { host: '', namespace: '' };\nexport let CONFIG: JSONAPIConfig = DEFAULT_CONFIG;\nexport let ACCEPT_HEADER_VALUE = 'application/vnd.api+json';\n\n/**\n * Allows setting extensions and profiles to be used in the `Accept` header.\n *\n * Extensions and profiles are keyed by their namespace with the value being\n * their URI.\n *\n * Example:\n *\n * ```ts\n * setBuildURLConfig({\n * extensions: {\n * atomic: 'https://jsonapi.org/ext/atomic'\n * },\n * profiles: {\n * pagination: 'https://jsonapi.org/profiles/ethanresnick/cursor-pagination'\n * }\n * });\n * ```\n *\n * This also sets the global configuration for `buildBaseURL`\n * for host and namespace values for the global coniguration\n * done via `import { setBuildURLConfig } from '@warp-drive-mirror/utilities';`\n *\n * These values may still be overridden by passing\n * them to buildBaseURL directly.\n *\n * This method may be called as many times as needed\n *\n * ```ts\n * type BuildURLConfig = {\n * host: string;\n * namespace: string'\n * }\n * ```\n *\n * @public\n * @param {BuildURLConfig} config\n * @return {void}\n */\nexport function setBuildURLConfig(config: JSONAPIConfig): void {\n CONFIG = Object.assign({}, DEFAULT_CONFIG, config);\n\n if (config.profiles || config.extensions) {\n let accept = JsonApiAccept;\n if (config.profiles) {\n const profiles = Object.values(config.profiles);\n if (profiles.length) {\n accept += ';profile=\"' + profiles.join(' ') + '\"';\n }\n }\n if (config.extensions) {\n const extensions = Object.values(config.extensions);\n if (extensions.length) {\n accept += ';ext=' + extensions.join(' ');\n }\n }\n ACCEPT_HEADER_VALUE = accept;\n }\n\n setConfig(config);\n}\n\ninterface RelatedObject {\n [key: string]: string | string[] | RelatedObject;\n}\n\nexport type JsonApiQuery = {\n include?: string | string[] | RelatedObject;\n fields?: Record<string, string | string[]>;\n page?: {\n size?: number;\n after?: string;\n before?: string;\n };\n};\n\nfunction isJsonApiQuery(query: JsonApiQuery | QueryParamsSource): query is JsonApiQuery {\n if ('include' in query && query.include && typeof query.include === 'object') {\n return true;\n }\n if ('fields' in query || 'page' in query) {\n return true;\n }\n return false;\n}\n\nfunction collapseIncludePaths(basePath: string, include: RelatedObject, paths: string[]) {\n const keys = Object.keys(include);\n for (let i = 0; i < keys.length; i++) {\n // the key is always included too\n paths.push(`${basePath}.${keys[i]}`);\n const key = keys[i];\n const value = include[key];\n\n // include: { 'company': 'field1,field2' }\n if (typeof value === 'string') {\n value.split(',').forEach((field) => {\n paths.push(`${basePath}.${key}.${field}`);\n });\n\n // include: { 'company': ['field1', 'field2'] }\n } else if (Array.isArray(value)) {\n value.forEach((field) => {\n paths.push(`${basePath}.${key}.${field}`);\n });\n\n // include: { 'company': { 'nested': 'field1,field2' } }\n } else {\n collapseIncludePaths(`${basePath}.${key}`, value, paths);\n }\n }\n}\n\n/**\n * Sorts query params by both key and value, returning a query params string\n *\n * Treats `included` specially, splicing it into an array if it is a string and sorting the array.\n * - If `included` is an object we build paths dynamically for you\n * Treats `fields` specially, building JSON:API partial fields params from an object\n * Treats `page` specially, building cursor-pagination profile page params from an object\n *\n * ```ts\n * const params = buildQueryParams({\n * include: {\n * company: {\n * locations: 'address'\n * }\n * },\n * fields: {\n * company: ['name', 'ticker'],\n * person: 'name'\n * },\n * page: {\n * size: 10,\n * after: 'abc',\n * }\n * });\n *\n * // => 'fields[company]=name,ticker&fields[person]=name&include=company.locations,company.locations.address&page[after]=abc&page[size]=10'\n * ```\n *\n * Options:\n * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'\n *\n * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`\n * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`\n * 'repeat': appends the key for every value e.g. `ids=1&ids=2`\n * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`\n *\n * @public\n * @param {URLSearchParams | Object} params\n * @param {Object} [options]\n * @return {String} A sorted query params string without the leading `?`\n */\nexport function buildQueryParams(query: JsonApiQuery | QueryParamsSource): string {\n if (query instanceof URLSearchParams) {\n return buildParams(query);\n }\n\n if (!isJsonApiQuery(query)) {\n return buildParams(query);\n }\n\n const { include, fields, page, ...rest } = query;\n const finalQuery: QueryParamsSource = {\n ...rest,\n };\n\n if ('include' in query) {\n // include: { 'company': 'field1,field2' }\n // include: { 'company': ['field1', 'field2'] }\n // include: { 'company': { 'nested': 'field1,field2' } }\n // include: { 'company': { 'nested': ['field1', 'field2'] } }\n if (include && !Array.isArray(include) && typeof include === 'object') {\n const includePaths: string[] = [];\n collapseIncludePaths('', include, includePaths);\n finalQuery.include = includePaths.sort();\n\n // include: 'field1,field2'\n // include: ['field1', 'field2']\n } else {\n finalQuery.include = include as string;\n }\n }\n\n if (fields) {\n const keys = Object.keys(fields).sort();\n for (let i = 0; i < keys.length; i++) {\n const resourceType = keys[i];\n const value = fields[resourceType];\n\n // fields: { 'company': ['field1', 'field2'] }\n if (Array.isArray(value)) {\n finalQuery[`fields[${resourceType}]`] = value.sort().join(',');\n\n // fields: { 'company': 'field1' }\n // fields: { 'company': 'field1,field2' }\n } else {\n finalQuery[`fields[${resourceType}]`] = value.split(',').sort().join(',');\n }\n }\n }\n\n if (page) {\n const keys = Object.keys(page).sort() as Array<'size' | 'after' | 'before'>;\n keys.forEach((key) => {\n const value = page[key];\n finalQuery[`page[${key}]`] = value!;\n });\n }\n\n return buildParams(finalQuery);\n}\n","import type { ReactiveDataDocument } from '@warp-drive-mirror/core/reactive';\nimport type { TypeFromInstance } from '@warp-drive-mirror/core/types/record';\nimport type {\n FindRecordOptions,\n FindRecordRequestOptions,\n RemotelyAccessibleIdentifier,\n} from '@warp-drive-mirror/core/types/request';\n\nimport { buildBaseURL, buildQueryParams, type FindRecordUrlOptions } from '../../index.ts';\nimport { pluralize } from '../../string.ts';\nimport { copyForwardUrlOptions, extractCacheOptions } from '../builder-utils.ts';\nimport { ACCEPT_HEADER_VALUE } from './-utils.ts';\n\n/**\n * Builds request options to fetch a single resource by a known id or identifier\n * configured for the url and header expectations of most JSON:API APIs.\n *\n * :::tabs\n *\n * == Basic Usage\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const result = await store.request(\n * findRecord<Person>('person', '1')\n * );\n * ```\n *\n * == With Options\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const data = await store.request(\n * findRecord<Person>(\n * 'person', '1',\n * { include: ['pets', 'friends'] }\n * )\n * );\n * ```\n *\n * == With an Identifier\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const data = await store.request(\n * findRecord<Person>(\n * { type: 'person', id: '1' },\n * { include: ['pets', 'friends'] }\n * )\n * );\n * ```\n *\n * :::\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const data = await store.request(\n * findRecord(\n * 'person', '1',\n * { include: ['pets', 'friends'] },\n * { namespace: 'api/v2' }\n * )\n * );\n * ```\n *\n * @public\n */\nexport function findRecord<T>(\n identifier: RemotelyAccessibleIdentifier<TypeFromInstance<T>>,\n options?: FindRecordOptions\n): FindRecordRequestOptions<ReactiveDataDocument<T>, T>;\nexport function findRecord(\n identifier: RemotelyAccessibleIdentifier,\n options?: FindRecordOptions\n): FindRecordRequestOptions;\nexport function findRecord<T>(\n type: TypeFromInstance<T>,\n id: string,\n options?: FindRecordOptions\n): FindRecordRequestOptions<ReactiveDataDocument<T>, T>;\nexport function findRecord(type: string, id: string, options?: FindRecordOptions): FindRecordRequestOptions;\nexport function findRecord(\n arg1: string | RemotelyAccessibleIdentifier,\n arg2: string | FindRecordOptions | undefined,\n arg3?: FindRecordOptions\n): FindRecordRequestOptions {\n const identifier: RemotelyAccessibleIdentifier = typeof arg1 === 'string' ? { type: arg1, id: arg2 as string } : arg1;\n const options = ((typeof arg1 === 'string' ? arg3 : arg2) || {}) as FindRecordOptions;\n const cacheOptions = extractCacheOptions(options);\n const urlOptions: FindRecordUrlOptions = {\n identifier,\n op: 'findRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url: options.include?.length\n ? `${url}?${buildQueryParams({ include: options.include }, options.urlParamsSettings)}`\n : url,\n method: 'GET',\n headers,\n cacheOptions,\n op: 'findRecord',\n records: [identifier],\n };\n}\n\n/** @deprecated use {@link ReactiveDataDocument} */\nexport type FindRecordResultDocument<T> = ReactiveDataDocument<T>;\n","import type { ReactiveDataDocument } from '@warp-drive-mirror/core/reactive';\nimport type { QueryParamsSource } from '@warp-drive-mirror/core/types/params';\nimport type { TypedRecordInstance, TypeFromInstance } from '@warp-drive-mirror/core/types/record';\nimport type {\n CacheOptions,\n ConstrainedRequestOptions,\n PostQueryRequestOptions,\n QueryRequestOptions,\n} from '@warp-drive-mirror/core/types/request';\n\nimport { buildBaseURL, buildQueryParams, type QueryUrlOptions } from '../../index.ts';\nimport { pluralize } from '../../string.ts';\nimport { copyForwardUrlOptions, extractCacheOptions } from '../builder-utils.ts';\nimport { ACCEPT_HEADER_VALUE } from './-utils.ts';\n/**\n * Builds request options to query for resources, usually by a primary\n * type, configured for the url and header expectations of most JSON:API APIs.\n *\n * The key difference between this and `postQuery` is that this method will send the query\n * as query params in the url of a \"GET\" request instead of as the JSON body of a \"POST\"\n * request.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { query } from '@warp-drive-mirror/utilities/json-api';\n *\n * const data = await store.request(query('person'));\n * ```\n *\n * **With Query Params**\n *\n * ```ts\n * import { query } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = query('person', { include: ['pets', 'friends'] });\n * const data = await store.request(options);\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { query } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = query('person', { include: ['pets', 'friends'] }, { reload: true });\n * const data = await store.request(options);\n * ```\n *\n * @public\n */\nexport function query<T extends TypedRecordInstance>(\n type: TypeFromInstance<T>,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): QueryRequestOptions<ReactiveDataDocument<T[]>>;\nexport function query(\n type: string,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): QueryRequestOptions;\nexport function query(\n type: string,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n query: QueryParamsSource = {},\n options: ConstrainedRequestOptions = {}\n): QueryRequestOptions {\n const cacheOptions = extractCacheOptions(options);\n const urlOptions: QueryUrlOptions = {\n identifier: { type },\n op: 'query',\n resourcePath: pluralize(type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n const queryString = buildQueryParams(query, options.urlParamsSettings);\n\n return {\n url: queryString ? `${url}?${queryString}` : url,\n method: 'GET',\n headers,\n cacheOptions,\n op: 'query',\n };\n}\n\n/**\n * Builds request options to query for resources, usually by a primary\n * type, configured for the url and header expectations of most JSON:API APIs.\n *\n * The key difference between this and `query` is that this method will send the query\n * as the JSON body of a \"POST\" request instead of as query params in the url of a \"GET\"\n * request.\n *\n * A CacheKey is generated from the url and query params, and used to cache the response\n * in the store.\n *\n * ```ts\n * import { postQuery } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = postQuery('person', { include: ['pets', 'friends'] });\n * const data = await store.request(options);\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { postQuery } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = postQuery('person', { include: ['pets', 'friends'] }, { reload: true });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param type - the name of the resource type to query\n * @param query - the query params to send with the request\n * @param options - options to modify the request behavior\n */\nexport function postQuery<T>(\n type: TypeFromInstance<T>,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): PostQueryRequestOptions<ReactiveDataDocument<T[]>>;\nexport function postQuery(\n type: string,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): PostQueryRequestOptions;\nexport function postQuery(\n type: string,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n query: QueryParamsSource = {},\n options: ConstrainedRequestOptions = {}\n): PostQueryRequestOptions {\n const cacheOptions = extractCacheOptions(options);\n const urlOptions: QueryUrlOptions = {\n identifier: { type },\n op: 'query',\n resourcePath: options.resourcePath ?? pluralize(type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n const queryData = structuredClone(query);\n cacheOptions.key = cacheOptions.key ?? `${url}?${buildQueryParams(queryData, options.urlParamsSettings)}`;\n\n return {\n url,\n method: 'POST',\n body: JSON.stringify(query),\n headers,\n cacheOptions: cacheOptions as CacheOptions & { key: string },\n op: 'query',\n };\n}\n","import { recordIdentifierFor } from '@warp-drive-mirror/core';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { ReactiveDataDocument } from '@warp-drive-mirror/core/reactive.js';\nimport type { PersistedResourceKey, ResourceKey } from '@warp-drive-mirror/core/types/identifier';\nimport type { TypedRecordInstance } from '@warp-drive-mirror/core/types/record';\nimport type {\n ConstrainedRequestOptions,\n CreateRequestOptions,\n DeleteRequestOptions,\n UpdateRequestOptions,\n} from '@warp-drive-mirror/core/types/request';\n\nimport {\n buildBaseURL,\n type CreateRecordUrlOptions,\n type DeleteRecordUrlOptions,\n type UpdateRecordUrlOptions,\n} from '../../index.ts';\nimport { pluralize } from '../../string.ts';\nimport { copyForwardUrlOptions } from '../builder-utils.ts';\nimport { ACCEPT_HEADER_VALUE } from './-utils.ts';\n\nfunction isExisting(identifier: ResourceKey): identifier is PersistedResourceKey {\n return 'id' in identifier && identifier.id !== null && 'type' in identifier && identifier.type !== null;\n}\n\n/**\n * :::warning ⚠️ **These Mutation Builders DO NOT Set The Request Body**\n * While this may come as a surprise, the app providing the body ensures that only\n * desired and correctly formatted data is sent with the request.\n * :::\n *\n * Builds request options to delete record for resources,\n * configured for the url, method and header expectations of most JSON:API APIs.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { deleteRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n *\n * // mark record as deleted\n * store.deleteRecord(person);\n *\n * // persist deletion\n * const data = await store.request(deleteRecord(person));\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { deleteRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n *\n * // mark record as deleted\n * store.deleteRecord(person);\n *\n * // persist deletion\n * const options = deleteRecord(person, { namespace: 'api/v1' });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function deleteRecord<T>(record: T, options?: ConstrainedRequestOptions): DeleteRequestOptions<T>;\nexport function deleteRecord(record: unknown, options?: ConstrainedRequestOptions): DeleteRequestOptions;\nexport function deleteRecord(record: unknown, options: ConstrainedRequestOptions = {}): DeleteRequestOptions {\n const identifier = recordIdentifierFor(record);\n assert(`Expected to be given a record instance`, identifier);\n assert(`Cannot delete a record that does not have an associated type and id.`, isExisting(identifier));\n\n const urlOptions: DeleteRecordUrlOptions = {\n identifier: identifier,\n op: 'deleteRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url,\n method: 'DELETE',\n headers,\n op: 'deleteRecord',\n data: {\n record: identifier,\n },\n records: [identifier],\n };\n}\n\n/**\n * :::warning ⚠️ **These Mutation Builders DO NOT Set The Necessary Request Body**\n * While this may come as a surprise, the app providing the body ensures that only\n * desired and correctly formatted data is sent with the request.\n * :::\n *\n * Builds request options to create new record for resources,\n * configured for the url, method and header expectations of most JSON:API APIs.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { cacheKeyFor } from '@warp-drive-mirror/core';\n * import { createRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const person = store.createRecord<Person>('person', { name: 'Ted' });\n * const init = createRecord(person);\n * init.body = JSON.stringify(\n * {\n * // it's likely you will want to transform this data\n * // somewhat\n * data: store.cache.peek(cacheKeyFor(person))\n * }\n * );\n * const data = await store.request(init);\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { createRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.createRecord('person', { name: 'Ted' });\n * const options = createRecord(person, { namespace: 'api/v1' });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function createRecord<T>(record: T, options?: ConstrainedRequestOptions): CreateRequestOptions<T>;\nexport function createRecord(record: unknown, options?: ConstrainedRequestOptions): CreateRequestOptions;\nexport function createRecord(record: unknown, options: ConstrainedRequestOptions = {}): CreateRequestOptions {\n const identifier = recordIdentifierFor(record);\n assert(`Expected to be given a record instance`, identifier);\n\n const urlOptions: CreateRecordUrlOptions = {\n identifier: identifier,\n op: 'createRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url,\n method: 'POST',\n headers,\n op: 'createRecord',\n data: {\n record: identifier,\n },\n records: [identifier],\n };\n}\n\n/**\n * :::warning ⚠️ **These Mutation Builders DO NOT Set The Necessary Request Body**\n * While this may come as a surprise, the app providing the body ensures that only\n * desired and correctly formatted data is sent with the request.\n * :::\n *\n * Builds request options to update existing record for resources,\n * configured for the url, method and header expectations of most JSON:API APIs.\n *\n * **Example Usage**\n *\n * ```ts\n * import { cacheKeyFor } from '@warp-drive-mirror/core';\n * import { updateRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { EditablePerson } from '#/data/types';\n *\n * const mutable = await checkout<EditablePerson>(person);\n * mutable.name = 'Chris';\n * const init = updateRecord(mutable);\n *\n * init.body = JSON.stringify(\n * // it's likely you will want to transform this data\n * // somewhat, or serialize only specific properties instead\n * serializePatch(store.cache, cacheKeyFor(mutable))\n * );\n * const data = await store.request(init);\n * ```\n *\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `patch` - Allows caller to specify whether to use a PATCH request instead of a PUT request, defaults to `false`.\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { updateRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n * person.name = 'Chris';\n * const options = updateRecord(person, { patch: true });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function updateRecord<T extends TypedRecordInstance, RT extends TypedRecordInstance = T>(\n record: T,\n options?: ConstrainedRequestOptions & { patch?: boolean }\n): UpdateRequestOptions<ReactiveDataDocument<RT>, T>;\nexport function updateRecord(\n record: unknown,\n options?: ConstrainedRequestOptions & { patch?: boolean }\n): UpdateRequestOptions;\nexport function updateRecord(\n record: unknown,\n options: ConstrainedRequestOptions & { patch?: boolean } = {}\n): UpdateRequestOptions {\n const identifier = recordIdentifierFor(record);\n assert(`Expected to be given a record instance`, identifier);\n assert(`Cannot update a record that does not have an associated type and id.`, isExisting(identifier));\n\n const urlOptions: UpdateRecordUrlOptions = {\n identifier: identifier,\n op: 'updateRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url,\n method: options.patch ? 'PATCH' : 'PUT',\n headers,\n op: 'updateRecord',\n data: {\n record: identifier,\n },\n records: [identifier],\n };\n}\n\n/**\n * Builds request options to update existing record for resources,\n * configured for the url and header expectations of most JSON:API APIs\n * for a PATCH request.\n *\n * Note: This is a convenience method that calls `updateRecord` with the\n * supplied request with the `patch` option set to `true`.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { patchRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n * person.name = 'Chris';\n * const data = await store.request(patchRecord(person));\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { patchRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n * person.name = 'Chris';\n * const options = patchRecord(person);\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function patchRecord<T>(record: T, options?: ConstrainedRequestOptions): UpdateRequestOptions<T>;\nexport function patchRecord(record: unknown, options?: ConstrainedRequestOptions): UpdateRequestOptions;\nexport function patchRecord(record: unknown, options: ConstrainedRequestOptions = {}): UpdateRequestOptions {\n const opts = options as ConstrainedRequestOptions & { patch: true };\n opts.patch = true;\n return updateRecord(record, opts);\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { Cache } from '@warp-drive-mirror/core/types/cache';\nimport type { Relationship } from '@warp-drive-mirror/core/types/cache/relationship';\nimport type { ResourceKey } from '@warp-drive-mirror/core/types/identifier';\nimport type { Value } from '@warp-drive-mirror/core/types/json/raw';\nimport type { InnerRelationshipDocument, ResourceObject } from '@warp-drive-mirror/core/types/spec/json-api-raw';\n\ntype ChangedRelationshipData = InnerRelationshipDocument;\n\nexport type JsonApiResourcePatch =\n | {\n type: string;\n id: string;\n attributes?: Record<string, Value>;\n relationships?: Record<string, ChangedRelationshipData>;\n }\n | {\n type: string;\n id: null;\n lid: string;\n attributes?: Record<string, Value>;\n relationships?: Record<string, ChangedRelationshipData>;\n };\n\n/**\n * :::warning ⚠️ **This util often won't produce the necessary body for a {json:api} request**\n *\n * While this may come as a surprise, they are intended to serialize cache state for more\n * generalized usage. {json:api} has a large variance in acceptable shapes, and only your\n * app can ensure that the body is correctly formatted and contains all necessary data.\n * :::\n *\n * Serializes the current state of a resource or array of resources for use with POST or PUT requests.\n *\n * @public\n * @param cache - the cache to serialize the resource(s) from\n * @param identifiers - the resource(s) to serialize\n * @return an object with a `data` property containing the serialized resource(s)\n */\nexport function serializeResources(\n cache: Cache,\n identifiers: ResourceKey\n): {\n /**\n * The serialized resource.\n */\n data: ResourceObject;\n};\nexport function serializeResources(\n cache: Cache,\n identifiers: ResourceKey[]\n): {\n /**\n * The serialized resources.\n */\n data: ResourceObject[];\n};\nexport function serializeResources(\n cache: Cache,\n identifiers: ResourceKey | ResourceKey[]\n): { data: ResourceObject | ResourceObject[] } {\n return {\n data: Array.isArray(identifiers)\n ? identifiers.map((identifier) => _serializeResource(cache, identifier))\n : _serializeResource(cache, identifiers),\n };\n}\n\ntype SerializedRef =\n | {\n id: string;\n type: string;\n }\n | { id: null; lid: string; type: string };\n\nfunction fixRef({\n id,\n lid,\n type,\n}: { id: string; lid?: string; type: string } | { id: null; lid: string; type: string }): SerializedRef {\n if (id !== null) {\n return { id, type };\n }\n return { id, lid, type };\n}\n\nfunction fixRelData(\n rel: Relationship['data'] | InnerRelationshipDocument['data']\n): SerializedRef | SerializedRef[] | null {\n if (Array.isArray(rel)) {\n return rel.map((ref) => fixRef(ref));\n } else if (typeof rel === 'object' && rel !== null) {\n return fixRef(rel);\n }\n return null;\n}\n\nfunction _serializeResource(cache: Cache, identifier: ResourceKey): ResourceObject {\n const { id, lid, type } = identifier;\n // peek gives us everything we want, but since its referentially the same data\n // as is in the cache we clone it to avoid any accidental mutations\n const record = structuredClone(cache.peek(identifier)) as ResourceObject;\n assert(\n `A record with id ${String(id)} and type ${type} for lid ${lid} was not found not in the supplied Cache.`,\n record\n );\n\n // remove lid from anything that has an ID and slice any relationship arrays\n if (record.id !== null) {\n delete record.lid;\n }\n\n if (record.relationships) {\n for (const key of Object.keys(record.relationships)) {\n const relationship = record.relationships[key];\n if (Array.isArray(relationship.data)) {\n relationship.data = relationship.data.map((ref) => fixRef(ref));\n } else if (typeof relationship.data === 'object' && relationship.data !== null) {\n relationship.data = fixRef(relationship.data);\n } else if (Object.keys(relationship ?? {}).length === 0) {\n delete record.relationships[key];\n }\n }\n }\n\n return record;\n}\n\n/**\n * :::warning ⚠️ **This util often won't produce the necessary body for a {json:api} request**\n *\n * While this may come as a surprise, they are intended to serialize cache state for more\n * generalized usage. {json:api} has a large variance in acceptable shapes, and only your\n * app can ensure that the body is correctly formatted and contains all necessary data.\n * :::\n *\n * Serializes changes to a resource. Useful for use with building bodies for PATCH requests.\n *\n * Only attributes which are changed are serialized.\n * Only relationships which are changed are serialized.\n *\n * Collection relationships serialize the collection as a whole.\n *\n * If you would like to serialize updates to a collection more granularly\n * (for instance, as operations) request the diff from the store and\n * serialize as desired:\n *\n * ```ts\n * const relationshipDiffMap = cache.changedRelationships(identifier);\n * ```\n *\n * @public\n * @param cache - the cache to serialize the resource's changes from\n * @param identifier - the resource whose changes should be serialized\n * @return an object with a `data` property containing the serialized resource patch\n */\nexport function serializePatch(\n cache: Cache,\n identifier: ResourceKey\n // options: { include?: string[] } = {}\n): {\n /**\n * The serialized resource patch.\n */\n data: JsonApiResourcePatch;\n} {\n const { id, lid, type } = identifier;\n assert(\n `A record with id ${String(id)} and type ${type} for lid ${lid} was not found not in the supplied Cache.`,\n cache.peek(identifier)\n );\n\n const data: JsonApiResourcePatch =\n id === null\n ? { type, lid, id }\n : {\n type,\n id,\n };\n\n if (cache.hasChangedAttrs(identifier)) {\n const attrsChanges = cache.changedAttrs(identifier);\n const attributes: ResourceObject['attributes'] = {};\n\n Object.keys(attrsChanges).forEach((key) => {\n const change = attrsChanges[key];\n const newVal = change[1];\n attributes[key] = newVal === undefined ? null : structuredClone(newVal);\n });\n\n data.attributes = attributes;\n }\n\n const changedRelationships = cache.changedRelationships(identifier);\n if (changedRelationships.size) {\n const relationships: Record<string, ChangedRelationshipData> = {};\n changedRelationships.forEach((diff, key) => {\n relationships[key] = { data: fixRelData(diff.localState) } as ChangedRelationshipData;\n });\n\n data.relationships = relationships;\n }\n\n return { data };\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,gBAAgB;AACtB,MAAM,iBAAgC;CAAE,MAAM;CAAI,WAAW;AAAG;AAChE,IAAW,SAAwB;AACnC,IAAW,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCjC,SAAgB,kBAAkB,QAA6B;CAC7D,SAAS,OAAO,OAAO,CAAC,GAAG,gBAAgB,MAAM;CAEjD,IAAI,OAAO,YAAY,OAAO,YAAY;EACxC,IAAI,SAAS;EACb,IAAI,OAAO,UAAU;GACnB,MAAM,WAAW,OAAO,OAAO,OAAO,QAAQ;GAC9C,IAAI,SAAS,QACX,UAAU,gBAAe,SAAS,KAAK,GAAG,IAAI;EAElD;EACA,IAAI,OAAO,YAAY;GACrB,MAAM,aAAa,OAAO,OAAO,OAAO,UAAU;GAClD,IAAI,WAAW,QACb,UAAU,UAAU,WAAW,KAAK,GAAG;EAE3C;EACA,sBAAsB;CACxB;CAEA,oBAAU,MAAM;AAClB;;;;ACqBA,SAAgB,WACd,MACA,MACA,MAC0B;CAC1B,MAAM,aAA2C,OAAO,SAAS,WAAW;EAAE,MAAM;EAAM,IAAI;CAAe,IAAI;CACjH,MAAM,WAAY,OAAO,SAAS,WAAW,OAAO,SAAS,CAAC;CAC9D,MAAM,eAAe,oBAAoB,OAAO;CAChD,MAAM,aAA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
1
+ {"version":3,"file":"json-api.js","names":["recordIdentifierFor","buildBaseURL","pluralize","copyForwardUrlOptions","ACCEPT_HEADER_VALUE","macroCondition","getGlobalConfig","isExisting","identifier","id","type","deleteRecord","record","options","WarpDrive","env","DEBUG","test","Error","urlOptions","op","resourcePath","url","headers","Headers","append","method","data","records","createRecord","updateRecord","patch","patchRecord","opts","serializeResources","cache","identifiers","data","Array","isArray","map","identifier","_serializeResource","fixRef","id","lid","type","fixRelData","rel","ref","record","structuredClone","peek","macroCondition","getGlobalConfig","WarpDrive","env","DEBUG","test","Error","String","relationships","key","Object","keys","relationship","length","serializePatch","hasChangedAttrs","attrsChanges","changedAttrs","attributes","forEach","change","newVal","undefined","changedRelationships","size","diff","localState"],"sources":["../src/-private/json-api/-utils.ts","../src/-private/json-api/find-record.ts","../src/-private/json-api/query.ts","../src/-private/json-api/save-record.ts","../src/-private/json-api/serialize.ts"],"sourcesContent":["import type { QueryParamsSource } from '@warp-drive-mirror/core/types/params';\n\nimport type { BuildURLConfig } from '../../index.ts';\nimport { buildQueryParams as buildParams, setBuildURLConfig as setConfig } from '../../index.ts';\n\nexport interface JSONAPIConfig extends BuildURLConfig {\n profiles?: {\n pagination?: string;\n [key: string]: string | undefined;\n };\n extensions?: {\n atomic?: string;\n [key: string]: string | undefined;\n };\n}\n\nconst JsonApiAccept = 'application/vnd.api+json';\nconst DEFAULT_CONFIG: JSONAPIConfig = { host: '', namespace: '' };\nexport let CONFIG: JSONAPIConfig = DEFAULT_CONFIG;\nexport let ACCEPT_HEADER_VALUE = 'application/vnd.api+json';\n\n/**\n * Allows setting extensions and profiles to be used in the `Accept` header.\n *\n * Extensions and profiles are keyed by their namespace with the value being\n * their URI.\n *\n * Example:\n *\n * ```ts\n * setBuildURLConfig({\n * extensions: {\n * atomic: 'https://jsonapi.org/ext/atomic'\n * },\n * profiles: {\n * pagination: 'https://jsonapi.org/profiles/ethanresnick/cursor-pagination'\n * }\n * });\n * ```\n *\n * This also sets the global configuration for `buildBaseURL`\n * for host and namespace values for the global coniguration\n * done via `import { setBuildURLConfig } from '@warp-drive-mirror/utilities';`\n *\n * These values may still be overridden by passing\n * them to buildBaseURL directly.\n *\n * This method may be called as many times as needed\n *\n * ```ts\n * type BuildURLConfig = {\n * host: string;\n * namespace: string'\n * }\n * ```\n *\n * @public\n * @param {BuildURLConfig} config\n * @return {void}\n */\nexport function setBuildURLConfig(config: JSONAPIConfig): void {\n CONFIG = Object.assign({}, DEFAULT_CONFIG, config);\n\n if (config.profiles || config.extensions) {\n let accept = JsonApiAccept;\n if (config.profiles) {\n const profiles = Object.values(config.profiles);\n if (profiles.length) {\n accept += ';profile=\"' + profiles.join(' ') + '\"';\n }\n }\n if (config.extensions) {\n const extensions = Object.values(config.extensions);\n if (extensions.length) {\n accept += ';ext=' + extensions.join(' ');\n }\n }\n ACCEPT_HEADER_VALUE = accept;\n }\n\n setConfig(config);\n}\n\ninterface RelatedObject {\n [key: string]: string | string[] | RelatedObject;\n}\n\nexport type JsonApiQuery = {\n include?: string | string[] | RelatedObject;\n fields?: Record<string, string | string[]>;\n page?: {\n size?: number;\n after?: string;\n before?: string;\n };\n};\n\nfunction isJsonApiQuery(query: JsonApiQuery | QueryParamsSource): query is JsonApiQuery {\n if ('include' in query && query.include && typeof query.include === 'object') {\n return true;\n }\n if ('fields' in query || 'page' in query) {\n return true;\n }\n return false;\n}\n\nfunction collapseIncludePaths(basePath: string, include: RelatedObject, paths: string[]) {\n const keys = Object.keys(include);\n for (let i = 0; i < keys.length; i++) {\n // the key is always included too\n paths.push(`${basePath}.${keys[i]}`);\n const key = keys[i];\n const value = include[key];\n\n // include: { 'company': 'field1,field2' }\n if (typeof value === 'string') {\n value.split(',').forEach((field) => {\n paths.push(`${basePath}.${key}.${field}`);\n });\n\n // include: { 'company': ['field1', 'field2'] }\n } else if (Array.isArray(value)) {\n value.forEach((field) => {\n paths.push(`${basePath}.${key}.${field}`);\n });\n\n // include: { 'company': { 'nested': 'field1,field2' } }\n } else {\n collapseIncludePaths(`${basePath}.${key}`, value, paths);\n }\n }\n}\n\n/**\n * Sorts query params by both key and value, returning a query params string\n *\n * Treats `included` specially, splicing it into an array if it is a string and sorting the array.\n * - If `included` is an object we build paths dynamically for you\n * Treats `fields` specially, building JSON:API partial fields params from an object\n * Treats `page` specially, building cursor-pagination profile page params from an object\n *\n * ```ts\n * const params = buildQueryParams({\n * include: {\n * company: {\n * locations: 'address'\n * }\n * },\n * fields: {\n * company: ['name', 'ticker'],\n * person: 'name'\n * },\n * page: {\n * size: 10,\n * after: 'abc',\n * }\n * });\n *\n * // => 'fields[company]=name,ticker&fields[person]=name&include=company.locations,company.locations.address&page[after]=abc&page[size]=10'\n * ```\n *\n * Options:\n * - arrayFormat: 'bracket' | 'indices' | 'repeat' | 'comma'\n *\n * 'bracket': appends [] to the key for every value e.g. `ids[]=1&ids[]=2`\n * 'indices': appends [i] to the key for every value e.g. `ids[0]=1&ids[1]=2`\n * 'repeat': appends the key for every value e.g. `ids=1&ids=2`\n * 'comma' (default): appends the key once with a comma separated list of values e.g. `ids=1,2`\n *\n * @public\n * @param {URLSearchParams | Object} params\n * @param {Object} [options]\n * @return {String} A sorted query params string without the leading `?`\n */\nexport function buildQueryParams(query: JsonApiQuery | QueryParamsSource): string {\n if (query instanceof URLSearchParams) {\n return buildParams(query);\n }\n\n if (!isJsonApiQuery(query)) {\n return buildParams(query);\n }\n\n const { include, fields, page, ...rest } = query;\n const finalQuery: QueryParamsSource = {\n ...rest,\n };\n\n if ('include' in query) {\n // include: { 'company': 'field1,field2' }\n // include: { 'company': ['field1', 'field2'] }\n // include: { 'company': { 'nested': 'field1,field2' } }\n // include: { 'company': { 'nested': ['field1', 'field2'] } }\n if (include && !Array.isArray(include) && typeof include === 'object') {\n const includePaths: string[] = [];\n collapseIncludePaths('', include, includePaths);\n finalQuery.include = includePaths.sort();\n\n // include: 'field1,field2'\n // include: ['field1', 'field2']\n } else {\n finalQuery.include = include as string;\n }\n }\n\n if (fields) {\n const keys = Object.keys(fields).sort();\n for (let i = 0; i < keys.length; i++) {\n const resourceType = keys[i];\n const value = fields[resourceType];\n\n // fields: { 'company': ['field1', 'field2'] }\n if (Array.isArray(value)) {\n finalQuery[`fields[${resourceType}]`] = value.sort().join(',');\n\n // fields: { 'company': 'field1' }\n // fields: { 'company': 'field1,field2' }\n } else {\n finalQuery[`fields[${resourceType}]`] = value.split(',').sort().join(',');\n }\n }\n }\n\n if (page) {\n const keys = Object.keys(page).sort() as Array<'size' | 'after' | 'before'>;\n keys.forEach((key) => {\n const value = page[key];\n finalQuery[`page[${key}]`] = value!;\n });\n }\n\n return buildParams(finalQuery);\n}\n","import type { ReactiveDataDocument } from '@warp-drive-mirror/core/reactive';\nimport type { TypeFromInstance } from '@warp-drive-mirror/core/types/record';\nimport type {\n FindRecordOptions,\n FindRecordRequestOptions,\n RemotelyAccessibleIdentifier,\n} from '@warp-drive-mirror/core/types/request';\n\nimport { buildBaseURL, buildQueryParams, type FindRecordUrlOptions } from '../../index.ts';\nimport { pluralize } from '../../string.ts';\nimport { copyForwardUrlOptions, extractCacheOptions } from '../builder-utils.ts';\nimport { ACCEPT_HEADER_VALUE } from './-utils.ts';\n\n/**\n * Builds request options to fetch a single resource by a known id or identifier\n * configured for the url and header expectations of most JSON:API APIs.\n *\n * :::tabs\n *\n * == Basic Usage\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const result = await store.request(\n * findRecord<Person>('person', '1')\n * );\n * ```\n *\n * == With Options\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const data = await store.request(\n * findRecord<Person>(\n * 'person', '1',\n * { include: ['pets', 'friends'] }\n * )\n * );\n * ```\n *\n * == With an Identifier\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const data = await store.request(\n * findRecord<Person>(\n * { type: 'person', id: '1' },\n * { include: ['pets', 'friends'] }\n * )\n * );\n * ```\n *\n * :::\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { findRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const data = await store.request(\n * findRecord(\n * 'person', '1',\n * { include: ['pets', 'friends'] },\n * { namespace: 'api/v2' }\n * )\n * );\n * ```\n *\n * @public\n */\nexport function findRecord<T>(\n identifier: RemotelyAccessibleIdentifier<TypeFromInstance<T>>,\n options?: FindRecordOptions\n): FindRecordRequestOptions<ReactiveDataDocument<T>, T>;\nexport function findRecord(\n identifier: RemotelyAccessibleIdentifier,\n options?: FindRecordOptions\n): FindRecordRequestOptions;\nexport function findRecord<T>(\n type: TypeFromInstance<T>,\n id: string,\n options?: FindRecordOptions\n): FindRecordRequestOptions<ReactiveDataDocument<T>, T>;\nexport function findRecord(type: string, id: string, options?: FindRecordOptions): FindRecordRequestOptions;\nexport function findRecord(\n arg1: string | RemotelyAccessibleIdentifier,\n arg2: string | FindRecordOptions | undefined,\n arg3?: FindRecordOptions\n): FindRecordRequestOptions {\n const identifier: RemotelyAccessibleIdentifier = typeof arg1 === 'string' ? { type: arg1, id: arg2 as string } : arg1;\n const options = ((typeof arg1 === 'string' ? arg3 : arg2) || {}) as FindRecordOptions;\n const cacheOptions = extractCacheOptions(options);\n const urlOptions: FindRecordUrlOptions = {\n identifier,\n op: 'findRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url: options.include?.length\n ? `${url}?${buildQueryParams({ include: options.include }, options.urlParamsSettings)}`\n : url,\n method: 'GET',\n headers,\n cacheOptions,\n op: 'findRecord',\n records: [identifier],\n };\n}\n\n/** @deprecated use {@link ReactiveDataDocument} */\nexport type FindRecordResultDocument<T> = ReactiveDataDocument<T>;\n","import type { ReactiveDataDocument } from '@warp-drive-mirror/core/reactive';\nimport type { QueryParamsSource } from '@warp-drive-mirror/core/types/params';\nimport type { TypedRecordInstance, TypeFromInstance } from '@warp-drive-mirror/core/types/record';\nimport type {\n CacheOptions,\n ConstrainedRequestOptions,\n PostQueryRequestOptions,\n QueryRequestOptions,\n} from '@warp-drive-mirror/core/types/request';\n\nimport { buildBaseURL, buildQueryParams, type QueryUrlOptions } from '../../index.ts';\nimport { pluralize } from '../../string.ts';\nimport { copyForwardUrlOptions, extractCacheOptions } from '../builder-utils.ts';\nimport { ACCEPT_HEADER_VALUE } from './-utils.ts';\n/**\n * Builds request options to query for resources, usually by a primary\n * type, configured for the url and header expectations of most JSON:API APIs.\n *\n * The key difference between this and `postQuery` is that this method will send the query\n * as query params in the url of a \"GET\" request instead of as the JSON body of a \"POST\"\n * request.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { query } from '@warp-drive-mirror/utilities/json-api';\n *\n * const data = await store.request(query('person'));\n * ```\n *\n * **With Query Params**\n *\n * ```ts\n * import { query } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = query('person', { include: ['pets', 'friends'] });\n * const data = await store.request(options);\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { query } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = query('person', { include: ['pets', 'friends'] }, { reload: true });\n * const data = await store.request(options);\n * ```\n *\n * @public\n */\nexport function query<T extends TypedRecordInstance>(\n type: TypeFromInstance<T>,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): QueryRequestOptions<ReactiveDataDocument<T[]>>;\nexport function query(\n type: string,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): QueryRequestOptions;\nexport function query(\n type: string,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n query: QueryParamsSource = {},\n options: ConstrainedRequestOptions = {}\n): QueryRequestOptions {\n const cacheOptions = extractCacheOptions(options);\n const urlOptions: QueryUrlOptions = {\n identifier: { type },\n op: 'query',\n resourcePath: pluralize(type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n const queryString = buildQueryParams(query, options.urlParamsSettings);\n\n return {\n url: queryString ? `${url}?${queryString}` : url,\n method: 'GET',\n headers,\n cacheOptions,\n op: 'query',\n };\n}\n\n/**\n * Builds request options to query for resources, usually by a primary\n * type, configured for the url and header expectations of most JSON:API APIs.\n *\n * The key difference between this and `query` is that this method will send the query\n * as the JSON body of a \"POST\" request instead of as query params in the url of a \"GET\"\n * request.\n *\n * A CacheKey is generated from the url and query params, and used to cache the response\n * in the store.\n *\n * ```ts\n * import { postQuery } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = postQuery('person', { include: ['pets', 'friends'] });\n * const data = await store.request(options);\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { postQuery } from '@warp-drive-mirror/utilities/json-api';\n *\n * const options = postQuery('person', { include: ['pets', 'friends'] }, { reload: true });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param type - the name of the resource type to query\n * @param query - the query params to send with the request\n * @param options - options to modify the request behavior\n */\nexport function postQuery<T>(\n type: TypeFromInstance<T>,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): PostQueryRequestOptions<ReactiveDataDocument<T[]>>;\nexport function postQuery(\n type: string,\n query?: QueryParamsSource,\n options?: ConstrainedRequestOptions\n): PostQueryRequestOptions;\nexport function postQuery(\n type: string,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n query: QueryParamsSource = {},\n options: ConstrainedRequestOptions = {}\n): PostQueryRequestOptions {\n const cacheOptions = extractCacheOptions(options);\n const urlOptions: QueryUrlOptions = {\n identifier: { type },\n op: 'query',\n resourcePath: options.resourcePath ?? pluralize(type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n const queryData = structuredClone(query);\n cacheOptions.key = cacheOptions.key ?? `${url}?${buildQueryParams(queryData, options.urlParamsSettings)}`;\n\n return {\n url,\n method: 'POST',\n body: JSON.stringify(query),\n headers,\n cacheOptions: cacheOptions as CacheOptions & { key: string },\n op: 'query',\n };\n}\n","import { recordIdentifierFor } from '@warp-drive-mirror/core';\nimport { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { ReactiveDataDocument } from '@warp-drive-mirror/core/reactive';\nimport type { PersistedResourceKey, ResourceKey } from '@warp-drive-mirror/core/types/identifier';\nimport type { TypedRecordInstance } from '@warp-drive-mirror/core/types/record';\nimport type {\n ConstrainedRequestOptions,\n CreateRequestOptions,\n DeleteRequestOptions,\n UpdateRequestOptions,\n} from '@warp-drive-mirror/core/types/request';\n\nimport {\n buildBaseURL,\n type CreateRecordUrlOptions,\n type DeleteRecordUrlOptions,\n type UpdateRecordUrlOptions,\n} from '../../index.ts';\nimport { pluralize } from '../../string.ts';\nimport { copyForwardUrlOptions } from '../builder-utils.ts';\nimport { ACCEPT_HEADER_VALUE } from './-utils.ts';\n\nfunction isExisting(identifier: ResourceKey): identifier is PersistedResourceKey {\n return 'id' in identifier && identifier.id !== null && 'type' in identifier && identifier.type !== null;\n}\n\n/**\n * :::warning ⚠️ **These Mutation Builders DO NOT Set The Request Body**\n * While this may come as a surprise, the app providing the body ensures that only\n * desired and correctly formatted data is sent with the request.\n * :::\n *\n * Builds request options to delete record for resources,\n * configured for the url, method and header expectations of most JSON:API APIs.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { deleteRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n *\n * // mark record as deleted\n * store.deleteRecord(person);\n *\n * // persist deletion\n * const data = await store.request(deleteRecord(person));\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { deleteRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n *\n * // mark record as deleted\n * store.deleteRecord(person);\n *\n * // persist deletion\n * const options = deleteRecord(person, { namespace: 'api/v1' });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function deleteRecord<T>(record: T, options?: ConstrainedRequestOptions): DeleteRequestOptions<T>;\nexport function deleteRecord(record: unknown, options?: ConstrainedRequestOptions): DeleteRequestOptions;\nexport function deleteRecord(record: unknown, options: ConstrainedRequestOptions = {}): DeleteRequestOptions {\n const identifier = recordIdentifierFor(record);\n assert(`Expected to be given a record instance`, identifier);\n assert(`Cannot delete a record that does not have an associated type and id.`, isExisting(identifier));\n\n const urlOptions: DeleteRecordUrlOptions = {\n identifier: identifier,\n op: 'deleteRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url,\n method: 'DELETE',\n headers,\n op: 'deleteRecord',\n data: {\n record: identifier,\n },\n records: [identifier],\n };\n}\n\n/**\n * :::warning ⚠️ **These Mutation Builders DO NOT Set The Necessary Request Body**\n * While this may come as a surprise, the app providing the body ensures that only\n * desired and correctly formatted data is sent with the request.\n * :::\n *\n * Builds request options to create new record for resources,\n * configured for the url, method and header expectations of most JSON:API APIs.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { cacheKeyFor } from '@warp-drive-mirror/core';\n * import { createRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { Person } from '#/data/types';\n *\n * const person = store.createRecord<Person>('person', { name: 'Ted' });\n * const init = createRecord(person);\n * init.body = JSON.stringify(\n * {\n * // it's likely you will want to transform this data\n * // somewhat\n * data: store.cache.peek(cacheKeyFor(person))\n * }\n * );\n * const data = await store.request(init);\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { createRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.createRecord('person', { name: 'Ted' });\n * const options = createRecord(person, { namespace: 'api/v1' });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function createRecord<T>(record: T, options?: ConstrainedRequestOptions): CreateRequestOptions<T>;\nexport function createRecord(record: unknown, options?: ConstrainedRequestOptions): CreateRequestOptions;\nexport function createRecord(record: unknown, options: ConstrainedRequestOptions = {}): CreateRequestOptions {\n const identifier = recordIdentifierFor(record);\n assert(`Expected to be given a record instance`, identifier);\n\n const urlOptions: CreateRecordUrlOptions = {\n identifier: identifier,\n op: 'createRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url,\n method: 'POST',\n headers,\n op: 'createRecord',\n data: {\n record: identifier,\n },\n records: [identifier],\n };\n}\n\n/**\n * :::warning ⚠️ **These Mutation Builders DO NOT Set The Necessary Request Body**\n * While this may come as a surprise, the app providing the body ensures that only\n * desired and correctly formatted data is sent with the request.\n * :::\n *\n * Builds request options to update existing record for resources,\n * configured for the url, method and header expectations of most JSON:API APIs.\n *\n * **Example Usage**\n *\n * ```ts\n * import { cacheKeyFor } from '@warp-drive-mirror/core';\n * import { updateRecord } from '@warp-drive-mirror/utilities/json-api';\n * import type { EditablePerson } from '#/data/types';\n *\n * const mutable = await checkout<EditablePerson>(person);\n * mutable.name = 'Chris';\n * const init = updateRecord(mutable);\n *\n * init.body = JSON.stringify(\n * // it's likely you will want to transform this data\n * // somewhat, or serialize only specific properties instead\n * serializePatch(store.cache, cacheKeyFor(mutable))\n * );\n * const data = await store.request(init);\n * ```\n *\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `patch` - Allows caller to specify whether to use a PATCH request instead of a PUT request, defaults to `false`.\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { updateRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n * person.name = 'Chris';\n * const options = updateRecord(person, { patch: true });\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function updateRecord<T extends TypedRecordInstance, RT extends TypedRecordInstance = T>(\n record: T,\n options?: ConstrainedRequestOptions & { patch?: boolean }\n): UpdateRequestOptions<ReactiveDataDocument<RT>, T>;\nexport function updateRecord(\n record: unknown,\n options?: ConstrainedRequestOptions & { patch?: boolean }\n): UpdateRequestOptions;\nexport function updateRecord(\n record: unknown,\n options: ConstrainedRequestOptions & { patch?: boolean } = {}\n): UpdateRequestOptions {\n const identifier = recordIdentifierFor(record);\n assert(`Expected to be given a record instance`, identifier);\n assert(`Cannot update a record that does not have an associated type and id.`, isExisting(identifier));\n\n const urlOptions: UpdateRecordUrlOptions = {\n identifier: identifier,\n op: 'updateRecord',\n resourcePath: pluralize(identifier.type),\n };\n\n copyForwardUrlOptions(urlOptions, options);\n\n const url = buildBaseURL(urlOptions);\n const headers = new Headers();\n headers.append('Accept', ACCEPT_HEADER_VALUE);\n\n return {\n url,\n method: options.patch ? 'PATCH' : 'PUT',\n headers,\n op: 'updateRecord',\n data: {\n record: identifier,\n },\n records: [identifier],\n };\n}\n\n/**\n * Builds request options to update existing record for resources,\n * configured for the url and header expectations of most JSON:API APIs\n * for a PATCH request.\n *\n * Note: This is a convenience method that calls `updateRecord` with the\n * supplied request with the `patch` option set to `true`.\n *\n * **Basic Usage**\n *\n * ```ts\n * import { patchRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n * person.name = 'Chris';\n * const data = await store.request(patchRecord(person));\n * ```\n *\n * **Supplying Options to Modify the Request Behavior**\n *\n * The following options are supported:\n *\n * - `host` - The host to use for the request, defaults to the `host` configured with `setBuildURLConfig`.\n * - `namespace` - The namespace to use for the request, defaults to the `namespace` configured with `setBuildURLConfig`.\n * - `resourcePath` - The resource path to use for the request, defaults to pluralizing the supplied type\n * - `reload` - Whether to forcibly reload the request if it is already in the store, not supplying this\n * option will delegate to the store's CachePolicy, defaulting to `false` if none is configured.\n * - `backgroundReload` - Whether to reload the request if it is already in the store, but to also resolve the\n * promise with the cached value, not supplying this option will delegate to the store's CachePolicy,\n * defaulting to `false` if none is configured.\n * - `urlParamsSetting` - an object containing options for how to serialize the query params (see `buildQueryParams`)\n *\n * ```ts\n * import { patchRecord } from '@warp-drive-mirror/utilities/json-api';\n *\n * const person = store.peekRecord('person', '1');\n * person.name = 'Chris';\n * const options = patchRecord(person);\n * const data = await store.request(options);\n * ```\n *\n * @public\n * @param record\n * @param options\n */\nexport function patchRecord<T>(record: T, options?: ConstrainedRequestOptions): UpdateRequestOptions<T>;\nexport function patchRecord(record: unknown, options?: ConstrainedRequestOptions): UpdateRequestOptions;\nexport function patchRecord(record: unknown, options: ConstrainedRequestOptions = {}): UpdateRequestOptions {\n const opts = options as ConstrainedRequestOptions & { patch: true };\n opts.patch = true;\n return updateRecord(record, opts);\n}\n","import { assert } from '@warp-drive-mirror/core/build-config/macros';\nimport type { Cache } from '@warp-drive-mirror/core/types/cache';\nimport type { Relationship } from '@warp-drive-mirror/core/types/cache/relationship';\nimport type { ResourceKey } from '@warp-drive-mirror/core/types/identifier';\nimport type { Value } from '@warp-drive-mirror/core/types/json/raw';\nimport type { InnerRelationshipDocument, ResourceObject } from '@warp-drive-mirror/core/types/spec/json-api-raw';\n\ntype ChangedRelationshipData = InnerRelationshipDocument;\n\nexport type JsonApiResourcePatch =\n | {\n type: string;\n id: string;\n attributes?: Record<string, Value>;\n relationships?: Record<string, ChangedRelationshipData>;\n }\n | {\n type: string;\n id: null;\n lid: string;\n attributes?: Record<string, Value>;\n relationships?: Record<string, ChangedRelationshipData>;\n };\n\n/**\n * :::warning ⚠️ **This util often won't produce the necessary body for a {json:api} request**\n *\n * While this may come as a surprise, they are intended to serialize cache state for more\n * generalized usage. {json:api} has a large variance in acceptable shapes, and only your\n * app can ensure that the body is correctly formatted and contains all necessary data.\n * :::\n *\n * Serializes the current state of a resource or array of resources for use with POST or PUT requests.\n *\n * @public\n * @param cache - the cache to serialize the resource(s) from\n * @param identifiers - the resource(s) to serialize\n * @return an object with a `data` property containing the serialized resource(s)\n */\nexport function serializeResources(\n cache: Cache,\n identifiers: ResourceKey\n): {\n /**\n * The serialized resource.\n */\n data: ResourceObject;\n};\nexport function serializeResources(\n cache: Cache,\n identifiers: ResourceKey[]\n): {\n /**\n * The serialized resources.\n */\n data: ResourceObject[];\n};\nexport function serializeResources(\n cache: Cache,\n identifiers: ResourceKey | ResourceKey[]\n): { data: ResourceObject | ResourceObject[] } {\n return {\n data: Array.isArray(identifiers)\n ? identifiers.map((identifier) => _serializeResource(cache, identifier))\n : _serializeResource(cache, identifiers),\n };\n}\n\ntype SerializedRef =\n | {\n id: string;\n type: string;\n }\n | { id: null; lid: string; type: string };\n\nfunction fixRef({\n id,\n lid,\n type,\n}: { id: string; lid?: string; type: string } | { id: null; lid: string; type: string }): SerializedRef {\n if (id !== null) {\n return { id, type };\n }\n return { id, lid, type };\n}\n\nfunction fixRelData(\n rel: Relationship['data'] | InnerRelationshipDocument['data']\n): SerializedRef | SerializedRef[] | null {\n if (Array.isArray(rel)) {\n return rel.map((ref) => fixRef(ref));\n } else if (typeof rel === 'object' && rel !== null) {\n return fixRef(rel);\n }\n return null;\n}\n\nfunction _serializeResource(cache: Cache, identifier: ResourceKey): ResourceObject {\n const { id, lid, type } = identifier;\n // peek gives us everything we want, but since its referentially the same data\n // as is in the cache we clone it to avoid any accidental mutations\n const record = structuredClone(cache.peek(identifier)) as ResourceObject;\n assert(\n `A record with id ${String(id)} and type ${type} for lid ${lid} was not found not in the supplied Cache.`,\n record\n );\n\n // remove lid from anything that has an ID and slice any relationship arrays\n if (record.id !== null) {\n delete record.lid;\n }\n\n if (record.relationships) {\n for (const key of Object.keys(record.relationships)) {\n const relationship = record.relationships[key];\n if (Array.isArray(relationship.data)) {\n relationship.data = relationship.data.map((ref) => fixRef(ref));\n } else if (typeof relationship.data === 'object' && relationship.data !== null) {\n relationship.data = fixRef(relationship.data);\n } else if (Object.keys(relationship ?? {}).length === 0) {\n delete record.relationships[key];\n }\n }\n }\n\n return record;\n}\n\n/**\n * :::warning ⚠️ **This util often won't produce the necessary body for a {json:api} request**\n *\n * While this may come as a surprise, they are intended to serialize cache state for more\n * generalized usage. {json:api} has a large variance in acceptable shapes, and only your\n * app can ensure that the body is correctly formatted and contains all necessary data.\n * :::\n *\n * Serializes changes to a resource. Useful for use with building bodies for PATCH requests.\n *\n * Only attributes which are changed are serialized.\n * Only relationships which are changed are serialized.\n *\n * Collection relationships serialize the collection as a whole.\n *\n * If you would like to serialize updates to a collection more granularly\n * (for instance, as operations) request the diff from the store and\n * serialize as desired:\n *\n * ```ts\n * const relationshipDiffMap = cache.changedRelationships(identifier);\n * ```\n *\n * @public\n * @param cache - the cache to serialize the resource's changes from\n * @param identifier - the resource whose changes should be serialized\n * @return an object with a `data` property containing the serialized resource patch\n */\nexport function serializePatch(\n cache: Cache,\n identifier: ResourceKey\n // options: { include?: string[] } = {}\n): {\n /**\n * The serialized resource patch.\n */\n data: JsonApiResourcePatch;\n} {\n const { id, lid, type } = identifier;\n assert(\n `A record with id ${String(id)} and type ${type} for lid ${lid} was not found not in the supplied Cache.`,\n cache.peek(identifier)\n );\n\n const data: JsonApiResourcePatch =\n id === null\n ? { type, lid, id }\n : {\n type,\n id,\n };\n\n if (cache.hasChangedAttrs(identifier)) {\n const attrsChanges = cache.changedAttrs(identifier);\n const attributes: ResourceObject['attributes'] = {};\n\n Object.keys(attrsChanges).forEach((key) => {\n const change = attrsChanges[key];\n const newVal = change[1];\n attributes[key] = newVal === undefined ? null : structuredClone(newVal);\n });\n\n data.attributes = attributes;\n }\n\n const changedRelationships = cache.changedRelationships(identifier);\n if (changedRelationships.size) {\n const relationships: Record<string, ChangedRelationshipData> = {};\n changedRelationships.forEach((diff, key) => {\n relationships[key] = { data: fixRelData(diff.localState) } as ChangedRelationshipData;\n });\n\n data.relationships = relationships;\n }\n\n return { data };\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,gBAAgB;AACtB,MAAM,iBAAgC;CAAE,MAAM;CAAI,WAAW;AAAG;AAChE,IAAW,SAAwB;AACnC,IAAW,sBAA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