Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

BIN
node_modules/@tanstack/.DS_Store generated vendored Normal file

Binary file not shown.

21
node_modules/@tanstack/match-sorter-utils/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016 Tanner Linsley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,57 @@
/**
* @name match-sorter
* @license MIT license.
* @copyright (c) 2099 Kent C. Dodds
* @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
*/
export type AccessorAttributes = {
threshold?: Ranking;
maxRanking: Ranking;
minRanking: Ranking;
};
export interface RankingInfo {
rankedValue: any;
rank: Ranking;
accessorIndex: number;
accessorThreshold: Ranking | undefined;
passed: boolean;
}
export interface AccessorOptions<TItem> {
accessor: AccessorFn<TItem>;
threshold?: Ranking;
maxRanking?: Ranking;
minRanking?: Ranking;
}
export type AccessorFn<TItem> = (item: TItem) => string | Array<string>;
export type Accessor<TItem> = AccessorFn<TItem> | AccessorOptions<TItem>;
export interface RankItemOptions<TItem = unknown> {
accessors?: ReadonlyArray<Accessor<TItem>>;
threshold?: Ranking;
keepDiacritics?: boolean;
}
export declare const rankings: {
readonly CASE_SENSITIVE_EQUAL: 7;
readonly EQUAL: 6;
readonly STARTS_WITH: 5;
readonly WORD_STARTS_WITH: 4;
readonly CONTAINS: 3;
readonly ACRONYM: 2;
readonly MATCHES: 1;
readonly NO_MATCH: 0;
};
export type Ranking = (typeof rankings)[keyof typeof rankings];
/**
* Gets the highest ranking for value for the given item based on its values for the given keys
* @param {*} item - the item to rank
* @param {String} value - the value to rank against
* @param {Object} options - options to control the ranking
* @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
*/
export declare function rankItem<TItem>(item: TItem, value: string, options?: RankItemOptions<TItem>): RankingInfo;
/**
* Sorts items that have a rank, index, and accessorIndex
* @param {Object} a - the first item to sort
* @param {Object} b - the second item to sort
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
*/
export declare function compareItems<TItem>(a: RankingInfo, b: RankingInfo): number;

View File

@@ -0,0 +1,710 @@
/**
* match-sorter-utils
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
const characterMap = {
À: 'A',
Á: 'A',
Â: 'A',
Ã: 'A',
Ä: 'A',
Å: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
Æ: 'AE',
: 'A',
: 'A',
Ȃ: 'A',
Ç: 'C',
: 'C',
È: 'E',
É: 'E',
Ê: 'E',
Ë: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
Ȇ: 'E',
Ì: 'I',
Í: 'I',
Î: 'I',
Ï: 'I',
: 'I',
Ȋ: 'I',
Ð: 'D',
Ñ: 'N',
Ò: 'O',
Ó: 'O',
Ô: 'O',
Õ: 'O',
Ö: 'O',
Ø: 'O',
: 'O',
: 'O',
: 'O',
Ȏ: 'O',
Ù: 'U',
Ú: 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: 'q',
U̧: 'U',
u̧: 'u',
X̧: 'X',
x̧: 'x',
Z̧: 'Z',
z̧: 'z'
};
const chars = Object.keys(characterMap).join('|');
const allAccents = new RegExp(chars, 'g');
function removeAccents(str) {
return str.replace(allAccents, match => {
return characterMap[match];
});
}
/**
* @name match-sorter
* @license MIT license.
* @copyright (c) 2099 Kent C. Dodds
* @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
*/
const rankings = {
CASE_SENSITIVE_EQUAL: 7,
EQUAL: 6,
STARTS_WITH: 5,
WORD_STARTS_WITH: 4,
CONTAINS: 3,
ACRONYM: 2,
MATCHES: 1,
NO_MATCH: 0
};
/**
* Gets the highest ranking for value for the given item based on its values for the given keys
* @param {*} item - the item to rank
* @param {String} value - the value to rank against
* @param {Object} options - options to control the ranking
* @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
*/
function rankItem(item, value, options) {
var _options$threshold;
options = options || {};
options.threshold = (_options$threshold = options.threshold) != null ? _options$threshold : rankings.MATCHES;
if (!options.accessors) {
// if keys is not specified, then we assume the item given is ready to be matched
const rank = getMatchRanking(item, value, options);
return {
// ends up being duplicate of 'item' in matches but consistent
rankedValue: item,
rank,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: rank >= options.threshold
};
}
const valuesToRank = getAllValuesToRank(item, options.accessors);
const rankingInfo = {
rankedValue: item,
rank: rankings.NO_MATCH,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: false
};
for (let i = 0; i < valuesToRank.length; i++) {
const rankValue = valuesToRank[i];
let newRank = getMatchRanking(rankValue.itemValue, value, options);
const {
minRanking,
maxRanking,
threshold = options.threshold
} = rankValue.attributes;
if (newRank < minRanking && newRank >= rankings.MATCHES) {
newRank = minRanking;
} else if (newRank > maxRanking) {
newRank = maxRanking;
}
newRank = Math.min(newRank, maxRanking);
if (newRank >= threshold && newRank > rankingInfo.rank) {
rankingInfo.rank = newRank;
rankingInfo.passed = true;
rankingInfo.accessorIndex = i;
rankingInfo.accessorThreshold = threshold;
rankingInfo.rankedValue = rankValue.itemValue;
}
}
return rankingInfo;
}
/**
* Gives a rankings score based on how well the two strings match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @param {Object} options - options for the match (like keepDiacritics for comparison)
* @returns {Number} the ranking for how well stringToRank matches testString
*/
function getMatchRanking(testString, stringToRank, options) {
testString = prepareValueForComparison(testString, options);
stringToRank = prepareValueForComparison(stringToRank, options);
// too long
if (stringToRank.length > testString.length) {
return rankings.NO_MATCH;
}
// case sensitive equals
if (testString === stringToRank) {
return rankings.CASE_SENSITIVE_EQUAL;
}
// Lower casing before further comparison
testString = testString.toLowerCase();
stringToRank = stringToRank.toLowerCase();
// case insensitive equals
if (testString === stringToRank) {
return rankings.EQUAL;
}
// starts with
if (testString.startsWith(stringToRank)) {
return rankings.STARTS_WITH;
}
// word starts with
if (testString.includes(` ${stringToRank}`)) {
return rankings.WORD_STARTS_WITH;
}
// contains
if (testString.includes(stringToRank)) {
return rankings.CONTAINS;
} else if (stringToRank.length === 1) {
// If the only character in the given stringToRank
// isn't even contained in the testString, then
// it's definitely not a match.
return rankings.NO_MATCH;
}
// acronym
if (getAcronym(testString).includes(stringToRank)) {
return rankings.ACRONYM;
}
// will return a number between rankings.MATCHES and
// rankings.MATCHES + 1 depending on how close of a match it is.
return getClosenessRanking(testString, stringToRank);
}
/**
* Generates an acronym for a string.
*
* @param {String} string the string for which to produce the acronym
* @returns {String} the acronym
*/
function getAcronym(string) {
let acronym = '';
const wordsInString = string.split(' ');
wordsInString.forEach(wordInString => {
const splitByHyphenWords = wordInString.split('-');
splitByHyphenWords.forEach(splitByHyphenWord => {
acronym += splitByHyphenWord.substr(0, 1);
});
});
return acronym;
}
/**
* Returns a score based on how spread apart the
* characters from the stringToRank are within the testString.
* A number close to rankings.MATCHES represents a loose match. A number close
* to rankings.MATCHES + 1 represents a tighter match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @returns {Number} the number between rankings.MATCHES and
* rankings.MATCHES + 1 for how well stringToRank matches testString
*/
function getClosenessRanking(testString, stringToRank) {
let matchingInOrderCharCount = 0;
let charNumber = 0;
function findMatchingCharacter(matchChar, string, index) {
for (let j = index, J = string.length; j < J; j++) {
const stringChar = string[j];
if (stringChar === matchChar) {
matchingInOrderCharCount += 1;
return j + 1;
}
}
return -1;
}
function getRanking(spread) {
const spreadPercentage = 1 / spread;
const inOrderPercentage = matchingInOrderCharCount / stringToRank.length;
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage;
return ranking;
}
const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0);
if (firstIndex < 0) {
return rankings.NO_MATCH;
}
charNumber = firstIndex;
for (let i = 1, I = stringToRank.length; i < I; i++) {
const matchChar = stringToRank[i];
charNumber = findMatchingCharacter(matchChar, testString, charNumber);
const found = charNumber > -1;
if (!found) {
return rankings.NO_MATCH;
}
}
const spread = charNumber - firstIndex;
return getRanking(spread);
}
/**
* Sorts items that have a rank, index, and accessorIndex
* @param {Object} a - the first item to sort
* @param {Object} b - the second item to sort
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
*/
function compareItems(a, b) {
return a.rank === b.rank ? 0 : a.rank > b.rank ? -1 : 1;
}
/**
* Prepares value for comparison by stringifying it, removing diacritics (if specified)
* @param {String} value - the value to clean
* @param {Object} options - {keepDiacritics: whether to remove diacritics}
* @return {String} the prepared value
*/
function prepareValueForComparison(value, _ref) {
let {
keepDiacritics
} = _ref;
// value might not actually be a string at this point (we don't get to choose)
// so part of preparing the value for comparison is ensure that it is a string
value = `${value}`; // toString
if (!keepDiacritics) {
value = removeAccents(value);
}
return value;
}
/**
* Gets value for key in item at arbitrarily nested keypath
* @param {Object} item - the item
* @param {Object|Function} key - the potentially nested keypath or property callback
* @return {Array} - an array containing the value(s) at the nested keypath
*/
function getItemValues(item, accessor) {
let accessorFn = accessor;
if (typeof accessor === 'object') {
accessorFn = accessor.accessor;
}
const value = accessorFn(item);
// because `value` can also be undefined
if (value == null) {
return [];
}
if (Array.isArray(value)) {
return value;
}
return [String(value)];
}
/**
* Gets all the values for the given keys in the given item and returns an array of those values
* @param item - the item from which the values will be retrieved
* @param keys - the keys to use to retrieve the values
* @return objects with {itemValue, attributes}
*/
function getAllValuesToRank(item, accessors) {
const allValues = [];
for (let j = 0, J = accessors.length; j < J; j++) {
const accessor = accessors[j];
const attributes = getAccessorAttributes(accessor);
const itemValues = getItemValues(item, accessor);
for (let i = 0, I = itemValues.length; i < I; i++) {
allValues.push({
itemValue: itemValues[i],
attributes
});
}
}
return allValues;
}
const defaultKeyAttributes = {
maxRanking: Infinity,
minRanking: -Infinity
};
/**
* Gets all the attributes for the given accessor
* @param accessor - the accessor from which the attributes will be retrieved
* @return object containing the accessor's attributes
*/
function getAccessorAttributes(accessor) {
if (typeof accessor === 'function') {
return defaultKeyAttributes;
}
return {
...defaultKeyAttributes,
...accessor
};
}
export { compareItems, rankItem, rankings };
//# sourceMappingURL=index.esm.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,307 @@
/**
* match-sorter-utils
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
var removeAccents = require('./remove-accents.js');
/**
* @name match-sorter
* @license MIT license.
* @copyright (c) 2099 Kent C. Dodds
* @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
*/
const rankings = {
CASE_SENSITIVE_EQUAL: 7,
EQUAL: 6,
STARTS_WITH: 5,
WORD_STARTS_WITH: 4,
CONTAINS: 3,
ACRONYM: 2,
MATCHES: 1,
NO_MATCH: 0
};
/**
* Gets the highest ranking for value for the given item based on its values for the given keys
* @param {*} item - the item to rank
* @param {String} value - the value to rank against
* @param {Object} options - options to control the ranking
* @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
*/
function rankItem(item, value, options) {
var _options$threshold;
options = options || {};
options.threshold = (_options$threshold = options.threshold) != null ? _options$threshold : rankings.MATCHES;
if (!options.accessors) {
// if keys is not specified, then we assume the item given is ready to be matched
const rank = getMatchRanking(item, value, options);
return {
// ends up being duplicate of 'item' in matches but consistent
rankedValue: item,
rank,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: rank >= options.threshold
};
}
const valuesToRank = getAllValuesToRank(item, options.accessors);
const rankingInfo = {
rankedValue: item,
rank: rankings.NO_MATCH,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: false
};
for (let i = 0; i < valuesToRank.length; i++) {
const rankValue = valuesToRank[i];
let newRank = getMatchRanking(rankValue.itemValue, value, options);
const {
minRanking,
maxRanking,
threshold = options.threshold
} = rankValue.attributes;
if (newRank < minRanking && newRank >= rankings.MATCHES) {
newRank = minRanking;
} else if (newRank > maxRanking) {
newRank = maxRanking;
}
newRank = Math.min(newRank, maxRanking);
if (newRank >= threshold && newRank > rankingInfo.rank) {
rankingInfo.rank = newRank;
rankingInfo.passed = true;
rankingInfo.accessorIndex = i;
rankingInfo.accessorThreshold = threshold;
rankingInfo.rankedValue = rankValue.itemValue;
}
}
return rankingInfo;
}
/**
* Gives a rankings score based on how well the two strings match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @param {Object} options - options for the match (like keepDiacritics for comparison)
* @returns {Number} the ranking for how well stringToRank matches testString
*/
function getMatchRanking(testString, stringToRank, options) {
testString = prepareValueForComparison(testString, options);
stringToRank = prepareValueForComparison(stringToRank, options);
// too long
if (stringToRank.length > testString.length) {
return rankings.NO_MATCH;
}
// case sensitive equals
if (testString === stringToRank) {
return rankings.CASE_SENSITIVE_EQUAL;
}
// Lower casing before further comparison
testString = testString.toLowerCase();
stringToRank = stringToRank.toLowerCase();
// case insensitive equals
if (testString === stringToRank) {
return rankings.EQUAL;
}
// starts with
if (testString.startsWith(stringToRank)) {
return rankings.STARTS_WITH;
}
// word starts with
if (testString.includes(` ${stringToRank}`)) {
return rankings.WORD_STARTS_WITH;
}
// contains
if (testString.includes(stringToRank)) {
return rankings.CONTAINS;
} else if (stringToRank.length === 1) {
// If the only character in the given stringToRank
// isn't even contained in the testString, then
// it's definitely not a match.
return rankings.NO_MATCH;
}
// acronym
if (getAcronym(testString).includes(stringToRank)) {
return rankings.ACRONYM;
}
// will return a number between rankings.MATCHES and
// rankings.MATCHES + 1 depending on how close of a match it is.
return getClosenessRanking(testString, stringToRank);
}
/**
* Generates an acronym for a string.
*
* @param {String} string the string for which to produce the acronym
* @returns {String} the acronym
*/
function getAcronym(string) {
let acronym = '';
const wordsInString = string.split(' ');
wordsInString.forEach(wordInString => {
const splitByHyphenWords = wordInString.split('-');
splitByHyphenWords.forEach(splitByHyphenWord => {
acronym += splitByHyphenWord.substr(0, 1);
});
});
return acronym;
}
/**
* Returns a score based on how spread apart the
* characters from the stringToRank are within the testString.
* A number close to rankings.MATCHES represents a loose match. A number close
* to rankings.MATCHES + 1 represents a tighter match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @returns {Number} the number between rankings.MATCHES and
* rankings.MATCHES + 1 for how well stringToRank matches testString
*/
function getClosenessRanking(testString, stringToRank) {
let matchingInOrderCharCount = 0;
let charNumber = 0;
function findMatchingCharacter(matchChar, string, index) {
for (let j = index, J = string.length; j < J; j++) {
const stringChar = string[j];
if (stringChar === matchChar) {
matchingInOrderCharCount += 1;
return j + 1;
}
}
return -1;
}
function getRanking(spread) {
const spreadPercentage = 1 / spread;
const inOrderPercentage = matchingInOrderCharCount / stringToRank.length;
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage;
return ranking;
}
const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0);
if (firstIndex < 0) {
return rankings.NO_MATCH;
}
charNumber = firstIndex;
for (let i = 1, I = stringToRank.length; i < I; i++) {
const matchChar = stringToRank[i];
charNumber = findMatchingCharacter(matchChar, testString, charNumber);
const found = charNumber > -1;
if (!found) {
return rankings.NO_MATCH;
}
}
const spread = charNumber - firstIndex;
return getRanking(spread);
}
/**
* Sorts items that have a rank, index, and accessorIndex
* @param {Object} a - the first item to sort
* @param {Object} b - the second item to sort
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
*/
function compareItems(a, b) {
return a.rank === b.rank ? 0 : a.rank > b.rank ? -1 : 1;
}
/**
* Prepares value for comparison by stringifying it, removing diacritics (if specified)
* @param {String} value - the value to clean
* @param {Object} options - {keepDiacritics: whether to remove diacritics}
* @return {String} the prepared value
*/
function prepareValueForComparison(value, _ref) {
let {
keepDiacritics
} = _ref;
// value might not actually be a string at this point (we don't get to choose)
// so part of preparing the value for comparison is ensure that it is a string
value = `${value}`; // toString
if (!keepDiacritics) {
value = removeAccents.removeAccents(value);
}
return value;
}
/**
* Gets value for key in item at arbitrarily nested keypath
* @param {Object} item - the item
* @param {Object|Function} key - the potentially nested keypath or property callback
* @return {Array} - an array containing the value(s) at the nested keypath
*/
function getItemValues(item, accessor) {
let accessorFn = accessor;
if (typeof accessor === 'object') {
accessorFn = accessor.accessor;
}
const value = accessorFn(item);
// because `value` can also be undefined
if (value == null) {
return [];
}
if (Array.isArray(value)) {
return value;
}
return [String(value)];
}
/**
* Gets all the values for the given keys in the given item and returns an array of those values
* @param item - the item from which the values will be retrieved
* @param keys - the keys to use to retrieve the values
* @return objects with {itemValue, attributes}
*/
function getAllValuesToRank(item, accessors) {
const allValues = [];
for (let j = 0, J = accessors.length; j < J; j++) {
const accessor = accessors[j];
const attributes = getAccessorAttributes(accessor);
const itemValues = getItemValues(item, accessor);
for (let i = 0, I = itemValues.length; i < I; i++) {
allValues.push({
itemValue: itemValues[i],
attributes
});
}
}
return allValues;
}
const defaultKeyAttributes = {
maxRanking: Infinity,
minRanking: -Infinity
};
/**
* Gets all the attributes for the given accessor
* @param accessor - the accessor from which the attributes will be retrieved
* @return object containing the accessor's attributes
*/
function getAccessorAttributes(accessor) {
if (typeof accessor === 'function') {
return defaultKeyAttributes;
}
return {
...defaultKeyAttributes,
...accessor
};
}
exports.compareItems = compareItems;
exports.rankItem = rankItem;
exports.rankings = rankings;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,710 @@
/**
* match-sorter-utils
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
const characterMap = {
À: 'A',
Á: 'A',
Â: 'A',
Ã: 'A',
Ä: 'A',
Å: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
Æ: 'AE',
: 'A',
: 'A',
Ȃ: 'A',
Ç: 'C',
: 'C',
È: 'E',
É: 'E',
Ê: 'E',
Ë: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
Ȇ: 'E',
Ì: 'I',
Í: 'I',
Î: 'I',
Ï: 'I',
: 'I',
Ȋ: 'I',
Ð: 'D',
Ñ: 'N',
Ò: 'O',
Ó: 'O',
Ô: 'O',
Õ: 'O',
Ö: 'O',
Ø: 'O',
: 'O',
: 'O',
: 'O',
Ȏ: 'O',
Ù: 'U',
Ú: 'U',
Û: 'U',
Ü: 'U',
Ý: 'Y',
à: 'a',
á: 'a',
â: 'a',
ã: 'a',
ä: 'a',
å: 'a',
: 'a',
: 'a',
: 'a',
: 'a',
: 'a',
æ: 'ae',
: 'a',
: 'a',
ȃ: 'a',
ç: 'c',
: 'c',
è: 'e',
é: 'e',
ê: 'e',
ë: 'e',
ế: 'e',
: 'e',
: 'e',
: 'e',
: 'e',
ȇ: 'e',
ì: 'i',
í: 'i',
î: 'i',
ï: 'i',
: 'i',
ȋ: 'i',
ð: 'd',
ñ: 'n',
ò: 'o',
ó: 'o',
ô: 'o',
õ: 'o',
ö: 'o',
ø: 'o',
: 'o',
: 'o',
: 'o',
ȏ: 'o',
ù: 'u',
ú: 'u',
û: 'u',
ü: 'u',
ý: 'y',
ÿ: 'y',
Ā: 'A',
ā: 'a',
Ă: 'A',
ă: 'a',
Ą: 'A',
ą: 'a',
Ć: 'C',
ć: 'c',
Ĉ: 'C',
ĉ: 'c',
Ċ: 'C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: 'B',
b̌: 'b',
Č̣: 'C',
č̣: 'c',
Ê̌: 'E',
ê̌: 'e',
F̌: 'F',
f̌: 'f',
Ǧ: 'G',
ǧ: 'g',
Ȟ: 'H',
ȟ: 'h',
J̌: 'J',
ǰ: 'j',
Ǩ: 'K',
ǩ: 'k',
M̌: 'M',
m̌: 'm',
P̌: 'P',
p̌: 'p',
Q̌: 'Q',
q̌: 'q',
Ř̩: 'R',
ř̩: 'r',
: 'S',
: 's',
V̌: 'V',
v̌: 'v',
W̌: 'W',
w̌: 'w',
X̌: 'X',
x̌: 'x',
Y̌: 'Y',
y̌: 'y',
A̧: 'A',
a̧: 'a',
B̧: 'B',
b̧: 'b',
: 'D',
: 'd',
Ȩ: 'E',
ȩ: 'e',
Ɛ̧: 'E',
ɛ̧: 'e',
: 'H',
: 'h',
I̧: 'I',
i̧: 'i',
Ɨ̧: 'I',
ɨ̧: 'i',
M̧: 'M',
m̧: 'm',
O̧: 'O',
o̧: 'o',
Q̧: 'Q',
q̧: 'q',
U̧: 'U',
u̧: 'u',
X̧: 'X',
x̧: 'x',
Z̧: 'Z',
z̧: 'z'
};
const chars = Object.keys(characterMap).join('|');
const allAccents = new RegExp(chars, 'g');
function removeAccents(str) {
return str.replace(allAccents, match => {
return characterMap[match];
});
}
/**
* @name match-sorter
* @license MIT license.
* @copyright (c) 2099 Kent C. Dodds
* @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
*/
const rankings = {
CASE_SENSITIVE_EQUAL: 7,
EQUAL: 6,
STARTS_WITH: 5,
WORD_STARTS_WITH: 4,
CONTAINS: 3,
ACRONYM: 2,
MATCHES: 1,
NO_MATCH: 0
};
/**
* Gets the highest ranking for value for the given item based on its values for the given keys
* @param {*} item - the item to rank
* @param {String} value - the value to rank against
* @param {Object} options - options to control the ranking
* @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
*/
function rankItem(item, value, options) {
var _options$threshold;
options = options || {};
options.threshold = (_options$threshold = options.threshold) != null ? _options$threshold : rankings.MATCHES;
if (!options.accessors) {
// if keys is not specified, then we assume the item given is ready to be matched
const rank = getMatchRanking(item, value, options);
return {
// ends up being duplicate of 'item' in matches but consistent
rankedValue: item,
rank,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: rank >= options.threshold
};
}
const valuesToRank = getAllValuesToRank(item, options.accessors);
const rankingInfo = {
rankedValue: item,
rank: rankings.NO_MATCH,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: false
};
for (let i = 0; i < valuesToRank.length; i++) {
const rankValue = valuesToRank[i];
let newRank = getMatchRanking(rankValue.itemValue, value, options);
const {
minRanking,
maxRanking,
threshold = options.threshold
} = rankValue.attributes;
if (newRank < minRanking && newRank >= rankings.MATCHES) {
newRank = minRanking;
} else if (newRank > maxRanking) {
newRank = maxRanking;
}
newRank = Math.min(newRank, maxRanking);
if (newRank >= threshold && newRank > rankingInfo.rank) {
rankingInfo.rank = newRank;
rankingInfo.passed = true;
rankingInfo.accessorIndex = i;
rankingInfo.accessorThreshold = threshold;
rankingInfo.rankedValue = rankValue.itemValue;
}
}
return rankingInfo;
}
/**
* Gives a rankings score based on how well the two strings match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @param {Object} options - options for the match (like keepDiacritics for comparison)
* @returns {Number} the ranking for how well stringToRank matches testString
*/
function getMatchRanking(testString, stringToRank, options) {
testString = prepareValueForComparison(testString, options);
stringToRank = prepareValueForComparison(stringToRank, options);
// too long
if (stringToRank.length > testString.length) {
return rankings.NO_MATCH;
}
// case sensitive equals
if (testString === stringToRank) {
return rankings.CASE_SENSITIVE_EQUAL;
}
// Lower casing before further comparison
testString = testString.toLowerCase();
stringToRank = stringToRank.toLowerCase();
// case insensitive equals
if (testString === stringToRank) {
return rankings.EQUAL;
}
// starts with
if (testString.startsWith(stringToRank)) {
return rankings.STARTS_WITH;
}
// word starts with
if (testString.includes(` ${stringToRank}`)) {
return rankings.WORD_STARTS_WITH;
}
// contains
if (testString.includes(stringToRank)) {
return rankings.CONTAINS;
} else if (stringToRank.length === 1) {
// If the only character in the given stringToRank
// isn't even contained in the testString, then
// it's definitely not a match.
return rankings.NO_MATCH;
}
// acronym
if (getAcronym(testString).includes(stringToRank)) {
return rankings.ACRONYM;
}
// will return a number between rankings.MATCHES and
// rankings.MATCHES + 1 depending on how close of a match it is.
return getClosenessRanking(testString, stringToRank);
}
/**
* Generates an acronym for a string.
*
* @param {String} string the string for which to produce the acronym
* @returns {String} the acronym
*/
function getAcronym(string) {
let acronym = '';
const wordsInString = string.split(' ');
wordsInString.forEach(wordInString => {
const splitByHyphenWords = wordInString.split('-');
splitByHyphenWords.forEach(splitByHyphenWord => {
acronym += splitByHyphenWord.substr(0, 1);
});
});
return acronym;
}
/**
* Returns a score based on how spread apart the
* characters from the stringToRank are within the testString.
* A number close to rankings.MATCHES represents a loose match. A number close
* to rankings.MATCHES + 1 represents a tighter match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @returns {Number} the number between rankings.MATCHES and
* rankings.MATCHES + 1 for how well stringToRank matches testString
*/
function getClosenessRanking(testString, stringToRank) {
let matchingInOrderCharCount = 0;
let charNumber = 0;
function findMatchingCharacter(matchChar, string, index) {
for (let j = index, J = string.length; j < J; j++) {
const stringChar = string[j];
if (stringChar === matchChar) {
matchingInOrderCharCount += 1;
return j + 1;
}
}
return -1;
}
function getRanking(spread) {
const spreadPercentage = 1 / spread;
const inOrderPercentage = matchingInOrderCharCount / stringToRank.length;
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage;
return ranking;
}
const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0);
if (firstIndex < 0) {
return rankings.NO_MATCH;
}
charNumber = firstIndex;
for (let i = 1, I = stringToRank.length; i < I; i++) {
const matchChar = stringToRank[i];
charNumber = findMatchingCharacter(matchChar, testString, charNumber);
const found = charNumber > -1;
if (!found) {
return rankings.NO_MATCH;
}
}
const spread = charNumber - firstIndex;
return getRanking(spread);
}
/**
* Sorts items that have a rank, index, and accessorIndex
* @param {Object} a - the first item to sort
* @param {Object} b - the second item to sort
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
*/
function compareItems(a, b) {
return a.rank === b.rank ? 0 : a.rank > b.rank ? -1 : 1;
}
/**
* Prepares value for comparison by stringifying it, removing diacritics (if specified)
* @param {String} value - the value to clean
* @param {Object} options - {keepDiacritics: whether to remove diacritics}
* @return {String} the prepared value
*/
function prepareValueForComparison(value, _ref) {
let {
keepDiacritics
} = _ref;
// value might not actually be a string at this point (we don't get to choose)
// so part of preparing the value for comparison is ensure that it is a string
value = `${value}`; // toString
if (!keepDiacritics) {
value = removeAccents(value);
}
return value;
}
/**
* Gets value for key in item at arbitrarily nested keypath
* @param {Object} item - the item
* @param {Object|Function} key - the potentially nested keypath or property callback
* @return {Array} - an array containing the value(s) at the nested keypath
*/
function getItemValues(item, accessor) {
let accessorFn = accessor;
if (typeof accessor === 'object') {
accessorFn = accessor.accessor;
}
const value = accessorFn(item);
// because `value` can also be undefined
if (value == null) {
return [];
}
if (Array.isArray(value)) {
return value;
}
return [String(value)];
}
/**
* Gets all the values for the given keys in the given item and returns an array of those values
* @param item - the item from which the values will be retrieved
* @param keys - the keys to use to retrieve the values
* @return objects with {itemValue, attributes}
*/
function getAllValuesToRank(item, accessors) {
const allValues = [];
for (let j = 0, J = accessors.length; j < J; j++) {
const accessor = accessors[j];
const attributes = getAccessorAttributes(accessor);
const itemValues = getItemValues(item, accessor);
for (let i = 0, I = itemValues.length; i < I; i++) {
allValues.push({
itemValue: itemValues[i],
attributes
});
}
}
return allValues;
}
const defaultKeyAttributes = {
maxRanking: Infinity,
minRanking: -Infinity
};
/**
* Gets all the attributes for the given accessor
* @param accessor - the accessor from which the attributes will be retrieved
* @return object containing the accessor's attributes
*/
function getAccessorAttributes(accessor) {
if (typeof accessor === 'function') {
return defaultKeyAttributes;
}
return {
...defaultKeyAttributes,
...accessor
};
}
export { compareItems, rankItem, rankings };
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare function removeAccents(str: string): string;

View File

@@ -0,0 +1,423 @@
/**
* match-sorter-utils
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
'use strict';
const characterMap = {
À: 'A',
Á: 'A',
Â: 'A',
Ã: 'A',
Ä: 'A',
Å: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
Æ: 'AE',
: 'A',
: 'A',
Ȃ: 'A',
Ç: 'C',
: 'C',
È: 'E',
É: 'E',
Ê: 'E',
Ë: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
Ȇ: 'E',
Ì: 'I',
Í: 'I',
Î: 'I',
Ï: 'I',
: 'I',
Ȋ: 'I',
Ð: 'D',
Ñ: 'N',
Ò: 'O',
Ó: 'O',
Ô: 'O',
Õ: 'O',
Ö: 'O',
Ø: 'O',
: 'O',
: 'O',
: 'O',
Ȏ: 'O',
Ù: 'U',
Ú: 'U',
Û: 'U',
Ü: 'U',
Ý: 'Y',
à: 'a',
á: 'a',
â: 'a',
ã: 'a',
ä: 'a',
å: 'a',
: 'a',
: 'a',
: 'a',
: 'a',
: 'a',
æ: 'ae',
: 'a',
: 'a',
ȃ: 'a',
ç: 'c',
: 'c',
è: 'e',
é: 'e',
ê: 'e',
ë: 'e',
ế: 'e',
: 'e',
: 'e',
: 'e',
: 'e',
ȇ: 'e',
ì: 'i',
í: 'i',
î: 'i',
ï: 'i',
: 'i',
ȋ: 'i',
ð: 'd',
ñ: 'n',
ò: 'o',
ó: 'o',
ô: 'o',
õ: 'o',
ö: 'o',
ø: 'o',
: 'o',
: 'o',
: 'o',
ȏ: 'o',
ù: 'u',
ú: 'u',
û: 'u',
ü: 'u',
ý: 'y',
ÿ: 'y',
Ā: 'A',
ā: 'a',
Ă: 'A',
ă: 'a',
Ą: 'A',
ą: 'a',
Ć: 'C',
ć: 'c',
Ĉ: 'C',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: 'U',
ȕ: 'u',
B̌: 'B',
b̌: 'b',
Č̣: 'C',
č̣: 'c',
Ê̌: 'E',
ê̌: 'e',
F̌: 'F',
f̌: 'f',
Ǧ: 'G',
ǧ: 'g',
Ȟ: 'H',
ȟ: 'h',
J̌: 'J',
ǰ: 'j',
Ǩ: 'K',
ǩ: 'k',
M̌: 'M',
m̌: 'm',
P̌: 'P',
p̌: 'p',
Q̌: 'Q',
q̌: 'q',
Ř̩: 'R',
ř̩: 'r',
: 'S',
: 's',
V̌: 'V',
v̌: 'v',
W̌: 'W',
w̌: 'w',
X̌: 'X',
x̌: 'x',
Y̌: 'Y',
y̌: 'y',
A̧: 'A',
a̧: 'a',
B̧: 'B',
b̧: 'b',
: 'D',
: 'd',
Ȩ: 'E',
ȩ: 'e',
Ɛ̧: 'E',
ɛ̧: 'e',
: 'H',
: 'h',
I̧: 'I',
i̧: 'i',
Ɨ̧: 'I',
ɨ̧: 'i',
M̧: 'M',
m̧: 'm',
O̧: 'O',
o̧: 'o',
Q̧: 'Q',
q̧: 'q',
U̧: 'U',
u̧: 'u',
X̧: 'X',
x̧: 'x',
Z̧: 'Z',
z̧: 'z'
};
const chars = Object.keys(characterMap).join('|');
const allAccents = new RegExp(chars, 'g');
function removeAccents(str) {
return str.replace(allAccents, match => {
return characterMap[match];
});
}
exports.removeAccents = removeAccents;
//# sourceMappingURL=remove-accents.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,720 @@
/**
* match-sorter-utils
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MatchSorterUtils = {}));
})(this, (function (exports) { 'use strict';
const characterMap = {
À: 'A',
Á: 'A',
Â: 'A',
Ã: 'A',
Ä: 'A',
Å: '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: 'Q',
q̌: 'q',
Ř̩: 'R',
ř̩: 'r',
: 'S',
: 's',
V̌: 'V',
v̌: 'v',
W̌: 'W',
w̌: 'w',
X̌: 'X',
x̌: 'x',
Y̌: 'Y',
y̌: 'y',
A̧: 'A',
a̧: 'a',
B̧: 'B',
b̧: 'b',
: 'D',
: 'd',
Ȩ: 'E',
ȩ: 'e',
Ɛ̧: 'E',
ɛ̧: 'e',
: 'H',
: 'h',
I̧: 'I',
i̧: 'i',
Ɨ̧: 'I',
ɨ̧: 'i',
M̧: 'M',
m̧: 'm',
O̧: 'O',
o̧: 'o',
Q̧: 'Q',
q̧: 'q',
U̧: 'U',
u̧: 'u',
X̧: 'X',
x̧: 'x',
Z̧: 'Z',
z̧: 'z'
};
const chars = Object.keys(characterMap).join('|');
const allAccents = new RegExp(chars, 'g');
function removeAccents(str) {
return str.replace(allAccents, match => {
return characterMap[match];
});
}
/**
* @name match-sorter
* @license MIT license.
* @copyright (c) 2099 Kent C. Dodds
* @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
*/
const rankings = {
CASE_SENSITIVE_EQUAL: 7,
EQUAL: 6,
STARTS_WITH: 5,
WORD_STARTS_WITH: 4,
CONTAINS: 3,
ACRONYM: 2,
MATCHES: 1,
NO_MATCH: 0
};
/**
* Gets the highest ranking for value for the given item based on its values for the given keys
* @param {*} item - the item to rank
* @param {String} value - the value to rank against
* @param {Object} options - options to control the ranking
* @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
*/
function rankItem(item, value, options) {
var _options$threshold;
options = options || {};
options.threshold = (_options$threshold = options.threshold) != null ? _options$threshold : rankings.MATCHES;
if (!options.accessors) {
// if keys is not specified, then we assume the item given is ready to be matched
const rank = getMatchRanking(item, value, options);
return {
// ends up being duplicate of 'item' in matches but consistent
rankedValue: item,
rank,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: rank >= options.threshold
};
}
const valuesToRank = getAllValuesToRank(item, options.accessors);
const rankingInfo = {
rankedValue: item,
rank: rankings.NO_MATCH,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: false
};
for (let i = 0; i < valuesToRank.length; i++) {
const rankValue = valuesToRank[i];
let newRank = getMatchRanking(rankValue.itemValue, value, options);
const {
minRanking,
maxRanking,
threshold = options.threshold
} = rankValue.attributes;
if (newRank < minRanking && newRank >= rankings.MATCHES) {
newRank = minRanking;
} else if (newRank > maxRanking) {
newRank = maxRanking;
}
newRank = Math.min(newRank, maxRanking);
if (newRank >= threshold && newRank > rankingInfo.rank) {
rankingInfo.rank = newRank;
rankingInfo.passed = true;
rankingInfo.accessorIndex = i;
rankingInfo.accessorThreshold = threshold;
rankingInfo.rankedValue = rankValue.itemValue;
}
}
return rankingInfo;
}
/**
* Gives a rankings score based on how well the two strings match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @param {Object} options - options for the match (like keepDiacritics for comparison)
* @returns {Number} the ranking for how well stringToRank matches testString
*/
function getMatchRanking(testString, stringToRank, options) {
testString = prepareValueForComparison(testString, options);
stringToRank = prepareValueForComparison(stringToRank, options);
// too long
if (stringToRank.length > testString.length) {
return rankings.NO_MATCH;
}
// case sensitive equals
if (testString === stringToRank) {
return rankings.CASE_SENSITIVE_EQUAL;
}
// Lower casing before further comparison
testString = testString.toLowerCase();
stringToRank = stringToRank.toLowerCase();
// case insensitive equals
if (testString === stringToRank) {
return rankings.EQUAL;
}
// starts with
if (testString.startsWith(stringToRank)) {
return rankings.STARTS_WITH;
}
// word starts with
if (testString.includes(` ${stringToRank}`)) {
return rankings.WORD_STARTS_WITH;
}
// contains
if (testString.includes(stringToRank)) {
return rankings.CONTAINS;
} else if (stringToRank.length === 1) {
// If the only character in the given stringToRank
// isn't even contained in the testString, then
// it's definitely not a match.
return rankings.NO_MATCH;
}
// acronym
if (getAcronym(testString).includes(stringToRank)) {
return rankings.ACRONYM;
}
// will return a number between rankings.MATCHES and
// rankings.MATCHES + 1 depending on how close of a match it is.
return getClosenessRanking(testString, stringToRank);
}
/**
* Generates an acronym for a string.
*
* @param {String} string the string for which to produce the acronym
* @returns {String} the acronym
*/
function getAcronym(string) {
let acronym = '';
const wordsInString = string.split(' ');
wordsInString.forEach(wordInString => {
const splitByHyphenWords = wordInString.split('-');
splitByHyphenWords.forEach(splitByHyphenWord => {
acronym += splitByHyphenWord.substr(0, 1);
});
});
return acronym;
}
/**
* Returns a score based on how spread apart the
* characters from the stringToRank are within the testString.
* A number close to rankings.MATCHES represents a loose match. A number close
* to rankings.MATCHES + 1 represents a tighter match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @returns {Number} the number between rankings.MATCHES and
* rankings.MATCHES + 1 for how well stringToRank matches testString
*/
function getClosenessRanking(testString, stringToRank) {
let matchingInOrderCharCount = 0;
let charNumber = 0;
function findMatchingCharacter(matchChar, string, index) {
for (let j = index, J = string.length; j < J; j++) {
const stringChar = string[j];
if (stringChar === matchChar) {
matchingInOrderCharCount += 1;
return j + 1;
}
}
return -1;
}
function getRanking(spread) {
const spreadPercentage = 1 / spread;
const inOrderPercentage = matchingInOrderCharCount / stringToRank.length;
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage;
return ranking;
}
const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0);
if (firstIndex < 0) {
return rankings.NO_MATCH;
}
charNumber = firstIndex;
for (let i = 1, I = stringToRank.length; i < I; i++) {
const matchChar = stringToRank[i];
charNumber = findMatchingCharacter(matchChar, testString, charNumber);
const found = charNumber > -1;
if (!found) {
return rankings.NO_MATCH;
}
}
const spread = charNumber - firstIndex;
return getRanking(spread);
}
/**
* Sorts items that have a rank, index, and accessorIndex
* @param {Object} a - the first item to sort
* @param {Object} b - the second item to sort
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
*/
function compareItems(a, b) {
return a.rank === b.rank ? 0 : a.rank > b.rank ? -1 : 1;
}
/**
* Prepares value for comparison by stringifying it, removing diacritics (if specified)
* @param {String} value - the value to clean
* @param {Object} options - {keepDiacritics: whether to remove diacritics}
* @return {String} the prepared value
*/
function prepareValueForComparison(value, _ref) {
let {
keepDiacritics
} = _ref;
// value might not actually be a string at this point (we don't get to choose)
// so part of preparing the value for comparison is ensure that it is a string
value = `${value}`; // toString
if (!keepDiacritics) {
value = removeAccents(value);
}
return value;
}
/**
* Gets value for key in item at arbitrarily nested keypath
* @param {Object} item - the item
* @param {Object|Function} key - the potentially nested keypath or property callback
* @return {Array} - an array containing the value(s) at the nested keypath
*/
function getItemValues(item, accessor) {
let accessorFn = accessor;
if (typeof accessor === 'object') {
accessorFn = accessor.accessor;
}
const value = accessorFn(item);
// because `value` can also be undefined
if (value == null) {
return [];
}
if (Array.isArray(value)) {
return value;
}
return [String(value)];
}
/**
* Gets all the values for the given keys in the given item and returns an array of those values
* @param item - the item from which the values will be retrieved
* @param keys - the keys to use to retrieve the values
* @return objects with {itemValue, attributes}
*/
function getAllValuesToRank(item, accessors) {
const allValues = [];
for (let j = 0, J = accessors.length; j < J; j++) {
const accessor = accessors[j];
const attributes = getAccessorAttributes(accessor);
const itemValues = getItemValues(item, accessor);
for (let i = 0, I = itemValues.length; i < I; i++) {
allValues.push({
itemValue: itemValues[i],
attributes
});
}
}
return allValues;
}
const defaultKeyAttributes = {
maxRanking: Infinity,
minRanking: -Infinity
};
/**
* Gets all the attributes for the given accessor
* @param accessor - the accessor from which the attributes will be retrieved
* @return object containing the accessor's attributes
*/
function getAccessorAttributes(accessor) {
if (typeof accessor === 'function') {
return defaultKeyAttributes;
}
return {
...defaultKeyAttributes,
...accessor
};
}
exports.compareItems = compareItems;
exports.rankItem = rankItem;
exports.rankings = rankings;
}));
//# sourceMappingURL=index.development.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,19 @@
/**
* match-sorter-utils
*
* Copyright (c) TanStack
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((e="undefined"!=typeof globalThis?globalThis:e||self).MatchSorterUtils={})}(this,(function(e){"use strict";const n={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","Ấ":"A","Ắ":"A","Ẳ":"A","Ẵ":"A","Ặ":"A","Æ":"AE","Ầ":"A","Ằ":"A","Ȃ":"A","Ç":"C","Ḉ":"C","È":"E","É":"E","Ê":"E","Ë":"E","Ế":"E","Ḗ":"E","Ề":"E","Ḕ":"E","Ḝ":"E","Ȇ":"E","Ì":"I","Í":"I","Î":"I","Ï":"I","Ḯ":"I","Ȋ":"I","Ð":"D","Ñ":"N","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","Ố":"O","Ṍ":"O","Ṓ":"O","Ȏ":"O","Ù":"U","Ú":"U","Û":"U","Ü":"U","Ý":"Y","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","ấ":"a","ắ":"a","ẳ":"a","ẵ":"a","ặ":"a","æ":"ae","ầ":"a","ằ":"a","ȃ":"a","ç":"c","ḉ":"c","è":"e","é":"e","ê":"e","ë":"e","ế":"e","ḗ":"e","ề":"e","ḕ":"e","ḝ":"e","ȇ":"e","ì":"i","í":"i","î":"i","ï":"i","ḯ":"i","ȋ":"i","ð":"d","ñ":"n","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","ố":"o","ṍ":"o","ṓ":"o","ȏ":"o","ù":"u","ú":"u","û":"u","ü":"u","ý":"y","ÿ":"y","Ā":"A","ā":"a","Ă":"A","ă":"a","Ą":"A","ą":"a","Ć":"C","ć":"c","Ĉ":"C","ĉ":"c","Ċ":"C","ċ":"c","Č":"C","č":"c","C̆":"C","c̆":"c","Ď":"D","ď":"d","Đ":"D","đ":"d","Ē":"E","ē":"e","Ĕ":"E","ĕ":"e","Ė":"E","ė":"e","Ę":"E","ę":"e","Ě":"E","ě":"e","Ĝ":"G","Ǵ":"G","ĝ":"g","ǵ":"g","Ğ":"G","ğ":"g","Ġ":"G","ġ":"g","Ģ":"G","ģ":"g","Ĥ":"H","ĥ":"h","Ħ":"H","ħ":"h","Ḫ":"H","ḫ":"h","Ĩ":"I","ĩ":"i","Ī":"I","ī":"i","Ĭ":"I","ĭ":"i","Į":"I","į":"i","İ":"I","ı":"i","IJ":"IJ","ij":"ij","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","Ḱ":"K","ḱ":"k","K̆":"K","k̆":"k","Ĺ":"L","ĺ":"l","Ļ":"L","ļ":"l","Ľ":"L","ľ":"l","Ŀ":"L","ŀ":"l","Ł":"l","ł":"l","Ḿ":"M","ḿ":"m","M̆":"M","m̆":"m","Ń":"N","ń":"n","Ņ":"N","ņ":"n","Ň":"N","ň":"n","ʼn":"n","N̆":"N","n̆":"n","Ō":"O","ō":"o","Ŏ":"O","ŏ":"o","Ő":"O","ő":"o","Œ":"OE","œ":"oe","P̆":"P","p̆":"p","Ŕ":"R","ŕ":"r","Ŗ":"R","ŗ":"r","Ř":"R","ř":"r","R̆":"R","r̆":"r","Ȓ":"R","ȓ":"r","Ś":"S","ś":"s","Ŝ":"S","ŝ":"s","Ş":"S","Ș":"S","ș":"s","ş":"s","Š":"S","š":"s","Ţ":"T","ţ":"t","ț":"t","Ț":"T","Ť":"T","ť":"t","Ŧ":"T","ŧ":"t","T̆":"T","t̆":"t","Ũ":"U","ũ":"u","Ū":"U","ū":"u","Ŭ":"U","ŭ":"u","Ů":"U","ů":"u","Ű":"U","ű":"u","Ų":"U","ų":"u","Ȗ":"U","ȗ":"u","V̆":"V","v̆":"v","Ŵ":"W","ŵ":"w","Ẃ":"W","ẃ":"w","X̆":"X","x̆":"x","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Y̆":"Y","y̆":"y","Ź":"Z","ź":"z","Ż":"Z","ż":"z","Ž":"Z","ž":"z","ſ":"s","ƒ":"f","Ơ":"O","ơ":"o","Ư":"U","ư":"u","Ǎ":"A","ǎ":"a","Ǐ":"I","ǐ":"i","Ǒ":"O","ǒ":"o","Ǔ":"U","ǔ":"u","Ǖ":"U","ǖ":"u","Ǘ":"U","ǘ":"u","Ǚ":"U","ǚ":"u","Ǜ":"U","ǜ":"u","Ứ":"U","ứ":"u","Ṹ":"U","ṹ":"u","Ǻ":"A","ǻ":"a","Ǽ":"AE","ǽ":"ae","Ǿ":"O","ǿ":"o","Þ":"TH","þ":"th","Ṕ":"P","ṕ":"p","Ṥ":"S","ṥ":"s","X́":"X","x́":"x","Ѓ":"Г","ѓ":"г","Ќ":"К","ќ":"к","A̋":"A","a̋":"a","E̋":"E","e̋":"e","I̋":"I","i̋":"i","Ǹ":"N","ǹ":"n","Ồ":"O","ồ":"o","Ṑ":"O","ṑ":"o","Ừ":"U","ừ":"u","Ẁ":"W","ẁ":"w","Ỳ":"Y","ỳ":"y","Ȁ":"A","ȁ":"a","Ȅ":"E","ȅ":"e","Ȉ":"I","ȉ":"i","Ȍ":"O","ȍ":"o","Ȑ":"R","ȑ":"r","Ȕ":"U","ȕ":"u","B̌":"B","b̌":"b","Č̣":"C","č̣":"c","Ê̌":"E","ê̌":"e","F̌":"F","f̌":"f","Ǧ":"G","ǧ":"g","Ȟ":"H","ȟ":"h","J̌":"J","ǰ":"j","Ǩ":"K","ǩ":"k","M̌":"M","m̌":"m","P̌":"P","p̌":"p","Q̌":"Q","q̌":"q","Ř̩":"R","ř̩":"r","Ṧ":"S","ṧ":"s","V̌":"V","v̌":"v","W̌":"W","w̌":"w","X̌":"X","x̌":"x","Y̌":"Y","y̌":"y","A̧":"A","a̧":"a","B̧":"B","b̧":"b","Ḑ":"D","ḑ":"d","Ȩ":"E","ȩ":"e","Ɛ̧":"E","ɛ̧":"e","Ḩ":"H","ḩ":"h","I̧":"I","i̧":"i","Ɨ̧":"I","ɨ̧":"i","M̧":"M","m̧":"m","O̧":"O","o̧":"o","Q̧":"Q","q̧":"q","U̧":"U","u̧":"u","X̧":"X","x̧":"x","Z̧":"Z","z̧":"z"},t=Object.keys(n).join("|"),r=new RegExp(t,"g");
/**
* @name match-sorter
* @license MIT license.
* @copyright (c) 2099 Kent C. Dodds
* @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
*/
const o={CASE_SENSITIVE_EQUAL:7,EQUAL:6,STARTS_WITH:5,WORD_STARTS_WITH:4,CONTAINS:3,ACRONYM:2,MATCHES:1,NO_MATCH:0};function s(e,n,t){return e=a(e,t),(n=a(n,t)).length>e.length?o.NO_MATCH:e===n?o.CASE_SENSITIVE_EQUAL:(e=e.toLowerCase())===(n=n.toLowerCase())?o.EQUAL:e.startsWith(n)?o.STARTS_WITH:e.includes(` ${n}`)?o.WORD_STARTS_WITH:e.includes(n)?o.CONTAINS:1===n.length?o.NO_MATCH:function(e){let n="";return e.split(" ").forEach((e=>{e.split("-").forEach((e=>{n+=e.substr(0,1)}))})),n}(e).includes(n)?o.ACRONYM:function(e,n){let t=0,r=0;function s(e,n,r){for(let o=r,s=n.length;o<s;o++){if(n[o]===e)return t+=1,o+1}return-1}function a(e){const r=1/e,s=t/n.length;return o.MATCHES+s*r}const i=s(n[0],e,0);if(i<0)return o.NO_MATCH;r=i;for(let t=1,a=n.length;t<a;t++){r=s(n[t],e,r);if(!(r>-1))return o.NO_MATCH}return a(r-i)}(e,n)}function a(e,t){let{keepDiacritics:o}=t;return e=`${e}`,o||(e=e.replace(r,(e=>n[e]))),e}function i(e,n){let t=n;"object"==typeof n&&(t=n.accessor);const r=t(e);return null==r?[]:Array.isArray(r)?r:[String(r)]}const u={maxRanking:1/0,minRanking:-1/0};function c(e){return"function"==typeof e?u:{...u,...e}}e.compareItems=function(e,n){return e.rank===n.rank?0:e.rank>n.rank?-1:1},e.rankItem=function(e,n,t){var r;if((t=t||{}).threshold=null!=(r=t.threshold)?r:o.MATCHES,!t.accessors){const r=s(e,n,t);return{rankedValue:e,rank:r,accessorIndex:-1,accessorThreshold:t.threshold,passed:r>=t.threshold}}const a=function(e,n){const t=[];for(let r=0,o=n.length;r<o;r++){const o=n[r],s=c(o),a=i(e,o);for(let e=0,n=a.length;e<n;e++)t.push({itemValue:a[e],attributes:s})}return t}(e,t.accessors),u={rankedValue:e,rank:o.NO_MATCH,accessorIndex:-1,accessorThreshold:t.threshold,passed:!1};for(let e=0;e<a.length;e++){const r=a[e];let i=s(r.itemValue,n,t);const{minRanking:c,maxRanking:l,threshold:A=t.threshold}=r.attributes;i<c&&i>=o.MATCHES?i=c:i>l&&(i=l),i=Math.min(i,l),i>=A&&i>u.rank&&(u.rank=i,u.passed=!0,u.accessorIndex=e,u.accessorThreshold=A,u.rankedValue=r.itemValue)}return u},e.rankings=o}));
//# sourceMappingURL=index.production.js.map

File diff suppressed because one or more lines are too long

54
node_modules/@tanstack/match-sorter-utils/package.json generated vendored Normal file
View File

@@ -0,0 +1,54 @@
{
"name": "@tanstack/match-sorter-utils",
"version": "8.19.4",
"description": "A fork of match-sorter with separated filtering and sorting phases",
"contributors": [
"Kent C. Dodds",
"Tanner Linsley"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/TanStack/table.git",
"directory": "packages/match-sorter-utils"
},
"homepage": "https://tanstack.com/table",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"keywords": [
"react",
"table",
"match-sorter",
"utils",
"split",
"separate",
"datagrid"
],
"type": "commonjs",
"module": "build/lib/index.esm.js",
"main": "build/lib/index.js",
"types": "build/lib/index.d.ts",
"exports": {
".": {
"types": "./build/lib/index.d.ts",
"import": "./build/lib/index.mjs",
"default": "./build/lib/index.js"
},
"./package.json": "./package.json"
},
"sideEffects": false,
"engines": {
"node": ">=12"
},
"files": [
"build/lib/*",
"build/umd/*",
"src"
],
"dependencies": {
"remove-accents": "0.5.0"
},
"scripts": {}
}

379
node_modules/@tanstack/match-sorter-utils/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,379 @@
/**
* @name match-sorter
* @license MIT license.
* @copyright (c) 2099 Kent C. Dodds
* @author Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
*/
// This is a fork of match-sorter. Instead of offering
// a unified API for filtering and sorting in a single pass,
// match-sorter-utils provides the lower-level utilities of
// ranking items and comparing ranks in a way that can
// be incrementally applied to a system rather than
// all-at-once.
// 1. Use the rankItem function to rank an item
// 2. Use the resulting rankingInfo.passed to filter
// 3. Use the resulting rankingInfo.rank to sort
// For bundling purposes (mainly remove-accents not being esm safe/ready),
// we've also hard-coded remove-accents into this source.
// The remove-accents package is still included as a dependency
// for attribution purposes, but it will not be imported and bundled.
import { removeAccents } from './remove-accents'
export type AccessorAttributes = {
threshold?: Ranking
maxRanking: Ranking
minRanking: Ranking
}
export interface RankingInfo {
rankedValue: any
rank: Ranking
accessorIndex: number
accessorThreshold: Ranking | undefined
passed: boolean
}
export interface AccessorOptions<TItem> {
accessor: AccessorFn<TItem>
threshold?: Ranking
maxRanking?: Ranking
minRanking?: Ranking
}
export type AccessorFn<TItem> = (item: TItem) => string | Array<string>
export type Accessor<TItem> = AccessorFn<TItem> | AccessorOptions<TItem>
export interface RankItemOptions<TItem = unknown> {
accessors?: ReadonlyArray<Accessor<TItem>>
threshold?: Ranking
keepDiacritics?: boolean
}
export const rankings = {
CASE_SENSITIVE_EQUAL: 7,
EQUAL: 6,
STARTS_WITH: 5,
WORD_STARTS_WITH: 4,
CONTAINS: 3,
ACRONYM: 2,
MATCHES: 1,
NO_MATCH: 0,
} as const
export type Ranking = (typeof rankings)[keyof typeof rankings]
/**
* Gets the highest ranking for value for the given item based on its values for the given keys
* @param {*} item - the item to rank
* @param {String} value - the value to rank against
* @param {Object} options - options to control the ranking
* @return {{rank: Number, accessorIndex: Number, accessorThreshold: Number}} - the highest ranking
*/
export function rankItem<TItem>(
item: TItem,
value: string,
options?: RankItemOptions<TItem>
): RankingInfo {
options = options || {}
options.threshold = options.threshold ?? rankings.MATCHES
if (!options.accessors) {
// if keys is not specified, then we assume the item given is ready to be matched
const rank = getMatchRanking(item as unknown as string, value, options)
return {
// ends up being duplicate of 'item' in matches but consistent
rankedValue: item,
rank,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: rank >= options.threshold,
}
}
const valuesToRank = getAllValuesToRank(item, options.accessors)
const rankingInfo: RankingInfo = {
rankedValue: item,
rank: rankings.NO_MATCH as Ranking,
accessorIndex: -1,
accessorThreshold: options.threshold,
passed: false,
}
for (let i = 0; i < valuesToRank.length; i++) {
const rankValue = valuesToRank[i]!
let newRank = getMatchRanking(rankValue.itemValue, value, options)
const {
minRanking,
maxRanking,
threshold = options.threshold,
} = rankValue.attributes
if (newRank < minRanking && newRank >= rankings.MATCHES) {
newRank = minRanking
} else if (newRank > maxRanking) {
newRank = maxRanking
}
newRank = Math.min(newRank, maxRanking) as Ranking
if (newRank >= threshold && newRank > rankingInfo.rank) {
rankingInfo.rank = newRank
rankingInfo.passed = true
rankingInfo.accessorIndex = i
rankingInfo.accessorThreshold = threshold
rankingInfo.rankedValue = rankValue.itemValue
}
}
return rankingInfo
}
/**
* Gives a rankings score based on how well the two strings match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @param {Object} options - options for the match (like keepDiacritics for comparison)
* @returns {Number} the ranking for how well stringToRank matches testString
*/
function getMatchRanking<TItem>(
testString: string,
stringToRank: string,
options: RankItemOptions<TItem>
): Ranking {
testString = prepareValueForComparison(testString, options)
stringToRank = prepareValueForComparison(stringToRank, options)
// too long
if (stringToRank.length > testString.length) {
return rankings.NO_MATCH
}
// case sensitive equals
if (testString === stringToRank) {
return rankings.CASE_SENSITIVE_EQUAL
}
// Lower casing before further comparison
testString = testString.toLowerCase()
stringToRank = stringToRank.toLowerCase()
// case insensitive equals
if (testString === stringToRank) {
return rankings.EQUAL
}
// starts with
if (testString.startsWith(stringToRank)) {
return rankings.STARTS_WITH
}
// word starts with
if (testString.includes(` ${stringToRank}`)) {
return rankings.WORD_STARTS_WITH
}
// contains
if (testString.includes(stringToRank)) {
return rankings.CONTAINS
} else if (stringToRank.length === 1) {
// If the only character in the given stringToRank
// isn't even contained in the testString, then
// it's definitely not a match.
return rankings.NO_MATCH
}
// acronym
if (getAcronym(testString).includes(stringToRank)) {
return rankings.ACRONYM
}
// will return a number between rankings.MATCHES and
// rankings.MATCHES + 1 depending on how close of a match it is.
return getClosenessRanking(testString, stringToRank)
}
/**
* Generates an acronym for a string.
*
* @param {String} string the string for which to produce the acronym
* @returns {String} the acronym
*/
function getAcronym(string: string): string {
let acronym = ''
const wordsInString = string.split(' ')
wordsInString.forEach(wordInString => {
const splitByHyphenWords = wordInString.split('-')
splitByHyphenWords.forEach(splitByHyphenWord => {
acronym += splitByHyphenWord.substr(0, 1)
})
})
return acronym
}
/**
* Returns a score based on how spread apart the
* characters from the stringToRank are within the testString.
* A number close to rankings.MATCHES represents a loose match. A number close
* to rankings.MATCHES + 1 represents a tighter match.
* @param {String} testString - the string to test against
* @param {String} stringToRank - the string to rank
* @returns {Number} the number between rankings.MATCHES and
* rankings.MATCHES + 1 for how well stringToRank matches testString
*/
function getClosenessRanking(
testString: string,
stringToRank: string
): Ranking {
let matchingInOrderCharCount = 0
let charNumber = 0
function findMatchingCharacter(
matchChar: undefined | string,
string: string,
index: number
) {
for (let j = index, J = string.length; j < J; j++) {
const stringChar = string[j]
if (stringChar === matchChar) {
matchingInOrderCharCount += 1
return j + 1
}
}
return -1
}
function getRanking(spread: number) {
const spreadPercentage = 1 / spread
const inOrderPercentage = matchingInOrderCharCount / stringToRank.length
const ranking = rankings.MATCHES + inOrderPercentage * spreadPercentage
return ranking as Ranking
}
const firstIndex = findMatchingCharacter(stringToRank[0], testString, 0)
if (firstIndex < 0) {
return rankings.NO_MATCH
}
charNumber = firstIndex
for (let i = 1, I = stringToRank.length; i < I; i++) {
const matchChar = stringToRank[i]
charNumber = findMatchingCharacter(matchChar, testString, charNumber)
const found = charNumber > -1
if (!found) {
return rankings.NO_MATCH
}
}
const spread = charNumber - firstIndex
return getRanking(spread)
}
/**
* Sorts items that have a rank, index, and accessorIndex
* @param {Object} a - the first item to sort
* @param {Object} b - the second item to sort
* @return {Number} -1 if a should come first, 1 if b should come first, 0 if equal
*/
export function compareItems<TItem>(a: RankingInfo, b: RankingInfo): number {
return a.rank === b.rank ? 0 : a.rank > b.rank ? -1 : 1
}
/**
* Prepares value for comparison by stringifying it, removing diacritics (if specified)
* @param {String} value - the value to clean
* @param {Object} options - {keepDiacritics: whether to remove diacritics}
* @return {String} the prepared value
*/
function prepareValueForComparison<TItem>(
value: string,
{ keepDiacritics }: RankItemOptions<TItem>
): string {
// value might not actually be a string at this point (we don't get to choose)
// so part of preparing the value for comparison is ensure that it is a string
value = `${value}` // toString
if (!keepDiacritics) {
value = removeAccents(value)
}
return value
}
/**
* Gets value for key in item at arbitrarily nested keypath
* @param {Object} item - the item
* @param {Object|Function} key - the potentially nested keypath or property callback
* @return {Array} - an array containing the value(s) at the nested keypath
*/
function getItemValues<TItem>(
item: TItem,
accessor: Accessor<TItem>
): Array<string> {
let accessorFn = accessor as AccessorFn<TItem>
if (typeof accessor === 'object') {
accessorFn = accessor.accessor
}
const value = accessorFn(item)
// because `value` can also be undefined
if (value == null) {
return []
}
if (Array.isArray(value)) {
return value
}
return [String(value)]
}
/**
* Gets all the values for the given keys in the given item and returns an array of those values
* @param item - the item from which the values will be retrieved
* @param keys - the keys to use to retrieve the values
* @return objects with {itemValue, attributes}
*/
function getAllValuesToRank<TItem>(
item: TItem,
accessors: ReadonlyArray<Accessor<TItem>>
) {
const allValues: Array<{
itemValue: string
attributes: AccessorAttributes
}> = []
for (let j = 0, J = accessors.length; j < J; j++) {
const accessor = accessors[j]!
const attributes = getAccessorAttributes(accessor)
const itemValues = getItemValues(item, accessor)
for (let i = 0, I = itemValues.length; i < I; i++) {
allValues.push({
itemValue: itemValues[i]!,
attributes,
})
}
}
return allValues
}
const defaultKeyAttributes = {
maxRanking: Infinity as Ranking,
minRanking: -Infinity as Ranking,
}
/**
* Gets all the attributes for the given accessor
* @param accessor - the accessor from which the attributes will be retrieved
* @return object containing the accessor's attributes
*/
function getAccessorAttributes<TItem>(
accessor: Accessor<TItem>
): AccessorAttributes {
if (typeof accessor === 'function') {
return defaultKeyAttributes
}
return { ...defaultKeyAttributes, ...accessor }
}

View File

@@ -0,0 +1,410 @@
const characterMap: Record<string, string> = {
À: 'A',
Á: 'A',
Â: 'A',
Ã: 'A',
Ä: 'A',
Å: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
: 'A',
Æ: 'AE',
: 'A',
: 'A',
Ȃ: 'A',
Ç: 'C',
: 'C',
È: 'E',
É: 'E',
Ê: 'E',
Ë: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
: 'E',
Ȇ: 'E',
Ì: 'I',
Í: 'I',
Î: 'I',
Ï: 'I',
: 'I',
Ȋ: 'I',
Ð: 'D',
Ñ: 'N',
Ò: 'O',
Ó: 'O',
Ô: 'O',
Õ: 'O',
Ö: 'O',
Ø: 'O',
: 'O',
: 'O',
: 'O',
Ȏ: 'O',
Ù: 'U',
Ú: 'U',
Û: 'U',
Ü: 'U',
Ý: 'Y',
à: 'a',
á: 'a',
â: 'a',
ã: 'a',
ä: 'a',
å: 'a',
: 'a',
: 'a',
: 'a',
: 'a',
: 'a',
æ: 'ae',
: 'a',
: 'a',
ȃ: 'a',
ç: 'c',
: 'c',
è: 'e',
é: 'e',
ê: 'e',
ë: 'e',
ế: 'e',
: 'e',
: 'e',
: 'e',
: 'e',
ȇ: 'e',
ì: 'i',
í: 'i',
î: 'i',
ï: 'i',
: 'i',
ȋ: 'i',
ð: 'd',
ñ: 'n',
ò: 'o',
ó: 'o',
ô: 'o',
õ: 'o',
ö: 'o',
ø: 'o',
: 'o',
: 'o',
: 'o',
ȏ: 'o',
ù: 'u',
ú: 'u',
û: 'u',
ü: 'u',
ý: 'y',
ÿ: 'y',
Ā: 'A',
ā: 'a',
Ă: 'A',
ă: 'a',
Ą: 'A',
ą: 'a',
Ć: 'C',
ć: 'c',
Ĉ: 'C',
ĉ: 'c',
Ċ: 'C',
ċ: 'c',
Č: 'C',
č: 'c',
: 'C',
: 'c',
Ď: 'D',
ď: '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: 'k',
: 'M',
: 'm',
: 'P',
: 'p',
: 'Q',
: 'q',
Ř̩: 'R',
ř̩: 'r',
: 'S',
: 's',
: 'V',
: 'v',
: 'W',
: 'w',
: 'X',
: 'x',
: 'Y',
: 'y',
: 'A',
: 'a',
: 'B',
: 'b',
: 'D',
: 'd',
Ȩ: 'E',
ȩ: 'e',
Ɛ̧: 'E',
ɛ̧: 'e',
: 'H',
: 'h',
: 'I',
: 'i',
Ɨ̧: 'I',
ɨ̧: 'i',
: 'M',
: 'm',
: 'O',
: 'o',
: 'Q',
: 'q',
: 'U',
: 'u',
: 'X',
: 'x',
: 'Z',
: 'z',
}
const chars = Object.keys(characterMap).join('|')
const allAccents = new RegExp(chars, 'g')
export function removeAccents(str: string) {
return str.replace(allAccents, match => {
return characterMap[match]!
})
}

21
node_modules/@tanstack/query-core/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-present Tanner Linsley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
var __typeError = (msg) => {
throw TypeError(msg);
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
export {
__privateGet,
__privateAdd,
__privateSet,
__privateMethod,
__privateWrapper
};
//# sourceMappingURL=chunk-PXG64RU4.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}

View File

@@ -0,0 +1,48 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/environmentManager.ts
var environmentManager_exports = {};
__export(environmentManager_exports, {
environmentManager: () => environmentManager
});
module.exports = __toCommonJS(environmentManager_exports);
var import_utils = require("./utils.cjs");
var environmentManager = /* @__PURE__ */ (() => {
let isServerFn = () => import_utils.isServer;
return {
/**
* Returns whether the current runtime should be treated as a server environment.
*/
isServer() {
return isServerFn();
},
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue) {
isServerFn = isServerValue;
}
};
})();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
environmentManager
});
//# sourceMappingURL=environmentManager.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\n/**\n * Manages environment detection used by TanStack Query internals.\n */\nexport const environmentManager = (() => {\n let isServerFn: IsServerValue = () => isServer\n\n return {\n /**\n * Returns whether the current runtime should be treated as a server environment.\n */\n isServer(): boolean {\n return isServerFn()\n },\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n }\n})()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAyB;AAOlB,IAAM,qBAAsB,uBAAM;AACvC,MAAI,aAA4B,MAAM;AAEtC,SAAO;AAAA;AAAA;AAAA;AAAA,IAIL,WAAoB;AAClB,aAAO,WAAW;AAAA,IACpB;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,eAAoC;AAC9C,mBAAa;AAAA,IACf;AAAA,EACF;AACF,GAAG;","names":[]}

View File

@@ -0,0 +1,2 @@
export { IsServerValue } from './_tsup-dts-rollup.cjs';
export { environmentManager } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,2 @@
export { IsServerValue } from './_tsup-dts-rollup.js';
export { environmentManager } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,25 @@
import "./chunk-PXG64RU4.js";
// src/environmentManager.ts
import { isServer } from "./utils.js";
var environmentManager = /* @__PURE__ */ (() => {
let isServerFn = () => isServer;
return {
/**
* Returns whether the current runtime should be treated as a server environment.
*/
isServer() {
return isServerFn();
},
/**
* Overrides the server check globally.
*/
setIsServer(isServerValue) {
isServerFn = isServerValue;
}
};
})();
export {
environmentManager
};
//# sourceMappingURL=environmentManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/environmentManager.ts"],"sourcesContent":["import { isServer } from './utils'\n\nexport type IsServerValue = () => boolean\n\n/**\n * Manages environment detection used by TanStack Query internals.\n */\nexport const environmentManager = (() => {\n let isServerFn: IsServerValue = () => isServer\n\n return {\n /**\n * Returns whether the current runtime should be treated as a server environment.\n */\n isServer(): boolean {\n return isServerFn()\n },\n /**\n * Overrides the server check globally.\n */\n setIsServer(isServerValue: IsServerValue): void {\n isServerFn = isServerValue\n },\n }\n})()\n"],"mappings":";;;AAAA,SAAS,gBAAgB;AAOlB,IAAM,qBAAsB,uBAAM;AACvC,MAAI,aAA4B,MAAM;AAEtC,SAAO;AAAA;AAAA;AAAA;AAAA,IAIL,WAAoB;AAClB,aAAO,WAAW;AAAA,IACpB;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,eAAoC;AAC9C,mBAAa;AAAA,IACf;AAAA,EACF;AACF,GAAG;","names":[]}

View File

@@ -0,0 +1,107 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
// src/focusManager.ts
var focusManager_exports = {};
__export(focusManager_exports, {
FocusManager: () => FocusManager,
focusManager: () => focusManager
});
module.exports = __toCommonJS(focusManager_exports);
var import_subscribable = require("./subscribable.cjs");
var _focused, _cleanup, _setup;
var FocusManager = class extends import_subscribable.Subscribable {
constructor() {
super();
__privateAdd(this, _focused);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onFocus) => {
if (typeof window !== "undefined" && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup((focused) => {
if (typeof focused === "boolean") {
this.setFocused(focused);
} else {
this.onFocus();
}
}));
}
setFocused(focused) {
const changed = __privateGet(this, _focused) !== focused;
if (changed) {
__privateSet(this, _focused, focused);
this.onFocus();
}
}
onFocus() {
const isFocused = this.isFocused();
this.listeners.forEach((listener) => {
listener(isFocused);
});
}
isFocused() {
var _a;
if (typeof __privateGet(this, _focused) === "boolean") {
return __privateGet(this, _focused);
}
return ((_a = globalThis.document) == null ? void 0 : _a.visibilityState) !== "hidden";
}
};
_focused = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var focusManager = new FocusManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
FocusManager,
focusManager
});
//# sourceMappingURL=focusManager.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\n\nexport class FocusManager extends Subscribable<Listener> {\n #focused?: boolean\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onFocus) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const listener = () => onFocus()\n // Listen to visibilitychange\n window.addEventListener('visibilitychange', listener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('visibilitychange', listener)\n }\n }\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup((focused) => {\n if (typeof focused === 'boolean') {\n this.setFocused(focused)\n } else {\n this.onFocus()\n }\n })\n }\n\n setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\n\n isFocused(): boolean {\n if (typeof this.#focused === 'boolean') {\n return this.#focused\n }\n\n // document global can be unavailable in react native\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return globalThis.document?.visibilityState !== 'hidden'\n }\n}\n\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,0BAA6B;AAA7B;AA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AzEE;AACA;AAEA;AAwEK,IAAM,eAAe,IAAI,aAAa;","names":[]}

View File

@@ -0,0 +1,2 @@
export { FocusManager } from './_tsup-dts-rollup.cjs';
export { focusManager } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,2 @@
export { FocusManager } from './_tsup-dts-rollup.js';
export { focusManager } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,80 @@
import {
__privateAdd,
__privateGet,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/focusManager.ts
import { Subscribable } from "./subscribable.js";
var _focused, _cleanup, _setup;
var FocusManager = class extends Subscribable {
constructor() {
super();
__privateAdd(this, _focused);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onFocus) => {
if (typeof window !== "undefined" && window.addEventListener) {
const listener = () => onFocus();
window.addEventListener("visibilitychange", listener, false);
return () => {
window.removeEventListener("visibilitychange", listener);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup((focused) => {
if (typeof focused === "boolean") {
this.setFocused(focused);
} else {
this.onFocus();
}
}));
}
setFocused(focused) {
const changed = __privateGet(this, _focused) !== focused;
if (changed) {
__privateSet(this, _focused, focused);
this.onFocus();
}
}
onFocus() {
const isFocused = this.isFocused();
this.listeners.forEach((listener) => {
listener(isFocused);
});
}
isFocused() {
var _a;
if (typeof __privateGet(this, _focused) === "boolean") {
return __privateGet(this, _focused);
}
return ((_a = globalThis.document) == null ? void 0 : _a.visibilityState) !== "hidden";
}
};
_focused = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var focusManager = new FocusManager();
export {
FocusManager,
focusManager
};
//# sourceMappingURL=focusManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/focusManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (focused: boolean) => void\n\ntype SetupFn = (\n setFocused: (focused?: boolean) => void,\n) => (() => void) | undefined\n\nexport class FocusManager extends Subscribable<Listener> {\n #focused?: boolean\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onFocus) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const listener = () => onFocus()\n // Listen to visibilitychange\n window.addEventListener('visibilitychange', listener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('visibilitychange', listener)\n }\n }\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup((focused) => {\n if (typeof focused === 'boolean') {\n this.setFocused(focused)\n } else {\n this.onFocus()\n }\n })\n }\n\n setFocused(focused?: boolean): void {\n const changed = this.#focused !== focused\n if (changed) {\n this.#focused = focused\n this.onFocus()\n }\n }\n\n onFocus(): void {\n const isFocused = this.isFocused()\n this.listeners.forEach((listener) => {\n listener(isFocused)\n })\n }\n\n isFocused(): boolean {\n if (typeof this.#focused === 'boolean') {\n return this.#focused\n }\n\n // document global can be unavailable in react native\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n return globalThis.document?.visibilityState !== 'hidden'\n }\n}\n\nexport const focusManager = new FocusManager()\n"],"mappings":";;;;;;;AAAA,SAAS,oBAAoB;AAA7B;AAQO,IAAM,eAAN,cAA2B,aAAuB;AAAA,EAMvD,cAAc;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":[]}

View File

@@ -0,0 +1,204 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/hydration.ts
var hydration_exports = {};
__export(hydration_exports, {
defaultShouldDehydrateMutation: () => defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery: () => defaultShouldDehydrateQuery,
dehydrate: () => dehydrate,
hydrate: () => hydrate
});
module.exports = __toCommonJS(hydration_exports);
var import_thenable = require("./thenable.cjs");
var import_utils = require("./utils.cjs");
function defaultTransformerFn(data) {
return data;
}
function dehydrateMutation(mutation) {
return {
mutationKey: mutation.options.mutationKey,
state: mutation.state,
...mutation.options.scope && { scope: mutation.options.scope },
...mutation.meta && { meta: mutation.meta }
};
}
function dehydrateQuery(query, serializeData, shouldRedactErrors) {
const dehydratePromise = () => {
var _a;
const promise = (_a = query.promise) == null ? void 0 : _a.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
return Promise.reject(error);
}
if (process.env.NODE_ENV !== "production") {
console.error(
`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`
);
}
return Promise.reject(new Error("redacted"));
});
promise == null ? void 0 : promise.catch(import_utils.noop);
return promise;
};
return {
dehydratedAt: Date.now(),
state: {
...query.state,
...query.state.data !== void 0 && {
data: serializeData(query.state.data)
}
},
queryKey: query.queryKey,
queryHash: query.queryHash,
...query.state.status === "pending" && {
promise: dehydratePromise()
},
...query.meta && { meta: query.meta },
...query.queryType && { queryType: query.queryType }
};
}
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
function defaultShouldRedactErrors(_) {
return true;
}
function dehydrate(client, options = {}) {
var _a, _b, _c, _d;
const filterMutation = options.shouldDehydrateMutation ?? ((_a = client.getDefaultOptions().dehydrate) == null ? void 0 : _a.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap(
(mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []
);
const filterQuery = options.shouldDehydrateQuery ?? ((_b = client.getDefaultOptions().dehydrate) == null ? void 0 : _b.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? ((_c = client.getDefaultOptions().dehydrate) == null ? void 0 : _c.shouldRedactErrors) ?? defaultShouldRedactErrors;
const serializeData = options.serializeData ?? ((_d = client.getDefaultOptions().dehydrate) == null ? void 0 : _d.serializeData) ?? defaultTransformerFn;
const queries = client.getQueryCache().getAll().flatMap(
(query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : []
);
return { mutations, queries };
}
function hydrate(client, dehydratedState, options) {
var _a, _b;
if (typeof dehydratedState !== "object" || dehydratedState === null) {
return;
}
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = ((_a = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _a.deserializeData) ?? ((_b = client.getDefaultOptions().hydrate) == null ? void 0 : _b.deserializeData) ?? defaultTransformerFn;
const mutations = dehydratedState.mutations || [];
const queries = dehydratedState.queries || [];
mutations.forEach(({ state, ...mutationOptions }) => {
var _a2, _b2;
mutationCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.mutations,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.mutations,
...mutationOptions
},
state
);
});
queries.forEach(
({
queryKey,
state,
queryHash,
meta,
promise,
dehydratedAt,
queryType
}) => {
var _a2, _b2;
const syncData = promise ? (0, import_thenable.tryResolveSync)(promise) : void 0;
const rawData = state.data === void 0 ? syncData == null ? void 0 : syncData.data : state.data;
const data = rawData === void 0 ? rawData : deserializeData(rawData);
let query = queryCache.get(queryHash);
const existingQueryIsPending = (query == null ? void 0 : query.state.status) === "pending";
const existingQueryIsFetching = (query == null ? void 0 : query.state.fetchStatus) === "fetching";
if (query) {
const hasNewerSyncData = syncData && // We only need this undefined check to handle older dehydration
// payloads that might not have dehydratedAt
dehydratedAt !== void 0 && dehydratedAt > query.state.dataUpdatedAt;
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
const { fetchStatus: _ignored, ...serializedState } = state;
query.setState({
...serializedState,
data,
// If the query was pending at the moment of dehydration, but resolved to have data
// before hydration, we can assume the query should be hydrated as successful.
//
// Since you can opt into dehydrating failed queries, and those can have data from
// previous successful fetches, we make sure we only do this for pending queries.
...state.status === "pending" && data !== void 0 && {
status: "success",
// Preserve existing fetchStatus if the existing query is actively fetching.
...!existingQueryIsFetching && {
fetchStatus: "idle"
}
}
});
}
} else {
query = queryCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.queries,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.queries,
queryKey,
queryHash,
meta,
_type: queryType
},
// Reset fetch status to idle to avoid
// query being stuck in fetching state upon hydration
{
...state,
data,
fetchStatus: "idle",
// Like above, if the query was pending at the moment of dehydration but has data,
// we can assume it should be hydrated as successful.
status: state.status === "pending" && data !== void 0 ? "success" : state.status
}
);
}
if (promise && // If the data was synchronously available, there is no need to set up
// a retryer and thus no reason to call fetch
!syncData && !existingQueryIsPending && !existingQueryIsFetching && // Only hydrate if dehydration is newer than any existing data,
// this is always true for new queries
(dehydratedAt === void 0 || dehydratedAt > query.state.dataUpdatedAt)) {
query.fetch(void 0, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData)
}).catch(import_utils.noop);
}
}
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
});
//# sourceMappingURL=hydration.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,7 @@
export { defaultShouldDehydrateMutation } from './_tsup-dts-rollup.cjs';
export { defaultShouldDehydrateQuery } from './_tsup-dts-rollup.cjs';
export { dehydrate } from './_tsup-dts-rollup.cjs';
export { hydrate } from './_tsup-dts-rollup.cjs';
export { DehydrateOptions } from './_tsup-dts-rollup.cjs';
export { HydrateOptions } from './_tsup-dts-rollup.cjs';
export { DehydratedState } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,7 @@
export { defaultShouldDehydrateMutation } from './_tsup-dts-rollup.js';
export { defaultShouldDehydrateQuery } from './_tsup-dts-rollup.js';
export { dehydrate } from './_tsup-dts-rollup.js';
export { hydrate } from './_tsup-dts-rollup.js';
export { DehydrateOptions } from './_tsup-dts-rollup.js';
export { HydrateOptions } from './_tsup-dts-rollup.js';
export { DehydratedState } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,178 @@
import "./chunk-PXG64RU4.js";
// src/hydration.ts
import { tryResolveSync } from "./thenable.js";
import { noop } from "./utils.js";
function defaultTransformerFn(data) {
return data;
}
function dehydrateMutation(mutation) {
return {
mutationKey: mutation.options.mutationKey,
state: mutation.state,
...mutation.options.scope && { scope: mutation.options.scope },
...mutation.meta && { meta: mutation.meta }
};
}
function dehydrateQuery(query, serializeData, shouldRedactErrors) {
const dehydratePromise = () => {
var _a;
const promise = (_a = query.promise) == null ? void 0 : _a.then(serializeData).catch((error) => {
if (!shouldRedactErrors(error)) {
return Promise.reject(error);
}
if (process.env.NODE_ENV !== "production") {
console.error(
`A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`
);
}
return Promise.reject(new Error("redacted"));
});
promise == null ? void 0 : promise.catch(noop);
return promise;
};
return {
dehydratedAt: Date.now(),
state: {
...query.state,
...query.state.data !== void 0 && {
data: serializeData(query.state.data)
}
},
queryKey: query.queryKey,
queryHash: query.queryHash,
...query.state.status === "pending" && {
promise: dehydratePromise()
},
...query.meta && { meta: query.meta },
...query.queryType && { queryType: query.queryType }
};
}
function defaultShouldDehydrateMutation(mutation) {
return mutation.state.isPaused;
}
function defaultShouldDehydrateQuery(query) {
return query.state.status === "success";
}
function defaultShouldRedactErrors(_) {
return true;
}
function dehydrate(client, options = {}) {
var _a, _b, _c, _d;
const filterMutation = options.shouldDehydrateMutation ?? ((_a = client.getDefaultOptions().dehydrate) == null ? void 0 : _a.shouldDehydrateMutation) ?? defaultShouldDehydrateMutation;
const mutations = client.getMutationCache().getAll().flatMap(
(mutation) => filterMutation(mutation) ? [dehydrateMutation(mutation)] : []
);
const filterQuery = options.shouldDehydrateQuery ?? ((_b = client.getDefaultOptions().dehydrate) == null ? void 0 : _b.shouldDehydrateQuery) ?? defaultShouldDehydrateQuery;
const shouldRedactErrors = options.shouldRedactErrors ?? ((_c = client.getDefaultOptions().dehydrate) == null ? void 0 : _c.shouldRedactErrors) ?? defaultShouldRedactErrors;
const serializeData = options.serializeData ?? ((_d = client.getDefaultOptions().dehydrate) == null ? void 0 : _d.serializeData) ?? defaultTransformerFn;
const queries = client.getQueryCache().getAll().flatMap(
(query) => filterQuery(query) ? [dehydrateQuery(query, serializeData, shouldRedactErrors)] : []
);
return { mutations, queries };
}
function hydrate(client, dehydratedState, options) {
var _a, _b;
if (typeof dehydratedState !== "object" || dehydratedState === null) {
return;
}
const mutationCache = client.getMutationCache();
const queryCache = client.getQueryCache();
const deserializeData = ((_a = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _a.deserializeData) ?? ((_b = client.getDefaultOptions().hydrate) == null ? void 0 : _b.deserializeData) ?? defaultTransformerFn;
const mutations = dehydratedState.mutations || [];
const queries = dehydratedState.queries || [];
mutations.forEach(({ state, ...mutationOptions }) => {
var _a2, _b2;
mutationCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.mutations,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.mutations,
...mutationOptions
},
state
);
});
queries.forEach(
({
queryKey,
state,
queryHash,
meta,
promise,
dehydratedAt,
queryType
}) => {
var _a2, _b2;
const syncData = promise ? tryResolveSync(promise) : void 0;
const rawData = state.data === void 0 ? syncData == null ? void 0 : syncData.data : state.data;
const data = rawData === void 0 ? rawData : deserializeData(rawData);
let query = queryCache.get(queryHash);
const existingQueryIsPending = (query == null ? void 0 : query.state.status) === "pending";
const existingQueryIsFetching = (query == null ? void 0 : query.state.fetchStatus) === "fetching";
if (query) {
const hasNewerSyncData = syncData && // We only need this undefined check to handle older dehydration
// payloads that might not have dehydratedAt
dehydratedAt !== void 0 && dehydratedAt > query.state.dataUpdatedAt;
if (state.dataUpdatedAt > query.state.dataUpdatedAt || hasNewerSyncData) {
const { fetchStatus: _ignored, ...serializedState } = state;
query.setState({
...serializedState,
data,
// If the query was pending at the moment of dehydration, but resolved to have data
// before hydration, we can assume the query should be hydrated as successful.
//
// Since you can opt into dehydrating failed queries, and those can have data from
// previous successful fetches, we make sure we only do this for pending queries.
...state.status === "pending" && data !== void 0 && {
status: "success",
// Preserve existing fetchStatus if the existing query is actively fetching.
...!existingQueryIsFetching && {
fetchStatus: "idle"
}
}
});
}
} else {
query = queryCache.build(
client,
{
...(_a2 = client.getDefaultOptions().hydrate) == null ? void 0 : _a2.queries,
...(_b2 = options == null ? void 0 : options.defaultOptions) == null ? void 0 : _b2.queries,
queryKey,
queryHash,
meta,
_type: queryType
},
// Reset fetch status to idle to avoid
// query being stuck in fetching state upon hydration
{
...state,
data,
fetchStatus: "idle",
// Like above, if the query was pending at the moment of dehydration but has data,
// we can assume it should be hydrated as successful.
status: state.status === "pending" && data !== void 0 ? "success" : state.status
}
);
}
if (promise && // If the data was synchronously available, there is no need to set up
// a retryer and thus no reason to call fetch
!syncData && !existingQueryIsPending && !existingQueryIsFetching && // Only hydrate if dehydration is newer than any existing data,
// this is always true for new queries
(dehydratedAt === void 0 || dehydratedAt > query.state.dataUpdatedAt)) {
query.fetch(void 0, {
// RSC transformed promises are not thenable
initialPromise: Promise.resolve(promise).then(deserializeData)
}).catch(noop);
}
}
);
}
export {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
};
//# sourceMappingURL=hydration.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,113 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
CancelledError: () => import_retryer.CancelledError,
InfiniteQueryObserver: () => import_infiniteQueryObserver.InfiniteQueryObserver,
Mutation: () => import_mutation.Mutation,
MutationCache: () => import_mutationCache.MutationCache,
MutationObserver: () => import_mutationObserver.MutationObserver,
QueriesObserver: () => import_queriesObserver.QueriesObserver,
Query: () => import_query.Query,
QueryCache: () => import_queryCache.QueryCache,
QueryClient: () => import_queryClient.QueryClient,
QueryObserver: () => import_queryObserver.QueryObserver,
defaultScheduler: () => import_notifyManager.defaultScheduler,
defaultShouldDehydrateMutation: () => import_hydration.defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery: () => import_hydration.defaultShouldDehydrateQuery,
dehydrate: () => import_hydration.dehydrate,
environmentManager: () => import_environmentManager.environmentManager,
experimental_streamedQuery: () => import_streamedQuery.streamedQuery,
focusManager: () => import_focusManager.focusManager,
hashKey: () => import_utils.hashKey,
hydrate: () => import_hydration.hydrate,
isCancelledError: () => import_retryer.isCancelledError,
isServer: () => import_utils.isServer,
keepPreviousData: () => import_utils.keepPreviousData,
matchMutation: () => import_utils.matchMutation,
matchQuery: () => import_utils.matchQuery,
noop: () => import_utils.noop,
notifyManager: () => import_notifyManager.notifyManager,
onlineManager: () => import_onlineManager.onlineManager,
partialMatchKey: () => import_utils.partialMatchKey,
replaceEqualDeep: () => import_utils.replaceEqualDeep,
shouldThrowError: () => import_utils.shouldThrowError,
skipToken: () => import_utils.skipToken,
timeoutManager: () => import_timeoutManager.timeoutManager
});
module.exports = __toCommonJS(index_exports);
var import_focusManager = require("./focusManager.cjs");
var import_environmentManager = require("./environmentManager.cjs");
var import_hydration = require("./hydration.cjs");
var import_infiniteQueryObserver = require("./infiniteQueryObserver.cjs");
var import_mutationCache = require("./mutationCache.cjs");
var import_mutationObserver = require("./mutationObserver.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_onlineManager = require("./onlineManager.cjs");
var import_queriesObserver = require("./queriesObserver.cjs");
var import_queryCache = require("./queryCache.cjs");
var import_queryClient = require("./queryClient.cjs");
var import_queryObserver = require("./queryObserver.cjs");
var import_retryer = require("./retryer.cjs");
var import_timeoutManager = require("./timeoutManager.cjs");
var import_utils = require("./utils.cjs");
var import_streamedQuery = require("./streamedQuery.cjs");
var import_mutation = require("./mutation.cjs");
var import_query = require("./query.cjs");
__reExport(index_exports, require("./types.cjs"), module.exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CancelledError,
InfiniteQueryObserver,
Mutation,
MutationCache,
MutationObserver,
QueriesObserver,
Query,
QueryCache,
QueryClient,
QueryObserver,
defaultScheduler,
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
environmentManager,
experimental_streamedQuery,
focusManager,
hashKey,
hydrate,
isCancelledError,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
notifyManager,
onlineManager,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken,
timeoutManager,
...require("./types.cjs")
});
//# sourceMappingURL=index.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\n hydrate,\n} from './hydration'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { defaultScheduler, notifyManager } from './notifyManager'\nexport { onlineManager } from './onlineManager'\nexport { QueriesObserver } from './queriesObserver'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { CancelledError, isCancelledError } from './retryer'\nexport {\n timeoutManager,\n type ManagedTimerId,\n type TimeoutCallback,\n type TimeoutProvider,\n} from './timeoutManager'\nexport {\n hashKey,\n isServer,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceEqualDeep,\n shouldThrowError,\n skipToken,\n} from './utils'\nexport type { MutationFilters, QueryFilters, SkipToken, Updater } from './utils'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport type {\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from './hydration'\nexport { Mutation } from './mutation'\nexport type { MutationState } from './mutation'\nexport type { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport * from './types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,0BAA6B;AAC7B,gCAAmC;AACnC,uBAKO;AACP,mCAAsC;AACtC,2BAA8B;AAE9B,8BAAiC;AACjC,2BAAgD;AAChD,2BAA8B;AAC9B,6BAAgC;AAChC,wBAA2B;AAE3B,yBAA4B;AAC5B,2BAA8B;AAC9B,qBAAiD;AACjD,4BAKO;AACP,mBAWO;AAGP,2BAA4D;AAQ5D,sBAAyB;AAGzB,mBAAsB;AAEtB,0BAAc,wBAvDd;","names":[]}

View File

@@ -0,0 +1,141 @@
export { focusManager_alias_1 as focusManager } from './_tsup-dts-rollup.cjs';
export { environmentManager_alias_1 as environmentManager } from './_tsup-dts-rollup.cjs';
export { defaultShouldDehydrateMutation_alias_1 as defaultShouldDehydrateMutation } from './_tsup-dts-rollup.cjs';
export { defaultShouldDehydrateQuery_alias_1 as defaultShouldDehydrateQuery } from './_tsup-dts-rollup.cjs';
export { dehydrate_alias_1 as dehydrate } from './_tsup-dts-rollup.cjs';
export { hydrate_alias_1 as hydrate } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserver } from './_tsup-dts-rollup.cjs';
export { MutationCache } from './_tsup-dts-rollup.cjs';
export { MutationCacheNotifyEvent } from './_tsup-dts-rollup.cjs';
export { MutationObserver } from './_tsup-dts-rollup.cjs';
export { defaultScheduler } from './_tsup-dts-rollup.cjs';
export { notifyManager } from './_tsup-dts-rollup.cjs';
export { onlineManager } from './_tsup-dts-rollup.cjs';
export { QueriesObserver } from './_tsup-dts-rollup.cjs';
export { QueryCache } from './_tsup-dts-rollup.cjs';
export { QueryCacheNotifyEvent } from './_tsup-dts-rollup.cjs';
export { QueryClient } from './_tsup-dts-rollup.cjs';
export { QueryObserver } from './_tsup-dts-rollup.cjs';
export { CancelledError } from './_tsup-dts-rollup.cjs';
export { isCancelledError } from './_tsup-dts-rollup.cjs';
export { timeoutManager } from './_tsup-dts-rollup.cjs';
export { ManagedTimerId } from './_tsup-dts-rollup.cjs';
export { TimeoutCallback } from './_tsup-dts-rollup.cjs';
export { TimeoutProvider } from './_tsup-dts-rollup.cjs';
export { hashKey } from './_tsup-dts-rollup.cjs';
export { isServer } from './_tsup-dts-rollup.cjs';
export { keepPreviousData } from './_tsup-dts-rollup.cjs';
export { matchMutation } from './_tsup-dts-rollup.cjs';
export { matchQuery } from './_tsup-dts-rollup.cjs';
export { noop } from './_tsup-dts-rollup.cjs';
export { partialMatchKey } from './_tsup-dts-rollup.cjs';
export { replaceEqualDeep } from './_tsup-dts-rollup.cjs';
export { shouldThrowError } from './_tsup-dts-rollup.cjs';
export { skipToken } from './_tsup-dts-rollup.cjs';
export { MutationFilters } from './_tsup-dts-rollup.cjs';
export { QueryFilters } from './_tsup-dts-rollup.cjs';
export { SkipToken } from './_tsup-dts-rollup.cjs';
export { Updater } from './_tsup-dts-rollup.cjs';
export { experimental_streamedQuery } from './_tsup-dts-rollup.cjs';
export { DehydratedState_alias_1 as DehydratedState } from './_tsup-dts-rollup.cjs';
export { DehydrateOptions_alias_1 as DehydrateOptions } from './_tsup-dts-rollup.cjs';
export { HydrateOptions_alias_1 as HydrateOptions } from './_tsup-dts-rollup.cjs';
export { Mutation } from './_tsup-dts-rollup.cjs';
export { MutationState } from './_tsup-dts-rollup.cjs';
export { QueriesObserverOptions } from './_tsup-dts-rollup.cjs';
export { Query } from './_tsup-dts-rollup.cjs';
export { QueryState } from './_tsup-dts-rollup.cjs';
export { NonUndefinedGuard } from './_tsup-dts-rollup.cjs';
export { DistributiveOmit } from './_tsup-dts-rollup.cjs';
export { OmitKeyof } from './_tsup-dts-rollup.cjs';
export { Override } from './_tsup-dts-rollup.cjs';
export { Register } from './_tsup-dts-rollup.cjs';
export { DefaultError } from './_tsup-dts-rollup.cjs';
export { QueryKey } from './_tsup-dts-rollup.cjs';
export { dataTagSymbol } from './_tsup-dts-rollup.cjs';
export { dataTagErrorSymbol } from './_tsup-dts-rollup.cjs';
export { unsetMarker } from './_tsup-dts-rollup.cjs';
export { UnsetMarker } from './_tsup-dts-rollup.cjs';
export { AnyDataTag } from './_tsup-dts-rollup.cjs';
export { DataTag } from './_tsup-dts-rollup.cjs';
export { InferDataFromTag } from './_tsup-dts-rollup.cjs';
export { InferErrorFromTag } from './_tsup-dts-rollup.cjs';
export { QueryFunction } from './_tsup-dts-rollup.cjs';
export { StaleTime } from './_tsup-dts-rollup.cjs';
export { StaleTimeFunction } from './_tsup-dts-rollup.cjs';
export { QueryBooleanOption } from './_tsup-dts-rollup.cjs';
export { QueryPersister } from './_tsup-dts-rollup.cjs';
export { QueryFunctionContext } from './_tsup-dts-rollup.cjs';
export { InitialDataFunction } from './_tsup-dts-rollup.cjs';
export { PlaceholderDataFunction } from './_tsup-dts-rollup.cjs';
export { QueriesPlaceholderDataFunction } from './_tsup-dts-rollup.cjs';
export { QueryKeyHashFunction } from './_tsup-dts-rollup.cjs';
export { GetPreviousPageParamFunction } from './_tsup-dts-rollup.cjs';
export { GetNextPageParamFunction } from './_tsup-dts-rollup.cjs';
export { InfiniteData } from './_tsup-dts-rollup.cjs';
export { QueryMeta } from './_tsup-dts-rollup.cjs';
export { NetworkMode } from './_tsup-dts-rollup.cjs';
export { NotifyOnChangeProps } from './_tsup-dts-rollup.cjs';
export { QueryOptions } from './_tsup-dts-rollup.cjs';
export { InitialPageParam } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryPageParamsOptions } from './_tsup-dts-rollup.cjs';
export { ThrowOnError } from './_tsup-dts-rollup.cjs';
export { QueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { WithRequired } from './_tsup-dts-rollup.cjs';
export { DefaultedQueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { DefaultedInfiniteQueryObserverOptions } from './_tsup-dts-rollup.cjs';
export { FetchQueryOptions } from './_tsup-dts-rollup.cjs';
export { EnsureQueryDataOptions } from './_tsup-dts-rollup.cjs';
export { EnsureInfiniteQueryDataOptions } from './_tsup-dts-rollup.cjs';
export { FetchInfiniteQueryOptions } from './_tsup-dts-rollup.cjs';
export { ResultOptions } from './_tsup-dts-rollup.cjs';
export { RefetchOptions } from './_tsup-dts-rollup.cjs';
export { InvalidateQueryFilters } from './_tsup-dts-rollup.cjs';
export { RefetchQueryFilters } from './_tsup-dts-rollup.cjs';
export { InvalidateOptions } from './_tsup-dts-rollup.cjs';
export { ResetOptions } from './_tsup-dts-rollup.cjs';
export { FetchNextPageOptions } from './_tsup-dts-rollup.cjs';
export { FetchPreviousPageOptions } from './_tsup-dts-rollup.cjs';
export { QueryStatus } from './_tsup-dts-rollup.cjs';
export { FetchStatus } from './_tsup-dts-rollup.cjs';
export { QueryObserverBaseResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverPendingResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverLoadingResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverLoadingErrorResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverRefetchErrorResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverSuccessResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverPlaceholderResult } from './_tsup-dts-rollup.cjs';
export { DefinedQueryObserverResult } from './_tsup-dts-rollup.cjs';
export { QueryObserverResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverBaseResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverPendingResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverLoadingResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverLoadingErrorResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverRefetchErrorResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverSuccessResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverPlaceholderResult } from './_tsup-dts-rollup.cjs';
export { DefinedInfiniteQueryObserverResult } from './_tsup-dts-rollup.cjs';
export { InfiniteQueryObserverResult } from './_tsup-dts-rollup.cjs';
export { MutationKey } from './_tsup-dts-rollup.cjs';
export { MutationStatus } from './_tsup-dts-rollup.cjs';
export { MutationScope } from './_tsup-dts-rollup.cjs';
export { MutationMeta } from './_tsup-dts-rollup.cjs';
export { MutationFunctionContext } from './_tsup-dts-rollup.cjs';
export { MutationFunction } from './_tsup-dts-rollup.cjs';
export { MutationOptions } from './_tsup-dts-rollup.cjs';
export { MutationObserverOptions } from './_tsup-dts-rollup.cjs';
export { MutateOptions } from './_tsup-dts-rollup.cjs';
export { MutateFunction } from './_tsup-dts-rollup.cjs';
export { MutationObserverBaseResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverIdleResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverLoadingResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverErrorResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverSuccessResult } from './_tsup-dts-rollup.cjs';
export { MutationObserverResult } from './_tsup-dts-rollup.cjs';
export { QueryClientConfig } from './_tsup-dts-rollup.cjs';
export { DefaultOptions } from './_tsup-dts-rollup.cjs';
export { CancelOptions } from './_tsup-dts-rollup.cjs';
export { SetDataOptions } from './_tsup-dts-rollup.cjs';
export { NotifyEventType } from './_tsup-dts-rollup.cjs';
export { NotifyEvent } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,141 @@
export { focusManager_alias_1 as focusManager } from './_tsup-dts-rollup.js';
export { environmentManager_alias_1 as environmentManager } from './_tsup-dts-rollup.js';
export { defaultShouldDehydrateMutation_alias_1 as defaultShouldDehydrateMutation } from './_tsup-dts-rollup.js';
export { defaultShouldDehydrateQuery_alias_1 as defaultShouldDehydrateQuery } from './_tsup-dts-rollup.js';
export { dehydrate_alias_1 as dehydrate } from './_tsup-dts-rollup.js';
export { hydrate_alias_1 as hydrate } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserver } from './_tsup-dts-rollup.js';
export { MutationCache } from './_tsup-dts-rollup.js';
export { MutationCacheNotifyEvent } from './_tsup-dts-rollup.js';
export { MutationObserver } from './_tsup-dts-rollup.js';
export { defaultScheduler } from './_tsup-dts-rollup.js';
export { notifyManager } from './_tsup-dts-rollup.js';
export { onlineManager } from './_tsup-dts-rollup.js';
export { QueriesObserver } from './_tsup-dts-rollup.js';
export { QueryCache } from './_tsup-dts-rollup.js';
export { QueryCacheNotifyEvent } from './_tsup-dts-rollup.js';
export { QueryClient } from './_tsup-dts-rollup.js';
export { QueryObserver } from './_tsup-dts-rollup.js';
export { CancelledError } from './_tsup-dts-rollup.js';
export { isCancelledError } from './_tsup-dts-rollup.js';
export { timeoutManager } from './_tsup-dts-rollup.js';
export { ManagedTimerId } from './_tsup-dts-rollup.js';
export { TimeoutCallback } from './_tsup-dts-rollup.js';
export { TimeoutProvider } from './_tsup-dts-rollup.js';
export { hashKey } from './_tsup-dts-rollup.js';
export { isServer } from './_tsup-dts-rollup.js';
export { keepPreviousData } from './_tsup-dts-rollup.js';
export { matchMutation } from './_tsup-dts-rollup.js';
export { matchQuery } from './_tsup-dts-rollup.js';
export { noop } from './_tsup-dts-rollup.js';
export { partialMatchKey } from './_tsup-dts-rollup.js';
export { replaceEqualDeep } from './_tsup-dts-rollup.js';
export { shouldThrowError } from './_tsup-dts-rollup.js';
export { skipToken } from './_tsup-dts-rollup.js';
export { MutationFilters } from './_tsup-dts-rollup.js';
export { QueryFilters } from './_tsup-dts-rollup.js';
export { SkipToken } from './_tsup-dts-rollup.js';
export { Updater } from './_tsup-dts-rollup.js';
export { experimental_streamedQuery } from './_tsup-dts-rollup.js';
export { DehydratedState_alias_1 as DehydratedState } from './_tsup-dts-rollup.js';
export { DehydrateOptions_alias_1 as DehydrateOptions } from './_tsup-dts-rollup.js';
export { HydrateOptions_alias_1 as HydrateOptions } from './_tsup-dts-rollup.js';
export { Mutation } from './_tsup-dts-rollup.js';
export { MutationState } from './_tsup-dts-rollup.js';
export { QueriesObserverOptions } from './_tsup-dts-rollup.js';
export { Query } from './_tsup-dts-rollup.js';
export { QueryState } from './_tsup-dts-rollup.js';
export { NonUndefinedGuard } from './_tsup-dts-rollup.js';
export { DistributiveOmit } from './_tsup-dts-rollup.js';
export { OmitKeyof } from './_tsup-dts-rollup.js';
export { Override } from './_tsup-dts-rollup.js';
export { Register } from './_tsup-dts-rollup.js';
export { DefaultError } from './_tsup-dts-rollup.js';
export { QueryKey } from './_tsup-dts-rollup.js';
export { dataTagSymbol } from './_tsup-dts-rollup.js';
export { dataTagErrorSymbol } from './_tsup-dts-rollup.js';
export { unsetMarker } from './_tsup-dts-rollup.js';
export { UnsetMarker } from './_tsup-dts-rollup.js';
export { AnyDataTag } from './_tsup-dts-rollup.js';
export { DataTag } from './_tsup-dts-rollup.js';
export { InferDataFromTag } from './_tsup-dts-rollup.js';
export { InferErrorFromTag } from './_tsup-dts-rollup.js';
export { QueryFunction } from './_tsup-dts-rollup.js';
export { StaleTime } from './_tsup-dts-rollup.js';
export { StaleTimeFunction } from './_tsup-dts-rollup.js';
export { QueryBooleanOption } from './_tsup-dts-rollup.js';
export { QueryPersister } from './_tsup-dts-rollup.js';
export { QueryFunctionContext } from './_tsup-dts-rollup.js';
export { InitialDataFunction } from './_tsup-dts-rollup.js';
export { PlaceholderDataFunction } from './_tsup-dts-rollup.js';
export { QueriesPlaceholderDataFunction } from './_tsup-dts-rollup.js';
export { QueryKeyHashFunction } from './_tsup-dts-rollup.js';
export { GetPreviousPageParamFunction } from './_tsup-dts-rollup.js';
export { GetNextPageParamFunction } from './_tsup-dts-rollup.js';
export { InfiniteData } from './_tsup-dts-rollup.js';
export { QueryMeta } from './_tsup-dts-rollup.js';
export { NetworkMode } from './_tsup-dts-rollup.js';
export { NotifyOnChangeProps } from './_tsup-dts-rollup.js';
export { QueryOptions } from './_tsup-dts-rollup.js';
export { InitialPageParam } from './_tsup-dts-rollup.js';
export { InfiniteQueryPageParamsOptions } from './_tsup-dts-rollup.js';
export { ThrowOnError } from './_tsup-dts-rollup.js';
export { QueryObserverOptions } from './_tsup-dts-rollup.js';
export { WithRequired } from './_tsup-dts-rollup.js';
export { DefaultedQueryObserverOptions } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverOptions } from './_tsup-dts-rollup.js';
export { DefaultedInfiniteQueryObserverOptions } from './_tsup-dts-rollup.js';
export { FetchQueryOptions } from './_tsup-dts-rollup.js';
export { EnsureQueryDataOptions } from './_tsup-dts-rollup.js';
export { EnsureInfiniteQueryDataOptions } from './_tsup-dts-rollup.js';
export { FetchInfiniteQueryOptions } from './_tsup-dts-rollup.js';
export { ResultOptions } from './_tsup-dts-rollup.js';
export { RefetchOptions } from './_tsup-dts-rollup.js';
export { InvalidateQueryFilters } from './_tsup-dts-rollup.js';
export { RefetchQueryFilters } from './_tsup-dts-rollup.js';
export { InvalidateOptions } from './_tsup-dts-rollup.js';
export { ResetOptions } from './_tsup-dts-rollup.js';
export { FetchNextPageOptions } from './_tsup-dts-rollup.js';
export { FetchPreviousPageOptions } from './_tsup-dts-rollup.js';
export { QueryStatus } from './_tsup-dts-rollup.js';
export { FetchStatus } from './_tsup-dts-rollup.js';
export { QueryObserverBaseResult } from './_tsup-dts-rollup.js';
export { QueryObserverPendingResult } from './_tsup-dts-rollup.js';
export { QueryObserverLoadingResult } from './_tsup-dts-rollup.js';
export { QueryObserverLoadingErrorResult } from './_tsup-dts-rollup.js';
export { QueryObserverRefetchErrorResult } from './_tsup-dts-rollup.js';
export { QueryObserverSuccessResult } from './_tsup-dts-rollup.js';
export { QueryObserverPlaceholderResult } from './_tsup-dts-rollup.js';
export { DefinedQueryObserverResult } from './_tsup-dts-rollup.js';
export { QueryObserverResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverBaseResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverPendingResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverLoadingResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverLoadingErrorResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverRefetchErrorResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverSuccessResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverPlaceholderResult } from './_tsup-dts-rollup.js';
export { DefinedInfiniteQueryObserverResult } from './_tsup-dts-rollup.js';
export { InfiniteQueryObserverResult } from './_tsup-dts-rollup.js';
export { MutationKey } from './_tsup-dts-rollup.js';
export { MutationStatus } from './_tsup-dts-rollup.js';
export { MutationScope } from './_tsup-dts-rollup.js';
export { MutationMeta } from './_tsup-dts-rollup.js';
export { MutationFunctionContext } from './_tsup-dts-rollup.js';
export { MutationFunction } from './_tsup-dts-rollup.js';
export { MutationOptions } from './_tsup-dts-rollup.js';
export { MutationObserverOptions } from './_tsup-dts-rollup.js';
export { MutateOptions } from './_tsup-dts-rollup.js';
export { MutateFunction } from './_tsup-dts-rollup.js';
export { MutationObserverBaseResult } from './_tsup-dts-rollup.js';
export { MutationObserverIdleResult } from './_tsup-dts-rollup.js';
export { MutationObserverLoadingResult } from './_tsup-dts-rollup.js';
export { MutationObserverErrorResult } from './_tsup-dts-rollup.js';
export { MutationObserverSuccessResult } from './_tsup-dts-rollup.js';
export { MutationObserverResult } from './_tsup-dts-rollup.js';
export { QueryClientConfig } from './_tsup-dts-rollup.js';
export { DefaultOptions } from './_tsup-dts-rollup.js';
export { CancelOptions } from './_tsup-dts-rollup.js';
export { SetDataOptions } from './_tsup-dts-rollup.js';
export { NotifyEventType } from './_tsup-dts-rollup.js';
export { NotifyEvent } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,75 @@
import "./chunk-PXG64RU4.js";
// src/index.ts
import { focusManager } from "./focusManager.js";
import { environmentManager } from "./environmentManager.js";
import {
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
hydrate
} from "./hydration.js";
import { InfiniteQueryObserver } from "./infiniteQueryObserver.js";
import { MutationCache } from "./mutationCache.js";
import { MutationObserver } from "./mutationObserver.js";
import { defaultScheduler, notifyManager } from "./notifyManager.js";
import { onlineManager } from "./onlineManager.js";
import { QueriesObserver } from "./queriesObserver.js";
import { QueryCache } from "./queryCache.js";
import { QueryClient } from "./queryClient.js";
import { QueryObserver } from "./queryObserver.js";
import { CancelledError, isCancelledError } from "./retryer.js";
import {
timeoutManager
} from "./timeoutManager.js";
import {
hashKey,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken
} from "./utils.js";
import { streamedQuery } from "./streamedQuery.js";
import { Mutation } from "./mutation.js";
import { Query } from "./query.js";
export * from "./types.js";
export {
CancelledError,
InfiniteQueryObserver,
Mutation,
MutationCache,
MutationObserver,
QueriesObserver,
Query,
QueryCache,
QueryClient,
QueryObserver,
defaultScheduler,
defaultShouldDehydrateMutation,
defaultShouldDehydrateQuery,
dehydrate,
environmentManager,
streamedQuery as experimental_streamedQuery,
focusManager,
hashKey,
hydrate,
isCancelledError,
isServer,
keepPreviousData,
matchMutation,
matchQuery,
noop,
notifyManager,
onlineManager,
partialMatchKey,
replaceEqualDeep,
shouldThrowError,
skipToken,
timeoutManager
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport { focusManager } from './focusManager'\nexport { environmentManager } from './environmentManager'\nexport {\n defaultShouldDehydrateMutation,\n defaultShouldDehydrateQuery,\n dehydrate,\n hydrate,\n} from './hydration'\nexport { InfiniteQueryObserver } from './infiniteQueryObserver'\nexport { MutationCache } from './mutationCache'\nexport type { MutationCacheNotifyEvent } from './mutationCache'\nexport { MutationObserver } from './mutationObserver'\nexport { defaultScheduler, notifyManager } from './notifyManager'\nexport { onlineManager } from './onlineManager'\nexport { QueriesObserver } from './queriesObserver'\nexport { QueryCache } from './queryCache'\nexport type { QueryCacheNotifyEvent } from './queryCache'\nexport { QueryClient } from './queryClient'\nexport { QueryObserver } from './queryObserver'\nexport { CancelledError, isCancelledError } from './retryer'\nexport {\n timeoutManager,\n type ManagedTimerId,\n type TimeoutCallback,\n type TimeoutProvider,\n} from './timeoutManager'\nexport {\n hashKey,\n isServer,\n keepPreviousData,\n matchMutation,\n matchQuery,\n noop,\n partialMatchKey,\n replaceEqualDeep,\n shouldThrowError,\n skipToken,\n} from './utils'\nexport type { MutationFilters, QueryFilters, SkipToken, Updater } from './utils'\n\nexport { streamedQuery as experimental_streamedQuery } from './streamedQuery'\n\n// Types\nexport type {\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from './hydration'\nexport { Mutation } from './mutation'\nexport type { MutationState } from './mutation'\nexport type { QueriesObserverOptions } from './queriesObserver'\nexport { Query } from './query'\nexport type { QueryState } from './query'\nexport * from './types'\n"],"mappings":";;;AAEA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,6BAA6B;AACtC,SAAS,qBAAqB;AAE9B,SAAS,wBAAwB;AACjC,SAAS,kBAAkB,qBAAqB;AAChD,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,kBAAkB;AAE3B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAA0B,qBAAkC;AAQ5D,SAAS,gBAAgB;AAGzB,SAAS,aAAa;AAEtB,cAAc;","names":[]}

View File

@@ -0,0 +1,146 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/infiniteQueryBehavior.ts
var infiniteQueryBehavior_exports = {};
__export(infiniteQueryBehavior_exports, {
hasNextPage: () => hasNextPage,
hasPreviousPage: () => hasPreviousPage,
infiniteQueryBehavior: () => infiniteQueryBehavior
});
module.exports = __toCommonJS(infiniteQueryBehavior_exports);
var import_utils = require("./utils.cjs");
function infiniteQueryBehavior(pages) {
return {
onFetch: (context, query) => {
var _a, _b, _c, _d, _e;
const options = context.options;
const direction = (_c = (_b = (_a = context.fetchOptions) == null ? void 0 : _a.meta) == null ? void 0 : _b.fetchMore) == null ? void 0 : _c.direction;
const oldPages = ((_d = context.state.data) == null ? void 0 : _d.pages) || [];
const oldPageParams = ((_e = context.state.data) == null ? void 0 : _e.pageParams) || [];
let result = { pages: [], pageParams: [] };
let currentPage = 0;
const fetchFn = async () => {
let cancelled = false;
const addSignalProperty = (object) => {
(0, import_utils.addConsumeAwareSignal)(
object,
() => context.signal,
() => cancelled = true
);
};
const queryFn = (0, import_utils.ensureQueryFn)(context.options, context.fetchOptions);
const fetchPage = async (data, param, previous) => {
if (cancelled) {
return Promise.reject(context.signal.reason);
}
if (param == null && data.pages.length) {
return Promise.resolve(data);
}
const createQueryFnContext = () => {
const queryFnContext2 = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
const page = await queryFn(queryFnContext);
const { maxPages } = context.options;
const addTo = previous ? import_utils.addToStart : import_utils.addToEnd;
return {
pages: addTo(data.pages, page, maxPages),
pageParams: addTo(data.pageParams, param, maxPages)
};
};
if (direction && oldPages.length) {
const previous = direction === "backward";
const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
const oldData = {
pages: oldPages,
pageParams: oldPageParams
};
const param = pageParamFn(options, oldData);
result = await fetchPage(oldData, param, previous);
} else {
const remainingPages = pages ?? oldPages.length;
do {
const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
if (currentPage > 0 && param == null) {
break;
}
result = await fetchPage(result, param);
currentPage++;
} while (currentPage < remainingPages);
}
return result;
};
if (context.options.persister) {
context.fetchFn = () => {
var _a2, _b2;
return (_b2 = (_a2 = context.options).persister) == null ? void 0 : _b2.call(
_a2,
fetchFn,
{
client: context.client,
queryKey: context.queryKey,
meta: context.options.meta,
signal: context.signal
},
query
);
};
} else {
context.fetchFn = fetchFn;
}
}
};
}
function getNextPageParam(options, { pages, pageParams }) {
const lastIndex = pages.length - 1;
return pages.length > 0 ? options.getNextPageParam(
pages[lastIndex],
pages,
pageParams[lastIndex],
pageParams
) : void 0;
}
function getPreviousPageParam(options, { pages, pageParams }) {
var _a;
return pages.length > 0 ? (_a = options.getPreviousPageParam) == null ? void 0 : _a.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
}
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
hasNextPage,
hasPreviousPage,
infiniteQueryBehavior
});
//# sourceMappingURL=infiniteQueryBehavior.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { infiniteQueryBehavior } from './_tsup-dts-rollup.cjs';
export { hasNextPage } from './_tsup-dts-rollup.cjs';
export { hasPreviousPage } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,3 @@
export { infiniteQueryBehavior } from './_tsup-dts-rollup.js';
export { hasNextPage } from './_tsup-dts-rollup.js';
export { hasPreviousPage } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,126 @@
import "./chunk-PXG64RU4.js";
// src/infiniteQueryBehavior.ts
import {
addConsumeAwareSignal,
addToEnd,
addToStart,
ensureQueryFn
} from "./utils.js";
function infiniteQueryBehavior(pages) {
return {
onFetch: (context, query) => {
var _a, _b, _c, _d, _e;
const options = context.options;
const direction = (_c = (_b = (_a = context.fetchOptions) == null ? void 0 : _a.meta) == null ? void 0 : _b.fetchMore) == null ? void 0 : _c.direction;
const oldPages = ((_d = context.state.data) == null ? void 0 : _d.pages) || [];
const oldPageParams = ((_e = context.state.data) == null ? void 0 : _e.pageParams) || [];
let result = { pages: [], pageParams: [] };
let currentPage = 0;
const fetchFn = async () => {
let cancelled = false;
const addSignalProperty = (object) => {
addConsumeAwareSignal(
object,
() => context.signal,
() => cancelled = true
);
};
const queryFn = ensureQueryFn(context.options, context.fetchOptions);
const fetchPage = async (data, param, previous) => {
if (cancelled) {
return Promise.reject(context.signal.reason);
}
if (param == null && data.pages.length) {
return Promise.resolve(data);
}
const createQueryFnContext = () => {
const queryFnContext2 = {
client: context.client,
queryKey: context.queryKey,
pageParam: param,
direction: previous ? "backward" : "forward",
meta: context.options.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
const page = await queryFn(queryFnContext);
const { maxPages } = context.options;
const addTo = previous ? addToStart : addToEnd;
return {
pages: addTo(data.pages, page, maxPages),
pageParams: addTo(data.pageParams, param, maxPages)
};
};
if (direction && oldPages.length) {
const previous = direction === "backward";
const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
const oldData = {
pages: oldPages,
pageParams: oldPageParams
};
const param = pageParamFn(options, oldData);
result = await fetchPage(oldData, param, previous);
} else {
const remainingPages = pages ?? oldPages.length;
do {
const param = currentPage === 0 ? oldPageParams[0] ?? options.initialPageParam : getNextPageParam(options, result);
if (currentPage > 0 && param == null) {
break;
}
result = await fetchPage(result, param);
currentPage++;
} while (currentPage < remainingPages);
}
return result;
};
if (context.options.persister) {
context.fetchFn = () => {
var _a2, _b2;
return (_b2 = (_a2 = context.options).persister) == null ? void 0 : _b2.call(
_a2,
fetchFn,
{
client: context.client,
queryKey: context.queryKey,
meta: context.options.meta,
signal: context.signal
},
query
);
};
} else {
context.fetchFn = fetchFn;
}
}
};
}
function getNextPageParam(options, { pages, pageParams }) {
const lastIndex = pages.length - 1;
return pages.length > 0 ? options.getNextPageParam(
pages[lastIndex],
pages,
pageParams[lastIndex],
pageParams
) : void 0;
}
function getPreviousPageParam(options, { pages, pageParams }) {
var _a;
return pages.length > 0 ? (_a = options.getPreviousPageParam) == null ? void 0 : _a.call(options, pages[0], pages, pageParams[0], pageParams) : void 0;
}
function hasNextPage(options, data) {
if (!data) return false;
return getNextPageParam(options, data) != null;
}
function hasPreviousPage(options, data) {
if (!data || !options.getPreviousPageParam) return false;
return getPreviousPageParam(options, data) != null;
}
export {
hasNextPage,
hasPreviousPage,
infiniteQueryBehavior
};
//# sourceMappingURL=infiniteQueryBehavior.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,91 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/infiniteQueryObserver.ts
var infiniteQueryObserver_exports = {};
__export(infiniteQueryObserver_exports, {
InfiniteQueryObserver: () => InfiniteQueryObserver
});
module.exports = __toCommonJS(infiniteQueryObserver_exports);
var import_queryObserver = require("./queryObserver.cjs");
var import_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
var InfiniteQueryObserver = class extends import_queryObserver.QueryObserver {
constructor(client, options) {
super(client, options);
}
bindMethods() {
super.bindMethods();
this.fetchNextPage = this.fetchNextPage.bind(this);
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
}
setOptions(options) {
options._type = "infinite";
super.setOptions(options);
}
getOptimisticResult(options) {
options._type = "infinite";
return super.getOptimisticResult(options);
}
fetchNextPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "forward" }
}
});
}
fetchPreviousPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "backward" }
}
});
}
createResult(query, options) {
var _a, _b;
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = (_b = (_a = state.fetchMeta) == null ? void 0 : _a.fetchMore) == null ? void 0 : _b.direction;
const isFetchNextPageError = isError && fetchDirection === "forward";
const isFetchingNextPage = isFetching && fetchDirection === "forward";
const isFetchPreviousPageError = isError && fetchDirection === "backward";
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
const result = {
...parentResult,
fetchNextPage: this.fetchNextPage,
fetchPreviousPage: this.fetchPreviousPage,
hasNextPage: (0, import_infiniteQueryBehavior.hasNextPage)(options, state.data),
hasPreviousPage: (0, import_infiniteQueryBehavior.hasPreviousPage)(options, state.data),
isFetchNextPageError,
isFetchingNextPage,
isFetchPreviousPageError,
isFetchingPreviousPage,
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
};
return result;
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
InfiniteQueryObserver
});
//# sourceMappingURL=infiniteQueryObserver.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export { InfiniteQueryObserver_alias_1 as InfiniteQueryObserver } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1 @@
export { InfiniteQueryObserver_alias_1 as InfiniteQueryObserver } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,68 @@
import "./chunk-PXG64RU4.js";
// src/infiniteQueryObserver.ts
import { QueryObserver } from "./queryObserver.js";
import { hasNextPage, hasPreviousPage } from "./infiniteQueryBehavior.js";
var InfiniteQueryObserver = class extends QueryObserver {
constructor(client, options) {
super(client, options);
}
bindMethods() {
super.bindMethods();
this.fetchNextPage = this.fetchNextPage.bind(this);
this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
}
setOptions(options) {
options._type = "infinite";
super.setOptions(options);
}
getOptimisticResult(options) {
options._type = "infinite";
return super.getOptimisticResult(options);
}
fetchNextPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "forward" }
}
});
}
fetchPreviousPage(options) {
return this.fetch({
...options,
meta: {
fetchMore: { direction: "backward" }
}
});
}
createResult(query, options) {
var _a, _b;
const { state } = query;
const parentResult = super.createResult(query, options);
const { isFetching, isRefetching, isError, isRefetchError } = parentResult;
const fetchDirection = (_b = (_a = state.fetchMeta) == null ? void 0 : _a.fetchMore) == null ? void 0 : _b.direction;
const isFetchNextPageError = isError && fetchDirection === "forward";
const isFetchingNextPage = isFetching && fetchDirection === "forward";
const isFetchPreviousPageError = isError && fetchDirection === "backward";
const isFetchingPreviousPage = isFetching && fetchDirection === "backward";
const result = {
...parentResult,
fetchNextPage: this.fetchNextPage,
fetchPreviousPage: this.fetchPreviousPage,
hasNextPage: hasNextPage(options, state.data),
hasPreviousPage: hasPreviousPage(options, state.data),
isFetchNextPageError,
isFetchingNextPage,
isFetchPreviousPageError,
isFetchingPreviousPage,
isRefetchError: isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError,
isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
};
return result;
}
};
export {
InfiniteQueryObserver
};
//# sourceMappingURL=infiniteQueryObserver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,333 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/mutation.ts
var mutation_exports = {};
__export(mutation_exports, {
Mutation: () => Mutation,
getDefaultState: () => getDefaultState
});
module.exports = __toCommonJS(mutation_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_removable = require("./removable.cjs");
var import_retryer = require("./retryer.cjs");
var _client, _observers, _mutationCache, _retryer, _Mutation_instances, dispatch_fn;
var Mutation = class extends import_removable.Removable {
constructor(config) {
super();
__privateAdd(this, _Mutation_instances);
__privateAdd(this, _client);
__privateAdd(this, _observers);
__privateAdd(this, _mutationCache);
__privateAdd(this, _retryer);
__privateSet(this, _client, config.client);
this.mutationId = config.mutationId;
__privateSet(this, _mutationCache, config.mutationCache);
__privateSet(this, _observers, []);
this.state = config.state || getDefaultState();
this.setOptions(config.options);
this.scheduleGc();
}
setOptions(options) {
this.options = options;
this.updateGcTime(this.options.gcTime);
}
get meta() {
return this.options.meta;
}
addObserver(observer) {
if (!__privateGet(this, _observers).includes(observer)) {
__privateGet(this, _observers).push(observer);
this.clearGcTimeout();
__privateGet(this, _mutationCache).notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
removeObserver(observer) {
__privateSet(this, _observers, __privateGet(this, _observers).filter((x) => x !== observer));
this.scheduleGc();
__privateGet(this, _mutationCache).notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!__privateGet(this, _observers).length) {
if (this.state.status === "pending") {
this.scheduleGc();
} else {
__privateGet(this, _mutationCache).remove(this);
}
}
}
continue() {
var _a;
return ((_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue()) ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
this.execute(this.state.variables);
}
async execute(variables) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
const onContinue = () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "continue" });
};
const mutationFnContext = {
client: __privateGet(this, _client),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
__privateSet(this, _retryer, (0, import_retryer.createRetryer)({
fn: () => {
if (!this.options.mutationFn) {
return Promise.reject(new Error("No mutationFn found"));
}
return this.options.mutationFn(variables, mutationFnContext);
},
onFail: (failureCount, error) => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
},
onPause: () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => __privateGet(this, _mutationCache).canRun(this)
}));
const restored = this.state.status === "pending";
const isPaused = !__privateGet(this, _retryer).canStart();
try {
if (restored) {
onContinue();
} else {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pending", variables, isPaused });
if (__privateGet(this, _mutationCache).config.onMutate) {
await __privateGet(this, _mutationCache).config.onMutate(
variables,
this,
mutationFnContext
);
}
const context = await ((_b = (_a = this.options).onMutate) == null ? void 0 : _b.call(
_a,
variables,
mutationFnContext
));
if (context !== this.state.context) {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, {
type: "pending",
context,
variables,
isPaused
});
}
}
const data = await __privateGet(this, _retryer).start();
await ((_d = (_c = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _d.call(
_c,
data,
variables,
this.state.context,
this,
mutationFnContext
));
await ((_f = (_e = this.options).onSuccess) == null ? void 0 : _f.call(
_e,
data,
variables,
this.state.context,
mutationFnContext
));
await ((_h = (_g = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _h.call(
_g,
data,
null,
this.state.variables,
this.state.context,
this,
mutationFnContext
));
await ((_j = (_i = this.options).onSettled) == null ? void 0 : _j.call(
_i,
data,
null,
variables,
this.state.context,
mutationFnContext
));
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "success", data });
return data;
} catch (error) {
try {
await ((_l = (_k = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _l.call(
_k,
error,
variables,
this.state.context,
this,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
try {
await ((_n = (_m = this.options).onError) == null ? void 0 : _n.call(
_m,
error,
variables,
this.state.context,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
try {
await ((_p = (_o = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _p.call(
_o,
void 0,
error,
this.state.variables,
this.state.context,
this,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
try {
await ((_r = (_q = this.options).onSettled) == null ? void 0 : _r.call(
_q,
void 0,
error,
variables,
this.state.context,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "error", error });
throw error;
} finally {
__privateGet(this, _mutationCache).runNext(this);
}
}
};
_client = new WeakMap();
_observers = new WeakMap();
_mutationCache = new WeakMap();
_retryer = new WeakMap();
_Mutation_instances = new WeakSet();
dispatch_fn = function(action) {
const reducer = (state) => {
switch (action.type) {
case "failed":
return {
...state,
failureCount: action.failureCount,
failureReason: action.error
};
case "pause":
return {
...state,
isPaused: true
};
case "continue":
return {
...state,
isPaused: false
};
case "pending":
return {
...state,
context: action.context,
data: void 0,
failureCount: 0,
failureReason: null,
error: null,
isPaused: action.isPaused,
status: "pending",
variables: action.variables,
submittedAt: Date.now()
};
case "success":
return {
...state,
data: action.data,
failureCount: 0,
failureReason: null,
error: null,
status: "success",
isPaused: false
};
case "error":
return {
...state,
data: void 0,
error: action.error,
failureCount: state.failureCount + 1,
failureReason: action.error,
isPaused: false,
status: "error"
};
}
};
this.state = reducer(this.state);
import_notifyManager.notifyManager.batch(() => {
__privateGet(this, _observers).forEach((observer) => {
observer.onMutationUpdate(action);
});
__privateGet(this, _mutationCache).notify({
mutation: this,
type: "updated",
action
});
});
};
function getDefaultState() {
return {
context: void 0,
data: void 0,
error: null,
failureCount: 0,
failureReason: null,
isPaused: false,
status: "idle",
variables: void 0,
submittedAt: 0
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Mutation,
getDefaultState
});
//# sourceMappingURL=mutation.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
export { getDefaultState } from './_tsup-dts-rollup.cjs';
export { MutationState_alias_1 as MutationState } from './_tsup-dts-rollup.cjs';
export { Action } from './_tsup-dts-rollup.cjs';
export { Mutation_alias_1 as Mutation } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,4 @@
export { getDefaultState } from './_tsup-dts-rollup.js';
export { MutationState_alias_1 as MutationState } from './_tsup-dts-rollup.js';
export { Action } from './_tsup-dts-rollup.js';
export { Mutation_alias_1 as Mutation } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,306 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/mutation.ts
import { notifyManager } from "./notifyManager.js";
import { Removable } from "./removable.js";
import { createRetryer } from "./retryer.js";
var _client, _observers, _mutationCache, _retryer, _Mutation_instances, dispatch_fn;
var Mutation = class extends Removable {
constructor(config) {
super();
__privateAdd(this, _Mutation_instances);
__privateAdd(this, _client);
__privateAdd(this, _observers);
__privateAdd(this, _mutationCache);
__privateAdd(this, _retryer);
__privateSet(this, _client, config.client);
this.mutationId = config.mutationId;
__privateSet(this, _mutationCache, config.mutationCache);
__privateSet(this, _observers, []);
this.state = config.state || getDefaultState();
this.setOptions(config.options);
this.scheduleGc();
}
setOptions(options) {
this.options = options;
this.updateGcTime(this.options.gcTime);
}
get meta() {
return this.options.meta;
}
addObserver(observer) {
if (!__privateGet(this, _observers).includes(observer)) {
__privateGet(this, _observers).push(observer);
this.clearGcTimeout();
__privateGet(this, _mutationCache).notify({
type: "observerAdded",
mutation: this,
observer
});
}
}
removeObserver(observer) {
__privateSet(this, _observers, __privateGet(this, _observers).filter((x) => x !== observer));
this.scheduleGc();
__privateGet(this, _mutationCache).notify({
type: "observerRemoved",
mutation: this,
observer
});
}
optionalRemove() {
if (!__privateGet(this, _observers).length) {
if (this.state.status === "pending") {
this.scheduleGc();
} else {
__privateGet(this, _mutationCache).remove(this);
}
}
}
continue() {
var _a;
return ((_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue()) ?? // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
this.execute(this.state.variables);
}
async execute(variables) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
const onContinue = () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "continue" });
};
const mutationFnContext = {
client: __privateGet(this, _client),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
__privateSet(this, _retryer, createRetryer({
fn: () => {
if (!this.options.mutationFn) {
return Promise.reject(new Error("No mutationFn found"));
}
return this.options.mutationFn(variables, mutationFnContext);
},
onFail: (failureCount, error) => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
},
onPause: () => {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pause" });
},
onContinue,
retry: this.options.retry ?? 0,
retryDelay: this.options.retryDelay,
networkMode: this.options.networkMode,
canRun: () => __privateGet(this, _mutationCache).canRun(this)
}));
const restored = this.state.status === "pending";
const isPaused = !__privateGet(this, _retryer).canStart();
try {
if (restored) {
onContinue();
} else {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "pending", variables, isPaused });
if (__privateGet(this, _mutationCache).config.onMutate) {
await __privateGet(this, _mutationCache).config.onMutate(
variables,
this,
mutationFnContext
);
}
const context = await ((_b = (_a = this.options).onMutate) == null ? void 0 : _b.call(
_a,
variables,
mutationFnContext
));
if (context !== this.state.context) {
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, {
type: "pending",
context,
variables,
isPaused
});
}
}
const data = await __privateGet(this, _retryer).start();
await ((_d = (_c = __privateGet(this, _mutationCache).config).onSuccess) == null ? void 0 : _d.call(
_c,
data,
variables,
this.state.context,
this,
mutationFnContext
));
await ((_f = (_e = this.options).onSuccess) == null ? void 0 : _f.call(
_e,
data,
variables,
this.state.context,
mutationFnContext
));
await ((_h = (_g = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _h.call(
_g,
data,
null,
this.state.variables,
this.state.context,
this,
mutationFnContext
));
await ((_j = (_i = this.options).onSettled) == null ? void 0 : _j.call(
_i,
data,
null,
variables,
this.state.context,
mutationFnContext
));
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "success", data });
return data;
} catch (error) {
try {
await ((_l = (_k = __privateGet(this, _mutationCache).config).onError) == null ? void 0 : _l.call(
_k,
error,
variables,
this.state.context,
this,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
try {
await ((_n = (_m = this.options).onError) == null ? void 0 : _n.call(
_m,
error,
variables,
this.state.context,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
try {
await ((_p = (_o = __privateGet(this, _mutationCache).config).onSettled) == null ? void 0 : _p.call(
_o,
void 0,
error,
this.state.variables,
this.state.context,
this,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
try {
await ((_r = (_q = this.options).onSettled) == null ? void 0 : _r.call(
_q,
void 0,
error,
variables,
this.state.context,
mutationFnContext
));
} catch (e) {
void Promise.reject(e);
}
__privateMethod(this, _Mutation_instances, dispatch_fn).call(this, { type: "error", error });
throw error;
} finally {
__privateGet(this, _mutationCache).runNext(this);
}
}
};
_client = new WeakMap();
_observers = new WeakMap();
_mutationCache = new WeakMap();
_retryer = new WeakMap();
_Mutation_instances = new WeakSet();
dispatch_fn = function(action) {
const reducer = (state) => {
switch (action.type) {
case "failed":
return {
...state,
failureCount: action.failureCount,
failureReason: action.error
};
case "pause":
return {
...state,
isPaused: true
};
case "continue":
return {
...state,
isPaused: false
};
case "pending":
return {
...state,
context: action.context,
data: void 0,
failureCount: 0,
failureReason: null,
error: null,
isPaused: action.isPaused,
status: "pending",
variables: action.variables,
submittedAt: Date.now()
};
case "success":
return {
...state,
data: action.data,
failureCount: 0,
failureReason: null,
error: null,
status: "success",
isPaused: false
};
case "error":
return {
...state,
data: void 0,
error: action.error,
failureCount: state.failureCount + 1,
failureReason: action.error,
isPaused: false,
status: "error"
};
}
};
this.state = reducer(this.state);
notifyManager.batch(() => {
__privateGet(this, _observers).forEach((observer) => {
observer.onMutationUpdate(action);
});
__privateGet(this, _mutationCache).notify({
mutation: this,
type: "updated",
action
});
});
};
function getDefaultState() {
return {
context: void 0,
data: void 0,
error: null,
failureCount: 0,
failureReason: null,
isPaused: false,
status: "idle",
variables: void 0,
submittedAt: 0
};
}
export {
Mutation,
getDefaultState
};
//# sourceMappingURL=mutation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,170 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateWrapper = (obj, member, setter, getter) => ({
set _(value) {
__privateSet(obj, member, value, setter);
},
get _() {
return __privateGet(obj, member, getter);
}
});
// src/mutationCache.ts
var mutationCache_exports = {};
__export(mutationCache_exports, {
MutationCache: () => MutationCache
});
module.exports = __toCommonJS(mutationCache_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_mutation = require("./mutation.cjs");
var import_utils = require("./utils.cjs");
var import_subscribable = require("./subscribable.cjs");
var _mutations, _scopes, _mutationId;
var MutationCache = class extends import_subscribable.Subscribable {
constructor(config = {}) {
super();
this.config = config;
__privateAdd(this, _mutations);
__privateAdd(this, _scopes);
__privateAdd(this, _mutationId);
__privateSet(this, _mutations, /* @__PURE__ */ new Set());
__privateSet(this, _scopes, /* @__PURE__ */ new Map());
__privateSet(this, _mutationId, 0);
}
build(client, options, state) {
const mutation = new import_mutation.Mutation({
client,
mutationCache: this,
mutationId: ++__privateWrapper(this, _mutationId)._,
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
add(mutation) {
__privateGet(this, _mutations).add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
scopedMutations.push(mutation);
} else {
__privateGet(this, _scopes).set(scope, [mutation]);
}
}
this.notify({ type: "added", mutation });
}
remove(mutation) {
if (__privateGet(this, _mutations).delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
if (scopedMutations.length > 1) {
const index = scopedMutations.indexOf(mutation);
if (index !== -1) {
scopedMutations.splice(index, 1);
}
} else if (scopedMutations[0] === mutation) {
__privateGet(this, _scopes).delete(scope);
}
}
}
}
this.notify({ type: "removed", mutation });
}
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = __privateGet(this, _scopes).get(scope);
const firstPendingMutation = mutationsWithSameScope == null ? void 0 : mutationsWithSameScope.find(
(m) => m.state.status === "pending"
);
return !firstPendingMutation || firstPendingMutation === mutation;
} else {
return true;
}
}
runNext(mutation) {
var _a;
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const foundMutation = (_a = __privateGet(this, _scopes).get(scope)) == null ? void 0 : _a.find((m) => m !== mutation && m.state.isPaused);
return (foundMutation == null ? void 0 : foundMutation.continue()) ?? Promise.resolve();
} else {
return Promise.resolve();
}
}
clear() {
import_notifyManager.notifyManager.batch(() => {
__privateGet(this, _mutations).forEach((mutation) => {
this.notify({ type: "removed", mutation });
});
__privateGet(this, _mutations).clear();
__privateGet(this, _scopes).clear();
});
}
getAll() {
return Array.from(__privateGet(this, _mutations));
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(mutation) => (0, import_utils.matchMutation)(defaultedFilters, mutation)
);
}
findAll(filters = {}) {
return this.getAll().filter((mutation) => (0, import_utils.matchMutation)(filters, mutation));
}
notify(event) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
resumePausedMutations() {
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
return import_notifyManager.notifyManager.batch(
() => Promise.all(
pausedMutations.map((mutation) => mutation.continue().catch(import_utils.noop))
)
);
}
};
_mutations = new WeakMap();
_scopes = new WeakMap();
_mutationId = new WeakMap();
function scopeFor(mutation) {
var _a;
return (_a = mutation.options.scope) == null ? void 0 : _a.id;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MutationCache
});
//# sourceMappingURL=mutationCache.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export { MutationCacheNotifyEvent_alias_1 as MutationCacheNotifyEvent } from './_tsup-dts-rollup.cjs';
export { MutationCache_alias_1 as MutationCache } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,2 @@
export { MutationCacheNotifyEvent_alias_1 as MutationCacheNotifyEvent } from './_tsup-dts-rollup.js';
export { MutationCache_alias_1 as MutationCache } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,137 @@
import {
__privateAdd,
__privateGet,
__privateSet,
__privateWrapper
} from "./chunk-PXG64RU4.js";
// src/mutationCache.ts
import { notifyManager } from "./notifyManager.js";
import { Mutation } from "./mutation.js";
import { matchMutation, noop } from "./utils.js";
import { Subscribable } from "./subscribable.js";
var _mutations, _scopes, _mutationId;
var MutationCache = class extends Subscribable {
constructor(config = {}) {
super();
this.config = config;
__privateAdd(this, _mutations);
__privateAdd(this, _scopes);
__privateAdd(this, _mutationId);
__privateSet(this, _mutations, /* @__PURE__ */ new Set());
__privateSet(this, _scopes, /* @__PURE__ */ new Map());
__privateSet(this, _mutationId, 0);
}
build(client, options, state) {
const mutation = new Mutation({
client,
mutationCache: this,
mutationId: ++__privateWrapper(this, _mutationId)._,
options: client.defaultMutationOptions(options),
state
});
this.add(mutation);
return mutation;
}
add(mutation) {
__privateGet(this, _mutations).add(mutation);
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
scopedMutations.push(mutation);
} else {
__privateGet(this, _scopes).set(scope, [mutation]);
}
}
this.notify({ type: "added", mutation });
}
remove(mutation) {
if (__privateGet(this, _mutations).delete(mutation)) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const scopedMutations = __privateGet(this, _scopes).get(scope);
if (scopedMutations) {
if (scopedMutations.length > 1) {
const index = scopedMutations.indexOf(mutation);
if (index !== -1) {
scopedMutations.splice(index, 1);
}
} else if (scopedMutations[0] === mutation) {
__privateGet(this, _scopes).delete(scope);
}
}
}
}
this.notify({ type: "removed", mutation });
}
canRun(mutation) {
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const mutationsWithSameScope = __privateGet(this, _scopes).get(scope);
const firstPendingMutation = mutationsWithSameScope == null ? void 0 : mutationsWithSameScope.find(
(m) => m.state.status === "pending"
);
return !firstPendingMutation || firstPendingMutation === mutation;
} else {
return true;
}
}
runNext(mutation) {
var _a;
const scope = scopeFor(mutation);
if (typeof scope === "string") {
const foundMutation = (_a = __privateGet(this, _scopes).get(scope)) == null ? void 0 : _a.find((m) => m !== mutation && m.state.isPaused);
return (foundMutation == null ? void 0 : foundMutation.continue()) ?? Promise.resolve();
} else {
return Promise.resolve();
}
}
clear() {
notifyManager.batch(() => {
__privateGet(this, _mutations).forEach((mutation) => {
this.notify({ type: "removed", mutation });
});
__privateGet(this, _mutations).clear();
__privateGet(this, _scopes).clear();
});
}
getAll() {
return Array.from(__privateGet(this, _mutations));
}
find(filters) {
const defaultedFilters = { exact: true, ...filters };
return this.getAll().find(
(mutation) => matchMutation(defaultedFilters, mutation)
);
}
findAll(filters = {}) {
return this.getAll().filter((mutation) => matchMutation(filters, mutation));
}
notify(event) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(event);
});
});
}
resumePausedMutations() {
const pausedMutations = this.getAll().filter((x) => x.state.isPaused);
return notifyManager.batch(
() => Promise.all(
pausedMutations.map((mutation) => mutation.continue().catch(noop))
)
);
}
};
_mutations = new WeakMap();
_scopes = new WeakMap();
_mutationId = new WeakMap();
function scopeFor(mutation) {
var _a;
return (_a = mutation.options.scope) == null ? void 0 : _a.id;
}
export {
MutationCache
};
//# sourceMappingURL=mutationCache.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,190 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/mutationObserver.ts
var mutationObserver_exports = {};
__export(mutationObserver_exports, {
MutationObserver: () => MutationObserver
});
module.exports = __toCommonJS(mutationObserver_exports);
var import_mutation = require("./mutation.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
var _client, _currentResult, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn;
var MutationObserver = class extends import_subscribable.Subscribable {
constructor(client, options) {
super();
__privateAdd(this, _MutationObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _currentResult);
__privateAdd(this, _currentMutation);
__privateAdd(this, _mutateOptions);
__privateSet(this, _client, client);
this.setOptions(options);
this.bindMethods();
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
}
bindMethods() {
this.mutate = this.mutate.bind(this);
this.reset = this.reset.bind(this);
}
setOptions(options) {
var _a;
const prevOptions = this.options;
this.options = __privateGet(this, _client).defaultMutationOptions(options);
if (!(0, import_utils.shallowEqualObjects)(this.options, prevOptions)) {
__privateGet(this, _client).getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: __privateGet(this, _currentMutation),
observer: this
});
}
if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && (0, import_utils.hashKey)(prevOptions.mutationKey) !== (0, import_utils.hashKey)(this.options.mutationKey)) {
this.reset();
} else if (((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state.status) === "pending") {
__privateGet(this, _currentMutation).setOptions(this.options);
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
}
}
onMutationUpdate(action) {
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this, action);
}
getCurrentResult() {
return __privateGet(this, _currentResult);
}
reset() {
var _a;
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, void 0);
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this);
}
mutate(variables, options) {
var _a;
__privateSet(this, _mutateOptions, options);
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, __privateGet(this, _client).getMutationCache().build(__privateGet(this, _client), this.options));
__privateGet(this, _currentMutation).addObserver(this);
return __privateGet(this, _currentMutation).execute(variables);
}
};
_client = new WeakMap();
_currentResult = new WeakMap();
_currentMutation = new WeakMap();
_mutateOptions = new WeakMap();
_MutationObserver_instances = new WeakSet();
updateResult_fn = function() {
var _a;
const state = ((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state) ?? (0, import_mutation.getDefaultState)();
__privateSet(this, _currentResult, {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
});
};
notify_fn = function(action) {
import_notifyManager.notifyManager.batch(() => {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
const variables = __privateGet(this, _currentResult).variables;
const onMutateResult = __privateGet(this, _currentResult).context;
const context = {
client: __privateGet(this, _client),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
if ((action == null ? void 0 : action.type) === "success") {
try {
(_b = (_a = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b.call(
_a,
action.data,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
(_d = (_c = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d.call(
_c,
action.data,
null,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
} else if ((action == null ? void 0 : action.type) === "error") {
try {
(_f = (_e = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f.call(
_e,
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
(_h = (_g = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h.call(
_g,
void 0,
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
}
}
this.listeners.forEach((listener) => {
listener(__privateGet(this, _currentResult));
});
});
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MutationObserver
});
//# sourceMappingURL=mutationObserver.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export { MutationObserver_alias_1 as MutationObserver } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1 @@
export { MutationObserver_alias_1 as MutationObserver } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,164 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/mutationObserver.ts
import { getDefaultState } from "./mutation.js";
import { notifyManager } from "./notifyManager.js";
import { Subscribable } from "./subscribable.js";
import { hashKey, shallowEqualObjects } from "./utils.js";
var _client, _currentResult, _currentMutation, _mutateOptions, _MutationObserver_instances, updateResult_fn, notify_fn;
var MutationObserver = class extends Subscribable {
constructor(client, options) {
super();
__privateAdd(this, _MutationObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _currentResult);
__privateAdd(this, _currentMutation);
__privateAdd(this, _mutateOptions);
__privateSet(this, _client, client);
this.setOptions(options);
this.bindMethods();
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
}
bindMethods() {
this.mutate = this.mutate.bind(this);
this.reset = this.reset.bind(this);
}
setOptions(options) {
var _a;
const prevOptions = this.options;
this.options = __privateGet(this, _client).defaultMutationOptions(options);
if (!shallowEqualObjects(this.options, prevOptions)) {
__privateGet(this, _client).getMutationCache().notify({
type: "observerOptionsUpdated",
mutation: __privateGet(this, _currentMutation),
observer: this
});
}
if ((prevOptions == null ? void 0 : prevOptions.mutationKey) && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) {
this.reset();
} else if (((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state.status) === "pending") {
__privateGet(this, _currentMutation).setOptions(this.options);
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
}
}
onMutationUpdate(action) {
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this, action);
}
getCurrentResult() {
return __privateGet(this, _currentResult);
}
reset() {
var _a;
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, void 0);
__privateMethod(this, _MutationObserver_instances, updateResult_fn).call(this);
__privateMethod(this, _MutationObserver_instances, notify_fn).call(this);
}
mutate(variables, options) {
var _a;
__privateSet(this, _mutateOptions, options);
(_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.removeObserver(this);
__privateSet(this, _currentMutation, __privateGet(this, _client).getMutationCache().build(__privateGet(this, _client), this.options));
__privateGet(this, _currentMutation).addObserver(this);
return __privateGet(this, _currentMutation).execute(variables);
}
};
_client = new WeakMap();
_currentResult = new WeakMap();
_currentMutation = new WeakMap();
_mutateOptions = new WeakMap();
_MutationObserver_instances = new WeakSet();
updateResult_fn = function() {
var _a;
const state = ((_a = __privateGet(this, _currentMutation)) == null ? void 0 : _a.state) ?? getDefaultState();
__privateSet(this, _currentResult, {
...state,
isPending: state.status === "pending",
isSuccess: state.status === "success",
isError: state.status === "error",
isIdle: state.status === "idle",
mutate: this.mutate,
reset: this.reset
});
};
notify_fn = function(action) {
notifyManager.batch(() => {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (__privateGet(this, _mutateOptions) && this.hasListeners()) {
const variables = __privateGet(this, _currentResult).variables;
const onMutateResult = __privateGet(this, _currentResult).context;
const context = {
client: __privateGet(this, _client),
meta: this.options.meta,
mutationKey: this.options.mutationKey
};
if ((action == null ? void 0 : action.type) === "success") {
try {
(_b = (_a = __privateGet(this, _mutateOptions)).onSuccess) == null ? void 0 : _b.call(
_a,
action.data,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
(_d = (_c = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _d.call(
_c,
action.data,
null,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
} else if ((action == null ? void 0 : action.type) === "error") {
try {
(_f = (_e = __privateGet(this, _mutateOptions)).onError) == null ? void 0 : _f.call(
_e,
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
try {
(_h = (_g = __privateGet(this, _mutateOptions)).onSettled) == null ? void 0 : _h.call(
_g,
void 0,
action.error,
variables,
onMutateResult,
context
);
} catch (e) {
void Promise.reject(e);
}
}
}
this.listeners.forEach((listener) => {
listener(__privateGet(this, _currentResult));
});
});
};
export {
MutationObserver
};
//# sourceMappingURL=mutationObserver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,113 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/notifyManager.ts
var notifyManager_exports = {};
__export(notifyManager_exports, {
createNotifyManager: () => createNotifyManager,
defaultScheduler: () => defaultScheduler,
notifyManager: () => notifyManager
});
module.exports = __toCommonJS(notifyManager_exports);
var import_timeoutManager = require("./timeoutManager.cjs");
var defaultScheduler = import_timeoutManager.systemSetTimeoutZero;
function createNotifyManager() {
let queue = [];
let transactions = 0;
let notifyFn = (callback) => {
callback();
};
let batchNotifyFn = (callback) => {
callback();
};
let scheduleFn = defaultScheduler;
const schedule = (callback) => {
if (transactions) {
queue.push(callback);
} else {
scheduleFn(() => {
notifyFn(callback);
});
}
};
const flush = () => {
const originalQueue = queue;
queue = [];
if (originalQueue.length) {
scheduleFn(() => {
batchNotifyFn(() => {
originalQueue.forEach((callback) => {
notifyFn(callback);
});
});
});
}
};
return {
batch: (callback) => {
let result;
transactions++;
try {
result = callback();
} finally {
transactions--;
if (!transactions) {
flush();
}
}
return result;
},
/**
* All calls to the wrapped function will be batched.
*/
batchCalls: (callback) => {
return (...args) => {
schedule(() => {
callback(...args);
});
};
},
schedule,
/**
* Use this method to set a custom notify function.
* This can be used to for example wrap notifications with `React.act` while running tests.
*/
setNotifyFunction: (fn) => {
notifyFn = fn;
},
/**
* Use this method to set a custom function to batch notifications together into a single tick.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
setBatchNotifyFunction: (fn) => {
batchNotifyFn = fn;
},
setScheduler: (fn) => {
scheduleFn = fn;
}
};
}
var notifyManager = createNotifyManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createNotifyManager,
defaultScheduler,
notifyManager
});
//# sourceMappingURL=notifyManager.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,4BAAqC;AAY9B,IAAM,mBAAqC;AAE3C,SAAS,sBAAsB;AACpC,MAAI,QAA+B,CAAC;AACpC,MAAI,eAAe;AACnB,MAAI,WAA2B,CAAC,aAAa;AAC3C,aAAS;AAAA,EACX;AACA,MAAI,gBAAqC,CAAC,aAAyB;AACjE,aAAS;AAAA,EACX;AACA,MAAI,aAAa;AAEjB,QAAM,WAAW,CAAC,aAAmC;AACnD,QAAI,cAAc;AAChB,YAAM,KAAK,QAAQ;AAAA,IACrB,OAAO;AACL,iBAAW,MAAM;AACf,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,QAAQ,MAAY;AACxB,UAAM,gBAAgB;AACtB,YAAQ,CAAC;AACT,QAAI,cAAc,QAAQ;AACxB,iBAAW,MAAM;AACf,sBAAc,MAAM;AAClB,wBAAc,QAAQ,CAAC,aAAa;AAClC,qBAAS,QAAQ;AAAA,UACnB,CAAC;AAAA,QACH,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,CAAI,aAAyB;AAClC,UAAI;AACJ;AACA,UAAI;AACF,iBAAS,SAAS;AAAA,MACpB,UAAE;AACA;AACA,YAAI,CAAC,cAAc;AACjB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,CACV,aAC0B;AAC1B,aAAO,IAAI,SAAS;AAClB,iBAAS,MAAM;AACb,mBAAS,GAAG,IAAI;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,mBAAmB,CAAC,OAAuB;AACzC,iBAAW;AAAA,IACb;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,wBAAwB,CAAC,OAA4B;AACnD,sBAAgB;AAAA,IAClB;AAAA,IACA,cAAc,CAAC,OAAyB;AACtC,mBAAa;AAAA,IACf;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB,oBAAoB;","names":[]}

View File

@@ -0,0 +1,3 @@
export { createNotifyManager } from './_tsup-dts-rollup.cjs';
export { defaultScheduler_alias_1 as defaultScheduler } from './_tsup-dts-rollup.cjs';
export { notifyManager_alias_1 as notifyManager } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,3 @@
export { createNotifyManager } from './_tsup-dts-rollup.js';
export { defaultScheduler_alias_1 as defaultScheduler } from './_tsup-dts-rollup.js';
export { notifyManager_alias_1 as notifyManager } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,88 @@
import "./chunk-PXG64RU4.js";
// src/notifyManager.ts
import { systemSetTimeoutZero } from "./timeoutManager.js";
var defaultScheduler = systemSetTimeoutZero;
function createNotifyManager() {
let queue = [];
let transactions = 0;
let notifyFn = (callback) => {
callback();
};
let batchNotifyFn = (callback) => {
callback();
};
let scheduleFn = defaultScheduler;
const schedule = (callback) => {
if (transactions) {
queue.push(callback);
} else {
scheduleFn(() => {
notifyFn(callback);
});
}
};
const flush = () => {
const originalQueue = queue;
queue = [];
if (originalQueue.length) {
scheduleFn(() => {
batchNotifyFn(() => {
originalQueue.forEach((callback) => {
notifyFn(callback);
});
});
});
}
};
return {
batch: (callback) => {
let result;
transactions++;
try {
result = callback();
} finally {
transactions--;
if (!transactions) {
flush();
}
}
return result;
},
/**
* All calls to the wrapped function will be batched.
*/
batchCalls: (callback) => {
return (...args) => {
schedule(() => {
callback(...args);
});
};
},
schedule,
/**
* Use this method to set a custom notify function.
* This can be used to for example wrap notifications with `React.act` while running tests.
*/
setNotifyFunction: (fn) => {
notifyFn = fn;
},
/**
* Use this method to set a custom function to batch notifications together into a single tick.
* By default React Query will use the batch function provided by ReactDOM or React Native.
*/
setBatchNotifyFunction: (fn) => {
batchNotifyFn = fn;
},
setScheduler: (fn) => {
scheduleFn = fn;
}
};
}
var notifyManager = createNotifyManager();
export {
createNotifyManager,
defaultScheduler,
notifyManager
};
//# sourceMappingURL=notifyManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/notifyManager.ts"],"sourcesContent":["// TYPES\n\nimport { systemSetTimeoutZero } from './timeoutManager'\n\ntype NotifyCallback = () => void\n\ntype NotifyFunction = (callback: () => void) => void\n\ntype BatchNotifyFunction = (callback: () => void) => void\n\ntype BatchCallsCallback<T extends Array<unknown>> = (...args: T) => void\n\ntype ScheduleFunction = (callback: () => void) => void\n\nexport const defaultScheduler: ScheduleFunction = systemSetTimeoutZero\n\nexport function createNotifyManager() {\n let queue: Array<NotifyCallback> = []\n let transactions = 0\n let notifyFn: NotifyFunction = (callback) => {\n callback()\n }\n let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => {\n callback()\n }\n let scheduleFn = defaultScheduler\n\n const schedule = (callback: NotifyCallback): void => {\n if (transactions) {\n queue.push(callback)\n } else {\n scheduleFn(() => {\n notifyFn(callback)\n })\n }\n }\n const flush = (): void => {\n const originalQueue = queue\n queue = []\n if (originalQueue.length) {\n scheduleFn(() => {\n batchNotifyFn(() => {\n originalQueue.forEach((callback) => {\n notifyFn(callback)\n })\n })\n })\n }\n }\n\n return {\n batch: <T>(callback: () => T): T => {\n let result\n transactions++\n try {\n result = callback()\n } finally {\n transactions--\n if (!transactions) {\n flush()\n }\n }\n return result\n },\n /**\n * All calls to the wrapped function will be batched.\n */\n batchCalls: <T extends Array<unknown>>(\n callback: BatchCallsCallback<T>,\n ): BatchCallsCallback<T> => {\n return (...args) => {\n schedule(() => {\n callback(...args)\n })\n }\n },\n schedule,\n /**\n * Use this method to set a custom notify function.\n * This can be used to for example wrap notifications with `React.act` while running tests.\n */\n setNotifyFunction: (fn: NotifyFunction) => {\n notifyFn = fn\n },\n /**\n * Use this method to set a custom function to batch notifications together into a single tick.\n * By default React Query will use the batch function provided by ReactDOM or React Native.\n */\n setBatchNotifyFunction: (fn: BatchNotifyFunction) => {\n batchNotifyFn = fn\n },\n setScheduler: (fn: ScheduleFunction) => {\n scheduleFn = fn\n },\n } as const\n}\n\n// SINGLETON\nexport const notifyManager = createNotifyManager()\n"],"mappings":";;;AAEA,SAAS,4BAA4B;AAY9B,IAAM,mBAAqC;AAE3C,SAAS,sBAAsB;AACpC,MAAI,QAA+B,CAAC;AACpC,MAAI,eAAe;AACnB,MAAI,WAA2B,CAAC,aAAa;AAC3C,aAAS;AAAA,EACX;AACA,MAAI,gBAAqC,CAAC,aAAyB;AACjE,aAAS;AAAA,EACX;AACA,MAAI,aAAa;AAEjB,QAAM,WAAW,CAAC,aAAmC;AACnD,QAAI,cAAc;AAChB,YAAM,KAAK,QAAQ;AAAA,IACrB,OAAO;AACL,iBAAW,MAAM;AACf,iBAAS,QAAQ;AAAA,MACnB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,QAAQ,MAAY;AACxB,UAAM,gBAAgB;AACtB,YAAQ,CAAC;AACT,QAAI,cAAc,QAAQ;AACxB,iBAAW,MAAM;AACf,sBAAc,MAAM;AAClB,wBAAc,QAAQ,CAAC,aAAa;AAClC,qBAAS,QAAQ;AAAA,UACnB,CAAC;AAAA,QACH,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,CAAI,aAAyB;AAClC,UAAI;AACJ;AACA,UAAI;AACF,iBAAS,SAAS;AAAA,MACpB,UAAE;AACA;AACA,YAAI,CAAC,cAAc;AACjB,gBAAM;AAAA,QACR;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAIA,YAAY,CACV,aAC0B;AAC1B,aAAO,IAAI,SAAS;AAClB,iBAAS,MAAM;AACb,mBAAS,GAAG,IAAI;AAAA,QAClB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,mBAAmB,CAAC,OAAuB;AACzC,iBAAW;AAAA,IACb;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA,wBAAwB,CAAC,OAA4B;AACnD,sBAAgB;AAAA,IAClB;AAAA,IACA,cAAc,CAAC,OAAyB;AACtC,mBAAa;AAAA,IACf;AAAA,EACF;AACF;AAGO,IAAM,gBAAgB,oBAAoB;","names":[]}

View File

@@ -0,0 +1,96 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
// src/onlineManager.ts
var onlineManager_exports = {};
__export(onlineManager_exports, {
OnlineManager: () => OnlineManager,
onlineManager: () => onlineManager
});
module.exports = __toCommonJS(onlineManager_exports);
var import_subscribable = require("./subscribable.cjs");
var _online, _cleanup, _setup;
var OnlineManager = class extends import_subscribable.Subscribable {
constructor() {
super();
__privateAdd(this, _online, true);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onOnline) => {
if (typeof window !== "undefined" && window.addEventListener) {
const onlineListener = () => onOnline(true);
const offlineListener = () => onOnline(false);
window.addEventListener("online", onlineListener, false);
window.addEventListener("offline", offlineListener, false);
return () => {
window.removeEventListener("online", onlineListener);
window.removeEventListener("offline", offlineListener);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup(this.setOnline.bind(this)));
}
setOnline(online) {
const changed = __privateGet(this, _online) !== online;
if (changed) {
__privateSet(this, _online, online);
this.listeners.forEach((listener) => {
listener(online);
});
}
}
isOnline() {
return __privateGet(this, _online);
}
};
_online = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var onlineManager = new OnlineManager();
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
OnlineManager,
onlineManager
});
//# sourceMappingURL=onlineManager.cjs.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n isOnline(): boolean {\n return this.#online\n }\n}\n\nexport const on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,gBAAgB,IAAI,cAAc;","names":[]}

View File

@@ -0,0 +1,2 @@
export { OnlineManager } from './_tsup-dts-rollup.cjs';
export { onlineManager_alias_1 as onlineManager } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,2 @@
export { OnlineManager } from './_tsup-dts-rollup.js';
export { onlineManager_alias_1 as onlineManager } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,69 @@
import {
__privateAdd,
__privateGet,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/onlineManager.ts
import { Subscribable } from "./subscribable.js";
var _online, _cleanup, _setup;
var OnlineManager = class extends Subscribable {
constructor() {
super();
__privateAdd(this, _online, true);
__privateAdd(this, _cleanup);
__privateAdd(this, _setup);
__privateSet(this, _setup, (onOnline) => {
if (typeof window !== "undefined" && window.addEventListener) {
const onlineListener = () => onOnline(true);
const offlineListener = () => onOnline(false);
window.addEventListener("online", onlineListener, false);
window.addEventListener("offline", offlineListener, false);
return () => {
window.removeEventListener("online", onlineListener);
window.removeEventListener("offline", offlineListener);
};
}
return;
});
}
onSubscribe() {
if (!__privateGet(this, _cleanup)) {
this.setEventListener(__privateGet(this, _setup));
}
}
onUnsubscribe() {
var _a;
if (!this.hasListeners()) {
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, void 0);
}
}
setEventListener(setup) {
var _a;
__privateSet(this, _setup, setup);
(_a = __privateGet(this, _cleanup)) == null ? void 0 : _a.call(this);
__privateSet(this, _cleanup, setup(this.setOnline.bind(this)));
}
setOnline(online) {
const changed = __privateGet(this, _online) !== online;
if (changed) {
__privateSet(this, _online, online);
this.listeners.forEach((listener) => {
listener(online);
});
}
}
isOnline() {
return __privateGet(this, _online);
}
};
_online = new WeakMap();
_cleanup = new WeakMap();
_setup = new WeakMap();
var onlineManager = new OnlineManager();
export {
OnlineManager,
onlineManager
};
//# sourceMappingURL=onlineManager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n isOnline(): boolean {\n return this.#online\n }\n}\n\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;AAAA,SAAS,oBAAoB;AAA7B;AAKO,IAAM,gBAAN,cAA4B,aAAuB;AAAA,EAMxD,cAAc;AACZ,UAAM;AANR,gCAAU;AACV;AAEA;AAIE,uBAAK,QAAS,CAAC,aAAa;AAG1B,UAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;AAC5D,cAAM,iBAAiB,MAAM,SAAS,IAAI;AAC1C,cAAM,kBAAkB,MAAM,SAAS,KAAK;AAE5C,eAAO,iBAAiB,UAAU,gBAAgB,KAAK;AACvD,eAAO,iBAAiB,WAAW,iBAAiB,KAAK;AAEzD,eAAO,MAAM;AAEX,iBAAO,oBAAoB,UAAU,cAAc;AACnD,iBAAO,oBAAoB,WAAW,eAAe;AAAA,QACvD;AAAA,MACF;AAEA;AAAA,IACF;AAAA,EACF;AAAA,EAEU,cAAoB;AAC5B,QAAI,CAAC,mBAAK,WAAU;AAClB,WAAK,iBAAiB,mBAAK,OAAM;AAAA,IACnC;AAAA,EACF;AAAA,EAEU,gBAAgB;AAxC5B;AAyCI,QAAI,CAAC,KAAK,aAAa,GAAG;AACxB,+BAAK,cAAL;AACA,yBAAK,UAAW;AAAA,IAClB;AAAA,EACF;AAAA,EAEA,iBAAiB,OAAsB;AA/CzC;AAgDI,uBAAK,QAAS;AACd,6BAAK,cAAL;AACA,uBAAK,UAAW,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC;AAAA,EACjD;AAAA,EAEA,UAAU,QAAuB;AAC/B,UAAM,UAAU,mBAAK,aAAY;AAEjC,QAAI,SAAS;AACX,yBAAK,SAAU;AACf,WAAK,UAAU,QAAQ,CAAC,aAAa;AACnC,iBAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,WAAoB;AAClB,WAAO,mBAAK;AAAA,EACd;AACF;AA7DE;AACA;AAEA;AA4DK,IAAM,gBAAgB,IAAI,cAAc;","names":[]}

View File

@@ -0,0 +1,268 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/queriesObserver.ts
var queriesObserver_exports = {};
__export(queriesObserver_exports, {
QueriesObserver: () => QueriesObserver
});
module.exports = __toCommonJS(queriesObserver_exports);
var import_notifyManager = require("./notifyManager.cjs");
var import_queryObserver = require("./queryObserver.cjs");
var import_subscribable = require("./subscribable.cjs");
var import_utils = require("./utils.cjs");
function difference(array1, array2) {
const excludeSet = new Set(array2);
return array1.filter((x) => !excludeSet.has(x));
}
function replaceAt(array, index, value) {
const copy = array.slice(0);
copy[index] = value;
return copy;
}
var _client, _result, _queries, _options, _observers, _combinedResult, _lastCombine, _lastResult, _lastQueryHashes, _observerMatches, _QueriesObserver_instances, trackResult_fn, combineResult_fn, shouldSkipCombine_fn, findMatchingObservers_fn, onUpdate_fn, notify_fn;
var QueriesObserver = class extends import_subscribable.Subscribable {
constructor(client, queries, options) {
super();
__privateAdd(this, _QueriesObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _result);
__privateAdd(this, _queries);
__privateAdd(this, _options);
__privateAdd(this, _observers);
__privateAdd(this, _combinedResult);
__privateAdd(this, _lastCombine);
__privateAdd(this, _lastResult);
__privateAdd(this, _lastQueryHashes);
__privateAdd(this, _observerMatches, []);
__privateSet(this, _client, client);
__privateSet(this, _options, options);
__privateSet(this, _queries, []);
__privateSet(this, _observers, []);
__privateSet(this, _result, []);
this.setQueries(queries);
}
onSubscribe() {
if (this.listeners.size === 1) {
__privateGet(this, _observers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
}
}
onUnsubscribe() {
if (!this.listeners.size) {
this.destroy();
}
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
__privateGet(this, _observers).forEach((observer) => {
observer.destroy();
});
}
setQueries(queries, options) {
__privateSet(this, _queries, queries);
__privateSet(this, _options, options);
if (process.env.NODE_ENV !== "production") {
const queryHashes = queries.map(
(query) => __privateGet(this, _client).defaultQueryOptions(query).queryHash
);
if (new Set(queryHashes).size !== queryHashes.length) {
console.warn(
"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior."
);
}
}
import_notifyManager.notifyManager.batch(() => {
const prevObservers = __privateGet(this, _observers);
const newObserverMatches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, __privateGet(this, _queries));
newObserverMatches.forEach(
(match) => match.observer.setOptions(match.defaultedQueryOptions)
);
const newObservers = newObserverMatches.map((match) => match.observer);
const newResult = newObservers.map(
(observer) => observer.getCurrentResult()
);
const hasLengthChange = prevObservers.length !== newObservers.length;
const hasIndexChange = newObservers.some(
(observer, index) => observer !== prevObservers[index]
);
const hasStructuralChange = hasLengthChange || hasIndexChange;
const hasResultChange = hasStructuralChange ? true : newResult.some((result, index) => {
const prev = __privateGet(this, _result)[index];
return !prev || !(0, import_utils.shallowEqualObjects)(result, prev);
});
if (!hasStructuralChange && !hasResultChange) return;
if (hasStructuralChange) {
__privateSet(this, _observerMatches, newObserverMatches);
__privateSet(this, _observers, newObservers);
}
__privateSet(this, _result, newResult);
if (!this.hasListeners()) return;
if (hasStructuralChange) {
difference(prevObservers, newObservers).forEach((observer) => {
observer.destroy();
});
difference(newObservers, prevObservers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
}
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
});
}
getCurrentResult() {
return __privateGet(this, _result);
}
getQueries() {
return __privateGet(this, _observers).map((observer) => observer.getCurrentQuery());
}
getObservers() {
return __privateGet(this, _observers);
}
getOptimisticResult(queries, combine) {
const matches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, queries);
const result = matches.map(
(match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)
);
const queryHashes = matches.map(
(match) => match.defaultedQueryOptions.queryHash
);
return [
result,
(r) => {
return __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, r ?? result, combine, queryHashes);
},
() => {
return __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, result, matches);
}
];
}
};
_client = new WeakMap();
_result = new WeakMap();
_queries = new WeakMap();
_options = new WeakMap();
_observers = new WeakMap();
_combinedResult = new WeakMap();
_lastCombine = new WeakMap();
_lastResult = new WeakMap();
_lastQueryHashes = new WeakMap();
_observerMatches = new WeakMap();
_QueriesObserver_instances = new WeakSet();
trackResult_fn = function(result, matches) {
return matches.map((match, index) => {
const observerResult = result[index];
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
matches.forEach((m) => {
m.observer.trackProp(accessedProp);
});
}) : observerResult;
});
};
combineResult_fn = function(input, combine, queryHashes) {
if (combine) {
const lastHashes = __privateGet(this, _lastQueryHashes);
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
if (!__privateGet(this, _combinedResult) || __privateGet(this, _result) !== __privateGet(this, _lastResult) || queryHashesChanged || combine !== __privateGet(this, _lastCombine)) {
__privateSet(this, _lastCombine, combine);
__privateSet(this, _lastResult, __privateGet(this, _result));
if (queryHashes !== void 0) {
__privateSet(this, _lastQueryHashes, queryHashes);
}
__privateSet(this, _combinedResult, (0, import_utils.replaceEqualDeep)(
__privateGet(this, _combinedResult),
combine(input)
));
}
return __privateGet(this, _combinedResult);
}
return input;
};
shouldSkipCombine_fn = function() {
var _a;
return ((_a = __privateGet(this, _options)) == null ? void 0 : _a.combine) !== void 0 && __privateGet(this, _observers).some((observer, index) => {
var _a2;
return observer.options.suspense && ((_a2 = __privateGet(this, _result)[index]) == null ? void 0 : _a2.data) === void 0;
});
};
findMatchingObservers_fn = function(queries) {
const prevObserversMap = /* @__PURE__ */ new Map();
__privateGet(this, _observers).forEach((observer) => {
const key = observer.options.queryHash;
if (!key) return;
const previousObservers = prevObserversMap.get(key);
if (previousObservers) {
previousObservers.push(observer);
} else {
prevObserversMap.set(key, [observer]);
}
});
const observers = [];
queries.forEach((options) => {
var _a;
const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options);
const match = (_a = prevObserversMap.get(defaultedOptions.queryHash)) == null ? void 0 : _a.shift();
const observer = match ?? new import_queryObserver.QueryObserver(__privateGet(this, _client), defaultedOptions);
observers.push({
defaultedQueryOptions: defaultedOptions,
observer
});
});
return observers;
};
onUpdate_fn = function(observer, result) {
const index = __privateGet(this, _observers).indexOf(observer);
if (index !== -1) {
__privateSet(this, _result, replaceAt(__privateGet(this, _result), index, result));
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
}
};
notify_fn = function() {
var _a;
if (this.hasListeners()) {
const newTracked = __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, __privateGet(this, _result), __privateGet(this, _observerMatches));
const shouldSkipCombine = __privateMethod(this, _QueriesObserver_instances, shouldSkipCombine_fn).call(this);
const previousResult = __privateGet(this, _combinedResult);
const newResult = shouldSkipCombine ? previousResult : __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, newTracked, (_a = __privateGet(this, _options)) == null ? void 0 : _a.combine);
if (shouldSkipCombine || previousResult !== newResult) {
import_notifyManager.notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(__privateGet(this, _result));
});
});
}
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
QueriesObserver
});
//# sourceMappingURL=queriesObserver.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export { QueriesObserverOptions_alias_1 as QueriesObserverOptions } from './_tsup-dts-rollup.cjs';
export { QueriesObserver_alias_1 as QueriesObserver } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,2 @@
export { QueriesObserverOptions_alias_1 as QueriesObserverOptions } from './_tsup-dts-rollup.js';
export { QueriesObserver_alias_1 as QueriesObserver } from './_tsup-dts-rollup.js';

View File

@@ -0,0 +1,242 @@
import {
__privateAdd,
__privateGet,
__privateMethod,
__privateSet
} from "./chunk-PXG64RU4.js";
// src/queriesObserver.ts
import { notifyManager } from "./notifyManager.js";
import { QueryObserver } from "./queryObserver.js";
import { Subscribable } from "./subscribable.js";
import { replaceEqualDeep, shallowEqualObjects } from "./utils.js";
function difference(array1, array2) {
const excludeSet = new Set(array2);
return array1.filter((x) => !excludeSet.has(x));
}
function replaceAt(array, index, value) {
const copy = array.slice(0);
copy[index] = value;
return copy;
}
var _client, _result, _queries, _options, _observers, _combinedResult, _lastCombine, _lastResult, _lastQueryHashes, _observerMatches, _QueriesObserver_instances, trackResult_fn, combineResult_fn, shouldSkipCombine_fn, findMatchingObservers_fn, onUpdate_fn, notify_fn;
var QueriesObserver = class extends Subscribable {
constructor(client, queries, options) {
super();
__privateAdd(this, _QueriesObserver_instances);
__privateAdd(this, _client);
__privateAdd(this, _result);
__privateAdd(this, _queries);
__privateAdd(this, _options);
__privateAdd(this, _observers);
__privateAdd(this, _combinedResult);
__privateAdd(this, _lastCombine);
__privateAdd(this, _lastResult);
__privateAdd(this, _lastQueryHashes);
__privateAdd(this, _observerMatches, []);
__privateSet(this, _client, client);
__privateSet(this, _options, options);
__privateSet(this, _queries, []);
__privateSet(this, _observers, []);
__privateSet(this, _result, []);
this.setQueries(queries);
}
onSubscribe() {
if (this.listeners.size === 1) {
__privateGet(this, _observers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
}
}
onUnsubscribe() {
if (!this.listeners.size) {
this.destroy();
}
}
destroy() {
this.listeners = /* @__PURE__ */ new Set();
__privateGet(this, _observers).forEach((observer) => {
observer.destroy();
});
}
setQueries(queries, options) {
__privateSet(this, _queries, queries);
__privateSet(this, _options, options);
if (process.env.NODE_ENV !== "production") {
const queryHashes = queries.map(
(query) => __privateGet(this, _client).defaultQueryOptions(query).queryHash
);
if (new Set(queryHashes).size !== queryHashes.length) {
console.warn(
"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior."
);
}
}
notifyManager.batch(() => {
const prevObservers = __privateGet(this, _observers);
const newObserverMatches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, __privateGet(this, _queries));
newObserverMatches.forEach(
(match) => match.observer.setOptions(match.defaultedQueryOptions)
);
const newObservers = newObserverMatches.map((match) => match.observer);
const newResult = newObservers.map(
(observer) => observer.getCurrentResult()
);
const hasLengthChange = prevObservers.length !== newObservers.length;
const hasIndexChange = newObservers.some(
(observer, index) => observer !== prevObservers[index]
);
const hasStructuralChange = hasLengthChange || hasIndexChange;
const hasResultChange = hasStructuralChange ? true : newResult.some((result, index) => {
const prev = __privateGet(this, _result)[index];
return !prev || !shallowEqualObjects(result, prev);
});
if (!hasStructuralChange && !hasResultChange) return;
if (hasStructuralChange) {
__privateSet(this, _observerMatches, newObserverMatches);
__privateSet(this, _observers, newObservers);
}
__privateSet(this, _result, newResult);
if (!this.hasListeners()) return;
if (hasStructuralChange) {
difference(prevObservers, newObservers).forEach((observer) => {
observer.destroy();
});
difference(newObservers, prevObservers).forEach((observer) => {
observer.subscribe((result) => {
__privateMethod(this, _QueriesObserver_instances, onUpdate_fn).call(this, observer, result);
});
});
}
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
});
}
getCurrentResult() {
return __privateGet(this, _result);
}
getQueries() {
return __privateGet(this, _observers).map((observer) => observer.getCurrentQuery());
}
getObservers() {
return __privateGet(this, _observers);
}
getOptimisticResult(queries, combine) {
const matches = __privateMethod(this, _QueriesObserver_instances, findMatchingObservers_fn).call(this, queries);
const result = matches.map(
(match) => match.observer.getOptimisticResult(match.defaultedQueryOptions)
);
const queryHashes = matches.map(
(match) => match.defaultedQueryOptions.queryHash
);
return [
result,
(r) => {
return __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, r ?? result, combine, queryHashes);
},
() => {
return __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, result, matches);
}
];
}
};
_client = new WeakMap();
_result = new WeakMap();
_queries = new WeakMap();
_options = new WeakMap();
_observers = new WeakMap();
_combinedResult = new WeakMap();
_lastCombine = new WeakMap();
_lastResult = new WeakMap();
_lastQueryHashes = new WeakMap();
_observerMatches = new WeakMap();
_QueriesObserver_instances = new WeakSet();
trackResult_fn = function(result, matches) {
return matches.map((match, index) => {
const observerResult = result[index];
return !match.defaultedQueryOptions.notifyOnChangeProps ? match.observer.trackResult(observerResult, (accessedProp) => {
matches.forEach((m) => {
m.observer.trackProp(accessedProp);
});
}) : observerResult;
});
};
combineResult_fn = function(input, combine, queryHashes) {
if (combine) {
const lastHashes = __privateGet(this, _lastQueryHashes);
const queryHashesChanged = queryHashes !== void 0 && lastHashes !== void 0 && (lastHashes.length !== queryHashes.length || queryHashes.some((hash, i) => hash !== lastHashes[i]));
if (!__privateGet(this, _combinedResult) || __privateGet(this, _result) !== __privateGet(this, _lastResult) || queryHashesChanged || combine !== __privateGet(this, _lastCombine)) {
__privateSet(this, _lastCombine, combine);
__privateSet(this, _lastResult, __privateGet(this, _result));
if (queryHashes !== void 0) {
__privateSet(this, _lastQueryHashes, queryHashes);
}
__privateSet(this, _combinedResult, replaceEqualDeep(
__privateGet(this, _combinedResult),
combine(input)
));
}
return __privateGet(this, _combinedResult);
}
return input;
};
shouldSkipCombine_fn = function() {
var _a;
return ((_a = __privateGet(this, _options)) == null ? void 0 : _a.combine) !== void 0 && __privateGet(this, _observers).some((observer, index) => {
var _a2;
return observer.options.suspense && ((_a2 = __privateGet(this, _result)[index]) == null ? void 0 : _a2.data) === void 0;
});
};
findMatchingObservers_fn = function(queries) {
const prevObserversMap = /* @__PURE__ */ new Map();
__privateGet(this, _observers).forEach((observer) => {
const key = observer.options.queryHash;
if (!key) return;
const previousObservers = prevObserversMap.get(key);
if (previousObservers) {
previousObservers.push(observer);
} else {
prevObserversMap.set(key, [observer]);
}
});
const observers = [];
queries.forEach((options) => {
var _a;
const defaultedOptions = __privateGet(this, _client).defaultQueryOptions(options);
const match = (_a = prevObserversMap.get(defaultedOptions.queryHash)) == null ? void 0 : _a.shift();
const observer = match ?? new QueryObserver(__privateGet(this, _client), defaultedOptions);
observers.push({
defaultedQueryOptions: defaultedOptions,
observer
});
});
return observers;
};
onUpdate_fn = function(observer, result) {
const index = __privateGet(this, _observers).indexOf(observer);
if (index !== -1) {
__privateSet(this, _result, replaceAt(__privateGet(this, _result), index, result));
__privateMethod(this, _QueriesObserver_instances, notify_fn).call(this);
}
};
notify_fn = function() {
var _a;
if (this.hasListeners()) {
const newTracked = __privateMethod(this, _QueriesObserver_instances, trackResult_fn).call(this, __privateGet(this, _result), __privateGet(this, _observerMatches));
const shouldSkipCombine = __privateMethod(this, _QueriesObserver_instances, shouldSkipCombine_fn).call(this);
const previousResult = __privateGet(this, _combinedResult);
const newResult = shouldSkipCombine ? previousResult : __privateMethod(this, _QueriesObserver_instances, combineResult_fn).call(this, newTracked, (_a = __privateGet(this, _options)) == null ? void 0 : _a.combine);
if (shouldSkipCombine || previousResult !== newResult) {
notifyManager.batch(() => {
this.listeners.forEach((listener) => {
listener(__privateGet(this, _result));
});
});
}
}
};
export {
QueriesObserver
};
//# sourceMappingURL=queriesObserver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,499 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
throw TypeError(msg);
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
// src/query.ts
var query_exports = {};
__export(query_exports, {
Query: () => Query,
fetchState: () => fetchState
});
module.exports = __toCommonJS(query_exports);
var import_utils = require("./utils.cjs");
var import_notifyManager = require("./notifyManager.cjs");
var import_retryer = require("./retryer.cjs");
var import_removable = require("./removable.cjs");
var import_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
var _queryType, _initialState, _revertState, _cache, _client, _retryer, _defaultOptions, _abortSignalConsumed, _Query_instances, isInitialPausedFetch_fn, dispatch_fn;
var Query = class extends import_removable.Removable {
constructor(config) {
super();
__privateAdd(this, _Query_instances);
__privateAdd(this, _queryType);
__privateAdd(this, _initialState);
__privateAdd(this, _revertState);
__privateAdd(this, _cache);
__privateAdd(this, _client);
__privateAdd(this, _retryer);
__privateAdd(this, _defaultOptions);
__privateAdd(this, _abortSignalConsumed);
__privateSet(this, _abortSignalConsumed, false);
__privateSet(this, _defaultOptions, config.defaultOptions);
this.setOptions(config.options);
this.observers = [];
__privateSet(this, _client, config.client);
__privateSet(this, _cache, __privateGet(this, _client).getQueryCache());
this.queryKey = config.queryKey;
this.queryHash = config.queryHash;
__privateSet(this, _initialState, getDefaultState(this.options));
this.state = config.state ?? __privateGet(this, _initialState);
this.scheduleGc();
}
get meta() {
return this.options.meta;
}
get queryType() {
return __privateGet(this, _queryType);
}
get promise() {
var _a;
return (_a = __privateGet(this, _retryer)) == null ? void 0 : _a.promise;
}
setOptions(options) {
this.options = { ...__privateGet(this, _defaultOptions), ...options };
if (options == null ? void 0 : options._type) {
__privateSet(this, _queryType, options._type);
}
this.updateGcTime(this.options.gcTime);
if (this.state && this.state.data === void 0) {
const defaultState = getDefaultState(this.options);
if (defaultState.data !== void 0) {
this.setState(
successState(defaultState.data, defaultState.dataUpdatedAt)
);
__privateSet(this, _initialState, defaultState);
}
}
}
optionalRemove() {
if (!this.observers.length && this.state.fetchStatus === "idle") {
__privateGet(this, _cache).remove(this);
}
}
setData(newData, options) {
const data = (0, import_utils.replaceData)(this.state.data, newData, this.options);
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
data,
type: "success",
dataUpdatedAt: options == null ? void 0 : options.updatedAt,
manual: options == null ? void 0 : options.manual
});
return data;
}
setState(state) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "setState", state });
}
cancel(options) {
var _a, _b;
const promise = (_a = __privateGet(this, _retryer)) == null ? void 0 : _a.promise;
(_b = __privateGet(this, _retryer)) == null ? void 0 : _b.cancel(options);
return promise ? promise.then(import_utils.noop).catch(import_utils.noop) : Promise.resolve();
}
destroy() {
super.destroy();
this.cancel({ silent: true });
}
get resetState() {
return __privateGet(this, _initialState);
}
reset() {
this.destroy();
this.setState(this.resetState);
}
isActive() {
return this.observers.some(
(observer) => (0, import_utils.resolveQueryBoolean)(observer.options.enabled, this) !== false
);
}
isDisabled() {
if (this.getObserversCount() > 0) {
return !this.isActive();
}
return this.options.queryFn === import_utils.skipToken || !this.isFetched();
}
isFetched() {
return this.state.dataUpdateCount + this.state.errorUpdateCount > 0;
}
isStatic() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => (0, import_utils.resolveStaleTime)(observer.options.staleTime, this) === "static"
);
}
return false;
}
isStale() {
if (this.getObserversCount() > 0) {
return this.observers.some(
(observer) => observer.getCurrentResult().isStale
);
}
return this.state.data === void 0 || this.state.isInvalidated;
}
isStaleByTime(staleTime = 0) {
if (this.state.data === void 0) {
return true;
}
if (staleTime === "static") {
return false;
}
if (this.state.isInvalidated) {
return true;
}
return !(0, import_utils.timeUntilStale)(this.state.dataUpdatedAt, staleTime);
}
onFocus() {
var _a;
const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus());
observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
(_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue();
}
onOnline() {
var _a;
const observer = this.observers.find((x) => x.shouldFetchOnReconnect());
observer == null ? void 0 : observer.refetch({ cancelRefetch: false });
(_a = __privateGet(this, _retryer)) == null ? void 0 : _a.continue();
}
addObserver(observer) {
if (!this.observers.includes(observer)) {
this.observers.push(observer);
this.clearGcTimeout();
__privateGet(this, _cache).notify({ type: "observerAdded", query: this, observer });
}
}
removeObserver(observer) {
if (this.observers.includes(observer)) {
this.observers = this.observers.filter((x) => x !== observer);
if (!this.observers.length) {
if (__privateGet(this, _retryer)) {
if (__privateGet(this, _abortSignalConsumed) || __privateMethod(this, _Query_instances, isInitialPausedFetch_fn).call(this)) {
__privateGet(this, _retryer).cancel({ revert: true });
} else {
__privateGet(this, _retryer).cancelRetry();
}
}
this.scheduleGc();
}
__privateGet(this, _cache).notify({ type: "observerRemoved", query: this, observer });
}
}
getObserversCount() {
return this.observers.length;
}
invalidate() {
if (!this.state.isInvalidated) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "invalidate" });
}
}
async fetch(options, fetchOptions) {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
if (this.state.fetchStatus !== "idle" && // If the promise in the retryer is already rejected, we have to definitely
// re-start the fetch; there is a chance that the query is still in a
// pending state when that happens
((_a = __privateGet(this, _retryer)) == null ? void 0 : _a.status()) !== "rejected") {
if (this.state.data !== void 0 && (fetchOptions == null ? void 0 : fetchOptions.cancelRefetch)) {
this.cancel({ silent: true });
} else if (__privateGet(this, _retryer)) {
__privateGet(this, _retryer).continueRetry();
return __privateGet(this, _retryer).promise;
}
}
if (options) {
this.setOptions(options);
}
if (!this.options.queryFn) {
const observer = this.observers.find((x) => x.options.queryFn);
if (observer) {
this.setOptions(observer.options);
}
}
if (process.env.NODE_ENV !== "production") {
if (!Array.isArray(this.options.queryKey)) {
console.error(
`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`
);
}
}
const abortController = new AbortController();
const addSignalProperty = (object) => {
Object.defineProperty(object, "signal", {
enumerable: true,
get: () => {
__privateSet(this, _abortSignalConsumed, true);
return abortController.signal;
}
});
};
const fetchFn = () => {
const queryFn = (0, import_utils.ensureQueryFn)(this.options, fetchOptions);
const createQueryFnContext = () => {
const queryFnContext2 = {
client: __privateGet(this, _client),
queryKey: this.queryKey,
meta: this.meta
};
addSignalProperty(queryFnContext2);
return queryFnContext2;
};
const queryFnContext = createQueryFnContext();
__privateSet(this, _abortSignalConsumed, false);
if (this.options.persister) {
return this.options.persister(
queryFn,
queryFnContext,
this
);
}
return queryFn(queryFnContext);
};
const createFetchContext = () => {
const context2 = {
fetchOptions,
options: this.options,
queryKey: this.queryKey,
client: __privateGet(this, _client),
state: this.state,
fetchFn
};
addSignalProperty(context2);
return context2;
};
const context = createFetchContext();
const behavior = __privateGet(this, _queryType) === "infinite" ? (0, import_infiniteQueryBehavior.infiniteQueryBehavior)(
this.options.pages
) : this.options.behavior;
behavior == null ? void 0 : behavior.onFetch(context, this);
__privateSet(this, _revertState, this.state);
if (this.state.fetchStatus === "idle" || this.state.fetchMeta !== ((_b = context.fetchOptions) == null ? void 0 : _b.meta)) {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "fetch", meta: (_c = context.fetchOptions) == null ? void 0 : _c.meta });
}
__privateSet(this, _retryer, (0, import_retryer.createRetryer)({
initialPromise: fetchOptions == null ? void 0 : fetchOptions.initialPromise,
fn: context.fetchFn,
onCancel: (error) => {
if (error instanceof import_retryer.CancelledError && error.revert) {
this.setState({
...__privateGet(this, _revertState),
fetchStatus: "idle"
});
}
abortController.abort();
},
onFail: (failureCount, error) => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "failed", failureCount, error });
},
onPause: () => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "pause" });
},
onContinue: () => {
__privateMethod(this, _Query_instances, dispatch_fn).call(this, { type: "continue" });
},
retry: context.options.retry,
retryDelay: context.options.retryDelay,
networkMode: context.options.networkMode,
canRun: () => true
}));
try {
const data = await __privateGet(this, _retryer).start();
if (data === void 0) {
if (process.env.NODE_ENV !== "production") {
console.error(
`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`
);
}
throw new Error(`${this.queryHash} data is undefined`);
}
this.setData(data);
(_e = (_d = __privateGet(this, _cache).config).onSuccess) == null ? void 0 : _e.call(_d, data, this);
(_g = (_f = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _g.call(
_f,
data,
this.state.error,
this
);
return data;
} catch (error) {
if (error instanceof import_retryer.CancelledError) {
if (error.silent) {
return __privateGet(this, _retryer).promise;
} else if (error.revert) {
if (this.state.data === void 0) {
throw error;
}
return this.state.data;
}
}
__privateMethod(this, _Query_instances, dispatch_fn).call(this, {
type: "error",
error
});
(_i = (_h = __privateGet(this, _cache).config).onError) == null ? void 0 : _i.call(
_h,
error,
this
);
(_k = (_j = __privateGet(this, _cache).config).onSettled) == null ? void 0 : _k.call(
_j,
this.state.data,
error,
this
);
throw error;
} finally {
this.scheduleGc();
}
}
};
_queryType = new WeakMap();
_initialState = new WeakMap();
_revertState = new WeakMap();
_cache = new WeakMap();
_client = new WeakMap();
_retryer = new WeakMap();
_defaultOptions = new WeakMap();
_abortSignalConsumed = new WeakMap();
_Query_instances = new WeakSet();
isInitialPausedFetch_fn = function() {
return this.state.fetchStatus === "paused" && this.state.status === "pending";
};
dispatch_fn = function(action) {
const reducer = (state) => {
switch (action.type) {
case "failed":
return {
...state,
fetchFailureCount: action.failureCount,
fetchFailureReason: action.error
};
case "pause":
return {
...state,
fetchStatus: "paused"
};
case "continue":
return {
...state,
fetchStatus: "fetching"
};
case "fetch":
return {
...state,
...fetchState(state.data, this.options),
fetchMeta: action.meta ?? null
};
case "success":
const newState = {
...state,
...successState(action.data, action.dataUpdatedAt),
dataUpdateCount: state.dataUpdateCount + 1,
...!action.manual && {
fetchStatus: "idle",
fetchFailureCount: 0,
fetchFailureReason: null
}
};
__privateSet(this, _revertState, action.manual ? newState : void 0);
return newState;
case "error":
const error = action.error;
return {
...state,
error,
errorUpdateCount: state.errorUpdateCount + 1,
errorUpdatedAt: Date.now(),
fetchFailureCount: state.fetchFailureCount + 1,
fetchFailureReason: error,
fetchStatus: "idle",
status: "error",
// flag existing data as invalidated if we get a background error
// note that "no data" always means stale so we can set unconditionally here
isInvalidated: true
};
case "invalidate":
return {
...state,
isInvalidated: true
};
case "setState":
return {
...state,
...action.state
};
}
};
this.state = reducer(this.state);
import_notifyManager.notifyManager.batch(() => {
this.observers.forEach((observer) => {
observer.onQueryUpdate();
});
__privateGet(this, _cache).notify({ query: this, type: "updated", action });
});
};
function fetchState(data, options) {
return {
fetchFailureCount: 0,
fetchFailureReason: null,
fetchStatus: (0, import_retryer.canFetch)(options.networkMode) ? "fetching" : "paused",
...data === void 0 && {
error: null,
status: "pending"
}
};
}
function successState(data, dataUpdatedAt) {
return {
data,
dataUpdatedAt: dataUpdatedAt ?? Date.now(),
error: null,
isInvalidated: false,
status: "success"
};
}
function getDefaultState(options) {
const data = typeof options.initialData === "function" ? options.initialData() : options.initialData;
const hasData = data !== void 0;
const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === "function" ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
return {
data,
dataUpdateCount: 0,
dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
error: null,
errorUpdateCount: 0,
errorUpdatedAt: 0,
fetchFailureCount: 0,
fetchFailureReason: null,
fetchMeta: null,
isInvalidated: false,
status: hasData ? "success" : "pending",
fetchStatus: "idle"
};
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Query,
fetchState
});
//# sourceMappingURL=query.cjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,9 @@
export { fetchState } from './_tsup-dts-rollup.cjs';
export { QueryState_alias_1 as QueryState } from './_tsup-dts-rollup.cjs';
export { FetchContext } from './_tsup-dts-rollup.cjs';
export { QueryBehavior } from './_tsup-dts-rollup.cjs';
export { FetchDirection } from './_tsup-dts-rollup.cjs';
export { FetchMeta } from './_tsup-dts-rollup.cjs';
export { FetchOptions } from './_tsup-dts-rollup.cjs';
export { Action_alias_1 as Action } from './_tsup-dts-rollup.cjs';
export { Query_alias_1 as Query } from './_tsup-dts-rollup.cjs';

View File

@@ -0,0 +1,9 @@
export { fetchState } from './_tsup-dts-rollup.js';
export { QueryState_alias_1 as QueryState } from './_tsup-dts-rollup.js';
export { FetchContext } from './_tsup-dts-rollup.js';
export { QueryBehavior } from './_tsup-dts-rollup.js';
export { FetchDirection } from './_tsup-dts-rollup.js';
export { FetchMeta } from './_tsup-dts-rollup.js';
export { FetchOptions } from './_tsup-dts-rollup.js';
export { Action_alias_1 as Action } from './_tsup-dts-rollup.js';
export { Query_alias_1 as Query } from './_tsup-dts-rollup.js';

Some files were not shown because too many files have changed in this diff Show More