UNPKG

@nullplatform/ingest

Version:

Client SDK for the nullplatform ingest API: push snapshots and delta events from a collector into the catalog and other targets, follow runs, replay and drift checks

7,391 lines • 249 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region \0rolldown/runtime.js
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
//#endregion
const require_types = require("./types-BKzpjXNm.cjs");
//#region src/enums.ts
/**
* The API's closed vocabularies, as runtime enums: write `Engine.JSONATA`,
* never `'jsonata'`. The values are what the wire carries.
*/
/** What a full run deletes when it finalizes: what it no longer saw, or nothing. */
let DeletePolicy = /* @__PURE__ */ function(DeletePolicy) {
	DeletePolicy["SOFT_DELETE_STALE"] = "soft_delete_stale";
	DeletePolicy["NONE"] = "none";
	return DeletePolicy;
}({});
/** Where a run is: open, finalizing, or closed (completed, its guard tripped, or aborted). */
let RunStatus = /* @__PURE__ */ function(RunStatus) {
	RunStatus["OPEN"] = "open";
	RunStatus["FINALIZING"] = "finalizing";
	RunStatus["COMPLETED"] = "completed";
	RunStatus["GUARD_TRIPPED"] = "guard_tripped";
	RunStatus["ABORTED"] = "aborted";
	return RunStatus;
}({});
/** Where an input is: waiting to be applied, or settled (applied, rejected, dropped, dead). */
let InputStatus = /* @__PURE__ */ function(InputStatus) {
	InputStatus["PENDING"] = "pending";
	InputStatus["APPLIED"] = "applied";
	InputStatus["REJECTED"] = "rejected";
	InputStatus["DROPPED"] = "dropped";
	InputStatus["DEAD"] = "dead";
	return InputStatus;
}({});
/** What became of an input, or of one entity it named. */
let Outcome = /* @__PURE__ */ function(Outcome) {
	Outcome["CREATED"] = "created";
	Outcome["UPDATED"] = "updated";
	Outcome["UNCHANGED"] = "unchanged";
	Outcome["FILTERED"] = "filtered";
	Outcome["DELETED"] = "deleted";
	Outcome["SKIPPED"] = "skipped";
	Outcome["STALE"] = "stale";
	Outcome["REJECTED"] = "rejected";
	Outcome["FAILED"] = "failed";
	/** A parent the source has not written yet (a target that assigns ids): tried again. */
	Outcome["WAITING"] = "waiting";
	return Outcome;
}({});
/** How a source came to own an entity: created by ingest, or adopted (already in the target). */
let EntityOrigin = /* @__PURE__ */ function(EntityOrigin) {
	EntityOrigin["CREATED"] = "created";
	EntityOrigin["ADOPTED"] = "adopted";
	return EntityOrigin;
}({});
/** What an event does to its entity: writes it (`UPSERT`, the default) or deletes it. */
let EventOp = /* @__PURE__ */ function(EventOp) {
	EventOp["UPSERT"] = "upsert";
	EventOp["DELETE"] = "delete";
	return EventOp;
}({});
/** The expression language of a mapping. */
let Engine = /* @__PURE__ */ function(Engine) {
	Engine["JSONATA"] = "jsonata";
	Engine["JQ"] = "jq";
	Engine["CEL"] = "cel";
	return Engine;
}({});
/** What a drift check does: reports what differs, or writes back what was last written. */
let DriftPolicy = /* @__PURE__ */ function(DriftPolicy) {
	DriftPolicy["REPORT"] = "report";
	DriftPolicy["RESTORE"] = "restore";
	return DriftPolicy;
}({});
/** Where a drift check is: queued, running, or done (completed, failed). */
let DriftCheckStatus = /* @__PURE__ */ function(DriftCheckStatus) {
	DriftCheckStatus["QUEUED"] = "queued";
	DriftCheckStatus["RUNNING"] = "running";
	DriftCheckStatus["COMPLETED"] = "completed";
	DriftCheckStatus["FAILED"] = "failed";
	return DriftCheckStatus;
}({});
/** How a drift check found an entity: changed in the target, or gone from it. */
let DriftType = /* @__PURE__ */ function(DriftType) {
	DriftType["CHANGED"] = "changed";
	DriftType["MISSING"] = "missing";
	return DriftType;
}({});
/** Where a replay is: queued, queueing its inputs a page at a time, or done (completed, failed). */
let ReplayStatus = /* @__PURE__ */ function(ReplayStatus) {
	ReplayStatus["QUEUED"] = "queued";
	ReplayStatus["RUNNING"] = "running";
	ReplayStatus["COMPLETED"] = "completed";
	ReplayStatus["FAILED"] = "failed";
	return ReplayStatus;
}({});
/** What a source type revision records. */
let SourceTypeRevisionAction = /* @__PURE__ */ function(SourceTypeRevisionAction) {
	SourceTypeRevisionAction["CREATE"] = "create";
	SourceTypeRevisionAction["UPDATE"] = "update";
	SourceTypeRevisionAction["DELETE"] = "delete";
	return SourceTypeRevisionAction;
}({});
/** What a source revision records. */
let SourceRevisionAction = /* @__PURE__ */ function(SourceRevisionAction) {
	SourceRevisionAction["CREATE"] = "create";
	SourceRevisionAction["UPDATE"] = "update";
	SourceRevisionAction["DELETE"] = "delete";
	return SourceRevisionAction;
}({});
/** What a mapping revision records. */
let MappingRevisionAction = /* @__PURE__ */ function(MappingRevisionAction) {
	MappingRevisionAction["CREATE"] = "create";
	MappingRevisionAction["UPDATE"] = "update";
	MappingRevisionAction["DELETE"] = "delete";
	return MappingRevisionAction;
}({});
/** What a destination revision records. */
let DestinationRevisionAction = /* @__PURE__ */ function(DestinationRevisionAction) {
	DestinationRevisionAction["CREATE"] = "create";
	DestinationRevisionAction["UPDATE"] = "update";
	DestinationRevisionAction["DELETE"] = "delete";
	return DestinationRevisionAction;
}({});
/**
* What happens to the entities a destination wrote when it stops applying to a
* source (deleted, disabled, or moved to another endpoint), in the words of a
* foreign key: `RESTRICT` refuses while it owns live ones, `CASCADE` leaves
* them to the next full run (deleted behind its guards), `SET_NULL` releases
* them (they stay in the target, no longer owned).
*/
let OnDelete = /* @__PURE__ */ function(OnDelete) {
	OnDelete["RESTRICT"] = "restrict";
	OnDelete["CASCADE"] = "cascade";
	OnDelete["SET_NULL"] = "set_null";
	return OnDelete;
}({});
/** What an upsert did with one spec (`sources.upsert`, `mappings.upsertForSource`…). */
let UpsertOutcome = /* @__PURE__ */ function(UpsertOutcome) {
	/** It was missing: created (a deleted one revived). */
	UpsertOutcome["CREATED"] = "created";
	/** It differed: what differs was written. */
	UpsertOutcome["UPDATED"] = "updated";
	/** It matched: nothing was sent. */
	UpsertOutcome["UNCHANGED"] = "unchanged";
	return UpsertOutcome;
}({});
/** What `runs.open` does when the source already has an open run. */
let OnConflict = /* @__PURE__ */ function(OnConflict) {
	/** Abort the open run (it deletes nothing) and open a new one. */
	OnConflict["ABORT"] = "abort";
	/** Throw the 409. */
	OnConflict["FAIL"] = "fail";
	return OnConflict;
}({});
/** Who assigns an entity's identity at an endpoint's backend (`identity.assignedBy`). */
let AssignedBy = /* @__PURE__ */ function(AssignedBy) {
	/** The source: the writer's key addresses the entity, and a write is an upsert by key. */
	AssignedBy["SOURCE"] = "source";
	/** The backend, at create: an entity is found again by its natural key. */
	AssignedBy["BACKEND"] = "backend";
	return AssignedBy;
}({});
/** How a list call of an endpoint's backend pages (`calls.paging`). */
let PagingStyle = /* @__PURE__ */ function(PagingStyle) {
	PagingStyle["OFFSET"] = "offset";
	PagingStyle["PAGE"] = "page";
	PagingStyle["CURSOR"] = "cursor";
	PagingStyle["LINK"] = "link";
	return PagingStyle;
}({});
/** The HTTP method of an endpoint's call (`EndpointCall.method`). */
let HttpMethod = /* @__PURE__ */ function(HttpMethod) {
	HttpMethod["GET"] = "GET";
	HttpMethod["POST"] = "POST";
	HttpMethod["PATCH"] = "PATCH";
	HttpMethod["PUT"] = "PUT";
	HttpMethod["DELETE"] = "DELETE";
	return HttpMethod;
}({});
/** An endpoint's calls by name (`calls.<name>`, an error rule's `operation`). */
let OperationName = /* @__PURE__ */ function(OperationName) {
	OperationName["UPSERT"] = "upsert";
	OperationName["CREATE"] = "create";
	OperationName["UPDATE"] = "update";
	OperationName["READ"] = "read";
	OperationName["DELETE"] = "delete";
	OperationName["FIND"] = "find";
	OperationName["LINK"] = "link";
	OperationName["UNLINK"] = "unlink";
	return OperationName;
}({});
/** What a call sends when its body names a shape (`EndpointCall.body`) rather than a template or an expression. */
let OperationBody = /* @__PURE__ */ function(OperationBody) {
	/** The entity's document. */
	OperationBody["DOCUMENT"] = "document";
	/** A link set as objects (`[{ id }]`). */
	OperationBody["LINK_OBJECTS"] = "link_objects";
	/** A link set as ids. */
	OperationBody["LINK_IDS"] = "link_ids";
	return OperationBody;
}({});
/** What an emptied link set becomes (`calls.link.emptySet`). */
let EmptyLinkSet = /* @__PURE__ */ function(EmptyLinkSet) {
	/** The empty set is sent. */
	EmptyLinkSet["REPLACE"] = "replace";
	/** Each link is removed by an `unlink` call (a backend that refuses an empty set). */
	EmptyLinkSet["UNLINK_EACH"] = "unlink_each";
	return EmptyLinkSet;
}({});
/** What may be written to a field (`fields[f].write`). */
let FieldRule = /* @__PURE__ */ function(FieldRule) {
	/** Sent on create only. */
	FieldRule["CREATE_ONLY"] = "create_only";
	/** Never changes once created: a change is refused. */
	FieldRule["IMMUTABLE"] = "immutable";
	/** Sent on update only. */
	FieldRule["UPDATE_ONLY"] = "update_only";
	return FieldRule;
}({});
/** How a drift check compares a field (`fields[f].drift`). */
let FieldComparison = /* @__PURE__ */ function(FieldComparison) {
	FieldComparison["EQUAL"] = "equal";
	/** What was written is contained in what the backend holds. */
	FieldComparison["SUBSET"] = "subset";
	FieldComparison["IGNORE"] = "ignore";
	return FieldComparison;
}({});
/** Whether ingest may delete at an endpoint (`behavior.delete`). */
let TargetDeletePolicy = /* @__PURE__ */ function(TargetDeletePolicy) {
	TargetDeletePolicy["ALLOWED"] = "allowed";
	/** Finalize and delete events never delete there. */
	TargetDeletePolicy["FORBIDDEN"] = "forbidden";
	return TargetDeletePolicy;
}({});
/** What a field removed from a document becomes (`behavior.clear`). */
let ClearSemantics = /* @__PURE__ */ function(ClearSemantics) {
	/** It is written as `null`. */
	ClearSemantics["WRITE_NULL"] = "write_null";
	/** The backend cannot clear it: a removal is refused. */
	ClearSemantics["UNSUPPORTED"] = "unsupported";
	return ClearSemantics;
}({});
/** What ingest does with an entity it finds already in the backend (`behavior.adopt`). */
let AdoptPolicy = /* @__PURE__ */ function(AdoptPolicy) {
	/** Leaves it alone. */
	AdoptPolicy["NONE"] = "none";
	/** Updates it. */
	AdoptPolicy["UPDATE"] = "update";
	/** Updates it and deletes it when the source stops reporting it. */
	AdoptPolicy["MANAGE"] = "manage";
	return AdoptPolicy;
}({});
/** What a backend's refusal means (`errors[].outcome`). */
let TargetErrorOutcome = /* @__PURE__ */ function(TargetErrorOutcome) {
	TargetErrorOutcome["RETRY"] = "retry";
	TargetErrorOutcome["REJECT"] = "reject";
	/** The entity is already there. */
	TargetErrorOutcome["EXISTS"] = "exists";
	/** The entity is gone. */
	TargetErrorOutcome["GONE"] = "gone";
	/** Not ready yet: tried again later without spending attempts. */
	TargetErrorOutcome["WAIT"] = "wait";
	return TargetErrorOutcome;
}({});
//#endregion
//#region node_modules/lodash.camelcase/index.js
var require_lodash_camelcase = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** `Object#toString` result references. */
	var symbolTag = "[object Symbol]";
	/** Used to match words composed of alphanumeric characters. */
	var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
	/** Used to match Latin Unicode letters (excluding mathematical operators). */
	var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
	/** Used to compose unicode character classes. */
	var rsAstralRange = "\\ud800-\\udfff";
	var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
	var rsComboSymbolsRange = "\\u20d0-\\u20f0";
	var rsDingbatRange = "\\u2700-\\u27bf";
	var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff";
	var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7";
	var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf";
	var rsPunctuationRange = "\\u2000-\\u206f";
	var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000";
	var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde";
	var rsVarRange = "\\ufe0e\\ufe0f";
	var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
	/** Used to compose unicode capture groups. */
	var rsApos = "['’]";
	var rsAstral = "[" + rsAstralRange + "]";
	var rsBreak = "[" + rsBreakRange + "]";
	var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
	var rsDigits = "\\d+";
	var rsDingbat = "[" + rsDingbatRange + "]";
	var rsLower = "[" + rsLowerRange + "]";
	var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]";
	var rsFitz = "\\ud83c[\\udffb-\\udfff]";
	var rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")";
	var rsNonAstral = "[^" + rsAstralRange + "]";
	var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
	var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
	var rsUpper = "[" + rsUpperRange + "]";
	var rsZWJ = "\\u200d";
	/** Used to compose unicode regexes. */
	var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")";
	var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")";
	var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?";
	var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?";
	var reOptMod = rsModifier + "?";
	var rsOptVar = "[" + rsVarRange + "]?";
	var rsOptJoin = "(?:" + rsZWJ + "(?:" + [
		rsNonAstral,
		rsRegional,
		rsSurrPair
	].join("|") + ")" + rsOptVar + reOptMod + ")*";
	var rsSeq = rsOptVar + reOptMod + rsOptJoin;
	var rsEmoji = "(?:" + [
		rsDingbat,
		rsRegional,
		rsSurrPair
	].join("|") + ")" + rsSeq;
	var rsSymbol = "(?:" + [
		rsNonAstral + rsCombo + "?",
		rsCombo,
		rsRegional,
		rsSurrPair,
		rsAstral
	].join("|") + ")";
	/** Used to match apostrophes. */
	var reApos = RegExp(rsApos, "g");
	/**
	* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
	* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
	*/
	var reComboMark = RegExp(rsCombo, "g");
	/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
	var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
	/** Used to match complex or compound words. */
	var reUnicodeWord = RegExp([
		rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [
			rsBreak,
			rsUpper,
			"$"
		].join("|") + ")",
		rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [
			rsBreak,
			rsUpper + rsLowerMisc,
			"$"
		].join("|") + ")",
		rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr,
		rsUpper + "+" + rsOptUpperContr,
		rsDigits,
		rsEmoji
	].join("|"), "g");
	/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
	var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + "]");
	/** Used to detect strings that need a more robust regexp to match words. */
	var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
	/** Used to map Latin Unicode letters to basic Latin letters. */
	var deburredLetters = {
		"À": "A",
		"Á": "A",
		"Â": "A",
		"Ã": "A",
		"Ä": "A",
		"Å": "A",
		"à": "a",
		"á": "a",
		"â": "a",
		"ã": "a",
		"ä": "a",
		"å": "a",
		"Ç": "C",
		"ç": "c",
		"Ð": "D",
		"ð": "d",
		"È": "E",
		"É": "E",
		"Ê": "E",
		"Ë": "E",
		"è": "e",
		"é": "e",
		"ê": "e",
		"ë": "e",
		"Ì": "I",
		"Í": "I",
		"Î": "I",
		"Ï": "I",
		"ì": "i",
		"í": "i",
		"î": "i",
		"ï": "i",
		"Ñ": "N",
		"ñ": "n",
		"Ò": "O",
		"Ó": "O",
		"Ô": "O",
		"Õ": "O",
		"Ö": "O",
		"Ø": "O",
		"ò": "o",
		"ó": "o",
		"ô": "o",
		"õ": "o",
		"ö": "o",
		"ø": "o",
		"Ù": "U",
		"Ú": "U",
		"Û": "U",
		"Ü": "U",
		"ù": "u",
		"ú": "u",
		"û": "u",
		"ü": "u",
		"Ý": "Y",
		"ý": "y",
		"ÿ": "y",
		"Æ": "Ae",
		"æ": "ae",
		"Þ": "Th",
		"þ": "th",
		"ß": "ss",
		"Ā": "A",
		"Ă": "A",
		"Ą": "A",
		"ā": "a",
		"ă": "a",
		"ą": "a",
		"Ć": "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",
		"Ĥ": "H",
		"Ħ": "H",
		"ĥ": "h",
		"ħ": "h",
		"Ĩ": "I",
		"Ī": "I",
		"Ĭ": "I",
		"Į": "I",
		"İ": "I",
		"ĩ": "i",
		"ī": "i",
		"ĭ": "i",
		"į": "i",
		"ı": "i",
		"Ĵ": "J",
		"ĵ": "j",
		"Ķ": "K",
		"ķ": "k",
		"ĸ": "k",
		"Ĺ": "L",
		"Ļ": "L",
		"Ľ": "L",
		"Ŀ": "L",
		"Ł": "L",
		"ĺ": "l",
		"ļ": "l",
		"ľ": "l",
		"ŀ": "l",
		"ł": "l",
		"Ń": "N",
		"Ņ": "N",
		"Ň": "N",
		"Ŋ": "N",
		"ń": "n",
		"ņ": "n",
		"ň": "n",
		"ŋ": "n",
		"Ō": "O",
		"Ŏ": "O",
		"Ő": "O",
		"ō": "o",
		"ŏ": "o",
		"ő": "o",
		"Ŕ": "R",
		"Ŗ": "R",
		"Ř": "R",
		"ŕ": "r",
		"ŗ": "r",
		"ř": "r",
		"Ś": "S",
		"Ŝ": "S",
		"Ş": "S",
		"Š": "S",
		"ś": "s",
		"ŝ": "s",
		"ş": "s",
		"š": "s",
		"Ţ": "T",
		"Ť": "T",
		"Ŧ": "T",
		"ţ": "t",
		"ť": "t",
		"ŧ": "t",
		"Ũ": "U",
		"Ū": "U",
		"Ŭ": "U",
		"Ů": "U",
		"Ű": "U",
		"Ų": "U",
		"ũ": "u",
		"ū": "u",
		"ŭ": "u",
		"ů": "u",
		"ű": "u",
		"ų": "u",
		"Ŵ": "W",
		"ŵ": "w",
		"Ŷ": "Y",
		"ŷ": "y",
		"Ÿ": "Y",
		"Ź": "Z",
		"Ż": "Z",
		"Ž": "Z",
		"ź": "z",
		"ż": "z",
		"ž": "z",
		"IJ": "IJ",
		"ij": "ij",
		"Œ": "Oe",
		"œ": "oe",
		"ʼn": "'n",
		"ſ": "ss"
	};
	/** Detect free variable `global` from Node.js. */
	var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
	/** Detect free variable `self`. */
	var freeSelf = typeof self == "object" && self && self.Object === Object && self;
	/** Used as a reference to the global object. */
	var root = freeGlobal || freeSelf || Function("return this")();
	/**
	* A specialized version of `_.reduce` for arrays without support for
	* iteratee shorthands.
	*
	* @private
	* @param {Array} [array] The array to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @param {*} [accumulator] The initial value.
	* @param {boolean} [initAccum] Specify using the first element of `array` as
	*  the initial value.
	* @returns {*} Returns the accumulated value.
	*/
	function arrayReduce(array, iteratee, accumulator, initAccum) {
		var index = -1, length = array ? array.length : 0;
		if (initAccum && length) accumulator = array[++index];
		while (++index < length) accumulator = iteratee(accumulator, array[index], index, array);
		return accumulator;
	}
	/**
	* Converts an ASCII `string` to an array.
	*
	* @private
	* @param {string} string The string to convert.
	* @returns {Array} Returns the converted array.
	*/
	function asciiToArray(string) {
		return string.split("");
	}
	/**
	* Splits an ASCII `string` into an array of its words.
	*
	* @private
	* @param {string} The string to inspect.
	* @returns {Array} Returns the words of `string`.
	*/
	function asciiWords(string) {
		return string.match(reAsciiWord) || [];
	}
	/**
	* The base implementation of `_.propertyOf` without support for deep paths.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Function} Returns the new accessor function.
	*/
	function basePropertyOf(object) {
		return function(key) {
			return object == null ? void 0 : object[key];
		};
	}
	/**
	* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
	* letters to basic Latin letters.
	*
	* @private
	* @param {string} letter The matched letter to deburr.
	* @returns {string} Returns the deburred letter.
	*/
	var deburrLetter = basePropertyOf(deburredLetters);
	/**
	* Checks if `string` contains Unicode symbols.
	*
	* @private
	* @param {string} string The string to inspect.
	* @returns {boolean} Returns `true` if a symbol is found, else `false`.
	*/
	function hasUnicode(string) {
		return reHasUnicode.test(string);
	}
	/**
	* Checks if `string` contains a word composed of Unicode symbols.
	*
	* @private
	* @param {string} string The string to inspect.
	* @returns {boolean} Returns `true` if a word is found, else `false`.
	*/
	function hasUnicodeWord(string) {
		return reHasUnicodeWord.test(string);
	}
	/**
	* Converts `string` to an array.
	*
	* @private
	* @param {string} string The string to convert.
	* @returns {Array} Returns the converted array.
	*/
	function stringToArray(string) {
		return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string);
	}
	/**
	* Converts a Unicode `string` to an array.
	*
	* @private
	* @param {string} string The string to convert.
	* @returns {Array} Returns the converted array.
	*/
	function unicodeToArray(string) {
		return string.match(reUnicode) || [];
	}
	/**
	* Splits a Unicode `string` into an array of its words.
	*
	* @private
	* @param {string} The string to inspect.
	* @returns {Array} Returns the words of `string`.
	*/
	function unicodeWords(string) {
		return string.match(reUnicodeWord) || [];
	}
	/**
	* Used to resolve the
	* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	* of values.
	*/
	var objectToString = Object.prototype.toString;
	/** Built-in value references. */
	var Symbol = root.Symbol;
	/** Used to convert symbols to primitives and strings. */
	var symbolProto = Symbol ? Symbol.prototype : void 0;
	var symbolToString = symbolProto ? symbolProto.toString : void 0;
	/**
	* The base implementation of `_.slice` without an iteratee call guard.
	*
	* @private
	* @param {Array} array The array to slice.
	* @param {number} [start=0] The start position.
	* @param {number} [end=array.length] The end position.
	* @returns {Array} Returns the slice of `array`.
	*/
	function baseSlice(array, start, end) {
		var index = -1, length = array.length;
		if (start < 0) start = -start > length ? 0 : length + start;
		end = end > length ? length : end;
		if (end < 0) end += length;
		length = start > end ? 0 : end - start >>> 0;
		start >>>= 0;
		var result = Array(length);
		while (++index < length) result[index] = array[index + start];
		return result;
	}
	/**
	* The base implementation of `_.toString` which doesn't convert nullish
	* values to empty strings.
	*
	* @private
	* @param {*} value The value to process.
	* @returns {string} Returns the string.
	*/
	function baseToString(value) {
		if (typeof value == "string") return value;
		if (isSymbol(value)) return symbolToString ? symbolToString.call(value) : "";
		var result = value + "";
		return result == "0" && 1 / value == -Infinity ? "-0" : result;
	}
	/**
	* Casts `array` to a slice if it's needed.
	*
	* @private
	* @param {Array} array The array to inspect.
	* @param {number} start The start position.
	* @param {number} [end=array.length] The end position.
	* @returns {Array} Returns the cast slice.
	*/
	function castSlice(array, start, end) {
		var length = array.length;
		end = end === void 0 ? length : end;
		return !start && end >= length ? array : baseSlice(array, start, end);
	}
	/**
	* Creates a function like `_.lowerFirst`.
	*
	* @private
	* @param {string} methodName The name of the `String` case method to use.
	* @returns {Function} Returns the new case function.
	*/
	function createCaseFirst(methodName) {
		return function(string) {
			string = toString(string);
			var strSymbols = hasUnicode(string) ? stringToArray(string) : void 0;
			var chr = strSymbols ? strSymbols[0] : string.charAt(0);
			var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1);
			return chr[methodName]() + trailing;
		};
	}
	/**
	* Creates a function like `_.camelCase`.
	*
	* @private
	* @param {Function} callback The function to combine each word.
	* @returns {Function} Returns the new compounder function.
	*/
	function createCompounder(callback) {
		return function(string) {
			return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "");
		};
	}
	/**
	* Checks if `value` is object-like. A value is object-like if it's not `null`
	* and has a `typeof` result of "object".
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
	* @example
	*
	* _.isObjectLike({});
	* // => true
	*
	* _.isObjectLike([1, 2, 3]);
	* // => true
	*
	* _.isObjectLike(_.noop);
	* // => false
	*
	* _.isObjectLike(null);
	* // => false
	*/
	function isObjectLike(value) {
		return !!value && typeof value == "object";
	}
	/**
	* Checks if `value` is classified as a `Symbol` primitive or object.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
	* @example
	*
	* _.isSymbol(Symbol.iterator);
	* // => true
	*
	* _.isSymbol('abc');
	* // => false
	*/
	function isSymbol(value) {
		return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
	}
	/**
	* Converts `value` to a string. An empty string is returned for `null`
	* and `undefined` values. The sign of `-0` is preserved.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to process.
	* @returns {string} Returns the string.
	* @example
	*
	* _.toString(null);
	* // => ''
	*
	* _.toString(-0);
	* // => '-0'
	*
	* _.toString([1, 2, 3]);
	* // => '1,2,3'
	*/
	function toString(value) {
		return value == null ? "" : baseToString(value);
	}
	/**
	* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category String
	* @param {string} [string=''] The string to convert.
	* @returns {string} Returns the camel cased string.
	* @example
	*
	* _.camelCase('Foo Bar');
	* // => 'fooBar'
	*
	* _.camelCase('--foo-bar--');
	* // => 'fooBar'
	*
	* _.camelCase('__FOO_BAR__');
	* // => 'fooBar'
	*/
	var camelCase = createCompounder(function(result, word, index) {
		word = word.toLowerCase();
		return result + (index ? capitalize(word) : word);
	});
	/**
	* Converts the first character of `string` to upper case and the remaining
	* to lower case.
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category String
	* @param {string} [string=''] The string to capitalize.
	* @returns {string} Returns the capitalized string.
	* @example
	*
	* _.capitalize('FRED');
	* // => 'Fred'
	*/
	function capitalize(string) {
		return upperFirst(toString(string).toLowerCase());
	}
	/**
	* Deburrs `string` by converting
	* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
	* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
	* letters to basic Latin letters and removing
	* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category String
	* @param {string} [string=''] The string to deburr.
	* @returns {string} Returns the deburred string.
	* @example
	*
	* _.deburr('déjà vu');
	* // => 'deja vu'
	*/
	function deburr(string) {
		string = toString(string);
		return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
	}
	/**
	* Converts the first character of `string` to upper case.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category String
	* @param {string} [string=''] The string to convert.
	* @returns {string} Returns the converted string.
	* @example
	*
	* _.upperFirst('fred');
	* // => 'Fred'
	*
	* _.upperFirst('FRED');
	* // => 'FRED'
	*/
	var upperFirst = createCaseFirst("toUpperCase");
	/**
	* Splits `string` into an array of its words.
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category String
	* @param {string} [string=''] The string to inspect.
	* @param {RegExp|string} [pattern] The pattern to match words.
	* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
	* @returns {Array} Returns the words of `string`.
	* @example
	*
	* _.words('fred, barney, & pebbles');
	* // => ['fred', 'barney', 'pebbles']
	*
	* _.words('fred, barney, & pebbles', /[^, ]+/g);
	* // => ['fred', 'barney', '&', 'pebbles']
	*/
	function words(string, pattern, guard) {
		string = toString(string);
		pattern = guard ? void 0 : pattern;
		if (pattern === void 0) return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
		return string.match(pattern) || [];
	}
	module.exports = camelCase;
}));
//#endregion
//#region node_modules/lodash.snakecase/index.js
var require_lodash_snakecase = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** `Object#toString` result references. */
	var symbolTag = "[object Symbol]";
	/** Used to match words composed of alphanumeric characters. */
	var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
	/** Used to match Latin Unicode letters (excluding mathematical operators). */
	var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
	/** Used to compose unicode character classes. */
	var rsAstralRange = "\\ud800-\\udfff";
	var rsComboMarksRange = "\\u0300-\\u036f\\ufe20-\\ufe23";
	var rsComboSymbolsRange = "\\u20d0-\\u20f0";
	var rsDingbatRange = "\\u2700-\\u27bf";
	var rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff";
	var rsMathOpRange = "\\xac\\xb1\\xd7\\xf7";
	var rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf";
	var rsPunctuationRange = "\\u2000-\\u206f";
	var rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000";
	var rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde";
	var rsVarRange = "\\ufe0e\\ufe0f";
	var rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
	/** Used to compose unicode capture groups. */
	var rsApos = "['’]";
	var rsBreak = "[" + rsBreakRange + "]";
	var rsCombo = "[" + rsComboMarksRange + rsComboSymbolsRange + "]";
	var rsDigits = "\\d+";
	var rsDingbat = "[" + rsDingbatRange + "]";
	var rsLower = "[" + rsLowerRange + "]";
	var rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]";
	var rsModifier = "(?:" + rsCombo + "|\\ud83c[\\udffb-\\udfff])";
	var rsNonAstral = "[^" + rsAstralRange + "]";
	var rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}";
	var rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]";
	var rsUpper = "[" + rsUpperRange + "]";
	var rsZWJ = "\\u200d";
	/** Used to compose unicode regexes. */
	var rsLowerMisc = "(?:" + rsLower + "|" + rsMisc + ")";
	var rsUpperMisc = "(?:" + rsUpper + "|" + rsMisc + ")";
	var rsOptLowerContr = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?";
	var rsOptUpperContr = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?";
	var reOptMod = rsModifier + "?";
	var rsOptVar = "[" + rsVarRange + "]?";
	var rsOptJoin = "(?:" + rsZWJ + "(?:" + [
		rsNonAstral,
		rsRegional,
		rsSurrPair
	].join("|") + ")" + rsOptVar + reOptMod + ")*";
	var rsSeq = rsOptVar + reOptMod + rsOptJoin;
	var rsEmoji = "(?:" + [
		rsDingbat,
		rsRegional,
		rsSurrPair
	].join("|") + ")" + rsSeq;
	/** Used to match apostrophes. */
	var reApos = RegExp(rsApos, "g");
	/**
	* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
	* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
	*/
	var reComboMark = RegExp(rsCombo, "g");
	/** Used to match complex or compound words. */
	var reUnicodeWord = RegExp([
		rsUpper + "?" + rsLower + "+" + rsOptLowerContr + "(?=" + [
			rsBreak,
			rsUpper,
			"$"
		].join("|") + ")",
		rsUpperMisc + "+" + rsOptUpperContr + "(?=" + [
			rsBreak,
			rsUpper + rsLowerMisc,
			"$"
		].join("|") + ")",
		rsUpper + "?" + rsLowerMisc + "+" + rsOptLowerContr,
		rsUpper + "+" + rsOptUpperContr,
		rsDigits,
		rsEmoji
	].join("|"), "g");
	/** Used to detect strings that need a more robust regexp to match words. */
	var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
	/** Used to map Latin Unicode letters to basic Latin letters. */
	var deburredLetters = {
		"À": "A",
		"Á": "A",
		"Â": "A",
		"Ã": "A",
		"Ä": "A",
		"Å": "A",
		"à": "a",
		"á": "a",
		"â": "a",
		"ã": "a",
		"ä": "a",
		"å": "a",
		"Ç": "C",
		"ç": "c",
		"Ð": "D",
		"ð": "d",
		"È": "E",
		"É": "E",
		"Ê": "E",
		"Ë": "E",
		"è": "e",
		"é": "e",
		"ê": "e",
		"ë": "e",
		"Ì": "I",
		"Í": "I",
		"Î": "I",
		"Ï": "I",
		"ì": "i",
		"í": "i",
		"î": "i",
		"ï": "i",
		"Ñ": "N",
		"ñ": "n",
		"Ò": "O",
		"Ó": "O",
		"Ô": "O",
		"Õ": "O",
		"Ö": "O",
		"Ø": "O",
		"ò": "o",
		"ó": "o",
		"ô": "o",
		"õ": "o",
		"ö": "o",
		"ø": "o",
		"Ù": "U",
		"Ú": "U",
		"Û": "U",
		"Ü": "U",
		"ù": "u",
		"ú": "u",
		"û": "u",
		"ü": "u",
		"Ý": "Y",
		"ý": "y",
		"ÿ": "y",
		"Æ": "Ae",
		"æ": "ae",
		"Þ": "Th",
		"þ": "th",
		"ß": "ss",
		"Ā": "A",
		"Ă": "A",
		"Ą": "A",
		"ā": "a",
		"ă": "a",
		"ą": "a",
		"Ć": "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",
		"Ĥ": "H",
		"Ħ": "H",
		"ĥ": "h",
		"ħ": "h",
		"Ĩ": "I",
		"Ī": "I",
		"Ĭ": "I",
		"Į": "I",
		"İ": "I",
		"ĩ": "i",
		"ī": "i",
		"ĭ": "i",
		"į": "i",
		"ı": "i",
		"Ĵ": "J",
		"ĵ": "j",
		"Ķ": "K",
		"ķ": "k",
		"ĸ": "k",
		"Ĺ": "L",
		"Ļ": "L",
		"Ľ": "L",
		"Ŀ": "L",
		"Ł": "L",
		"ĺ": "l",
		"ļ": "l",
		"ľ": "l",
		"ŀ": "l",
		"ł": "l",
		"Ń": "N",
		"Ņ": "N",
		"Ň": "N",
		"Ŋ": "N",
		"ń": "n",
		"ņ": "n",
		"ň": "n",
		"ŋ": "n",
		"Ō": "O",
		"Ŏ": "O",
		"Ő": "O",
		"ō": "o",
		"ŏ": "o",
		"ő": "o",
		"Ŕ": "R",
		"Ŗ": "R",
		"Ř": "R",
		"ŕ": "r",
		"ŗ": "r",
		"ř": "r",
		"Ś": "S",
		"Ŝ": "S",
		"Ş": "S",
		"Š": "S",
		"ś": "s",
		"ŝ": "s",
		"ş": "s",
		"š": "s",
		"Ţ": "T",
		"Ť": "T",
		"Ŧ": "T",
		"ţ": "t",
		"ť": "t",
		"ŧ": "t",
		"Ũ": "U",
		"Ū": "U",
		"Ŭ": "U",
		"Ů": "U",
		"Ű": "U",
		"Ų": "U",
		"ũ": "u",
		"ū": "u",
		"ŭ": "u",
		"ů": "u",
		"ű": "u",
		"ų": "u",
		"Ŵ": "W",
		"ŵ": "w",
		"Ŷ": "Y",
		"ŷ": "y",
		"Ÿ": "Y",
		"Ź": "Z",
		"Ż": "Z",
		"Ž": "Z",
		"ź": "z",
		"ż": "z",
		"ž": "z",
		"IJ": "IJ",
		"ij": "ij",
		"Œ": "Oe",
		"œ": "oe",
		"ʼn": "'n",
		"ſ": "ss"
	};
	/** Detect free variable `global` from Node.js. */
	var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
	/** Detect free variable `self`. */
	var freeSelf = typeof self == "object" && self && self.Object === Object && self;
	/** Used as a reference to the global object. */
	var root = freeGlobal || freeSelf || Function("return this")();
	/**
	* A specialized version of `_.reduce` for arrays without support for
	* iteratee shorthands.
	*
	* @private
	* @param {Array} [array] The array to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @param {*} [accumulator] The initial value.
	* @param {boolean} [initAccum] Specify using the first element of `array` as
	*  the initial value.
	* @returns {*} Returns the accumulated value.
	*/
	function arrayReduce(array, iteratee, accumulator, initAccum) {
		var index = -1, length = array ? array.length : 0;
		if (initAccum && length) accumulator = array[++index];
		while (++index < length) accumulator = iteratee(accumulator, array[index], index, array);
		return accumulator;
	}
	/**
	* Splits an ASCII `string` into an array of its words.
	*
	* @private
	* @param {string} The string to inspect.
	* @returns {Array} Returns the words of `string`.
	*/
	function asciiWords(string) {
		return string.match(reAsciiWord) || [];
	}
	/**
	* The base implementation of `_.propertyOf` without support for deep paths.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Function} Returns the new accessor function.
	*/
	function basePropertyOf(object) {
		return function(key) {
			return object == null ? void 0 : object[key];
		};
	}
	/**
	* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
	* letters to basic Latin letters.
	*
	* @private
	* @param {string} letter The matched letter to deburr.
	* @returns {string} Returns the deburred letter.
	*/
	var deburrLetter = basePropertyOf(deburredLetters);
	/**
	* Checks if `string` contains a word composed of Unicode symbols.
	*
	* @private
	* @param {string} string The string to inspect.
	* @returns {boolean} Returns `true` if a word is found, else `false`.
	*/
	function hasUnicodeWord(string) {
		return reHasUnicodeWord.test(string);
	}
	/**
	* Splits a Unicode `string` into an array of its words.
	*
	* @private
	* @param {string} The string to inspect.
	* @returns {Array} Returns the words of `string`.
	*/
	function unicodeWords(string) {
		return string.match(reUnicodeWord) || [];
	}
	/**
	* Used to resolve the
	* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	* of values.
	*/
	var objectToString = Object.prototype.toString;
	/** Built-in value references. */
	var Symbol = root.Symbol;
	/** Used to convert symbols to primitives and strings. */
	var symbolProto = Symbol ? Symbol.prototype : void 0;
	var symbolToString = symbolProto ? symbolProto.toString : void 0;
	/**
	* The base implementation of `_.toString` which doesn't convert nullish
	* values to empty strings.
	*
	* @private
	* @param {*} value The value to process.
	* @returns {string} Returns the string.
	*/
	function baseToString(value) {
		if (typeof value == "string") return value;
		if (isSymbol(value)) return symbolToString ? symbolToString.call(value) : "";
		var result = value + "";
		return result == "0" && 1 / value == -Infinity ? "-0" : result;
	}
	/**
	* Creates a function like `_.camelCase`.
	*
	* @private
	* @param {Function} callback The function to combine each word.
	* @returns {Function} Returns the new compounder function.
	*/
	function createCompounder(callback) {
		return function(string) {
			return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "");
		};
	}
	/**
	* Checks if `value` is object-like. A value is object-like if it's not `null`
	* and has a `typeof` result of "object".
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
	* @example
	*
	* _.isObjectLike({});
	* // => true
	*
	* _.isObjectLike([1, 2, 3]);
	* // => true
	*
	* _.isObjectLike(_.noop);
	* // => false
	*
	* _.isObjectLike(null);
	* // => false
	*/
	function isObjectLike(value) {
		return !!value && typeof value == "object";
	}
	/**
	* Checks if `value` is classified as a `Symbol` primitive or object.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
	* @example
	*
	* _.isSymbol(Symbol.iterator);
	* // => true
	*
	* _.isSymbol('abc');
	* // => false
	*/
	function isSymbol(value) {
		return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
	}
	/**
	* Converts `value` to a string. An empty string is returned for `null`
	* and `undefined` values. The sign of `-0` is preserved.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to process.
	* @returns {string} Returns the string.
	* @example
	*
	* _.toString(null);
	* // => ''
	*
	* _.toString(-0);
	* // => '-0'
	*
	* _.toString([1, 2, 3]);
	* // => '1,2,3'
	*/
	function toString(value) {
		return value == null ? "" : baseToString(value);
	}
	/**
	* Deburrs `string` by converting
	* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
	* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
	* letters to basic Latin letters and removing
	* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category String
	* @param {string} [string=''] The string to deburr.
	* @returns {string} Returns the deburred string.
	* @example
	*
	* _.deburr('déjà vu');
	* // => 'deja vu'
	*/
	function deburr(string) {
		string = toString(string);
		return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
	}
	/**
	* Converts `string` to
	* [snake case](https://en.wikipedia.org/wiki/Snake_case).
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category String
	* @param {string} [string=''] The string to convert.
	* @returns {string} Returns the snake cased string.
	* @example
	*
	* _.snakeCase('Foo Bar');
	* // => 'foo_bar'
	*
	* _.snakeCase('fooBar');
	* // => 'foo_bar'
	*
	* _.snakeCase('--FOO-BAR--');
	* // => 'foo_bar'
	*/
	var snakeCase = createCompounder(function(result, word, index) {
		return result + (index ? "_" : "") + word.toLowerCase();
	});
	/**
	* Splits `string` into an array of its words.
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category String
	* @param {string} [string=''] The string to inspect.
	* @param {RegExp|string} [pattern] The pattern to match words.
	* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
	* @returns {Array} Returns the words of `string`.
	* @example
	*
	* _.words('fred, barney, & pebbles');
	* // => ['fred', 'barney', 'pebbles']
	*
	* _.words('fred, barney, & pebbles', /[^, ]+/g);
	* // => ['fred', 'barney', '&', 'pebbles']
	*/
	function words(string, pattern, guard) {
		string = toString(string);
		pattern = guard ? void 0 : pattern;
		if (pattern === void 0) return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
		return string.match(pattern) || [];
	}
	module.exports = snakeCase;
}));
//#endregion
//#region node_modules/lodash.transform/index.js
var require_lodash_transform = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** Used as the `TypeError` message for "Functions" methods. */
	var FUNC_ERROR_TEXT = "Expected a function";
	/** Used to stand-in for `undefined` hash values. */
	var HASH_UNDEFINED = "__lodash_hash_undefined__";
	/** Used to compose bitmasks for comparison styles. */
	var UNORDERED_COMPARE_FLAG = 1;
	var PARTIAL_COMPARE_FLAG = 2;
	var MAX_SAFE_INTEGER = 9007199254740991;
	/** `Object#toString` result references. */
	var argsTag = "[object Arguments]";
	var arrayTag = "[object Array]";
	var boolTag = "[object Boolean]";
	var dateTag = "[object Date]";
	var errorTag = "[object Error]";
	var funcTag = "[object Function]";
	var genTag = "[object GeneratorFunction]";
	var mapTag = "[object Map]";
	var numberTag = "[object Number]";
	var objectTag = "[object Object]";
	var promiseTag = "[object Promise]";
	var regexpTag = "[object RegExp]";
	var setTag = "[object Set]";
	var stringTag = "[object String]";
	var symbolTag = "[object Symbol]";
	var weakMapTag = "[object WeakMap]";
	var arrayBufferTag = "[object ArrayBuffer]";
	var dataViewTag = "[object DataView]";
	var float32Tag = "[object Float32Array]";
	var float64Tag = "[object Float64Array]";
	var int8Tag = "[object Int8Array]";
	var int16Tag = "[object Int16Array]";
	var int32Tag = "[object Int32Array]";
	var uint8Tag = "[object Uint8Array]";
	var uint8ClampedTag = "[object Uint8ClampedArray]";
	var uint16Tag = "[object Uint16Array]";
	var uint32Tag = "[object Uint32Array]";
	/** Used to match property names within property paths. */
	var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
	var reIsPlainProp = /^\w*$/;
	var reLeadingDot = /^\./;
	var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
	/**
	* Used to match `RegExp`
	* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
	*/
	var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
	/** Used to match backslashes in property paths. */
	var reEscapeChar = /\\(\\)?/g;
	/** Used to detect host constructors (Safari). */
	var reIsHostCtor = /^\[object .+?Constructor\]$/;
	/** Used to detect unsigned integer values. */
	var reIsUint = /^(?:0|[1-9]\d*)$/;
	/** Used to identify `toStringTag` values of typed arrays. */
	var typedArrayTags = {};
	typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
	typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
	/** Detect free variable `global` from Node.js. */
	var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
	/** Detect free variable `self`. */
	var freeSelf = typeof self == "object" && self && self.Object === Object && self;
	/** Used as a reference to the global object. */
	var root = freeGlobal || freeSelf || Function("return this")();
	/** Detect free variable `exports`. */
	var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
	/** Detect free variable `module`. */
	var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
	/** Detect free variable `process` from Node.js. */
	var freeProcess = freeModule && freeModule.exports === freeExports && freeGlobal.process;
	/** Used to access faster Node.js helpers. */
	var nodeUtil = function() {
		try {
			return freeProcess && freeProcess.binding("util");
		} catch (e) {}
	}();
	var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
	/**
	* A specialized version of `_.forEach` for arrays without support for
	* iteratee shorthands.
	*
	* @private
	* @param {Array} [array] The array to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @returns {Array} Returns `array`.
	*/
	function arrayEach(array, iteratee) {
		var index = -1, length = array ? array.length : 0;
		while (++index < length) if (iteratee(array[index], index, array) === false) break;
		return array;
	}
	/**
	* A specialized version of `_.some` for arrays without support for iteratee
	* shorthands.
	*
	* @private
	* @param {Array} [array] The array to iterate over.
	* @param {Function} predicate The function invoked per iteration.
	* @returns {boolean} Returns `true` if any element passes the predicate check,
	*  else `false`.
	*/
	function arraySome(array, predicate) {
		var index = -1, length = array ? array.length : 0;
		while (++index < length) if (predicate(array[index], index, array)) return true;
		return false;
	}
	/**
	* The base implementation of `_.property` without support for deep paths.
	*
	* @private
	* @param {string} key The key of the property to get.
	* @returns {Function} Returns the new accessor function.
	*/
	function baseProperty(key) {
		return function(object) {
			return object == null ? void 0 : object[key];
		};
	}
	/**
	* The base implementation of `_.times` without support for iteratee shorthands
	* or max array length checks.
	*
	* @private
	* @param {number} n The number of times to invoke `iteratee`.
	* @param {Function} iteratee The function invoked per iteration.
	* @returns {Array} Returns the array of results.
	*/
	function baseTimes(n, iteratee) {
		var index = -1, result = Array(n);
		while (++index < n) result[index] = iteratee(index);
		return result;
	}
	/**
	* The base implementation of `_.unary` without support for storing metadata.
	*
	* @private
	* @param {Function} func The function to cap arguments for.
	* @returns {Function} Returns the new capped function.
	*/
	function baseUnary(func) {
		return function(value) {
			return func(value);
		};
	}
	/**
	* Gets the value at `key` of `object`.
	*
	* @private
	* @param {Object} [object] The object to query.
	* @param {string} key The key of the property to get.
	* @returns {*} Returns the property value.
	*/
	function getValue(object, key) {
		return object == null ? void 0 : object[key];
	}
	/**
	* Checks if `value` is a host object in IE < 9.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
	*/
	function isHostObject(value) {
		var result = false;
		if (value != null && typeof value.toString != "function") try {
			result = !!(value + "");
		} catch (e) {}
		return result;
	}
	/**
	* Converts `map` to its key-value pairs.
	*
	* @private
	* @param {Object} map The map to convert.
	* @returns {Array} Returns the key-value pairs.
	*/
	function mapToArray(map) {
		var index = -1, result = Array(map.size);
		map.forEach(function(value, key) {
			result[++index] = [key, value];
		});
		return result;
	}
	/**
	* Creates a unary function that invokes `func` with its argument transformed.
	*
	* @private
	* @param {Function} func The function to wrap.
	* @param {Function} transform The argument transform.
	* @returns {Function} Returns the new function.
	*/
	function overArg(func, transform) {
		return function(arg) {
			return func(transform(arg));
		};
	}
	/**
	* Converts `set` to an array of its values.
	*
	* @private
	* @param {Object} set The set to convert.
	* @returns {Array} Returns the values.
	*/
	function setToArray(set) {
		var index = -1, result = Array(set.size);
		set.forEach(function(value) {
			result[++index] = value;
		});
		return result;
	}
	/** Used for built-in method references. */
	var arrayProto = Array.prototype;
	var funcProto = Function.prototype;
	var objectProto = Object.prototype;
	/** Used to detect overreaching core-js shims. */
	var coreJsData = root["__core-js_shared__"];
	/** Used to detect methods masquerading as native. */
	var maskSrcKey = function() {
		var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
		return uid ? "Symbol(src)_1." + uid : "";
	}();
	/** Used to resolve the decompiled source of functions. */
	var funcToString = funcProto.toString;
	/** Used to check objects for own properties. */
	var hasOwnProperty = objectProto.hasOwnProperty;
	/**
	* Used to resolve the
	* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	* of values.
	*/
	var objectToString = objectProto.toString;
	/** Used to detect if a method is native. */
	var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
	/** Built-in value references. */
	var Symbol = root.Symbol;
	var Uint8Array = root.Uint8Array;
	var getPrototype = overArg(Object.getPrototypeOf, Object);
	var objectCreate = Object.create;
	var propertyIsEnumerable = objectProto.propertyIsEnumerable;
	var splice = arrayProto.splice;
	var nativeKeys = overArg(Object.keys, Object);
	var DataView = getNative(root, "DataView");
	var Map = getNative(root, "Map");
	var Promise = getNative(root, "Promise");
	var Set = getNative(root, "Set");
	var WeakMap = getNative(root, "WeakMap");
	var nativeCreate = getNative(Object, "create");
	/** Used to detect maps, sets, and weakmaps. */
	var dataViewCtorString = toSource(DataView);
	var mapCtorString = toSource(Map);
	var promiseCtorString = toSource(Promise);
	var setCtorString = toSource(Set);
	var weakMapCtorString = toSource(WeakMap);
	/** Used to convert symbols to primitives and strings. */
	var symbolProto = Symbol ? Symbol.prototype : void 0;
	var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
	var symbolToString = symbolProto ? symbolProto.toString : void 0;
	/**
	* Creates a hash object.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function Hash(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the hash.
	*
	* @private
	* @name clear
	* @memberOf Hash
	*/
	function hashClear() {
		this.__data__ = nativeCreate ? nativeCreate(null) : {};
	}
	/**
	* Removes `key` and its value from the hash.
	*
	* @private
	* @name delete
	* @memberOf Hash
	* @param {Object} hash The hash to modify.
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function hashDelete(key) {
		return this.has(key) && delete this.__data__[key];
	}
	/**
	* Gets the hash value for `key`.
	*
	* @private
	* @name get
	* @memberOf Hash
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function hashGet(key) {
		var data = this.__data__;
		if (nativeCreate) {
			var result = data[key];
			return result === HASH_UNDEFINED ? void 0 : result;
		}
		return hasOwnProperty.call(data, key) ? data[key] : void 0;
	}
	/**
	* Checks if a hash value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf Hash
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function hashHas(key) {
		var data = this.__data__;
		return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key);
	}
	/**
	* Sets the hash `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf Hash
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the hash instance.
	*/
	function hashSet(key, value) {
		var data = this.__data__;
		data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
		return this;
	}
	Hash.prototype.clear = hashClear;
	Hash.prototype["delete"] = hashDelete;
	Hash.prototype.get = hashGet;
	Hash.prototype.has = hashHas;
	Hash.prototype.set = hashSet;
	/**
	* Creates an list cache object.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function ListCache(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the list cache.
	*
	* @private
	* @name clear
	* @memberOf ListCache
	*/
	function listCacheClear() {
		this.__data__ = [];
	}
	/**
	* Removes `key` and its value from the list cache.
	*
	* @private
	* @name delete
	* @memberOf ListCache
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function listCacheDelete(key) {
		var data = this.__data__, index = assocIndexOf(data, key);
		if (index < 0) return false;
		if (index == data.length - 1) data.pop();
		else splice.call(data, index, 1);
		return true;
	}
	/**
	* Gets the list cache value for `key`.
	*
	* @private
	* @name get
	* @memberOf ListCache
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function listCacheGet(key) {
		var data = this.__data__, index = assocIndexOf(data, key);
		return index < 0 ? void 0 : data[index][1];
	}
	/**
	* Checks if a list cache value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf ListCache
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function listCacheHas(key) {
		return assocIndexOf(this.__data__, key) > -1;
	}
	/**
	* Sets the list cache `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf ListCache
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the list cache instance.
	*/
	function listCacheSet(key, value) {
		var data = this.__data__, index = assocIndexOf(data, key);
		if (index < 0) data.push([key, value]);
		else data[index][1] = value;
		return this;
	}
	ListCache.prototype.clear = listCacheClear;
	ListCache.prototype["delete"] = listCacheDelete;
	ListCache.prototype.get = listCacheGet;
	ListCache.prototype.has = listCacheHas;
	ListCache.prototype.set = listCacheSet;
	/**
	* Creates a map cache object to store key-value pairs.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function MapCache(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the map.
	*
	* @private
	* @name clear
	* @memberOf MapCache
	*/
	function mapCacheClear() {
		this.__data__ = {
			"hash": new Hash(),
			"map": new (Map || ListCache)(),
			"string": new Hash()
		};
	}
	/**
	* Removes `key` and its value from the map.
	*
	* @private
	* @name delete
	* @memberOf MapCache
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function mapCacheDelete(key) {
		return getMapData(this, key)["delete"](key);
	}
	/**
	* Gets the map value for `key`.
	*
	* @private
	* @name get
	* @memberOf MapCache
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function mapCacheGet(key) {
		return getMapData(this, key).get(key);
	}
	/**
	* Checks if a map value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf MapCache
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function mapCacheHas(key) {
		return getMapData(this, key).has(key);
	}
	/**
	* Sets the map `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf MapCache
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the map cache instance.
	*/
	function mapCacheSet(key, value) {
		getMapData(this, key).set(key, value);
		return this;
	}
	MapCache.prototype.clear = mapCacheClear;
	MapCache.prototype["delete"] = mapCacheDelete;
	MapCache.prototype.get = mapCacheGet;
	MapCache.prototype.has = mapCacheHas;
	MapCache.prototype.set = mapCacheSet;
	/**
	*
	* Creates an array cache object to store unique values.
	*
	* @private
	* @constructor
	* @param {Array} [values] The values to cache.
	*/
	function SetCache(values) {
		var index = -1, length = values ? values.length : 0;
		this.__data__ = new MapCache();
		while (++index < length) this.add(values[index]);
	}
	/**
	* Adds `value` to the array cache.
	*
	* @private
	* @name add
	* @memberOf SetCache
	* @alias push
	* @param {*} value The value to cache.
	* @returns {Object} Returns the cache instance.
	*/
	function setCacheAdd(value) {
		this.__data__.set(value, HASH_UNDEFINED);
		return this;
	}
	/**
	* Checks if `value` is in the array cache.
	*
	* @private
	* @name has
	* @memberOf SetCache
	* @param {*} value The value to search for.
	* @returns {number} Returns `true` if `value` is found, else `false`.
	*/
	function setCacheHas(value) {
		return this.__data__.has(value);
	}
	SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
	SetCache.prototype.has = setCacheHas;
	/**
	* Creates a stack cache object to store key-value pairs.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function Stack(entries) {
		this.__data__ = new ListCache(entries);
	}
	/**
	* Removes all key-value entries from the stack.
	*
	* @private
	* @name clear
	* @memberOf Stack
	*/
	function stackClear() {
		this.__data__ = new ListCache();
	}
	/**
	* Removes `key` and its value from the stack.
	*
	* @private
	* @name delete
	* @memberOf Stack
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function stackDelete(key) {
		return this.__data__["delete"](key);
	}
	/**
	* Gets the stack value for `key`.
	*
	* @private
	* @name get
	* @memberOf Stack
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function stackGet(key) {
		return this.__data__.get(key);
	}
	/**
	* Checks if a stack value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf Stack
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function stackHas(key) {
		return this.__data__.has(key);
	}
	/**
	* Sets the stack `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf Stack
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the stack cache instance.
	*/
	function stackSet(key, value) {
		var cache = this.__data__;
		if (cache instanceof ListCache) {
			var pairs = cache.__data__;
			if (!Map || pairs.length < 199) {
				pairs.push([key, value]);
				return this;
			}
			cache = this.__data__ = new MapCache(pairs);
		}
		cache.set(key, value);
		return this;
	}
	Stack.prototype.clear = stackClear;
	Stack.prototype["delete"] = stackDelete;
	Stack.prototype.get = stackGet;
	Stack.prototype.has = stackHas;
	Stack.prototype.set = stackSet;
	/**
	* Creates an array of the enumerable property names of the array-like `value`.
	*
	* @private
	* @param {*} value The value to query.
	* @param {boolean} inherited Specify returning inherited property names.
	* @returns {Array} Returns the array of property names.
	*/
	function arrayLikeKeys(value, inherited) {
		var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
		var length = result.length, skipIndexes = !!length;
		for (var key in value) if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) result.push(key);
		return result;
	}
	/**
	* Gets the index at which the `key` is found in `array` of key-value pairs.
	*
	* @private
	* @param {Array} array The array to inspect.
	* @param {*} key The key to search for.
	* @returns {number} Returns the index of the matched value, else `-1`.
	*/
	function assocIndexOf(array, key) {
		var length = array.length;
		while (length--) if (eq(array[length][0], key)) return length;
		return -1;
	}
	/**
	* The base implementation of `_.create` without support for assigning
	* properties to the created object.
	*
	* @private
	* @param {Object} prototype The object to inherit from.
	* @returns {Object} Returns the new object.
	*/
	function baseCreate(proto) {
		return isObject(proto) ? objectCreate(proto) : {};
	}
	/**
	* The base implementation of `baseForOwn` which iterates over `object`
	* properties returned by `keysFunc` and invokes `iteratee` for each property.
	* Iteratee functions may exit iteration early by explicitly returning `false`.
	*
	* @private
	* @param {Object} object The object to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @param {Function} keysFunc The function to get the keys of `object`.
	* @returns {Object} Returns `object`.
	*/
	var baseFor = createBaseFor();
	/**
	* The base implementation of `_.forOwn` without support for iteratee shorthands.
	*
	* @private
	* @param {Object} object The object to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @returns {Object} Returns `object`.
	*/
	function baseForOwn(object, iteratee) {
		return object && baseFor(object, iteratee, keys);
	}
	/**
	* The base implementation of `_.get` without support for default values.
	*
	* @private
	* @param {Object} object The object to query.
	* @param {Array|string} path The path of the property to get.
	* @returns {*} Returns the resolved value.
	*/
	function baseGet(object, path) {
		path = isKey(path, object) ? [path] : castPath(path);
		var index = 0, length = path.length;
		while (object != null && index < length) object = object[toKey(path[index++])];
		return index && index == length ? object : void 0;
	}
	/**
	* The base implementation of `getTag`.
	*
	* @private
	* @param {*} value The value to query.
	* @returns {string} Returns the `toStringTag`.
	*/
	function baseGetTag(value) {
		return objectToString.call(value);
	}
	/**
	* The base implementation of `_.hasIn` without support for deep paths.
	*
	* @private
	* @param {Object} [object] The object to query.
	* @param {Array|string} key The key to check.
	* @returns {boolean} Returns `true` if `key` exists, else `false`.
	*/
	function baseHasIn(object, key) {
		return object != null && key in Object(object);
	}
	/**
	* The base implementation of `_.isEqual` which supports partial comparisons
	* and tracks traversed objects.
	*
	* @private
	* @param {*} value The value to compare.
	* @param {*} other The other value to compare.
	* @param {Function} [customizer] The function to customize comparisons.
	* @param {boolean} [bitmask] The bitmask of comparison flags.
	*  The bitmask may be composed of the following flags:
	*     1 - Unordered comparison
	*     2 - Partial comparison
	* @param {Object} [stack] Tracks traversed `value` and `other` objects.
	* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
	*/
	function baseIsEqual(value, other, customizer, bitmask, stack) {
		if (value === other) return true;
		if (value == null || other == null || !isObject(value) && !isObjectLike(other)) return value !== value && other !== other;
		return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
	}
	/**
	* A specialized version of `baseIsEqual` for arrays and objects which performs
	* deep comparisons and tracks traversed objects enabling objects with circular
	* references to be compared.
	*
	* @private
	* @param {Object} object The object to compare.
	* @param {Object} other The other object to compare.
	* @param {Function} equalFunc The function to determine equivalents of values.
	* @param {Function} [customizer] The function to customize comparisons.
	* @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
	*  for more details.
	* @param {Object} [stack] Tracks traversed `object` and `other` objects.
	* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
	*/
	function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
		var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag;
		if (!objIsArr) {
			objTag = getTag(object);
			objTag = objTag == argsTag ? objectTag : objTag;
		}
		if (!othIsArr) {
			othTag = getTag(other);
			othTag = othTag == argsTag ? objectTag : othTag;
		}
		var objIsObj = objTag == objectTag && !isHostObject(object), othIsObj = othTag == objectTag && !isHostObject(other), isSameTag = objTag == othTag;
		if (isSameTag && !objIsObj) {
			stack || (stack = new Stack());
			return objIsArr || isTypedArray(object) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
		}
		if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
			var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__");
			if (objIsWrapped || othIsWrapped) {
				var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
				stack || (stack = new Stack());
				return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
			}
		}
		if (!isSameTag) return false;
		stack || (stack = new Stack());
		return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
	}
	/**
	* The base implementation of `_.isMatch` without support for iteratee shorthands.
	*
	* @private
	* @param {Object} object The object to inspect.
	* @param {Object} source The object of property values to match.
	* @param {Array} matchData The property names, values, and compare flags to match.
	* @param {Function} [customizer] The function to customize comparisons.
	* @returns {boolean} Returns `true` if `object` is a match, else `false`.
	*/
	function baseIsMatch(object, source, matchData, customizer) {
		var index = matchData.length, length = index, noCustomizer = !customizer;
		if (object == null) return !length;
		object = Object(object);
		while (index--) {
			var data = matchData[index];
			if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) return false;
		}
		while (++index < length) {
			data = matchData[index];
			var key = data[0], objValue = object[key], srcValue = data[1];
			if (noCustomizer && data[2]) {
				if (objValue === void 0 && !(key in object)) return false;
			} else {
				var stack = new Stack();
				if (customizer) var result = customizer(objValue, srcValue, key, object, source, stack);
				if (!(result === void 0 ? baseIsEqual(srcValue, objValue, customizer, 3, stack) : result)) return false;
			}
		}
		return true;
	}
	/**
	* The base implementation of `_.isNative` without bad shim checks.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a native function,
	*  else `false`.
	*/
	function baseIsNative(value) {
		if (!isObject(value) || isMasked(value)) return false;
		return (isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor).test(toSource(value));
	}
	/**
	* The base implementation of `_.isTypedArray` without Node.js optimizations.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
	*/
	function baseIsTypedArray(value) {
		return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
	}
	/**
	* The base implementation of `_.iteratee`.
	*
	* @private
	* @param {*} [value=_.identity] The value to convert to an iteratee.
	* @returns {Function} Returns the iteratee.
	*/
	function baseIteratee(value) {
		if (typeof value == "function") return value;
		if (value == null) return identity;
		if (typeof value == "object") return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
		return property(value);
	}
	/**
	* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property names.
	*/
	function baseKeys(object) {
		if (!isPrototype(object)) return nativeKeys(object);
		var result = [];
		for (var key in Object(object)) if (hasOwnProperty.call(object, key) && key != "constructor") result.push(key);
		return result;
	}
	/**
	* The base implementation of `_.matches` which doesn't clone `source`.
	*
	* @private
	* @param {Object} source The object of property values to match.
	* @returns {Function} Returns the new spec function.
	*/
	function baseMatches(source) {
		var matchData = getMatchData(source);
		if (matchData.length == 1 && matchData[0][2]) return matchesStrictComparable(matchData[0][0], matchData[0][1]);
		return function(object) {
			return object === source || baseIsMatch(object, source, matchData);
		};
	}
	/**
	* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
	*
	* @private
	* @param {string} path The path of the property to get.
	* @param {*} srcValue The value to match.
	* @returns {Function} Returns the new spec function.
	*/
	function baseMatchesProperty(path, srcValue) {
		if (isKey(path) && isStrictComparable(srcValue)) return matchesStrictComparable(toKey(path), srcValue);
		return function(object) {
			var objValue = get(object, path);
			return objValue === void 0 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, void 0, 3);
		};
	}
	/**
	* A specialized version of `baseProperty` which supports deep paths.
	*
	* @private
	* @param {Array|string} path The path of the property to get.
	* @returns {Function} Returns the new accessor function.
	*/
	function basePropertyDeep(path) {
		return function(object) {
			return baseGet(object, path);
		};
	}
	/**
	* The base implementation of `_.toString` which doesn't convert nullish
	* values to empty strings.
	*
	* @private
	* @param {*} value The value to process.
	* @returns {string} Returns the string.
	*/
	function baseToString(value) {
		if (typeof value == "string") return value;
		if (isSymbol(value)) return symbolToString ? symbolToString.call(value) : "";
		var result = value + "";
		return result == "0" && 1 / value == -Infinity ? "-0" : result;
	}
	/**
	* Casts `value` to a path array if it's not one.
	*
	* @private
	* @param {*} value The value to inspect.
	* @returns {Array} Returns the cast property path array.
	*/
	function castPath(value) {
		return isArray(value) ? value : stringToPath(value);
	}
	/**
	* Creates a base function for methods like `_.forIn` and `_.forOwn`.
	*
	* @private
	* @param {boolean} [fromRight] Specify iterating from right to left.
	* @returns {Function} Returns the new base function.
	*/
	function createBaseFor(fromRight) {
		return function(object, iteratee, keysFunc) {
			var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
			while (length--) {
				var key = props[fromRight ? length : ++index];
				if (iteratee(iterable[key], key, iterable) === false) break;
			}
			return object;
		};
	}
	/**
	* A specialized version of `baseIsEqualDeep` for arrays with support for
	* partial deep comparisons.
	*
	* @private
	* @param {Array} array The array to compare.
	* @param {Array} other The other array to compare.
	* @param {Function} equalFunc The function to determine equivalents of values.
	* @param {Function} customizer The function to customize comparisons.
	* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
	*  for more details.
	* @param {Object} stack Tracks traversed `array` and `other` objects.
	* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
	*/
	function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
		var isPartial = bitmask & PARTIAL_COMPARE_FLAG, arrLength = array.length, othLength = other.length;
		if (arrLength != othLength && !(isPartial && othLength > arrLength)) return false;
		var stacked = stack.get(array);
		if (stacked && stack.get(other)) return stacked == other;
		var index = -1, result = true, seen = bitmask & UNORDERED_COMPARE_FLAG ? new SetCache() : void 0;
		stack.set(array, other);
		stack.set(other, array);
		while (++index < arrLength) {
			var arrValue = array[index], othValue = other[index];
			if (customizer) var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
			if (compared !== void 0) {
				if (compared) continue;
				result = false;
				break;
			}
			if (seen) {
				if (!arraySome(other, function(othValue, othIndex) {
					if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) return seen.add(othIndex);
				})) {
					result = false;
					break;
				}
			} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
				result = false;
				break;
			}
		}
		stack["delete"](array);
		stack["delete"](other);
		return result;
	}
	/**
	* A specialized version of `baseIsEqualDeep` for comparing objects of
	* the same `toStringTag`.
	*
	* **Note:** This function only supports comparing values with tags of
	* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
	*
	* @private
	* @param {Object} object The object to compare.
	* @param {Object} other The other object to compare.
	* @param {string} tag The `toStringTag` of the objects to compare.
	* @param {Function} equalFunc The function to determine equivalents of values.
	* @param {Function} customizer The function to customize comparisons.
	* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
	*  for more details.
	* @param {Object} stack Tracks traversed `object` and `other` objects.
	* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
	*/
	function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
		switch (tag) {
			case dataViewTag:
				if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) return false;
				object = object.buffer;
				other = other.buffer;
			case arrayBufferTag:
				if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) return false;
				return true;
			case boolTag:
			case dateTag:
			case numberTag: return eq(+object, +other);
			case errorTag: return object.name == other.name && object.message == other.message;
			case regexpTag:
			case stringTag: return object == other + "";
			case mapTag: var convert = mapToArray;
			case setTag:
				var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
				convert || (convert = setToArray);
				if (object.size != other.size && !isPartial) return false;
				var stacked = stack.get(object);
				if (stacked) return stacked == other;
				bitmask |= UNORDERED_COMPARE_FLAG;
				stack.set(object, other);
				var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
				stack["delete"](object);
				return result;
			case symbolTag: if (symbolValueOf) return symbolValueOf.call(object) == symbolValueOf.call(other);
		}
		return false;
	}
	/**
	* A specialized version of `baseIsEqualDeep` for objects with support for
	* partial deep comparisons.
	*
	* @private
	* @param {Object} object The object to compare.
	* @param {Object} other The other object to compare.
	* @param {Function} equalFunc The function to determine equivalents of values.
	* @param {Function} customizer The function to customize comparisons.
	* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
	*  for more details.
	* @param {Object} stack Tracks traversed `object` and `other` objects.
	* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
	*/
	function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
		var isPartial = bitmask & PARTIAL_COMPARE_FLAG, objProps = keys(object), objLength = objProps.length;
		if (objLength != keys(other).length && !isPartial) return false;
		var index = objLength;
		while (index--) {
			var key = objProps[index];
			if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) return false;
		}
		var stacked = stack.get(object);
		if (stacked && stack.get(other)) return stacked == other;
		var result = true;
		stack.set(object, other);
		stack.set(other, object);
		var skipCtor = isPartial;
		while (++index < objLength) {
			key = objProps[index];
			var objValue = object[key], othValue = other[key];
			if (customizer) var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
			if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack) : compared)) {
				result = false;
				break;
			}
			skipCtor || (skipCtor = key == "constructor");
		}
		if (result && !skipCtor) {
			var objCtor = object.constructor, othCtor = other.constructor;
			if (objCtor != othCtor && "constructor" in object && "constructor" in other && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) result = false;
		}
		stack["delete"](object);
		stack["delete"](other);
		return result;
	}
	/**
	* Gets the data for `map`.
	*
	* @private
	* @param {Object} map The map to query.
	* @param {string} key The reference key.
	* @returns {*} Returns the map data.
	*/
	function getMapData(map, key) {
		var data = map.__data__;
		return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
	}
	/**
	* Gets the property names, values, and compare flags of `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Array} Returns the match data of `object`.
	*/
	function getMatchData(object) {
		var result = keys(object), length = result.length;
		while (length--) {
			var key = result[length], value = object[key];
			result[length] = [
				key,
				value,
				isStrictComparable(value)
			];
		}
		return result;
	}
	/**
	* Gets the native function at `key` of `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @param {string} key The key of the method to get.
	* @returns {*} Returns the function if it's native, else `undefined`.
	*/
	function getNative(object, key) {
		var value = getValue(object, key);
		return baseIsNative(value) ? value : void 0;
	}
	/**
	* Gets the `toStringTag` of `value`.
	*
	* @private
	* @param {*} value The value to query.
	* @returns {string} Returns the `toStringTag`.
	*/
	var getTag = baseGetTag;
	if (DataView && getTag(new DataView(/* @__PURE__ */ new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) getTag = function(value) {
		var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : void 0;
		if (ctorString) switch (ctorString) {
			case dataViewCtorString: return dataViewTag;
			case mapCtorString: return mapTag;
			case promiseCtorString: return promiseTag;
			case setCtorString: return setTag;
			case weakMapCtorString: return weakMapTag;
		}
		return result;
	};
	/**
	* Checks if `path` exists on `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @param {Array|string} path The path to check.
	* @param {Function} hasFunc The function to check properties.
	* @returns {boolean} Returns `true` if `path` exists, else `false`.
	*/
	function hasPath(object, path, hasFunc) {
		path = isKey(path, object) ? [path] : castPath(path);
		var result, index = -1, length = path.length;
		while (++index < length) {
			var key = toKey(path[index]);
			if (!(result = object != null && hasFunc(object, key))) break;
			object = object[key];
		}
		if (result) return result;
		var length = object ? object.length : 0;
		return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
	}
	/**
	* Checks if `value` is a valid array-like index.
	*
	* @private
	* @param {*} value The value to check.
	* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
	* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
	*/
	function isIndex(value, length) {
		length = length == null ? MAX_SAFE_INTEGER : length;
		return !!length && (typeof value == "number" || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
	}
	/**
	* Checks if `value` is a property name and not a property path.
	*
	* @private
	* @param {*} value The value to check.
	* @param {Object} [object] The object to query keys on.
	* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
	*/
	function isKey(value, object) {
		if (isArray(value)) return false;
		var type = typeof value;
		if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) return true;
		return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
	}
	/**
	* Checks if `value` is suitable for use as unique object key.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
	*/
	function isKeyable(value) {
		var type = typeof value;
		return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
	}
	/**
	* Checks if `func` has its source masked.
	*
	* @private
	* @param {Function} func The function to check.
	* @returns {boolean} Returns `true` if `func` is masked, else `false`.
	*/
	function isMasked(func) {
		return !!maskSrcKey && maskSrcKey in func;
	}
	/**
	* Checks if `value` is likely a prototype object.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
	*/
	function isPrototype(value) {
		var Ctor = value && value.constructor;
		return value === (typeof Ctor == "function" && Ctor.prototype || objectProto);
	}
	/**
	* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` if suitable for strict
	*  equality comparisons, else `false`.
	*/
	function isStrictComparable(value) {
		return value === value && !isObject(value);
	}
	/**
	* A specialized version of `matchesProperty` for source values suitable
	* for strict equality comparisons, i.e. `===`.
	*
	* @private
	* @param {string} key The key of the property to get.
	* @param {*} srcValue The value to match.
	* @returns {Function} Returns the new spec function.
	*/
	function matchesStrictComparable(key, srcValue) {
		return function(object) {
			if (object == null) return false;
			return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
		};
	}
	/**
	* Converts `string` to a property path array.
	*
	* @private
	* @param {string} string The string to convert.
	* @returns {Array} Returns the property path array.
	*/
	var stringToPath = memoize(function(string) {
		string = toString(string);
		var result = [];
		if (reLeadingDot.test(string)) result.push("");
		string.replace(rePropName, function(match, number, quote, string) {
			result.push(quote ? string.replace(reEscapeChar, "$1") : number || match);
		});
		return result;
	});
	/**
	* Converts `value` to a string key if it's not a string or symbol.
	*
	* @private
	* @param {*} value The value to inspect.
	* @returns {string|symbol} Returns the key.
	*/
	function toKey(value) {
		if (typeof value == "string" || isSymbol(value)) return value;
		var result = value + "";
		return result == "0" && 1 / value == -Infinity ? "-0" : result;
	}
	/**
	* Converts `func` to its source code.
	*
	* @private
	* @param {Function} func The function to process.
	* @returns {string} Returns the source code.
	*/
	function toSource(func) {
		if (func != null) {
			try {
				return funcToString.call(func);
			} catch (e) {}
			try {
				return func + "";
			} catch (e) {}
		}
		return "";
	}
	/**
	* Creates a function that memoizes the result of `func`. If `resolver` is
	* provided, it determines the cache key for storing the result based on the
	* arguments provided to the memoized function. By default, the first argument
	* provided to the memoized function is used as the map cache key. The `func`
	* is invoked with the `this` binding of the memoized function.
	*
	* **Note:** The cache is exposed as the `cache` property on the memoized
	* function. Its creation may be customized by replacing the `_.memoize.Cache`
	* constructor with one whose instances implement the
	* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
	* method interface of `delete`, `get`, `has`, and `set`.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Function
	* @param {Function} func The function to have its output memoized.
	* @param {Function} [resolver] The function to resolve the cache key.
	* @returns {Function} Returns the new memoized function.
	* @example
	*
	* var object = { 'a': 1, 'b': 2 };
	* var other = { 'c': 3, 'd': 4 };
	*
	* var values = _.memoize(_.values);
	* values(object);
	* // => [1, 2]
	*
	* values(other);
	* // => [3, 4]
	*
	* object.a = 2;
	* values(object);
	* // => [1, 2]
	*
	* // Modify the result cache.
	* values.cache.set(object, ['a', 'b']);
	* values(object);
	* // => ['a', 'b']
	*
	* // Replace `_.memoize.Cache`.
	* _.memoize.Cache = WeakMap;
	*/
	function memoize(func, resolver) {
		if (typeof func != "function" || resolver && typeof resolver != "function") throw new TypeError(FUNC_ERROR_TEXT);
		var memoized = function() {
			var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
			if (cache.has(key)) return cache.get(key);
			var result = func.apply(this, args);
			memoized.cache = cache.set(key, result);
			return result;
		};
		memoized.cache = new (memoize.Cache || MapCache)();
		return memoized;
	}
	memoize.Cache = MapCache;
	/**
	* Performs a
	* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
	* comparison between two values to determine if they are equivalent.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to compare.
	* @param {*} other The other value to compare.
	* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
	* @example
	*
	* var object = { 'a': 1 };
	* var other = { 'a': 1 };
	*
	* _.eq(object, object);
	* // => true
	*
	* _.eq(object, other);
	* // => false
	*
	* _.eq('a', 'a');
	* // => true
	*
	* _.eq('a', Object('a'));
	* // => false
	*
	* _.eq(NaN, NaN);
	* // => true
	*/
	function eq(value, other) {
		return value === other || value !== value && other !== other;
	}
	/**
	* Checks if `value` is likely an `arguments` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an `arguments` object,
	*  else `false`.
	* @example
	*
	* _.isArguments(function() { return arguments; }());
	* // => true
	*
	* _.isArguments([1, 2, 3]);
	* // => false
	*/
	function isArguments(value) {
		return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag);
	}
	/**
	* Checks if `value` is classified as an `Array` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an array, else `false`.
	* @example
	*
	* _.isArray([1, 2, 3]);
	* // => true
	*
	* _.isArray(document.body.children);
	* // => false
	*
	* _.isArray('abc');
	* // => false
	*
	* _.isArray(_.noop);
	* // => false
	*/
	var isArray = Array.isArray;
	/**
	* Checks if `value` is array-like. A value is considered array-like if it's
	* not a function and has a `value.length` that's an integer greater than or
	* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
	* @example
	*
	* _.isArrayLike([1, 2, 3]);
	* // => true
	*
	* _.isArrayLike(document.body.children);
	* // => true
	*
	* _.isArrayLike('abc');
	* // => true
	*
	* _.isArrayLike(_.noop);
	* // => false
	*/
	function isArrayLike(value) {
		return value != null && isLength(value.length) && !isFunction(value);
	}
	/**
	* This method is like `_.isArrayLike` except that it also checks if `value`
	* is an object.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an array-like object,
	*  else `false`.
	* @example
	*
	* _.isArrayLikeObject([1, 2, 3]);
	* // => true
	*
	* _.isArrayLikeObject(document.body.children);
	* // => true
	*
	* _.isArrayLikeObject('abc');
	* // => false
	*
	* _.isArrayLikeObject(_.noop);
	* // => false
	*/
	function isArrayLikeObject(value) {
		return isObjectLike(value) && isArrayLike(value);
	}
	/**
	* Checks if `value` is classified as a `Function` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a function, else `false`.
	* @example
	*
	* _.isFunction(_);
	* // => true
	*
	* _.isFunction(/abc/);
	* // => false
	*/
	function isFunction(value) {
		var tag = isObject(value) ? objectToString.call(value) : "";
		return tag == funcTag || tag == genTag;
	}
	/**
	* Checks if `value` is a valid array-like length.
	*
	* **Note:** This method is loosely based on
	* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
	* @example
	*
	* _.isLength(3);
	* // => true
	*
	* _.isLength(Number.MIN_VALUE);
	* // => false
	*
	* _.isLength(Infinity);
	* // => false
	*
	* _.isLength('3');
	* // => false
	*/
	function isLength(value) {
		return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
	}
	/**
	* Checks if `value` is the
	* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
	* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an object, else `false`.
	* @example
	*
	* _.isObject({});
	* // => true
	*
	* _.isObject([1, 2, 3]);
	* // => true
	*
	* _.isObject(_.noop);
	* // => true
	*
	* _.isObject(null);
	* // => false
	*/
	function isObject(value) {
		var type = typeof value;
		return !!value && (type == "object" || type == "function");
	}
	/**
	* Checks if `value` is object-like. A value is object-like if it's not `null`
	* and has a `typeof` result of "object".
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
	* @example
	*
	* _.isObjectLike({});
	* // => true
	*
	* _.isObjectLike([1, 2, 3]);
	* // => true
	*
	* _.isObjectLike(_.noop);
	* // => false
	*
	* _.isObjectLike(null);
	* // => false
	*/
	function isObjectLike(value) {
		return !!value && typeof value == "object";
	}
	/**
	* Checks if `value` is classified as a `Symbol` primitive or object.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
	* @example
	*
	* _.isSymbol(Symbol.iterator);
	* // => true
	*
	* _.isSymbol('abc');
	* // => false
	*/
	function isSymbol(value) {
		return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
	}
	/**
	* Checks if `value` is classified as a typed array.
	*
	* @static
	* @memberOf _
	* @since 3.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
	* @example
	*
	* _.isTypedArray(new Uint8Array);
	* // => true
	*
	* _.isTypedArray([]);
	* // => false
	*/
	var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
	/**
	* Converts `value` to a string. An empty string is returned for `null`
	* and `undefined` values. The sign of `-0` is preserved.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to process.
	* @returns {string} Returns the string.
	* @example
	*
	* _.toString(null);
	* // => ''
	*
	* _.toString(-0);
	* // => '-0'
	*
	* _.toString([1, 2, 3]);
	* // => '1,2,3'
	*/
	function toString(value) {
		return value == null ? "" : baseToString(value);
	}
	/**
	* Gets the value at `path` of `object`. If the resolved value is
	* `undefined`, the `defaultValue` is returned in its place.
	*
	* @static
	* @memberOf _
	* @since 3.7.0
	* @category Object
	* @param {Object} object The object to query.
	* @param {Array|string} path The path of the property to get.
	* @param {*} [defaultValue] The value returned for `undefined` resolved values.
	* @returns {*} Returns the resolved value.
	* @example
	*
	* var object = { 'a': [{ 'b': { 'c': 3 } }] };
	*
	* _.get(object, 'a[0].b.c');
	* // => 3
	*
	* _.get(object, ['a', '0', 'b', 'c']);
	* // => 3
	*
	* _.get(object, 'a.b.c', 'default');
	* // => 'default'
	*/
	function get(object, path, defaultValue) {
		var result = object == null ? void 0 : baseGet(object, path);
		return result === void 0 ? defaultValue : result;
	}
	/**
	* Checks if `path` is a direct or inherited property of `object`.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Object
	* @param {Object} object The object to query.
	* @param {Array|string} path The path to check.
	* @returns {boolean} Returns `true` if `path` exists, else `false`.
	* @example
	*
	* var object = _.create({ 'a': _.create({ 'b': 2 }) });
	*
	* _.hasIn(object, 'a');
	* // => true
	*
	* _.hasIn(object, 'a.b');
	* // => true
	*
	* _.hasIn(object, ['a', 'b']);
	* // => true
	*
	* _.hasIn(object, 'b');
	* // => false
	*/
	function hasIn(object, path) {
		return object != null && hasPath(object, path, baseHasIn);
	}
	/**
	* Creates an array of the own enumerable property names of `object`.
	*
	* **Note:** Non-object values are coerced to objects. See the
	* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
	* for more details.
	*
	* @static
	* @since 0.1.0
	* @memberOf _
	* @category Object
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property names.
	* @example
	*
	* function Foo() {
	*   this.a = 1;
	*   this.b = 2;
	* }
	*
	* Foo.prototype.c = 3;
	*
	* _.keys(new Foo);
	* // => ['a', 'b'] (iteration order is not guaranteed)
	*
	* _.keys('hi');
	* // => ['0', '1']
	*/
	function keys(object) {
		return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
	}
	/**
	* An alternative to `_.reduce`; this method transforms `object` to a new
	* `accumulator` object which is the result of running each of its own
	* enumerable string keyed properties thru `iteratee`, with each invocation
	* potentially mutating the `accumulator` object. If `accumulator` is not
	* provided, a new object with the same `[[Prototype]]` will be used. The
	* iteratee is invoked with four arguments: (accumulator, value, key, object).
	* Iteratee functions may exit iteration early by explicitly returning `false`.
	*
	* @static
	* @memberOf _
	* @since 1.3.0
	* @category Object
	* @param {Object} object The object to iterate over.
	* @param {Function} [iteratee=_.identity] The function invoked per iteration.
	* @param {*} [accumulator] The custom accumulator value.
	* @returns {*} Returns the accumulated value.
	* @example
	*
	* _.transform([2, 3, 4], function(result, n) {
	*   result.push(n *= n);
	*   return n % 2 == 0;
	* }, []);
	* // => [4, 9]
	*
	* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
	*   (result[value] || (result[value] = [])).push(key);
	* }, {});
	* // => { '1': ['a', 'c'], '2': ['b'] }
	*/
	function transform(object, iteratee, accumulator) {
		var isArr = isArray(object) || isTypedArray(object);
		iteratee = baseIteratee(iteratee, 4);
		if (accumulator == null) {
			if (isArr || isObject(object)) {
				var Ctor = object.constructor;
				if (isArr) accumulator = isArray(object) ? new Ctor() : [];
				else accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
			} else accumulator = {};
		}
		(isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
			return iteratee(accumulator, value, index, object);
		});
		return accumulator;
	}
	/**
	* This method returns the first argument it receives.
	*
	* @static
	* @since 0.1.0
	* @memberOf _
	* @category Util
	* @param {*} value Any value.
	* @returns {*} Returns `value`.
	* @example
	*
	* var object = { 'a': 1 };
	*
	* console.log(_.identity(object) === object);
	* // => true
	*/
	function identity(value) {
		return value;
	}
	/**
	* Creates a function that returns the value at `path` of a given object.
	*
	* @static
	* @memberOf _
	* @since 2.4.0
	* @category Util
	* @param {Array|string} path The path of the property to get.
	* @returns {Function} Returns the new accessor function.
	* @example
	*
	* var objects = [
	*   { 'a': { 'b': 2 } },
	*   { 'a': { 'b': 1 } }
	* ];
	*
	* _.map(objects, _.property('a.b'));
	* // => [2, 1]
	*
	* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
	* // => [1, 2]
	*/
	function property(path) {
		return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
	}
	module.exports = transform;
}));
//#endregion
//#region node_modules/lodash.includes/index.js
var require_lodash_includes = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* lodash (Custom Build) <https://lodash.com/>
	* Build: `lodash modularize exports="npm" -o ./`
	* Copyright jQuery Foundation and other contributors <https://jquery.org/>
	* Released under MIT license <https://lodash.com/license>
	* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
	* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
	*/
	/** Used as references for various `Number` constants. */
	var INFINITY = 1 / 0;
	var MAX_SAFE_INTEGER = 9007199254740991;
	var MAX_INTEGER = 17976931348623157e292;
	var NAN = NaN;
	/** `Object#toString` result references. */
	var argsTag = "[object Arguments]";
	var funcTag = "[object Function]";
	var genTag = "[object GeneratorFunction]";
	var stringTag = "[object String]";
	var symbolTag = "[object Symbol]";
	/** Used to match leading and trailing whitespace. */
	var reTrim = /^\s+|\s+$/g;
	/** Used to detect bad signed hexadecimal string values. */
	var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
	/** Used to detect binary string values. */
	var reIsBinary = /^0b[01]+$/i;
	/** Used to detect octal string values. */
	var reIsOctal = /^0o[0-7]+$/i;
	/** Used to detect unsigned integer values. */
	var reIsUint = /^(?:0|[1-9]\d*)$/;
	/** Built-in method references without a dependency on `root`. */
	var freeParseInt = parseInt;
	/**
	* A specialized version of `_.map` for arrays without support for iteratee
	* shorthands.
	*
	* @private
	* @param {Array} [array] The array to iterate over.
	* @param {Function} iteratee The function invoked per iteration.
	* @returns {Array} Returns the new mapped array.
	*/
	function arrayMap(array, iteratee) {
		var index = -1, length = array ? array.length : 0, result = Array(length);
		while (++index < length) result[index] = iteratee(array[index], index, array);
		return result;
	}
	/**
	* The base implementation of `_.findIndex` and `_.findLastIndex` without
	* support for iteratee shorthands.
	*
	* @private
	* @param {Array} array The array to inspect.
	* @param {Function} predicate The function invoked per iteration.
	* @param {number} fromIndex The index to search from.
	* @param {boolean} [fromRight] Specify iterating from right to left.
	* @returns {number} Returns the index of the matched value, else `-1`.
	*/
	function baseFindIndex(array, predicate, fromIndex, fromRight) {
		var length = array.length, index = fromIndex + (fromRight ? 1 : -1);
		while (fromRight ? index-- : ++index < length) if (predicate(array[index], index, array)) return index;
		return -1;
	}
	/**
	* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
	*
	* @private
	* @param {Array} array The array to inspect.
	* @param {*} value The value to search for.
	* @param {number} fromIndex The index to search from.
	* @returns {number} Returns the index of the matched value, else `-1`.
	*/
	function baseIndexOf(array, value, fromIndex) {
		if (value !== value) return baseFindIndex(array, baseIsNaN, fromIndex);
		var index = fromIndex - 1, length = array.length;
		while (++index < length) if (array[index] === value) return index;
		return -1;
	}
	/**
	* The base implementation of `_.isNaN` without support for number objects.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
	*/
	function baseIsNaN(value) {
		return value !== value;
	}
	/**
	* The base implementation of `_.times` without support for iteratee shorthands
	* or max array length checks.
	*
	* @private
	* @param {number} n The number of times to invoke `iteratee`.
	* @param {Function} iteratee The function invoked per iteration.
	* @returns {Array} Returns the array of results.
	*/
	function baseTimes(n, iteratee) {
		var index = -1, result = Array(n);
		while (++index < n) result[index] = iteratee(index);
		return result;
	}
	/**
	* The base implementation of `_.values` and `_.valuesIn` which creates an
	* array of `object` property values corresponding to the property names
	* of `props`.
	*
	* @private
	* @param {Object} object The object to query.
	* @param {Array} props The property names to get values for.
	* @returns {Object} Returns the array of property values.
	*/
	function baseValues(object, props) {
		return arrayMap(props, function(key) {
			return object[key];
		});
	}
	/**
	* Creates a unary function that invokes `func` with its argument transformed.
	*
	* @private
	* @param {Function} func The function to wrap.
	* @param {Function} transform The argument transform.
	* @returns {Function} Returns the new function.
	*/
	function overArg(func, transform) {
		return function(arg) {
			return func(transform(arg));
		};
	}
	/** Used for built-in method references. */
	var objectProto = Object.prototype;
	/** Used to check objects for own properties. */
	var hasOwnProperty = objectProto.hasOwnProperty;
	/**
	* Used to resolve the
	* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	* of values.
	*/
	var objectToString = objectProto.toString;
	/** Built-in value references. */
	var propertyIsEnumerable = objectProto.propertyIsEnumerable;
	var nativeKeys = overArg(Object.keys, Object);
	var nativeMax = Math.max;
	/**
	* Creates an array of the enumerable property names of the array-like `value`.
	*
	* @private
	* @param {*} value The value to query.
	* @param {boolean} inherited Specify returning inherited property names.
	* @returns {Array} Returns the array of property names.
	*/
	function arrayLikeKeys(value, inherited) {
		var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
		var length = result.length, skipIndexes = !!length;
		for (var key in value) if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isIndex(key, length)))) result.push(key);
		return result;
	}
	/**
	* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
	*
	* @private
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property names.
	*/
	function baseKeys(object) {
		if (!isPrototype(object)) return nativeKeys(object);
		var result = [];
		for (var key in Object(object)) if (hasOwnProperty.call(object, key) && key != "constructor") result.push(key);
		return result;
	}
	/**
	* Checks if `value` is a valid array-like index.
	*
	* @private
	* @param {*} value The value to check.
	* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
	* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
	*/
	function isIndex(value, length) {
		length = length == null ? MAX_SAFE_INTEGER : length;
		return !!length && (typeof value == "number" || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
	}
	/**
	* Checks if `value` is likely a prototype object.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
	*/
	function isPrototype(value) {
		var Ctor = value && value.constructor;
		return value === (typeof Ctor == "function" && Ctor.prototype || objectProto);
	}
	/**
	* Checks if `value` is in `collection`. If `collection` is a string, it's
	* checked for a substring of `value`, otherwise
	* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
	* is used for equality comparisons. If `fromIndex` is negative, it's used as
	* the offset from the end of `collection`.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Collection
	* @param {Array|Object|string} collection The collection to inspect.
	* @param {*} value The value to search for.
	* @param {number} [fromIndex=0] The index to search from.
	* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
	* @returns {boolean} Returns `true` if `value` is found, else `false`.
	* @example
	*
	* _.includes([1, 2, 3], 1);
	* // => true
	*
	* _.includes([1, 2, 3], 1, 2);
	* // => false
	*
	* _.includes({ 'a': 1, 'b': 2 }, 1);
	* // => true
	*
	* _.includes('abcd', 'bc');
	* // => true
	*/
	function includes(collection, value, fromIndex, guard) {
		collection = isArrayLike(collection) ? collection : values(collection);
		fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
		var length = collection.length;
		if (fromIndex < 0) fromIndex = nativeMax(length + fromIndex, 0);
		return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;
	}
	/**
	* Checks if `value` is likely an `arguments` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an `arguments` object,
	*  else `false`.
	* @example
	*
	* _.isArguments(function() { return arguments; }());
	* // => true
	*
	* _.isArguments([1, 2, 3]);
	* // => false
	*/
	function isArguments(value) {
		return isArrayLikeObject(value) && hasOwnProperty.call(value, "callee") && (!propertyIsEnumerable.call(value, "callee") || objectToString.call(value) == argsTag);
	}
	/**
	* Checks if `value` is classified as an `Array` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an array, else `false`.
	* @example
	*
	* _.isArray([1, 2, 3]);
	* // => true
	*
	* _.isArray(document.body.children);
	* // => false
	*
	* _.isArray('abc');
	* // => false
	*
	* _.isArray(_.noop);
	* // => false
	*/
	var isArray = Array.isArray;
	/**
	* Checks if `value` is array-like. A value is considered array-like if it's
	* not a function and has a `value.length` that's an integer greater than or
	* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
	* @example
	*
	* _.isArrayLike([1, 2, 3]);
	* // => true
	*
	* _.isArrayLike(document.body.children);
	* // => true
	*
	* _.isArrayLike('abc');
	* // => true
	*
	* _.isArrayLike(_.noop);
	* // => false
	*/
	function isArrayLike(value) {
		return value != null && isLength(value.length) && !isFunction(value);
	}
	/**
	* This method is like `_.isArrayLike` except that it also checks if `value`
	* is an object.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an array-like object,
	*  else `false`.
	* @example
	*
	* _.isArrayLikeObject([1, 2, 3]);
	* // => true
	*
	* _.isArrayLikeObject(document.body.children);
	* // => true
	*
	* _.isArrayLikeObject('abc');
	* // => false
	*
	* _.isArrayLikeObject(_.noop);
	* // => false
	*/
	function isArrayLikeObject(value) {
		return isObjectLike(value) && isArrayLike(value);
	}
	/**
	* Checks if `value` is classified as a `Function` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a function, else `false`.
	* @example
	*
	* _.isFunction(_);
	* // => true
	*
	* _.isFunction(/abc/);
	* // => false
	*/
	function isFunction(value) {
		var tag = isObject(value) ? objectToString.call(value) : "";
		return tag == funcTag || tag == genTag;
	}
	/**
	* Checks if `value` is a valid array-like length.
	*
	* **Note:** This method is loosely based on
	* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
	* @example
	*
	* _.isLength(3);
	* // => true
	*
	* _.isLength(Number.MIN_VALUE);
	* // => false
	*
	* _.isLength(Infinity);
	* // => false
	*
	* _.isLength('3');
	* // => false
	*/
	function isLength(value) {
		return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
	}
	/**
	* Checks if `value` is the
	* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
	* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an object, else `false`.
	* @example
	*
	* _.isObject({});
	* // => true
	*
	* _.isObject([1, 2, 3]);
	* // => true
	*
	* _.isObject(_.noop);
	* // => true
	*
	* _.isObject(null);
	* // => false
	*/
	function isObject(value) {
		var type = typeof value;
		return !!value && (type == "object" || type == "function");
	}
	/**
	* Checks if `value` is object-like. A value is object-like if it's not `null`
	* and has a `typeof` result of "object".
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
	* @example
	*
	* _.isObjectLike({});
	* // => true
	*
	* _.isObjectLike([1, 2, 3]);
	* // => true
	*
	* _.isObjectLike(_.noop);
	* // => false
	*
	* _.isObjectLike(null);
	* // => false
	*/
	function isObjectLike(value) {
		return !!value && typeof value == "object";
	}
	/**
	* Checks if `value` is classified as a `String` primitive or object.
	*
	* @static
	* @since 0.1.0
	* @memberOf _
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a string, else `false`.
	* @example
	*
	* _.isString('abc');
	* // => true
	*
	* _.isString(1);
	* // => false
	*/
	function isString(value) {
		return typeof value == "string" || !isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag;
	}
	/**
	* Checks if `value` is classified as a `Symbol` primitive or object.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
	* @example
	*
	* _.isSymbol(Symbol.iterator);
	* // => true
	*
	* _.isSymbol('abc');
	* // => false
	*/
	function isSymbol(value) {
		return typeof value == "symbol" || isObjectLike(value) && objectToString.call(value) == symbolTag;
	}
	/**
	* Converts `value` to a finite number.
	*
	* @static
	* @memberOf _
	* @since 4.12.0
	* @category Lang
	* @param {*} value The value to convert.
	* @returns {number} Returns the converted number.
	* @example
	*
	* _.toFinite(3.2);
	* // => 3.2
	*
	* _.toFinite(Number.MIN_VALUE);
	* // => 5e-324
	*
	* _.toFinite(Infinity);
	* // => 1.7976931348623157e+308
	*
	* _.toFinite('3.2');
	* // => 3.2
	*/
	function toFinite(value) {
		if (!value) return value === 0 ? value : 0;
		value = toNumber(value);
		if (value === INFINITY || value === -Infinity) return (value < 0 ? -1 : 1) * MAX_INTEGER;
		return value === value ? value : 0;
	}
	/**
	* Converts `value` to an integer.
	*
	* **Note:** This method is loosely based on
	* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to convert.
	* @returns {number} Returns the converted integer.
	* @example
	*
	* _.toInteger(3.2);
	* // => 3
	*
	* _.toInteger(Number.MIN_VALUE);
	* // => 0
	*
	* _.toInteger(Infinity);
	* // => 1.7976931348623157e+308
	*
	* _.toInteger('3.2');
	* // => 3
	*/
	function toInteger(value) {
		var result = toFinite(value), remainder = result % 1;
		return result === result ? remainder ? result - remainder : result : 0;
	}
	/**
	* Converts `value` to a number.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to process.
	* @returns {number} Returns the number.
	* @example
	*
	* _.toNumber(3.2);
	* // => 3.2
	*
	* _.toNumber(Number.MIN_VALUE);
	* // => 5e-324
	*
	* _.toNumber(Infinity);
	* // => Infinity
	*
	* _.toNumber('3.2');
	* // => 3.2
	*/
	function toNumber(value) {
		if (typeof value == "number") return value;
		if (isSymbol(value)) return NAN;
		if (isObject(value)) {
			var other = typeof value.valueOf == "function" ? value.valueOf() : value;
			value = isObject(other) ? other + "" : other;
		}
		if (typeof value != "string") return value === 0 ? value : +value;
		value = value.replace(reTrim, "");
		var isBinary = reIsBinary.test(value);
		return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
	}
	/**
	* Creates an array of the own enumerable property names of `object`.
	*
	* **Note:** Non-object values are coerced to objects. See the
	* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
	* for more details.
	*
	* @static
	* @since 0.1.0
	* @memberOf _
	* @category Object
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property names.
	* @example
	*
	* function Foo() {
	*   this.a = 1;
	*   this.b = 2;
	* }
	*
	* Foo.prototype.c = 3;
	*
	* _.keys(new Foo);
	* // => ['a', 'b'] (iteration order is not guaranteed)
	*
	* _.keys('hi');
	* // => ['0', '1']
	*/
	function keys(object) {
		return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
	}
	/**
	* Creates an array of the own enumerable string keyed property values of `object`.
	*
	* **Note:** Non-object values are coerced to objects.
	*
	* @static
	* @since 0.1.0
	* @memberOf _
	* @category Object
	* @param {Object} object The object to query.
	* @returns {Array} Returns the array of property values.
	* @example
	*
	* function Foo() {
	*   this.a = 1;
	*   this.b = 2;
	* }
	*
	* Foo.prototype.c = 3;
	*
	* _.values(new Foo);
	* // => [1, 2] (iteration order is not guaranteed)
	*
	* _.values('hi');
	* // => ['h', 'i']
	*/
	function values(object) {
		return object ? baseValues(object, keys(object)) : [];
	}
	module.exports = includes;
}));
//#endregion
//#region node_modules/lodash.isplainobject/index.js
var require_lodash_isplainobject = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* lodash (Custom Build) <https://lodash.com/>
	* Build: `lodash modularize exports="npm" -o ./`
	* Copyright jQuery Foundation and other contributors <https://jquery.org/>
	* Released under MIT license <https://lodash.com/license>
	* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
	* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
	*/
	/** `Object#toString` result references. */
	var objectTag = "[object Object]";
	/**
	* Checks if `value` is a host object in IE < 9.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
	*/
	function isHostObject(value) {
		var result = false;
		if (value != null && typeof value.toString != "function") try {
			result = !!(value + "");
		} catch (e) {}
		return result;
	}
	/**
	* Creates a unary function that invokes `func` with its argument transformed.
	*
	* @private
	* @param {Function} func The function to wrap.
	* @param {Function} transform The argument transform.
	* @returns {Function} Returns the new function.
	*/
	function overArg(func, transform) {
		return function(arg) {
			return func(transform(arg));
		};
	}
	/** Used for built-in method references. */
	var funcProto = Function.prototype;
	var objectProto = Object.prototype;
	/** Used to resolve the decompiled source of functions. */
	var funcToString = funcProto.toString;
	/** Used to check objects for own properties. */
	var hasOwnProperty = objectProto.hasOwnProperty;
	/** Used to infer the `Object` constructor. */
	var objectCtorString = funcToString.call(Object);
	/**
	* Used to resolve the
	* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	* of values.
	*/
	var objectToString = objectProto.toString;
	/** Built-in value references. */
	var getPrototype = overArg(Object.getPrototypeOf, Object);
	/**
	* Checks if `value` is object-like. A value is object-like if it's not `null`
	* and has a `typeof` result of "object".
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
	* @example
	*
	* _.isObjectLike({});
	* // => true
	*
	* _.isObjectLike([1, 2, 3]);
	* // => true
	*
	* _.isObjectLike(_.noop);
	* // => false
	*
	* _.isObjectLike(null);
	* // => false
	*/
	function isObjectLike(value) {
		return !!value && typeof value == "object";
	}
	/**
	* Checks if `value` is a plain object, that is, an object created by the
	* `Object` constructor or one with a `[[Prototype]]` of `null`.
	*
	* @static
	* @memberOf _
	* @since 0.8.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
	* @example
	*
	* function Foo() {
	*   this.a = 1;
	* }
	*
	* _.isPlainObject(new Foo);
	* // => false
	*
	* _.isPlainObject([1, 2, 3]);
	* // => false
	*
	* _.isPlainObject({ 'x': 0, 'y': 0 });
	* // => true
	*
	* _.isPlainObject(Object.create(null));
	* // => true
	*/
	function isPlainObject(value) {
		if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) return false;
		var proto = getPrototype(value);
		if (proto === null) return true;
		var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
		return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
	}
	module.exports = isPlainObject;
}));
//#endregion
//#region node_modules/lodash.memoize/index.js
var require_lodash_memoize = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/**
	* lodash (Custom Build) <https://lodash.com/>
	* Build: `lodash modularize exports="npm" -o ./`
	* Copyright jQuery Foundation and other contributors <https://jquery.org/>
	* Released under MIT license <https://lodash.com/license>
	* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
	* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
	*/
	/** Used as the `TypeError` message for "Functions" methods. */
	var FUNC_ERROR_TEXT = "Expected a function";
	/** Used to stand-in for `undefined` hash values. */
	var HASH_UNDEFINED = "__lodash_hash_undefined__";
	/** `Object#toString` result references. */
	var funcTag = "[object Function]";
	var genTag = "[object GeneratorFunction]";
	/**
	* Used to match `RegExp`
	* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
	*/
	var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
	/** Used to detect host constructors (Safari). */
	var reIsHostCtor = /^\[object .+?Constructor\]$/;
	/** Detect free variable `global` from Node.js. */
	var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
	/** Detect free variable `self`. */
	var freeSelf = typeof self == "object" && self && self.Object === Object && self;
	/** Used as a reference to the global object. */
	var root = freeGlobal || freeSelf || Function("return this")();
	/**
	* Gets the value at `key` of `object`.
	*
	* @private
	* @param {Object} [object] The object to query.
	* @param {string} key The key of the property to get.
	* @returns {*} Returns the property value.
	*/
	function getValue(object, key) {
		return object == null ? void 0 : object[key];
	}
	/**
	* Checks if `value` is a host object in IE < 9.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
	*/
	function isHostObject(value) {
		var result = false;
		if (value != null && typeof value.toString != "function") try {
			result = !!(value + "");
		} catch (e) {}
		return result;
	}
	/** Used for built-in method references. */
	var arrayProto = Array.prototype;
	var funcProto = Function.prototype;
	var objectProto = Object.prototype;
	/** Used to detect overreaching core-js shims. */
	var coreJsData = root["__core-js_shared__"];
	/** Used to detect methods masquerading as native. */
	var maskSrcKey = function() {
		var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
		return uid ? "Symbol(src)_1." + uid : "";
	}();
	/** Used to resolve the decompiled source of functions. */
	var funcToString = funcProto.toString;
	/** Used to check objects for own properties. */
	var hasOwnProperty = objectProto.hasOwnProperty;
	/**
	* Used to resolve the
	* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	* of values.
	*/
	var objectToString = objectProto.toString;
	/** Used to detect if a method is native. */
	var reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
	/** Built-in value references. */
	var splice = arrayProto.splice;
	var Map = getNative(root, "Map");
	var nativeCreate = getNative(Object, "create");
	/**
	* Creates a hash object.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function Hash(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the hash.
	*
	* @private
	* @name clear
	* @memberOf Hash
	*/
	function hashClear() {
		this.__data__ = nativeCreate ? nativeCreate(null) : {};
	}
	/**
	* Removes `key` and its value from the hash.
	*
	* @private
	* @name delete
	* @memberOf Hash
	* @param {Object} hash The hash to modify.
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function hashDelete(key) {
		return this.has(key) && delete this.__data__[key];
	}
	/**
	* Gets the hash value for `key`.
	*
	* @private
	* @name get
	* @memberOf Hash
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function hashGet(key) {
		var data = this.__data__;
		if (nativeCreate) {
			var result = data[key];
			return result === HASH_UNDEFINED ? void 0 : result;
		}
		return hasOwnProperty.call(data, key) ? data[key] : void 0;
	}
	/**
	* Checks if a hash value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf Hash
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function hashHas(key) {
		var data = this.__data__;
		return nativeCreate ? data[key] !== void 0 : hasOwnProperty.call(data, key);
	}
	/**
	* Sets the hash `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf Hash
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the hash instance.
	*/
	function hashSet(key, value) {
		var data = this.__data__;
		data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
		return this;
	}
	Hash.prototype.clear = hashClear;
	Hash.prototype["delete"] = hashDelete;
	Hash.prototype.get = hashGet;
	Hash.prototype.has = hashHas;
	Hash.prototype.set = hashSet;
	/**
	* Creates an list cache object.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function ListCache(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the list cache.
	*
	* @private
	* @name clear
	* @memberOf ListCache
	*/
	function listCacheClear() {
		this.__data__ = [];
	}
	/**
	* Removes `key` and its value from the list cache.
	*
	* @private
	* @name delete
	* @memberOf ListCache
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function listCacheDelete(key) {
		var data = this.__data__, index = assocIndexOf(data, key);
		if (index < 0) return false;
		if (index == data.length - 1) data.pop();
		else splice.call(data, index, 1);
		return true;
	}
	/**
	* Gets the list cache value for `key`.
	*
	* @private
	* @name get
	* @memberOf ListCache
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function listCacheGet(key) {
		var data = this.__data__, index = assocIndexOf(data, key);
		return index < 0 ? void 0 : data[index][1];
	}
	/**
	* Checks if a list cache value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf ListCache
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function listCacheHas(key) {
		return assocIndexOf(this.__data__, key) > -1;
	}
	/**
	* Sets the list cache `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf ListCache
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the list cache instance.
	*/
	function listCacheSet(key, value) {
		var data = this.__data__, index = assocIndexOf(data, key);
		if (index < 0) data.push([key, value]);
		else data[index][1] = value;
		return this;
	}
	ListCache.prototype.clear = listCacheClear;
	ListCache.prototype["delete"] = listCacheDelete;
	ListCache.prototype.get = listCacheGet;
	ListCache.prototype.has = listCacheHas;
	ListCache.prototype.set = listCacheSet;
	/**
	* Creates a map cache object to store key-value pairs.
	*
	* @private
	* @constructor
	* @param {Array} [entries] The key-value pairs to cache.
	*/
	function MapCache(entries) {
		var index = -1, length = entries ? entries.length : 0;
		this.clear();
		while (++index < length) {
			var entry = entries[index];
			this.set(entry[0], entry[1]);
		}
	}
	/**
	* Removes all key-value entries from the map.
	*
	* @private
	* @name clear
	* @memberOf MapCache
	*/
	function mapCacheClear() {
		this.__data__ = {
			"hash": new Hash(),
			"map": new (Map || ListCache)(),
			"string": new Hash()
		};
	}
	/**
	* Removes `key` and its value from the map.
	*
	* @private
	* @name delete
	* @memberOf MapCache
	* @param {string} key The key of the value to remove.
	* @returns {boolean} Returns `true` if the entry was removed, else `false`.
	*/
	function mapCacheDelete(key) {
		return getMapData(this, key)["delete"](key);
	}
	/**
	* Gets the map value for `key`.
	*
	* @private
	* @name get
	* @memberOf MapCache
	* @param {string} key The key of the value to get.
	* @returns {*} Returns the entry value.
	*/
	function mapCacheGet(key) {
		return getMapData(this, key).get(key);
	}
	/**
	* Checks if a map value for `key` exists.
	*
	* @private
	* @name has
	* @memberOf MapCache
	* @param {string} key The key of the entry to check.
	* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
	*/
	function mapCacheHas(key) {
		return getMapData(this, key).has(key);
	}
	/**
	* Sets the map `key` to `value`.
	*
	* @private
	* @name set
	* @memberOf MapCache
	* @param {string} key The key of the value to set.
	* @param {*} value The value to set.
	* @returns {Object} Returns the map cache instance.
	*/
	function mapCacheSet(key, value) {
		getMapData(this, key).set(key, value);
		return this;
	}
	MapCache.prototype.clear = mapCacheClear;
	MapCache.prototype["delete"] = mapCacheDelete;
	MapCache.prototype.get = mapCacheGet;
	MapCache.prototype.has = mapCacheHas;
	MapCache.prototype.set = mapCacheSet;
	/**
	* Gets the index at which the `key` is found in `array` of key-value pairs.
	*
	* @private
	* @param {Array} array The array to inspect.
	* @param {*} key The key to search for.
	* @returns {number} Returns the index of the matched value, else `-1`.
	*/
	function assocIndexOf(array, key) {
		var length = array.length;
		while (length--) if (eq(array[length][0], key)) return length;
		return -1;
	}
	/**
	* The base implementation of `_.isNative` without bad shim checks.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a native function,
	*  else `false`.
	*/
	function baseIsNative(value) {
		if (!isObject(value) || isMasked(value)) return false;
		return (isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor).test(toSource(value));
	}
	/**
	* Gets the data for `map`.
	*
	* @private
	* @param {Object} map The map to query.
	* @param {string} key The reference key.
	* @returns {*} Returns the map data.
	*/
	function getMapData(map, key) {
		var data = map.__data__;
		return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
	}
	/**
	* Gets the native function at `key` of `object`.
	*
	* @private
	* @param {Object} object The object to query.
	* @param {string} key The key of the method to get.
	* @returns {*} Returns the function if it's native, else `undefined`.
	*/
	function getNative(object, key) {
		var value = getValue(object, key);
		return baseIsNative(value) ? value : void 0;
	}
	/**
	* Checks if `value` is suitable for use as unique object key.
	*
	* @private
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
	*/
	function isKeyable(value) {
		var type = typeof value;
		return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
	}
	/**
	* Checks if `func` has its source masked.
	*
	* @private
	* @param {Function} func The function to check.
	* @returns {boolean} Returns `true` if `func` is masked, else `false`.
	*/
	function isMasked(func) {
		return !!maskSrcKey && maskSrcKey in func;
	}
	/**
	* Converts `func` to its source code.
	*
	* @private
	* @param {Function} func The function to process.
	* @returns {string} Returns the source code.
	*/
	function toSource(func) {
		if (func != null) {
			try {
				return funcToString.call(func);
			} catch (e) {}
			try {
				return func + "";
			} catch (e) {}
		}
		return "";
	}
	/**
	* Creates a function that memoizes the result of `func`. If `resolver` is
	* provided, it determines the cache key for storing the result based on the
	* arguments provided to the memoized function. By default, the first argument
	* provided to the memoized function is used as the map cache key. The `func`
	* is invoked with the `this` binding of the memoized function.
	*
	* **Note:** The cache is exposed as the `cache` property on the memoized
	* function. Its creation may be customized by replacing the `_.memoize.Cache`
	* constructor with one whose instances implement the
	* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
	* method interface of `delete`, `get`, `has`, and `set`.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Function
	* @param {Function} func The function to have its output memoized.
	* @param {Function} [resolver] The function to resolve the cache key.
	* @returns {Function} Returns the new memoized function.
	* @example
	*
	* var object = { 'a': 1, 'b': 2 };
	* var other = { 'c': 3, 'd': 4 };
	*
	* var values = _.memoize(_.values);
	* values(object);
	* // => [1, 2]
	*
	* values(other);
	* // => [3, 4]
	*
	* object.a = 2;
	* values(object);
	* // => [1, 2]
	*
	* // Modify the result cache.
	* values.cache.set(object, ['a', 'b']);
	* values(object);
	* // => ['a', 'b']
	*
	* // Replace `_.memoize.Cache`.
	* _.memoize.Cache = WeakMap;
	*/
	function memoize(func, resolver) {
		if (typeof func != "function" || resolver && typeof resolver != "function") throw new TypeError(FUNC_ERROR_TEXT);
		var memoized = function() {
			var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
			if (cache.has(key)) return cache.get(key);
			var result = func.apply(this, args);
			memoized.cache = cache.set(key, result);
			return result;
		};
		memoized.cache = new (memoize.Cache || MapCache)();
		return memoized;
	}
	memoize.Cache = MapCache;
	/**
	* Performs a
	* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
	* comparison between two values to determine if they are equivalent.
	*
	* @static
	* @memberOf _
	* @since 4.0.0
	* @category Lang
	* @param {*} value The value to compare.
	* @param {*} other The other value to compare.
	* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
	* @example
	*
	* var object = { 'a': 1 };
	* var other = { 'a': 1 };
	*
	* _.eq(object, object);
	* // => true
	*
	* _.eq(object, other);
	* // => false
	*
	* _.eq('a', 'a');
	* // => true
	*
	* _.eq('a', Object('a'));
	* // => false
	*
	* _.eq(NaN, NaN);
	* // => true
	*/
	function eq(value, other) {
		return value === other || value !== value && other !== other;
	}
	/**
	* Checks if `value` is classified as a `Function` object.
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is a function, else `false`.
	* @example
	*
	* _.isFunction(_);
	* // => true
	*
	* _.isFunction(/abc/);
	* // => false
	*/
	function isFunction(value) {
		var tag = isObject(value) ? objectToString.call(value) : "";
		return tag == funcTag || tag == genTag;
	}
	/**
	* Checks if `value` is the
	* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
	* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
	*
	* @static
	* @memberOf _
	* @since 0.1.0
	* @category Lang
	* @param {*} value The value to check.
	* @returns {boolean} Returns `true` if `value` is an object, else `false`.
	* @example
	*
	* _.isObject({});
	* // => true
	*
	* _.isObject([1, 2, 3]);
	* // => true
	*
	* _.isObject(_.noop);
	* // => true
	*
	* _.isObject(null);
	* // => false
	*/
	function isObject(value) {
		var type = typeof value;
		return !!value && (type == "object" || type == "function");
	}
	module.exports = memoize;
}));
//#endregion
//#region node_modules/@nullplatform/json-keys-transform/src/transform.js
var require_transform = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	const camelCase = require_lodash_camelcase();
	const snakeCase = require_lodash_snakecase();
	const transform = require_lodash_transform();
	const includes = require_lodash_includes();
	const isPlainObject = require_lodash_isplainobject();
	const memoize = require_lodash_memoize();
	/**
	* Enum for specifying key styles.
	* @readonly
	* @enum {Object}
	*/
	const Style = Object.freeze({
		/** Snake case style */
		SNAKE_CASE: {
			name: "SNAKE_CASE",
			resolver: snakeCase
		},
		/** Camel case style */
		CAMEL_CASE: {
			name: "CAMEL_CASE",
			resolver: camelCase
		}
	});
	/**
	* Default options for the transformation.
	* @type {Object}
	* @property {Array<Object>} from - The source styles.
	* @property {Array<Object>} to - The target styles.
	* @property {Array<string>} exclude - The paths to exclude from transformation.
	*/
	const DefaultOptions = {
		from: [Style.CAMEL_CASE, Style.SNAKE_CASE],
		to: [Style.CAMEL_CASE, Style.SNAKE_CASE],
		exclude: []
	};
	/**
	* Validates the options object.
	* @param {Object} options - The options object to validate.
	* @throws {Error} If the options object is invalid.
	*/
	const assertOptions = (options) => {
		if (!options) throw new Error("\"options\" object must be specified");
		const { from, to } = options;
		if (!includes(DefaultOptions.from, from)) throw new Error(`"from" option must be one of this valid "Style" options: ${DefaultOptions.from.map((style) => style.name).join(", ")}`);
		if (!includes(DefaultOptions.to, to)) throw new Error(`"to" option must be one of this valid "Style" options: ${DefaultOptions.to.map((style) => style.name).join(", ")}`);
	};
	/**
	* Checks if a given path matches a specified pattern.
	* @param {string} path - The path to check.
	* @param {string} pattern - The pattern to match against.
	* @returns {boolean} True if the path matches the pattern, false otherwise.
	*/
	const pathMatch = (path, pattern) => {
		const splitAndFilter = (str) => str.split(/[.[\]]/).filter((segment) => segment !== "");
		const pathSegments = splitAndFilter(path);
		const patternSegments = splitAndFilter(pattern);
		if (patternSegments.length !== pathSegments.length) return false;
		for (let i = 0; i < patternSegments.length; i += 1) if (patternSegments[i] !== "*" && patternSegments[i] !== pathSegments[i]) return false;
		return true;
	};
	/**
	* Determines if a path should be excluded based on provided patterns.
	* @param {string} path - The path to check.
	* @param {Array<string>} exclude - The patterns to exclude.
	* @returns {boolean} True if the path should be excluded, false otherwise.
	*/
	const shouldExclude = memoize((path, exclude) => {
		return exclude ? exclude.some((pattern) => pathMatch(path, pattern)) : false;
	}, (path, exclude) => `${path}:${JSON.stringify(exclude)}`);
	/**
	* Processes an object to transform its keys according to specified styles.
	*
	* This function recursively transforms the keys of the provided object based on the given
	* options. It supports transforming keys from snake_case to camelCase and vice versa. It
	* can also exclude specified paths from transformation.
	*
	* @param {Object} object - The object to be transformed.
	* @param {Object} options - Options to customize the transformation.
	* @param {Object} options.from - The style to transform from.
	* @param {Object} options.to - The style to transform to.
	* @param {Array<string>} [options.exclude=[]] - The paths to exclude from transformation.
	* @param {string} [currentPath=''] - The current path being processed (for internal use).
	* @returns {Object} The transformed object.
	* @throws {Error} If a transformed key would overwrite an existing key.
	*
	* @example
	* const { process, Style } = require('path/to/this/module');
	*
	* const obj = { first_name: 'John', last_name: 'Doe' };
	* const transformedObj = process(obj, { from: Style.SNAKE_CASE, to: Style.CAMEL_CASE });
	* console.log(transformedObj); // { firstName: 'John', lastName: 'Doe' }
	*/
	const process = (object, options, currentPath = "") => {
		assertOptions(options);
		const { to: { resolver }, exclude } = options;
		if (!object) return object;
		if (object instanceof Date) return object;
		if (Array.isArray(object)) return object.map((element, index) => process(element, options, `${currentPath}[${index}]`));
		if (isPlainObject(object)) return transform(object, (result, value, key) => {
			const newPath = currentPath ? `${currentPath}.${key}` : key;
			if (shouldExclude(newPath, exclude)) result[key] = value;
			else {
				const newKey = resolver(key);
				if (key !== newKey && newKey in object) throw new Error(`Key \`${newKey}\` would overwrite existing key of the given JSON object`);
				result[newKey] = process(value, options, newPath);
			}
		}, {});
		shouldExclude.cache.clear();
		return object;
	};
	module.exports = {
		/**
		* Processes an object to transform its keys according to specified styles.
		*
		* @function
		* @param {Object} object - The object to be transformed.
		* @param {Object} options - Options to customize the transformation.
		* @returns {Object} The transformed object.
		*/
		process,
		/**
		* Enum for specifying key styles.
		* @enum {Object}
		*/
		Style
	};
}));
//#endregion
//#region src/wire.ts
var import_src = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
	const { process, Style } = require_transform();
	/**
	* Converts the keys of an object from snake_case to camelCase.
	*
	* This function transforms the keys of the provided object from snake_case to camelCase.
	* It uses the `process` function from the 'transform.js' module with predefined styles.
	* Additional options can be provided to override the default behavior.
	*
	* @param {Object} object - The object to be transformed.
	* @param {Object} [options={}] - Additional options to customize the transformation.
	* @param {string} [options.from=Style.SNAKE_CASE] - The style of the keys to transform from.
	* @param {string} [options.to=Style.CAMEL_CASE] - The style of the keys to transform to.
	* @param {Array<string>} [options.exclude=[]] - The paths to exclude from transformation.
	* @returns {Object} The transformed object with camelCase keys.
	*
	* @example
	* const { snakeCaseToCamelCase } = require('@nullplatform/json-keys-transform');
	*
	* const snakeCaseObject = { first_name: 'John', last_name: 'Doe' };
	* const camelCaseObject = snakeCaseToCamelCase(snakeCaseObject);
	* console.log(camelCaseObject); // { firstName: 'John', lastName: 'Doe' }
	*
	* // Example with exclusion
	* const snakeCaseObjectWithNested = { user_info: { first_name: 'John', last_name: 'Doe' } };
	* const camelCaseObjectWithExclusion = snakeCaseToCamelCase(snakeCaseObjectWithNested, { exclude: ['user_info.first_name'] });
	* console.log(camelCaseObjectWithExclusion); // { userInfo: { first_name: 'John', lastName: 'Doe' } }
	*/
	const snakeCaseToCamelCase = (object, options = {}) => {
		const defaultOptions = {
			from: Style.SNAKE_CASE,
			to: Style.CAMEL_CASE
		};
		return process(object, {
			...defaultOptions,
			...options
		});
	};
	/**
	* Converts the keys of an object from camelCase to snake_case.
	*
	* This function transforms the keys of the provided object from camelCase to snake_case.
	* It uses the `process` function from the 'transform.js' module with predefined styles.
	* Additional options can be provided to override the default behavior.
	*
	* @param {Object} object - The object to be transformed.
	* @param {Object} [options={}] - Additional options to customize the transformation.
	* @param {string} [options.from=Style.CAMEL_CASE] - The style of the keys to transform from.
	* @param {string} [options.to=Style.SNAKE_CASE] - The style of the keys to transform to.
	* @param {Array<string>} [options.exclude=[]] - The paths to exclude from transformation.
	* @returns {Object} The transformed object with snake_case keys.
	*
	* @example
	* const { camelCaseToSnakeCase } = require('@nullplatform/json-keys-transform');
	*
	* const camelCaseObject = { firstName: 'John', lastName: 'Doe' };
	* const snakeCaseObject = camelCaseToSnakeCase(camelCaseObject);
	* console.log(snakeCaseObject); // { first_name: 'John', last_name: 'Doe' }
	*
	* // Example with exclusion
	* const camelCaseObjectWithNested = { userInfo: { firstName: 'John', lastName: 'Doe' } };
	* const snakeCaseObjectWithExclusion = camelCaseToSnakeCase(camelCaseObjectWithNested, { exclude: ['userInfo.firstName'] });
	* console.log(snakeCaseObjectWithExclusion); // { user_info: { firstName: 'John', last_name: 'Doe' } }
	*/
	const camelCaseToSnakeCase = (object, options = {}) => {
		const defaultOptions = {
			from: Style.CAMEL_CASE,
			to: Style.SNAKE_CASE
		};
		return process(object, {
			...defaultOptions,
			...options
		});
	};
	module.exports = {
		/**
		* Processes an object to transform its keys according to specified styles.
		*
		* @function
		* @param {Object} object - The object to be transformed.
		* @param {Object} options - Options to customize the transformation.
		* @param {Array<string>} [options.exclude=[]] - The paths to exclude from transformation.
		* @returns {Object} The transformed object.
		*/
		transform: process,
		/**
		* Converts the keys of an object from snake_case to camelCase.
		* @function
		* @param {Object} object - The object to be transformed.
		* @param {Object} [options={}] - Additional options to customize the transformation.
		* @param {Array<string>} [options.exclude=[]] - The paths to exclude from transformation.
		* @returns {Object} The transformed object with camelCase keys.
		*/
		snakeCaseToCamelCase,
		/**
		* Converts the keys of an object from camelCase to snake_case.
		* @function
		* @param {Object} object - The object to be transformed.
		* @param {Object} [options={}] - Additional options to customize the transformation.
		* @param {Array<string>} [options.exclude=[]] - The paths to exclude from transformation.
		* @returns {Object} The transformed object with snake_case keys.
		*/
		camelCaseToSnakeCase,
		/**
		* Enum for specifying key styles.
		* @enum {Object}
		*/
		Style
	};
})))();
/** A request body as the API reads it. */
const toWire = (body, exclude = []) => (0, import_src.camelCaseToSnakeCase)(body, { exclude });
/** A response as the SDK answers it. */
const fromWire = (body, exclude = []) => (0, import_src.snakeCaseToCamelCase)(body, { exclude });
/** A query key as the API reads it. */
const wireKey = (key) => import_src.Style.SNAKE_CASE.resolver(key);
/** A `sort` value (`createdAt:desc,slug`) with its field names as the API reads them. */
const wireSort = (sort) => sort.split(",").map((part) => {
	const [field, order] = part.split(":");
	return [wireKey(field.trim()), order].filter(Boolean).join(":");
}).join(",");
//#endregion
//#region src/inputs.ts
/** Fill in a missing `id` and `observedAt`; refuse an `id` that is not a UUIDv7. */
function prepareInput(spec) {
	if (spec.id !== void 0 && !require_types.isUuidV7(spec.id)) throw new TypeError(`input id ${JSON.stringify(spec.id)} is not a UUIDv7: the API requires a UUIDv7 per input (omit id to have one generated, or create it with uuidv7())`);
	return {
		id: spec.id ?? require_types.uuidv7(),
		...spec.runId !== void 0 ? { runId: spec.runId } : {},
		type: spec.type,
		...spec.op !== void 0 ? { op: spec.op } : {},
		observedAt: spec.observedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
		payload: spec.payload
	};
}
/**
* An input as `POST /sources/{sourceId}/inputs` takes it under `data`: built
* from the known fields only.
*/
function inputOf(spec) {
	const { id, runId, type, op, observedAt, payload } = prepareInput(spec);
	return {
		id,
		...runId !== void 0 ? { runId } : {},
		type,
		...op !== void 0 ? { op } : {},
		observedAt,
		payload
	};
}
//#endregion
//#region src/batcher.ts
/**
* Buffers inputs and ships them in batches bounded by count and by encoded
* size, so a collector can `add()` records as it enumerates them and never
* think about the API's limits. Every input gets a UUIDv7 id (idempotency;
* a given id is validated) and an `observedAt` (ordering) before it is
* buffered, so a retried batch is harmless and a late batch cannot reorder
* changes.
*
* A batch that fails for good (refused, or still failing after the
* transport's retries) stops the batcher: every later `add`, `flush` and
* `close` throws that failure. For a snapshot this is the safety: a run that
* lost a batch can never be finalized, so it can never delete what the lost
* batch carried.
*/
const encoder = new TextEncoder();
/** An input's size as the API receives it (its wire form, its payload as it is), plus its separator. */
const sizeOf = (input) => encoder.encode(JSON.stringify(toWire(input, ["payload"]))).length + 1;
/** The request around a batch (`{"data":[…]}`): counted against `maxBytes` too. */
const ENVELOPE_BYTES = encoder.encode("{\"data\":[]}").length;
/** The most inputs the API takes in one request. */
const MAX_BATCH = 500;
/**
* Refuses batching options a batcher cannot honour: no worker (`concurrency`
* below 1) would send nothing and still resolve, so a run would finalize as if
* its records had been delivered.
* @throws {RangeError} For an option out of range.
*/
function checkBatching(options) {
	const { maxBatch, maxBytes, flushIntervalMs, concurrency } = options;
	if (!Number.isInteger(maxBatch) || maxBatch < 1 || maxBatch > MAX_BATCH) throw new RangeError(`batching.maxBatch must be an integer in 1–${MAX_BATCH}, got ${maxBatch}`);
	if (!Number.isInteger(maxBytes) || maxBytes <= ENVELOPE_BYTES) throw new RangeError(`batching.maxBytes must be an integer above ${ENVELOPE_BYTES}, got ${maxBytes}`);
	if (!Number.isFinite(flushIntervalMs) || flushIntervalMs < 0) throw new RangeError(`batching.flushIntervalMs must be 0 or more, got ${flushIntervalMs}`);
	if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError(`batching.concurrency must be an integer of 1 or more, got ${concurrency}`);
}
/** The batching behind run handles and event batchers (see the module comment). */
var Batcher = class {
	#options;
	#send;
	/** What the sender adds to every input (a run handle's `runId`): sized with it. */
	#stamp;
	/** The bytes a batch's inputs may take: `maxBytes` less the request around them. */
	#maxInputBytes;
	#buffer = [];
	#bufferedBytes = 0;
	#timer = null;
	#inFlight = null;
	#closed = false;
	#failure = null;
	/** What it buffered, sent and had accepted so far. */
	stats = {
		buffered: 0,
		sent: 0,
		accepted: 0,
		duplicates: 0
	};
	/**
	* @param options Batch bounds, timer and concurrency.
	* @param send Sends one batch (the inputs are prepared: id and observation time set).
	* @param stamp What `send` adds to every input, counted in its size.
	* @throws {RangeError} For batching options out of range (see `checkBatching`).
	*/
	constructor(options, send, stamp = {}) {
		checkBatching(options);
		this.#options = options;
		this.#send = send;
		this.#stamp = stamp;
		this.#maxInputBytes = options.maxBytes - ENVELOPE_BYTES;
	}
	/** The failure that stopped this batcher, if one did. */
	get failure() {
		return this.#failure;
	}
	/** Buffer one input; returns its id. Flushes when a limit is reached. */
	add(input) {
		if (this.#failure) throw this.#failure;
		if (this.#closed) throw new Error("this batcher is closed");
		const prepared = prepareInput({
			...input,
			...this.#stamp
		});
		const bytes = sizeOf(prepared);
		if (bytes > this.#maxInputBytes) throw new RangeError(`input ${prepared.id} (${prepared.type}) encodes to ${bytes} bytes, above the ${this.#options.maxBytes}-byte batch limit`);
		if (this.#buffer.length > 0 && this.#bufferedBytes + bytes > this.#maxInputBytes) this.#flushInBackground();
		this.#buffer.push({
			input: prepared,
			bytes
		});
		this.#bufferedBytes += bytes;
		this.stats.buffered = this.#buffer.length;
		if (this.#buffer.length >= this.#options.maxBatch) this.#flushInBackground();
		else this.#arm();
		return prepared.id;
	}
	/** Send everything buffered so far; resolves when it has been accepted. */
	async flush() {
		if (this.#timer) {
			clearTimeout(this.#timer);
			this.#timer = null;
		}
		const batches = this.#drain();
		const ship = async () => {
			if (this.#failure || batches.length === 0) return;
			try {
				await this.#ship(batches);
			} catch (error) {
				this.#failure ??= error;
			}
		};
		const current = (this.#inFlight ?? Promise.resolve()).then(ship);
		this.#inFlight = current;
		await current;
		if (this.#inFlight === current) this.#inFlight = null;
		if (this.#failure) throw this.#failure;
	}
	/** Flush and refuse further inputs. */
	async close() {
		this.#closed = true;
		await this.flush();
	}
	/** The failure is kept and surfaces on the next add, flush or close. */
	#flushInBackground() {
		this.flush().catch(() => void 0);
	}
	#arm() {
		if (this.#options.flushIntervalMs > 0 && !this.#timer) {
			this.#timer = setTimeout(() => {
				this.#timer = null;
				this.#flushInBackground();
			}, this.#options.flushIntervalMs);
			if (typeof this.#timer === "object" && "unref" in this.#timer) this.#timer.unref();
		}
	}
	#drain() {
		const batches = [];
		let current = [];
		let bytes = 0;
		this.#buffer.forEach((entry) => {
			if (current.length >= this.#options.maxBatch || current.length > 0 && bytes + entry.bytes > this.#maxInputBytes) {
				batches.push(current);
				current = [];
				bytes = 0;
			}
			current.push(entry.input);
			bytes += entry.bytes;
		});
		if (current.length) batches.push(current);
		this.#buffer = [];
		this.#bufferedBytes = 0;
		this.stats.buffered = 0;
		return batches;
	}
	async #ship(batches) {
		const queue = [...batches];
		let failed = false;
		const worker = async () => {
			const batch = failed ? void 0 : queue.shift();
			if (!batch) return;
			try {
				const accepted = await this.#send(batch);
				this.stats.sent += batch.length;
				this.stats.accepted += accepted.accepted;
				this.stats.duplicates += accepted.duplicates;
			} catch (error) {
				failed = true;
				throw error;
			}
			await worker();
		};
		await Promise.all(Array.from({ length: Math.min(this.#options.concurrency, queue.length) }, worker));
	}
};
//#endregion
//#region src/event-batcher.ts
/**
* Events of one source, from `IngestClient.events.batcher`: buffered and sent
* in batches by count, bytes and time. `close` it on shutdown.
*/
var EventBatcher = class {
	#batcher;
	/** Made by `IngestClient.events.batcher`; not meant to be built by hand. */
	constructor(send, batching) {
		this.#batcher = new Batcher(batching, send);
	}
	/** What the batcher buffered, sent and had accepted so far. */
	get stats() {
		return this.#batcher.stats;
	}
	/**
	* Buffer an upsert of an entity's state.
	* @param options `observedAt` (when the state was observed; now by default) and `id` (a UUIDv7).
	* @returns Its input id.
	* @throws {TypeError} For an id that is not a UUIDv7.
	*/
	upsert(type, payload, options = {}) {
		return this.#batcher.add({
			...options,
			type,
			op: "upsert",
			payload
		});
	}
	/**
	* Buffer a delete: the entity the payload maps to is deleted (only one this source owns).
	* @param options `observedAt` (when it was deleted; now by default) and `id` (a UUIDv7).
	* @returns Its input id.
	* @throws {TypeError} For an id that is not a UUIDv7.
	*/
	delete(type, payload, options = {}) {
		return this.#batcher.add({
			...options,
			type,
			op: "delete",
			payload
		});
	}
	/** Send what is buffered now (events are otherwise sent about every second). */
	flush() {
		return this.#batcher.flush();
	}
	/** Send what is buffered and refuse further events. Call it on shutdown. */
	close() {
		return this.#batcher.close();
	}
};
//#endregion
//#region src/ingest-error.ts
/**
* The error codes the API answers with (`IngestError.code`), by status:
* 400 VALIDATION (including an undeclared body property), 401 AUTHENTICATION,
* 403 AUTHORIZATION, 404 NOT_FOUND, 409 CONFLICT, 429 TOO_MANY_REQUESTS
* (with Retry-After), 502 TARGET_REJECTED (a target refused what the API
* asked it on the call's behalf) and 503 SERVICE_UNAVAILABLE.
*/
let IngestErrorCode = /* @__PURE__ */ function(IngestErrorCode) {
	IngestErrorCode["VALIDATION"] = "FST_ERR_VALIDATION";
	IngestErrorCode["AUTHENTICATION"] = "FST_ERR_AUTHENTICATION";
	IngestErrorCode["AUTHORIZATION"] = "FST_ERR_AUTHORIZATION";
	IngestErrorCode["NOT_FOUND"] = "FST_ERR_NOT_FOUND";
	IngestErrorCode["CONFLICT"] = "FST_ERR_CONFLICT";
	IngestErrorCode["TOO_MANY_REQUESTS"] = "FST_ERR_TOO_MANY_REQUESTS";
	IngestErrorCode["TARGET_REJECTED"] = "FST_ERR_TARGET_REJECTED";
	IngestErrorCode["SERVICE_UNAVAILABLE"] = "FST_ERR_SERVICE_UNAVAILABLE";
	return IngestErrorCode;
}({});
/**
* A request the API refused, or could not be reached for. Thrown by every
* client call, and kept by a batcher whose batch failed for good.
*/
var IngestError = class extends Error {
	/** HTTP status; 0 when the API could not be reached. */
	status;
	/** The API's error code (see `IngestErrorCode`), when the response carried one. */
	code;
	/** The response body, parsed when it was JSON. */
	body;
	/**
	* @param status HTTP status; 0 when the API could not be reached.
	* @param message The API's message, or why it could not be reached.
	* @param code The API's error code.
	* @param body The response body.
	*/
	constructor(status, message, code, body) {
		super(message);
		this.name = "IngestError";
		this.status = status;
		this.code = code;
		this.body = body;
	}
	/**
	* True for the failures the SDK retries on its own: unreachable (0), 429 and
	* 5xx (503 included). When one reaches you, the retries (or the backpressure
	* budget) ran out. Every other 4xx — 403 included — is deterministic.
	*/
	get retryable() {
		return this.status === 0 || this.status === 429 || this.status >= 500;
	}
};
//#endregion
//#region src/must-exist.ts
/** A read that must find what it reads: a wait cannot wait on what is not there. */
/**
* What a read answered; a 404 when it answered none (`get` answers `null`
* for a resource that does not exist).
* @throws {IngestError} 404 when the resource does not exist.
*/
async function mustExist(read, what) {
	const found = await read;
	if (found === null) throw new IngestError(404, `${what} does not exist`, "FST_ERR_NOT_FOUND");
	return found;
}
//#endregion
//#region src/http.ts
/**
* Small HTTP helpers shared by the transport and the wait helpers. Internal —
* not part of the package's public surface.
*/
/** Retry-After as milliseconds (delta-seconds or an HTTP date); null when absent or unreadable. */
function retryAfterMs(header, now = Date.now()) {
	if (!header) return null;
	const seconds = Number(header);
	if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
	const at = Date.parse(header);
	return Number.isNaN(at) ? null : Math.max(0, at - now);
}
const sleep = (ms) => new Promise((resolve) => {
	setTimeout(resolve, ms);
});
/** Parse JSON, returning the raw text unchanged when it isn't valid JSON (and null when empty). */
const safeJson = (text) => {
	if (!text) return null;
	try {
		return JSON.parse(text);
	} catch {
		return text;
	}
};
//#endregion
//#region src/timeout-error.ts
/** A wait helper gave up before the API reached the awaited state. */
var TimeoutError = class extends Error {
	constructor(message) {
		super(message);
		this.name = "TimeoutError";
	}
};
//#endregion
//#region src/poll.ts
/**
* Polling for the wait helpers: the API applies inputs asynchronously, so a
* collector that needs the outcome reads until the awaited state is reached.
*/
async function poll(read, done, what, options) {
	const deadline = Date.now() + (options.timeoutMs ?? 6e5);
	const interval = options.intervalMs ?? 500;
	const step = async () => {
		const value = await read();
		if (done(value)) return value;
		if (Date.now() > deadline) throw new TimeoutError(`timed out waiting for ${what}`);
		await sleep(interval);
		return step();
	};
	return step();
}
//#endregion
//#region src/run-handle.ts
/**
* A snapshot run in progress: `add()` the records of the snapshot as you
* enumerate them, then `finalize()`. The handle batches the records and keeps
* a lost batch sticky (see `Batcher`), so a run that lost records can never be
* finalized into deleting what they carried.
*/
/**
* A run in progress, from `IngestClient.runs.open`. `add` every record of the
* listing, then `finalize`; on any failure `abort` (it deletes nothing).
*
* @example
* const run = await ingest.runs.open(source.id, { onConflict: OnConflict.ABORT });
* try {
*   items.forEach((item) => run.add({ type: 'deployment', observedAt, payload: item }));
*   const done = await run.finalize();
* } catch (error) {
*   await run.abort();
*   throw error;
* }
*/
var RunHandle = class {
	#runs;
	#batcher;
	#run;
	/** Made by `IngestClient.runs.open`; not meant to be built by hand. */
	constructor(runs, run, batching) {
		this.#runs = runs;
		this.#run = run;
		this.#batcher = new Batcher(batching, (batch) => runs.sendRecords(run.sourceId, run.id, batch), { runId: run.id });
	}
	/** The run's id. */
	get id() {
		return this.#run.id;
	}
	/** The id of the source the run belongs to. */
	get sourceId() {
		return this.#run.sourceId;
	}
	/** The run as last read from the API. */
	get run() {
		return this.#run;
	}
	/** What the handle buffered, sent and had accepted so far. */
	get stats() {
		return this.#batcher.stats;
	}
	/**
	* Buffer one record of the listing; it is sent in a batch.
	* @returns Its input id: the given UUIDv7, or a generated one.
	* @throws {TypeError} For an id that is not a UUIDv7.
	* @throws {IngestError} The failure of an earlier batch: the run can no longer be finalized.
	*/
	add(record) {
		return this.#batcher.add(record);
	}
	/**
	* Send what is buffered now (records are otherwise sent as batches fill).
	* @throws {IngestError} When a batch fails for good; the run can no longer be finalized.
	*/
	flush() {
		return this.#batcher.flush();
	}
	/** Read the run again from the API; {@link RunHandle.run} answers it after. */
	async refresh() {
		this.#run = await mustExist(this.#runs.get(this.id), `run '${this.id}'`);
		return this.#run;
	}
	/**
	* Send what is buffered and wait until every record of the run is applied.
	* @throws {TimeoutError} When it is not within `options.timeoutMs`.
	*/
	async waitApplied(options = {}) {
		await this.flush();
		this.#run = await this.#runs.waitApplied(this.id, options);
		return this.#run;
	}
	/**
	* Send what is buffered, finalize, and wait until the run is closed (or,
	* for a dry run, assessed: it stays open).
	* @param options Guard overrides for this run, and `dryRun`.
	* @param wait How long to wait for it.
	* @returns The run: `status` is `RunStatus.COMPLETED` or `RunStatus.GUARD_TRIPPED`
	*   (nothing deleted), and `reconciliation` says what was seen, stale and deleted.
	* @throws {IngestError} When a batch failed: the run cannot be finalized; abort it.
	*/
	async finalize(options = {}, wait = {}) {
		await (options.dryRun ? this.#batcher.flush() : this.#batcher.close());
		await this.#runs.finalize(this.id, options);
		this.#run = options.dryRun ? await this.#runs.waitDryRun(this.id, wait) : await this.#runs.waitClosed(this.id, wait);
		return this.#run;
	}
	/** Close the run without reconciling: nothing is deleted. Call it on any failure. */
	async abort() {
		await this.#batcher.close().catch(() => void 0);
		this.#run = await this.#runs.abort(this.id);
		return this.#run;
	}
};
//#endregion
//#region src/tokens/api-key-token.ts
/**
* A nullplatform API key exchanged for a token (`POST {authBaseURL}/token`),
* cached, and refreshed with the refresh token shortly before it expires.
* Concurrent callers share one exchange.
*/
/** Lifetime assumed when the token response states none. */
const DEFAULT_LIFETIME_MS = 9e5;
/** A token from a nullplatform API key: exchanged, cached and refreshed before it expires. */
var ApiKeyToken = class {
	#options;
	#token = null;
	#expiresAt = 0;
	#inFlight = null;
	/** @param options The API key, where it is exchanged, and how. */
	constructor(options) {
		this.#options = {
			expiryBufferMs: 6e4,
			...options
		};
	}
	/**
	* The current token: the cached one while it is fresh, otherwise a new one
	* (refreshed, or exchanged from the key again when the refresh is refused).
	* @throws {IngestError} When the exchange fails.
	*/
	async get() {
		if (this.#token && Date.now() < this.#expiresAt - this.#options.expiryBufferMs) return this.#token.access_token;
		if (!this.#inFlight) this.#inFlight = this.#exchange().finally(() => {
			this.#inFlight = null;
		});
		return this.#inFlight;
	}
	/** Drop the cached token (after a 401): the next `get` exchanges the key again. */
	invalidate() {
		this.#token = null;
		this.#expiresAt = 0;
	}
	async #exchange() {
		const refresh = this.#token?.refresh_token;
		const body = refresh ? {
			refresh_token: refresh,
			organization_id: this.#token?.organization_id,
			account_id: this.#token?.account_id
		} : { apikey: this.#options.apiKey };
		let response;
		try {
			response = await this.#options.fetchImpl(`${this.#options.authBaseURL.replace(/\/+$/, "")}/token`, {
				method: "POST",
				headers: {
					"content-type": "application/json",
					accept: "application/json"
				},
				body: JSON.stringify(body),
				signal: AbortSignal.timeout(this.#options.timeoutMs)
			});
		} catch (error) {
			throw new IngestError(0, `token exchange failed: ${error instanceof Error ? error.message : String(error)}`);
		}
		if (!response.ok) {
			if (refresh) {
				this.#token = null;
				return this.#exchange();
			}
			throw new IngestError(response.status, `token exchange failed: ${response.status}`);
		}
		let token;
		try {
			token = await response.json();
		} catch (error) {
			throw new IngestError(0, `token exchange failed: ${error instanceof Error ? error.message : String(error)}`);
		}
		this.#token = token;
		if (typeof token.token_expires_at === "number") this.#expiresAt = token.token_expires_at < 0xe8d4a51000 ? token.token_expires_at * 1e3 : token.token_expires_at;
		else if (typeof token.expires_in === "number") this.#expiresAt = Date.now() + token.expires_in * 1e3;
		else this.#expiresAt = Date.now() + DEFAULT_LIFETIME_MS;
		return token.access_token;
	}
};
//#endregion
//#region src/tokens/token-provider.ts
/** Strip an optional `Bearer ` prefix. */
const bareToken = (token) => token.replace(/^Bearer\s+/i, "");
//#endregion
//#region src/tokens/callback-token.ts
/** Your own way to get a token: called once, then again after a 401. */
var CallbackToken = class {
	#getToken;
	#cached = null;
	/** @param getToken Answers a bearer token, with or without `Bearer `. */
	constructor(getToken) {
		this.#getToken = getToken;
	}
	/** The token `getToken` answered, cached until invalidated. */
	async get() {
		if (this.#cached === null) this.#cached = bareToken(await this.#getToken());
		return this.#cached;
	}
	/** Drop the cached token (after a 401): the next `get` calls `getToken` again. */
	invalidate() {
		this.#cached = null;
	}
};
//#endregion
//#region src/tokens/static-token.ts
/** A ready token. Nothing to refresh: a 401 surfaces to the caller. */
var StaticToken = class {
	#token;
	/** A static token never changes: a 401 is not tried again. */
	refreshable = false;
	/** @param token A bearer token, with or without `Bearer `. */
	constructor(token) {
		this.#token = bareToken(token);
	}
	/** The token as given (without `Bearer `). */
	async get() {
		return this.#token;
	}
	/** Nothing to do: a static token cannot be refreshed. */
	invalidate() {}
};
//#endregion
//#region src/pages.ts
/** The page size the idempotent calls read with: the API's largest. */
const EVERY_PAGE_LIMIT = 1e3;
/** How many values one filter takes in one request (`recordType: ['pod', 'node']`): the API's most. */
const MAX_FILTER_VALUES = 100;
/**
* Every item of a list, read a page at a time until a page comes back short:
* an upsert that saw only the first page would create a duplicate of what is
* on the next.
*/
async function everyPage(read, offset = 0) {
	const { results } = await read({
		limit: EVERY_PAGE_LIMIT,
		offset
	});
	return results.length < 1e3 ? results : [...results, ...await everyPage(read, offset + EVERY_PAGE_LIMIT)];
}
/**
* Every item of a list filtered by any of `values`, each once: every page of
* one request per `MAX_FILTER_VALUES` of them, read together. No values, no
* request: a filter of none matches nothing.
*/
async function everyPageFor(values, read) {
	const distinct = [...new Set(values)];
	const parts = Array.from({ length: Math.ceil(distinct.length / 100) }, (_, index) => distinct.slice(index * 100, (index + 1) * 100));
	return (await Promise.all(parts.map((part) => everyPage((page) => read(part, page))))).flat();
}
//#endregion
//#region src/transport.ts
/**
* HTTP transport: JSON in and out, a bearer from the token provider, retries
* with full-jitter backoff on 5xx and network errors (a POST only when it is
* idempotent: a retried create could create twice), one token refresh on 401
* when the provider can refresh, and backpressure on 429 (wait as Retry-After
* says, without spending a retry). Any other 4xx is never retried. Getting
* the token is retried like the request. Internal — `IngestClient` is the
* public surface.
*/
/** Longest single wait on one 429, whatever Retry-After says. */
const MAX_BACKPRESSURE_WAIT_MS = 6e4;
function describe(status, body) {
	if (body && typeof body === "object") {
		const error = body;
		return {
			message: error.message ?? `the ingest API responded ${status}`,
			code: error.code
		};
	}
	return { message: `the ingest API responded ${status}` };
}
var Transport = class {
	#options;
	constructor(options) {
		this.#options = {
			...options,
			baseURL: options.baseURL.replace(/\/+$/, "")
		};
	}
	async request(options) {
		const backpressureUntil = Date.now() + this.#options.backpressureMs;
		const retries = options.method !== "POST" || options.idempotent === true;
		const attempt = async (retry, refreshed) => {
			let token;
			try {
				token = await this.#options.tokens.get();
			} catch (error) {
				if (error instanceof IngestError && error.retryable && retry < this.#options.maxRetries) {
					await sleep(this.#backoff(retry));
					return attempt(retry + 1, refreshed);
				}
				throw error;
			}
			let response;
			let text;
			try {
				response = await this.#options.fetchImpl(this.#url(options), {
					method: options.method,
					headers: {
						...options.headers,
						authorization: `Bearer ${token}`,
						accept: "application/json",
						...options.body !== void 0 ? { "content-type": "application/json" } : {}
					},
					body: options.body !== void 0 ? JSON.stringify(toWire(options.body, options.exclude?.request)) : void 0,
					signal: AbortSignal.timeout(this.#options.timeoutMs)
				});
				text = await response.text();
			} catch (error) {
				const failure = new IngestError(0, `the ingest API is unreachable: ${error instanceof Error ? error.message : String(error)}`);
				if (retries && retry < this.#options.maxRetries) {
					await sleep(this.#backoff(retry));
					return attempt(retry + 1, refreshed);
				}
				throw failure;
			}
			const body = safeJson(text);
			if (response.ok) return fromWire(body, options.exclude?.response);
			if (options.tolerate?.includes(response.status)) return null;
			if (response.status === 401 && !refreshed && this.#options.tokens.refreshable !== false) {
				this.#options.tokens.invalidate();
				return attempt(retry, true);
			}
			const { message, code } = describe(response.status, body);
			const failure = new IngestError(response.status, message, code, body);
			if (response.status === 429) {
				const wait = Math.min(retryAfterMs(response.headers.get("retry-after")) ?? this.#backoff(retry), MAX_BACKPRESSURE_WAIT_MS);
				if (Date.now() + wait <= backpressureUntil) {
					await sleep(wait);
					return attempt(retry, refreshed);
				}
				throw failure;
			}
			if (retries && failure.retryable && retry < this.#options.maxRetries) {
				await sleep(this.#backoff(retry));
				return attempt(retry + 1, refreshed);
			}
			throw failure;
		};
		return attempt(0, false);
	}
	#url(options) {
		const url = new URL(`${this.#options.baseURL}${options.path}`);
		Object.entries(options.query ?? {}).forEach(([key, value]) => {
			if (value !== void 0) {
				const text = String(value);
				url.searchParams.set(wireKey(key), key === "sort" ? wireSort(text) : text);
			}
		});
		return url.toString();
	}
	/** Full jitter: uniform in [0, min(max, base · 2^retry)). */
	#backoff(retry) {
		const cap = Math.min(this.#options.retryMaxMs, this.#options.retryBaseMs * 2 ** retry);
		return Math.floor(Math.random() * cap);
	}
};
//#endregion
//#region src/client.ts
/** Where API keys are exchanged for tokens unless `authBaseURL` says otherwise. */
const DEFAULT_AUTH_BASE_URL = "https://api.nullplatform.com";
/** The public ingest API, unless `baseURL` says otherwise. */
const DEFAULT_BASE_URL = `${DEFAULT_AUTH_BASE_URL}/catalog/ingest`;
const TERMINAL_RUN = [
	"completed",
	"guard_tripped",
	"aborted"
];
const TERMINAL_INPUT = [
	"applied",
	"rejected",
	"dropped",
	"dead"
];
const DEFAULT_BATCHING = {
	maxBatch: 500,
	maxBytes: 6291456,
	flushIntervalMs: 1e3,
	concurrency: 2
};
function tokenProvider(options, fetchImpl, timeoutMs) {
	if ([
		options.apiKey,
		options.token,
		options.getToken
	].filter(Boolean).length !== 1) throw new Error("exactly one of apiKey, token or getToken is required");
	if (options.apiKey) return new ApiKeyToken({
		apiKey: options.apiKey,
		authBaseURL: options.authBaseURL ?? "https://api.nullplatform.com",
		fetchImpl,
		timeoutMs
	});
	if (options.token) return new StaticToken(options.token);
	return new CallbackToken(options.getToken);
}
/**
* What each call leaves as it is: the caller's own content, at the paths the
* API leaves out of its key renaming on that route. Keep each in step with
* its route.
*/
const CONTENT = {
	/** `POST /sources`, `PATCH /sources/{id}`, `GET /sources/{id}`. */
	source: {
		request: ["attributes"],
		response: ["attributes"]
	},
	/** `GET /sources`. */
	sources: { response: ["results[*].attributes"] },
	/** `GET /sources/{id}/revisions`: the source as each write left it, under `snapshot`. */
	sourceRevisions: { response: ["results[*].snapshot.attributes"] },
	/** `POST /sources/{id}/inputs`. */
	inputs: { request: ["data[*].payload"] },
	/** `GET /inputs/{id}`. */
	input: { response: ["payload"] },
	/** `POST /mapping_previews`: the sample as sent, and what the engine made as it made it. */
	mappingPreview: {
		request: ["sample.payload"],
		response: [
			"sample.payload",
			"output",
			"entities"
		]
	},
	/**
	* `GET /targets/{id}/endpoints/{id}`: the backend's own content in an
	* endpoint document (what the API leaves as the backend wrote it).
	*/
	endpoint: { response: [
		"model.schema",
		"model.parents",
		"model.relations",
		"fields",
		"calls.*.query",
		"calls.*.body",
		"behavior.gone.in"
	] },
	/** `GET /sources/{id}/entities`. */
	entities: { response: ["results[*].data", "results[*].links"] },
	/** `GET /entities/{id}`. */
	entity: { response: [
		"data",
		"links",
		"payload"
	] }
};
const segment = encodeURIComponent;
/**
* A list query: the filters as given, and the page checked client-side so a
* bad value fails here with a clear message instead of as a 400.
*/
function listQuery(query = {}) {
	const { limit, offset } = query;
	if (limit !== void 0 && !(Number.isInteger(limit) && limit >= 1)) throw new RangeError(`limit must be a positive integer, got ${String(limit)}`);
	if (offset !== void 0 && !(Number.isInteger(offset) && offset >= 0)) throw new RangeError(`offset must be a non-negative integer, got ${String(offset)}`);
	return Object.fromEntries(Object.entries(query).map(([key, value]) => [key, Array.isArray(value) ? value.join(",") : value]));
}
/** `?dry_run=true` when asked: the write is checked as it would be made, and not made. */
function dryRunQuery({ dryRun }) {
	return dryRun ? { dryRun: "true" } : {};
}
/** A resource as an upsert answers it: with what it did. */
const upserted = (resource, outcome) => ({
	...resource,
	upserted: outcome
});
/**
* The owner's destinations of the mappings `specs` name, every page: the ones
* named by slug queried by slug, the ones by id by id (the API takes one of
* the two per request), each destination once.
*/
async function destinationsOfMappings(specs, list) {
	const slugs = specs.flatMap((spec) => spec.mapping === void 0 ? [] : [spec.mapping]);
	const ids = specs.flatMap((spec) => spec.mappingId === void 0 ? [] : [spec.mappingId]);
	const [bySlug, byId] = await Promise.all([everyPageFor(slugs, (mapping, page) => list({
		mapping,
		...page
	})), everyPageFor(ids, (mappingId, page) => list({
		mappingId,
		...page
	}))]);
	return [...new Map([...bySlug, ...byId].map((destination) => [destination.id, destination])).values()];
}
/**
* Refuses, before anything is sent, specs that name one resource twice: an
* upsert would write it twice, and which one wins would be a race.
*/
function uniqueKeys(specs, keyOf, what) {
	const keys = specs.map(keyOf);
	const repeated = keys.find((key, index) => keys.indexOf(key) !== index);
	if (repeated !== void 0) throw new Error(`two specs name the ${what} '${repeated}': name each once`);
}
/**
* Runs an upsert once more when one of its creates answers 409: another
* writer created that resource between the read and the write, and a second
* read finds it. A create is never retried on its own (it is not idempotent).
*/
async function rereadOnConflict(upsert) {
	try {
		return await upsert();
	} catch (error) {
		if (error instanceof IngestError && error.status === 409) return upsert();
		throw error;
	}
}
/** A mapping's slug as a create names it: the record type by default. */
const slugOf = (spec) => spec.slug ?? spec.recordType;
/** What names a destination under its owner: its mapping, target and endpoint (each by slug or by id). */
const destinationKeyOf = (spec) => `${spec.mapping ?? spec.mappingId}:${spec.target ?? spec.targetId}:${spec.endpoint ?? spec.endpointId}`;
/** Whether a destination is the one a spec names: its mapping, and its target and endpoint as the spec names them. */
const isNamedBy = (destination, spec) => (spec.mappingId === void 0 ? destination.mapping === spec.mapping : destination.mappingId === spec.mappingId) && (spec.targetId === void 0 ? destination.target === spec.target : destination.targetId === spec.targetId) && (spec.endpointId === void 0 ? destination.endpoint === spec.endpoint : destination.endpointId === spec.endpointId);
/** JSON with its object keys sorted: equal for equal documents, whatever their key order. */
function canonicalJson(value) {
	if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
	if (value !== null && typeof value === "object") return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
	return JSON.stringify(value);
}
/** Whether two JSON documents are equal. */
const sameJson = (left, right) => canonicalJson(left) === canonicalJson(right);
/** Whether two run settings are equal: a list (`unguardedTypes`) as a set, in any order. */
const sameSetting = (left, right) => Array.isArray(left) && Array.isArray(right) ? sameJson([...left].sort(), [...right].sort()) : left === right;
/**
* The run settings `wanted` names that differ from `current` (what applies to
* the type or the source); `undefined` when none do. A setting that already
* applies, its type's included, is not written again.
*/
function changedRuns(current, wanted) {
	const runs = Object.fromEntries(Object.entries(wanted ?? {}).filter(([setting, value]) => !sameSetting(current[setting], value)));
	return Object.keys(runs).length ? runs : void 0;
}
/** Whether a mapping's definition differs from what is wanted. */
const differs = (current, wanted) => current.engine !== wanted.engine || current.expression !== wanted.expression;
/**
* The client of the nullplatform ingest API. Create one per process and share
* it: it holds the token, the transport (retries, backpressure) and the
* batching defaults. Every resource is a namespace (`sources`, `sourceTypes`, `mappings`, `mappingPreviews`, `destinations`, `targets`, `endpoints`, `runs`, `events`, `inputs`, `replays`, `entities`, `driftChecks`); a resource that belongs to a source or to a
* source type is listed and created under it (`listForSource`, `listForSourceType`)
* and read, changed and deleted by its own id.
*
* @example
* const ingest = new IngestClient({ apiKey: process.env.NULLPLATFORM_API_KEY });
* const [source] = await ingest.sources.upsert([{ slug: 'prod-eu', name: 'Production EU', type: 'kubernetes' }]);
*/
var IngestClient = class {
	#transport;
	#batching;
	/** Where the bearer of every request comes from (the API key's exchange, a token, or yours). */
	tokens;
	/**
	* @param options Exactly one of `apiKey`, `token` or `getToken`; everything
	*   else has a default (the public API, 30 s timeouts, 4 retries).
	* @throws {Error} When not exactly one of `apiKey`, `token`, `getToken` is given.
	*/
	constructor(options) {
		const fetchImpl = options.fetchImpl ?? globalThis.fetch;
		const timeoutMs = options.timeoutMs ?? 3e4;
		this.tokens = tokenProvider(options, fetchImpl, timeoutMs);
		this.#transport = new Transport({
			baseURL: options.baseURL ?? DEFAULT_BASE_URL,
			tokens: this.tokens,
			fetchImpl,
			timeoutMs,
			maxRetries: options.maxRetries ?? 4,
			retryBaseMs: options.retryBaseMs ?? 250,
			retryMaxMs: options.retryMaxMs ?? 1e4,
			backpressureMs: options.backpressureMs ?? 9e5
		});
		this.#batching = {
			...DEFAULT_BATCHING,
			...options.batching
		};
		checkBatching(this.#batching);
	}
	/** Sources: one system of record each (a cluster, an account), the unit of ownership. */
	sources = {
		/**
		* Create a source. Creating a deleted slug revives it under the same id.
		* Prefer {@link IngestClient.sources.upsert} in a collector.
		* @param spec Its slug (unique in the organization), name and type; optionally its NRN,
		*   attributes and the run settings it overrides.
		* @returns The source, with the id the API minted.
		* @throws {IngestError} 409 when a live source has the slug; 400 for an unknown type.
		*/
		create: (spec) => this.#transport.request({
			method: "POST",
			path: "/sources",
			body: spec,
			exclude: CONTENT.source
		}),
		/**
		* Read a source by id, a deleted one too (`deletedAt` set).
		* @returns The source, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read it.
		*/
		get: (id) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(id)}`,
			tolerate: [404],
			exclude: CONTENT.source
		}),
		/**
		* Find the live source of a slug, looked for at `nrn` (the organization's
		* root by default): a key granted beneath the organization finds its
		* sources only where it is granted.
		* @returns The source, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not list sources.
		*/
		find: async (slug, options = {}) => {
			return (await this.sources.list({
				slug,
				nrn: options.nrn,
				limit: 1
			})).results[0] ?? null;
		},
		/**
		* List the organization's sources, narrowed by slug or NRN; deleted ones with `deleted`.
		* @throws {IngestError} 400 for an unknown sort field; 403 when the token may not list sources.
		*/
		list: async (filter) => this.#transport.request({
			method: "GET",
			path: "/sources",
			query: listQuery(filter),
			exclude: CONTENT.sources
		}),
		/**
		* A source's revisions, newest first: every write (created or revived,
		* changed, deleted), who made it, and what the source set itself then.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not read it.
		*/
		revisions: (id, page) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(id)}/revisions`,
			query: listQuery(page),
			exclude: CONTENT.sourceRevisions
		}),
		/**
		* The source at a glance: its backlog, last activity, and what became of
		* the inputs settled since `since` (24 h by default).
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not read it.
		*/
		stats: (id, options = {}) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(id)}/stats`,
			query: Object.fromEntries(Object.entries(options))
		}),
		/**
		* Change a source's name, description, attributes or run settings (a run
		* setting set to `null` goes back to its type's). Needs `ingest:source:write`.
		* @throws {IngestError} 400 for an invalid change; 404 when there is no such source; 403 when the token may not write it.
		*/
		update: (id, patch) => this.#transport.request({
			method: "PATCH",
			path: `/sources/${segment(id)}`,
			body: patch,
			exclude: CONTENT.source
		}),
		/**
		* Soft-delete a source. Its input log, its entities and its runs are kept,
		* and the entities it wrote are left in their targets.
		* @returns The source, with `deletedAt` set.
		* @throws {IngestError} 409 while a run is open; 404 when there is no such source; 403 when the token may not delete it.
		*/
		delete: (id) => this.#transport.request({
			method: "DELETE",
			path: `/sources/${segment(id)}`,
			exclude: CONTENT.source
		}),
		/**
		* Sources as `specs` define them, each found by its slug (at its `nrn`,
		* when it names one): created when missing (a deleted one revived where it
		* lived), updated where its name, description, attributes (replaced whole)
		* or a run setting it names differ, nothing sent when they match. Never
		* deletes. A collector sends only what it owns: what it sends is set again
		* on every start, over any change made in the console.
		* @returns The sources, in the order of `specs`, each with what the upsert did
		*   (`upserted`: created, updated or unchanged); keep their ids, every other call takes them.
		* @throws {Error} Before sending anything, when two specs name one slug; when
		*   a slug is a source of another type, or lives at another NRN (neither can change).
		* @example
		* const [source] = await ingest.sources.upsert([
		*   { slug: 'prod-eu', name: 'Production EU', type: 'kubernetes' },
		* ]);
		*/
		upsert: async (specs) => {
			uniqueKeys(specs, (spec) => spec.slug, "source");
			return rereadOnConflict(async () => {
				const found = await Promise.all(specs.map((spec) => this.sources.find(spec.slug, { nrn: spec.nrn })));
				specs.forEach((spec, index) => {
					const existing = found[index];
					if (!existing) return;
					if (spec.type !== void 0 ? existing.type !== spec.type : existing.typeId !== spec.typeId) throw new Error(`source '${spec.slug}' is a '${existing.type}' source, not '${spec.type ?? spec.typeId}': use another slug`);
					if (spec.nrn !== void 0 && existing.nrn !== spec.nrn) throw new Error(`source '${spec.slug}' lives at '${existing.nrn}', not '${spec.nrn}'`);
				});
				return Promise.all(specs.map(async (spec, index) => {
					const existing = found[index];
					if (!existing) return upserted(await this.sources.create(spec), "created");
					const runs = changedRuns(existing.runs, spec.runs);
					const patch = {
						...spec.name !== existing.name ? { name: spec.name } : {},
						...spec.description !== void 0 && spec.description !== existing.description ? { description: spec.description } : {},
						...spec.attributes !== void 0 && !sameJson(spec.attributes, existing.attributes) ? { attributes: spec.attributes } : {},
						...runs ? { runs } : {}
					};
					return Object.keys(patch).length ? upserted(await this.sources.update(existing.id, patch), "updated") : upserted(existing, "unchanged");
				}));
			});
		}
	};
	/** Source types: global ones (nullplatform's, such as `kubernetes`) and the organization's own. */
	sourceTypes = {
		/**
		* List the types the organization sees: the global ones and its own; `slug` finds one.
		* @throws {IngestError} 403 when the token may not list source types.
		*/
		list: (filter) => this.#transport.request({
			method: "GET",
			path: "/source_types",
			query: listQuery(filter)
		}),
		/**
		* Read a type by id.
		* @returns The type, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read it.
		*/
		get: (id) => this.#transport.request({
			method: "GET",
			path: `/source_types/${segment(id)}`,
			tolerate: [404]
		}),
		/**
		* Find the live type a slug names for the organization (a global one, or its own).
		* @returns The type, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not list source types.
		*/
		find: async (slug) => {
			return (await this.sourceTypes.list({
				slug,
				limit: 1
			})).results[0] ?? null;
		},
		/**
		* Create one of the organization's own types; a deleted one of the slug is
		* revived under its id. Its run settings are every source's defaults.
		* @throws {IngestError} 409 when the slug is taken, by the organization or by a global type.
		*/
		create: (spec) => this.#transport.request({
			method: "POST",
			path: "/source_types",
			body: spec
		}),
		/**
		* Change a type's name, description or run settings (only the settings named).
		* @throws {IngestError} 400 for an invalid change; 404 when there is no such type; 403 for nullplatform's (global) types.
		*/
		update: (id, patch) => this.#transport.request({
			method: "PATCH",
			path: `/source_types/${segment(id)}`,
			body: patch
		}),
		/**
		* A type's revisions, newest first: every write, who made it, and what the type became.
		* @throws {IngestError} 404 when there is no such type; 403 when the token may not read it.
		*/
		revisions: (id, page) => this.#transport.request({
			method: "GET",
			path: `/source_types/${segment(id)}/revisions`,
			query: listQuery(page)
		}),
		/**
		* Soft-delete a type.
		* @throws {IngestError} 409 while a live source or mapping uses it.
		*/
		delete: (id) => this.#transport.request({
			method: "DELETE",
			path: `/source_types/${segment(id)}`
		}),
		/**
		* The organization's own types as `specs` define them, each found by its
		* slug: created when missing (a deleted one revived), updated where its
		* name, description or a run setting it names differ, nothing sent when
		* they match. Never deletes.
		* @returns The types, in the order of `specs`.
		* @throws {Error} Before sending anything, when two specs name one slug.
		* @throws {IngestError} 409 when a global type holds a slug; 403 when a
		*   slug names a global type that differs (nullplatform's are not the organization's to change).
		* @example
		* const [github] = await ingest.sourceTypes.upsert([
		*   { slug: 'github', name: 'GitHub org', runs: { maxDeleteRatio: 0.2 } },
		* ]);
		*/
		upsert: async (specs) => {
			uniqueKeys(specs, (spec) => spec.slug, "source type");
			return rereadOnConflict(async () => {
				const found = await Promise.all(specs.map((spec) => this.sourceTypes.find(spec.slug)));
				return Promise.all(specs.map(async (spec, index) => {
					const existing = found[index];
					if (!existing) return upserted(await this.sourceTypes.create(spec), "created");
					const runs = changedRuns(existing.runs, spec.runs);
					const patch = {
						...spec.name !== existing.name ? { name: spec.name } : {},
						...spec.description !== void 0 && spec.description !== existing.description ? { description: spec.description } : {},
						...runs ? { runs } : {}
					};
					return Object.keys(patch).length ? upserted(await this.sourceTypes.update(existing.id, patch), "updated") : upserted(existing, "unchanged");
				}));
			});
		}
	};
	/**
	* Mappings: how a record type becomes entities (an expression), owned by a
	* source type (shared by every source of it) or by one source. Where a
	* mapping writes is its destinations'.
	*/
	mappings = {
		/**
		* Create a mapping of a source type: the organization's own (with
		* `global`, nullplatform's, an operator's call). Creating a deleted slug
		* revives it.
		* @param options `dryRun` checks it as it would be written and stores
		*   nothing. What it makes of a record is `mappingPreviews.create`.
		* @throws {IngestError} 400 for an invalid expression; 409 when the slug is live.
		*/
		createForSourceType: (sourceTypeId, spec, options = {}) => this.#transport.request({
			method: "POST",
			path: `/source_types/${segment(sourceTypeId)}/mappings`,
			query: dryRunQuery(options),
			body: spec
		}),
		/**
		* Create a source's own mapping: for a source whose type shares none for
		* the record type, or to customize one (bind it where the type's is bound,
		* and it shadows it). Creating a deleted slug revives it.
		* @param options `dryRun` checks it as it would be written and stores
		*   nothing. What it makes of a record is `mappingPreviews.create`.
		* @throws {IngestError} 400 for an invalid expression; 409 when the slug is live.
		*/
		createForSource: (sourceId, spec, options = {}) => this.#transport.request({
			method: "POST",
			path: `/sources/${segment(sourceId)}/mappings`,
			query: dryRunQuery(options),
			body: spec
		}),
		/**
		* Read a mapping by id (a type's or a source's).
		* @returns The mapping, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read it.
		*/
		get: (id) => this.#transport.request({
			method: "GET",
			path: `/mappings/${segment(id)}`,
			tolerate: [404]
		}),
		/**
		* Find a source's own live mapping of a slug (its record type, unless named otherwise).
		* @returns The mapping, or `null` when there is none.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not list its mappings.
		*/
		findForSource: async (sourceId, slug) => {
			return (await this.mappings.listForSource(sourceId, {
				slug,
				limit: 1
			})).results[0] ?? null;
		},
		/**
		* Find a type's live mapping of a slug the organization sees: nullplatform's
		* or its own (a slug names one of them on a type).
		* @returns The mapping, or `null` when there is none.
		* @throws {IngestError} 404 when there is no such type; 403 when the token may not list its mappings.
		*/
		findForSourceType: async (sourceTypeId, slug) => {
			return (await this.mappings.listForSourceType(sourceTypeId, {
				slug,
				limit: 1
			})).results[0] ?? null;
		},
		/**
		* List a type's mappings the organization sees: the global ones and its own.
		* @throws {IngestError} 404 when there is no such type; 403 when the token may not list its mappings.
		*/
		listForSourceType: async (sourceTypeId, filter) => this.#transport.request({
			method: "GET",
			path: `/source_types/${segment(sourceTypeId)}/mappings`,
			query: listQuery(filter)
		}),
		/**
		* List a source's own mappings.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not list its mappings.
		*/
		listForSource: async (sourceId, filter) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(sourceId)}/mappings`,
			query: listQuery(filter)
		}),
		/**
		* Change a mapping's definition (engine, expression): a new revision, which
		* every destination following the latest applies. A change of nothing
		* writes nothing.
		* @param options `dryRun` checks it as it would be written and stores
		*   nothing. What it makes of a record is `mappingPreviews.create`.
		* @throws {IngestError} 400 for an expression that does not compile; 404 when there is no such mapping; 403 for nullplatform's (global) mappings.
		*/
		update: (id, patch, options = {}) => this.#transport.request({
			method: "PATCH",
			path: `/mappings/${segment(id)}`,
			query: dryRunQuery(options),
			body: patch
		}),
		/**
		* Soft-delete a mapping.
		* @throws {IngestError} 409 while a live destination binds it.
		*/
		delete: (id) => this.#transport.request({
			method: "DELETE",
			path: `/mappings/${segment(id)}`
		}),
		/**
		* A mapping's revisions, newest first: every definition it had, kept for good.
		* @throws {IngestError} 404 when there is no such mapping; 403 when the token may not read it.
		*/
		revisions: async (id, page) => this.#transport.request({
			method: "GET",
			path: `/mappings/${segment(id)}/revisions`,
			query: listQuery(page)
		}),
		/**
		* A type's mappings as `specs` define them (the organization's own), each
		* found by its slug (the record type by default) among the ones the
		* organization sees: created when missing (a deleted one revived), its
		* definition updated where it differs, nothing sent when it matches.
		* Never deletes. Where they are written is `destinations.upsertForSourceType`.
		* @returns The mappings, in the order of `specs`.
		* @throws {Error} Before sending anything, when two specs name one slug;
		*   when a slug's mapping maps another record type.
		* @throws {IngestError} 403 when a slug is nullplatform's mapping and the
		*   spec differs from it (customize it under another slug); 400 for an invalid expression.
		* @example
		* const [pods] = await ingest.mappings.upsertForSourceType(type.id, [
		*   { slug: 'pod-team', recordType: 'pod', engine: Engine.JSONATA, expression },
		* ]);
		*/
		upsertForSourceType: async (sourceTypeId, specs) => this.#upsertMappings(specs, (slugs) => everyPageFor(slugs, (slug, page) => this.mappings.listForSourceType(sourceTypeId, {
			slug,
			...page
		})), (spec) => this.mappings.createForSourceType(sourceTypeId, spec)),
		/**
		* A source's own mappings as `specs` define them, each found by its slug
		* (the record type by default): created when missing (a deleted one
		* revived), its definition updated where it differs, nothing sent when it
		* matches. Never deletes. For a collector of the organization's own type
		* (a collector of a global type, `kubernetes`, defines none); where they
		* are written is `destinations.upsertForSource`.
		* @returns The mappings, in the order of `specs`.
		* @throws {Error} Before sending anything, when two specs name one slug;
		*   when a slug's mapping maps another record type.
		* @throws {IngestError} 400 for an invalid expression.
		* @example
		* const mappings = await ingest.mappings.upsertForSource(source.id, [
		*   { recordType: 'repository', engine: Engine.JSONATA, expression },
		* ]);
		* await ingest.destinations.upsertForSource(source.id, mappings.map((mapping) => ({
		*   mappingId: mapping.id, target: 'catalog', endpoint: `github-${mapping.recordType}`,
		* })));
		*/
		upsertForSource: async (sourceId, specs) => this.#upsertMappings(specs, (slugs) => everyPageFor(slugs, (slug, page) => this.mappings.listForSource(sourceId, {
			slug,
			...page
		})), (spec) => this.mappings.createForSource(sourceId, spec))
	};
	/** Mapping previews: what a mapping makes of a record, nothing stored. */
	mappingPreviews = { 
	/**
	* Evaluate a mapping on a sample: a stored one as it is (`mappingId`), a
	* definition not written yet, or a stored one changed by `definition`.
	* Nothing is written. With `sourceId`, it is evaluated as that source
	* (`$source`) and each entity validated against what the source applies.
	* @returns What was evaluated, its output, its entities, and what each
	*   endpoint would say; a runtime error is the preview's `errors`.
	* @throws {IngestError} 400 for an expression that does not compile, or a
	*   sample that is not exactly one of `payload` and `inputId`.
	* @example
	* const preview = await ingest.mappingPreviews.create({
	*   mappingId: mapping.id,
	*   sourceId: source.id,
	*   sample: { payload: deployment },
	* });
	*/
create: (spec) => this.#transport.request({
		method: "POST",
		path: "/mapping_previews",
		body: spec,
		exclude: CONTENT.mappingPreview,
		idempotent: true
	}) };
	/**
	* Destinations: a mapping bound to an endpoint of a target, for every source
	* of a type (the organization's) or for one source (which shadows the
	* organization's of the same record type, target and endpoint). Created and
	* listed under their owner; read, changed and deleted by their own id.
	*/
	destinations = {
		/**
		* Bind mappings for every source of a type in the organization: one
		* batch, all or none (1–100). Re-binding a deleted one revives it.
		* @returns The destinations, in the order given.
		* @throws {IngestError} 404 for an unknown mapping, target or endpoint; 409 for a key
		*   bound already. A refusal names its item: `data[i]: …`.
		* @example
		* await ingest.destinations.createForSourceType(type.id, [
		*   { mappingId: deployments.id, target: 'catalog', endpoint: 'k8s-deployment' },
		* ]);
		*/
		createForSourceType: async (sourceTypeId, specs) => (await this.#transport.request({
			method: "POST",
			path: `/source_types/${segment(sourceTypeId)}/destinations`,
			body: { data: specs }
		})).data,
		/**
		* Bind mappings for one source: one batch, all or none (1–100). Each
		* shadows the organization's of the same record type, target and endpoint.
		* @returns The destinations, in the order given.
		* @throws {IngestError} 404 for an unknown mapping, target or endpoint; 409 for a key
		*   bound already. A refusal names its item: `data[i]: …`.
		*/
		createForSource: async (sourceId, specs) => (await this.#transport.request({
			method: "POST",
			path: `/sources/${segment(sourceId)}/destinations`,
			body: { data: specs }
		})).data,
		/**
		* Read a destination by id, a deleted one too.
		* @returns The destination, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read it.
		*/
		get: (id) => this.#transport.request({
			method: "GET",
			path: `/destinations/${segment(id)}`,
			tolerate: [404]
		}),
		/**
		* List the organization's destinations for every source of a type, newest first.
		* @throws {IngestError} 404 when there is no such type; 403 when the token may not list its destinations.
		*/
		listForSourceType: (sourceTypeId, filter) => this.#transport.request({
			method: "GET",
			path: `/source_types/${segment(sourceTypeId)}/destinations`,
			query: listQuery(filter)
		}),
		/**
		* List what a source applies: its own destinations and the organization's
		* of its type, after shadowing (`effective`, the default); with
		* `effective: false`, its own destinations only.
		* @example
		* const applied = await ingest.destinations.listForSource(source.id);
		* const types = new Set(applied.results.map((destination) => destination.recordType));
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not list its destinations.
		*/
		listForSource: (sourceId, filter) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(sourceId)}/destinations`,
			query: listQuery(filter)
		}),
		/**
		* Change a destination's endpoint (within its target), the revision it
		* pins (`null`: follow the latest), its switch or its `onDelete`.
		* @throws {IngestError} 400 for an invalid change; 404 when there is no such destination or endpoint; 409 when `onDelete: OnDelete.RESTRICT` refuses to stop applying.
		*/
		update: (id, patch) => this.#transport.request({
			method: "PATCH",
			path: `/destinations/${segment(id)}`,
			body: patch
		}),
		/**
		* Soft-delete a destination; its `onDelete` decides what becomes of what
		* it wrote.
		* @throws {IngestError} 409 when its `onDelete` is `RESTRICT` and it owns live entities.
		*/
		delete: (id) => this.#transport.request({
			method: "DELETE",
			path: `/destinations/${segment(id)}`
		}),
		/**
		* A destination's revisions, newest first.
		* @throws {IngestError} 404 when there is no such destination; 403 when the token may not read it.
		*/
		revisions: (id, page) => this.#transport.request({
			method: "GET",
			path: `/destinations/${segment(id)}/revisions`,
			query: listQuery(page)
		}),
		/**
		* The organization's destinations for every source of a type, as `specs`
		* define them, each found by its mapping, target and endpoint: created
		* when missing (in one batch, all or none), updated where its pin,
		* switch or `onDelete` differ, nothing sent when they match. Never deletes
		* one the specs leave out.
		* @returns The destinations, in the order of `specs`.
		* @example
		* await ingest.destinations.upsertForSourceType(type.id, [
		*   { mappingId: deployments.id, target: 'catalog', endpoint: 'k8s-deployment' },
		* ]);
		* @throws {Error} Before sending anything, when two specs name one destination (by slug or by id).
		* @throws {IngestError} 404 for a mapping, target or endpoint that does not exist; 400 for a mapping of another type.
		*/
		upsertForSourceType: async (sourceTypeId, specs) => this.#upsertDestinations((filter) => this.destinations.listForSourceType(sourceTypeId, filter), specs, (missing) => this.destinations.createForSourceType(sourceTypeId, missing)),
		/**
		* One source's own destinations, as `specs` define them, each found by its
		* mapping, target and endpoint: created when missing (in one batch, all or
		* none), updated where its pin, switch or `onDelete` differ, nothing sent
		* when they match. Never deletes one the specs leave out.
		* @returns The destinations, in the order of `specs`.
		* @throws {Error} Before sending anything, when two specs name one destination (by slug or by id).
		* @throws {IngestError} 404 for a mapping, target or endpoint that does not exist; 400 for a mapping of another type.
		*/
		upsertForSource: async (sourceId, specs) => this.#upsertDestinations((filter) => this.destinations.listForSource(sourceId, {
			effective: false,
			...filter
		}), specs, (missing) => this.destinations.createForSource(sourceId, missing))
	};
	/**
	* Each spec's mapping among the owner's, found by its slug (the owner's of
	* the specs' slugs, queried by them): created when missing, updated where
	* its definition differs.
	*/
	async #upsertMappings(specs, readNamed, create) {
		uniqueKeys(specs, slugOf, "mapping");
		return rereadOnConflict(async () => {
			const existing = await readNamed(specs.map(slugOf));
			const found = specs.map((spec) => existing.find((each) => each.slug === slugOf(spec)));
			specs.forEach((spec, index) => {
				const mapping = found[index];
				if (mapping && mapping.recordType !== spec.recordType) throw new Error(`mapping '${mapping.slug}' maps '${mapping.recordType}' records, not '${spec.recordType}': use another slug`);
			});
			return Promise.all(specs.map(async (spec, index) => {
				const mapping = found[index];
				if (!mapping) return upserted(await create(spec), "created");
				const definition = {
					engine: spec.engine,
					expression: spec.expression
				};
				return differs(mapping, definition) ? upserted(await this.mappings.update(mapping.id, definition), "updated") : upserted(mapping, "unchanged");
			}));
		});
	}
	/**
	* Each spec's destination among the owner's of the mappings the specs name
	* (queried by them, by slug and by id): updated where it differs, the
	* missing ones created.
	*/
	async #upsertDestinations(list, specs, create) {
		uniqueKeys(specs, destinationKeyOf, "destination");
		return rereadOnConflict(async () => {
			const existing = await destinationsOfMappings(specs, list);
			const found = specs.map((spec) => existing.find((destination) => isNamedBy(destination, spec)));
			uniqueKeys(found.filter((destination) => destination !== void 0), (destination) => destination.id, "destination");
			return this.#writeDestinations(specs, found, create);
		});
	}
	/** The destinations `found` for `specs` updated where they differ, the missing ones created in one batch. */
	async #writeDestinations(specs, found, create) {
		const missing = specs.filter((_, index) => !found[index]);
		const created = missing.length ? await create(missing) : [];
		return await Promise.all(specs.map(async (spec, index) => {
			const destination = found[index];
			if (!destination) return upserted(created[missing.indexOf(spec)], "created");
			const patch = {
				...spec.mappingRevision !== void 0 && spec.mappingRevision !== destination.mappingRevision ? { mappingRevision: spec.mappingRevision } : {},
				...spec.enabled !== void 0 && spec.enabled !== destination.enabled ? { enabled: spec.enabled } : {},
				...spec.onDelete !== void 0 && spec.onDelete !== destination.onDelete ? { onDelete: spec.onDelete } : {}
			};
			return Object.keys(patch).length ? upserted(await this.destinations.update(destination.id, patch), "updated") : upserted(destination, "unchanged");
		}));
	}
	/** Targets: the backends the platform configured (`catalog`, `core_entities`). Read only. */
	targets = {
		/**
		* List the targets, by slug: what a destination's `target` names; `slug` finds one.
		* @throws {IngestError} 403 when the token may not list targets.
		*/
		list: (filter) => this.#transport.request({
			method: "GET",
			path: "/targets",
			query: listQuery(filter)
		}),
		/**
		* Find the live target of a slug.
		* @returns The target, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not list targets.
		*/
		find: async (slug) => {
			return (await this.targets.list({
				slug,
				limit: 1
			})).results[0] ?? null;
		}
	};
	/**
	* Endpoints: the places in a target's API an entity is written to, listed
	* under their target and read by its id and theirs. Read only.
	*/
	endpoints = {
		/**
		* List a target's endpoints (declared, and for the catalog its
		* specifications); `id` or `slug` finds one. At most 100 a page.
		* @throws {IngestError} 404 when there is no such target; 503 when the target cannot be read now; 403 when it refused the token.
		*/
		listForTarget: (targetId, filter) => this.#transport.request({
			method: "GET",
			path: `/targets/${segment(targetId)}/endpoints`,
			query: listQuery(filter)
		}),
		/**
		* Read one of a target's endpoints by its id (the organization's own id
		* for it, what a destination's `endpointId` holds): as it runs, every
		* section and key present; with `{ effective: false }`, as it was written.
		* @returns The endpoint, or `null` when there is none.
		* @throws {IngestError} 404 when there is no such target; 503 when the
		*   target cannot be read now.
		* @example
		* const endpoint = await ingest.endpoints.get(catalog.id, destination.endpointId);
		*/
		get: ((targetId, endpointId, options = {}) => this.#transport.request({
			method: "GET",
			path: `/targets/${segment(targetId)}/endpoints/${segment(endpointId)}`,
			query: options.effective === false ? { effective: "false" } : {},
			tolerate: [404],
			exclude: CONTENT.endpoint
		}))
	};
	/**
	* Runs: one complete listing of a source (a backfill or a resync). On
	* finalize, what the source owned and the run did not report is deleted,
	* behind its guards. Prefer {@link IngestClient.runs.open}.
	*/
	runs = {
		/**
		* Open a run of the source, of some record types (all the source maps when omitted).
		* @throws {RangeError} Before sending, for an empty `types` (omit it for all of them).
		* @throws {IngestError} 409 when the source has an open run; 404 when there is no such source.
		*/
		create: (sourceId, types) => {
			if (types !== void 0 && types.length === 0) return Promise.reject(/* @__PURE__ */ new RangeError("a run names at least one record type: omit types for all of them"));
			return this.#transport.request({
				method: "POST",
				path: `/sources/${segment(sourceId)}/runs`,
				body: types ? { types } : {}
			});
		},
		/**
		* Read a run by id.
		* @returns The run, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read it.
		*/
		get: (runId) => this.#transport.request({
			method: "GET",
			path: `/runs/${segment(runId)}`,
			tolerate: [404]
		}),
		/**
		* List the source's runs, newest first; of one status when asked.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not read it.
		*/
		list: async (sourceId, filter) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(sourceId)}/runs`,
			query: listQuery(filter)
		}),
		/**
		* Send one batch of records to an open run (a run handle batches for
		* you). Each record gets a UUIDv7 id unless it has one, which must be a
		* UUIDv7.
		* @throws {TypeError} Before sending, for an id that is not a UUIDv7.
		*/
		sendRecords: async (sourceId, runId, records) => this.inputs.create(sourceId, records.map((record) => ({
			...record,
			runId
		}))),
		/**
		* Finalize a run: it reconciles once every record is applied, behind the
		* source's guards. `dryRun` reports what would be deleted and leaves it open.
		* @param options Guard overrides for this run (`maxDeleteRatio` needs `ingest:source:write`).
		* @throws {IngestError} 409 when the run is not open; 404 when there is no such run; 403 when the token may not write its source.
		*/
		finalize: (runId, options = {}) => {
			const { dryRun, ...settings } = options;
			return this.#transport.request({
				method: "PATCH",
				path: `/runs/${segment(runId)}`,
				query: dryRunQuery({ dryRun }),
				body: {
					status: "finalizing",
					...Object.keys(settings).length ? { finalize: settings } : {}
				}
			});
		},
		/**
		* Abort a run: closed without reconciling, nothing deleted.
		* @throws {IngestError} 409 when the run is not open; 404 when there is no such run; 403 when the token may not write its source.
		*/
		abort: (runId) => this.#transport.request({
			method: "PATCH",
			path: `/runs/${segment(runId)}`,
			body: { status: "aborted" }
		}),
		/**
		* Find the source's open run.
		* @returns The run, or `null` when it has none.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not read it.
		*/
		findOpen: async (sourceId) => {
			return (await this.runs.list(sourceId, { limit: 5 })).results.find((run) => run.status === "open" || run.status === "finalizing") ?? null;
		},
		/**
		* Open a run and get a handle to feed it: `add` every record, then
		* `finalize` (or `abort` on any failure: it deletes nothing).
		* @param options `types` limits the run; `onConflict` (`OnConflict.ABORT` by
		*   default) aborts a run left open, `OnConflict.FAIL` throws its 409.
		* @example
		* const run = await ingest.runs.open(source.id, { types: ['deployment'], onConflict: OnConflict.ABORT });
		* items.forEach((item) => run.add({ type: 'deployment', observedAt, payload: item }));
		* const done = await run.finalize();
		* @throws {RangeError} Before sending, for an empty `types`.
		* @throws {IngestError} 404 when there is no such source; 409 when it has an open run and `onConflict` is `OnConflict.FAIL`.
		*/
		open: async (sourceId, options = {}) => {
			let run;
			try {
				run = await this.runs.create(sourceId, options.types);
			} catch (error) {
				if (!(error instanceof IngestError && error.status === 409) || options.onConflict === "fail") throw error;
				const open = await this.runs.findOpen(sourceId);
				if (open) await this.runs.abort(open.id);
				run = await this.runs.create(sourceId, options.types);
			}
			return new RunHandle(this.runs, run, this.#batching);
		},
		/**
		* Wait until every input of the run has been applied.
		* @throws {TimeoutError} When it is not within `options.timeoutMs`.
		*/
		waitApplied: (runId, options = {}) => poll(() => mustExist(this.runs.get(runId), `run '${runId}'`), (run) => run.pending === 0, `run ${runId} to be applied`, options),
		/**
		* Wait until the run is closed: completed, guard tripped or aborted.
		* @throws {TimeoutError} When it is not within `options.timeoutMs`.
		*/
		waitClosed: (runId, options = {}) => poll(() => mustExist(this.runs.get(runId), `run '${runId}'`), (run) => TERMINAL_RUN.includes(run.status), `run ${runId} to close`, options),
		/**
		* Wait until a dry-run finalize has been assessed (the run stays open).
		* @throws {TimeoutError} When it is not within `options.timeoutMs`.
		*/
		waitDryRun: (runId, options = {}) => poll(() => mustExist(this.runs.get(runId), `run '${runId}'`), (run) => run.finalize === null, `dry run of ${runId} to be assessed`, options)
	};
	/** Events: a source's changes, one by one, between runs (the steady state). */
	events = {
		/**
		* Send one batch of events (an event batcher batches for you). `op`
		* defaults to `EventOp.UPSERT`; each event gets a UUIDv7 id unless it has
		* one, which must be a UUIDv7.
		* @throws {TypeError} Before sending, for an id that is not a UUIDv7.
		*/
		send: async (sourceId, events) => this.inputs.create(sourceId, events.map((event) => ({
			...event,
			op: event.op ?? "upsert"
		}))),
		/**
		* A batcher that sends events as they come, batched by count, bytes and
		* time. Close it on shutdown.
		* @example
		* const events = ingest.events.batcher(source.id);
		* events.upsert('deployment', deployment, { observedAt: event.time });
		* await events.close();
		* @throws {RangeError} For batching options out of range.
		*/
		batcher: (sourceId, batching = {}) => new EventBatcher((events) => this.events.send(sourceId, events), {
			...this.#batching,
			...batching
		})
	};
	/** Inputs: every record and event a source sent, and what became of each. */
	inputs = {
		/**
		* Send one batch of inputs: records of the open runs they name (`runId`),
		* or events. Run handles and event batchers batch for you. Each input gets
		* a UUIDv7 id unless it has one, which must be a UUIDv7.
		* @returns How many were accepted, and which were duplicates (an id sent before).
		* @throws {TypeError} Before sending, for an id that is not a UUIDv7.
		* @throws {IngestError} 409 when an id belongs to another source.
		*/
		create: async (sourceId, inputs) => this.#transport.request({
			method: "POST",
			path: `/sources/${segment(sourceId)}/inputs`,
			body: { data: inputs.map(inputOf) },
			idempotent: true,
			exclude: CONTENT.inputs
		}),
		/**
		* List the source's input log, in arrival order, with what became of each input.
		* @throws {IngestError} 400 for an `after` that is not the source's; 404 when there is no such source.
		*/
		list: async (sourceId, filter) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(sourceId)}/inputs`,
			query: listQuery(filter)
		}),
		/**
		* Read one input, its payload included.
		* @returns The input, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read the input log.
		*/
		get: (inputId) => this.#transport.request({
			method: "GET",
			path: `/inputs/${segment(inputId)}`,
			tolerate: [404],
			exclude: CONTENT.input
		}),
		/**
		* Wait until the given inputs are all settled.
		* @returns The inputs, in the order of `ids`.
		* @throws {TimeoutError} When they are not within `options.timeoutMs`.
		*/
		wait: async (ids, options = {}) => poll(() => Promise.all(ids.map((id) => mustExist(this.inputs.get(id), `input '${id}'`))), (rows) => rows.every((row) => TERMINAL_INPUT.includes(row.status)), `inputs ${ids.join(", ")} to settle`, options),
		/**
		* Wait until the source has no pending input.
		* @throws {TimeoutError} When it does not within `options.timeoutMs`.
		*/
		waitIdle: (sourceId, options = {}) => poll(() => this.inputs.list(sourceId, {
			status: "pending",
			limit: 1
		}), (page) => page.results.length === 0, `source ${sourceId} to be idle`, options).then(() => void 0)
	};
	/** Replays: the current mappings applied again to what a source owns (after changing one). */
	replays = {
		/**
		* Create a replay: each live entity's last record is queued again, in the
		* background. With an `idempotencyKey`, a resend answers the same replay.
		* @param request Which record types (all when omitted).
		* @throws {IngestError} 404 when there is no such source; 409 when the idempotency key names another request.
		*/
		create: (sourceId, request = {}, options = {}) => this.#transport.request({
			method: "POST",
			path: `/sources/${segment(sourceId)}/replays`,
			body: request,
			headers: options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : void 0,
			idempotent: options.idempotencyKey !== void 0
		}),
		/**
		* Read a replay by id: its status and progress.
		* @returns The replay, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read it.
		*/
		get: (replayId) => this.#transport.request({
			method: "GET",
			path: `/replays/${segment(replayId)}`,
			tolerate: [404]
		}),
		/**
		* List the source's replays, newest first; of one status when asked.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not read it.
		*/
		list: async (sourceId, filter) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(sourceId)}/replays`,
			query: listQuery(filter)
		}),
		/**
		* Wait until the replay has queued everything (or failed); the inputs it
		* queued may still be applying.
		* @throws {TimeoutError} When it does not finish within `options.timeoutMs`.
		*/
		wait: (replayId, options = {}) => poll(() => mustExist(this.replays.get(replayId), `replay '${replayId}'`), (replay) => replay.status === "completed" || replay.status === "failed", `replay ${replayId} to finish`, options)
	};
	/** Entities: what a source owns, and what was last written to each. */
	entities = {
		/**
		* List the entities the source owns, with the data last written (no raw records).
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not read it.
		*/
		list: async (sourceId, filter) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(sourceId)}/entities`,
			query: listQuery(filter),
			exclude: CONTENT.entities
		}),
		/**
		* Read one owned entity by its id, with the raw record it was last mapped
		* from (needs `ingest:input:read`).
		* @returns The entry, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read the input log (`ingest:input:read`).
		*/
		get: (entityId) => this.#transport.request({
			method: "GET",
			path: `/entities/${segment(entityId)}`,
			tolerate: [404],
			exclude: CONTENT.entity
		})
	};
	/** Drift checks: what a source owns compared with what its targets hold. */
	driftChecks = {
		/**
		* Create a drift check of the source: `DriftPolicy.REPORT` (the default)
		* flags what changed or went missing; `DriftPolicy.RESTORE` writes it back.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not write it.
		*/
		create: (sourceId, policy = "report") => this.#transport.request({
			method: "POST",
			path: `/sources/${segment(sourceId)}/drift_checks`,
			body: { policy }
		}),
		/**
		* Read a drift check by id.
		* @returns The drift check, or `null` when there is none.
		* @throws {IngestError} 403 when the token may not read it.
		*/
		get: (checkId) => this.#transport.request({
			method: "GET",
			path: `/drift_checks/${segment(checkId)}`,
			tolerate: [404]
		}),
		/**
		* List the source's drift checks, newest first; of one status when asked.
		* @throws {IngestError} 404 when there is no such source; 403 when the token may not read it.
		*/
		list: async (sourceId, filter) => this.#transport.request({
			method: "GET",
			path: `/sources/${segment(sourceId)}/drift_checks`,
			query: listQuery(filter)
		}),
		/**
		* Wait until a drift check is completed or failed.
		* @throws {TimeoutError} When it is not within `options.timeoutMs`.
		*/
		wait: (checkId, options = {}) => poll(() => mustExist(this.driftChecks.get(checkId), `drift check '${checkId}'`), (check) => check.status === "completed" || check.status === "failed", `drift check ${checkId}`, options),
		/**
		* Create a drift check and wait for it.
		* @throws {TimeoutError} When it does not finish within `options.timeoutMs`.
		*/
		createAndWait: async (sourceId, policy = "report", options = {}) => {
			const check = await this.driftChecks.create(sourceId, policy);
			return this.driftChecks.wait(check.id, options);
		}
	};
};
//#endregion
//#region src/collector/runtime.ts
/**
* Records between two flushes the listing waits on. A full API batch: when
* the API pushes back (429, its worker is behind) the listing pauses here
* instead of buffering the rest of the system of record in memory.
*/
const FLUSH_EVERY = 500;
const messageOf = (error) => error instanceof Error ? error.message : String(error);
/** Resolves after `ms`, or as soon as `signal` aborts. */
function pause(ms, signal) {
	return new Promise((resolve) => {
		if (signal?.aborted) {
			resolve();
			return;
		}
		const timer = setTimeout(resolve, ms);
		signal?.addEventListener("abort", () => {
			clearTimeout(timer);
			resolve();
		}, { once: true });
	});
}
/** The record types a collector produces: its `recordTypes` and its own mappings'. */
function declaredTypes(definition) {
	return [.../* @__PURE__ */ new Set([...definition.recordTypes ?? [], ...Object.keys(definition.mappings ?? {})])];
}
/**
* Refuses a collector that could never feed a source: no source type, no
* record types, a mapping with no endpoint, or no snapshot.
* @throws {Error} naming what is missing.
*/
function validateDefinition(definition) {
	if (!definition.source?.type) throw new Error("collector: `source.type` is required");
	if (declaredTypes(definition).length === 0) throw new Error("collector: declare the record types it produces (`recordTypes`, or its own `mappings`)");
	const unrouted = Object.entries(definition.mappings ?? {}).find(([, mapping]) => !mapping?.endpoint);
	if (unrouted) throw new Error(`collector: mapping '${unrouted[0]}' needs an \`endpoint\` (the target's endpoint it writes to)`);
	if (typeof definition.snapshot !== "function") throw new Error("collector: `snapshot` is required");
}
/**
* Creates or updates the source (by slug) and the collector's own mappings,
* then learns which of its record types the source applies (an organization
* binds a type's shared mappings once; a type it has not bound is not sent).
* @throws {Error} when the source applies none of them: there is nothing to feed.
*/
async function prepareSource(definition, port, options) {
	const source = await port.upsertSource({
		...definition.source,
		...options.source,
		name: options.source.name || definition.source.name
	});
	if (definition.mappings && Object.keys(definition.mappings).length) {
		const changed = await port.upsertMappings(source.id, definition.mappings);
		if (changed.length) options.log.info(`mappings updated: ${changed.join(", ")}`);
	}
	const declared = declaredTypes(definition);
	const types = await port.appliedTypes(source.id, declared);
	if (types.length === 0) throw new Error(`no record type of this collector is bound for source ${source.slug}: bind the ${definition.source.type} type's mappings to endpoints (POST /source_types/{source_type_id}/destinations, or /sources/{source_id}/destinations for this source)`);
	const unbound = declared.filter((type) => !types.includes(type));
	if (unbound.length) options.log.warn(`not bound for this source, not sent: ${unbound.join(", ")}`);
	return {
		...source,
		types
	};
}
/**
* How long until the first snapshot is due: `0` when the source has no run,
* or its last run started more than `intervalSeconds` ago; otherwise the rest
* of the interval since then, never more than one interval (a run dated ahead
* of this clock). Says what it decided, once; a last run that cannot be read
* is logged and the snapshot is due at once.
*/
async function firstSnapshotDelay(port, source, intervalSeconds, log) {
	const intervalMs = intervalSeconds * 1e3;
	let last;
	try {
		const latest = await port.lastRun(source.id);
		const startedAt = latest ? Date.parse(latest.createdAt) : NaN;
		if (latest && Number.isNaN(startedAt)) throw new Error(`run ${latest.id} has no valid creation time ('${latest.createdAt}')`);
		last = latest ? {
			id: latest.id,
			startedAt
		} : null;
	} catch (error) {
		log.error(`could not read the last run of source ${source.slug}: ${messageOf(error)}`);
		log.info("snapshot due now (last run unknown)");
		return 0;
	}
	if (!last) {
		log.info("snapshot due now (no previous run)");
		return 0;
	}
	const previous = `last run ${last.id} at ${new Date(last.startedAt).toISOString()}`;
	const now = Date.now();
	if (now - last.startedAt > intervalMs) {
		log.info(`snapshot due now (${previous})`);
		return 0;
	}
	const delay = Math.min(last.startedAt + intervalMs - now, intervalMs);
	log.info(`next snapshot at ${new Date(now + delay).toISOString()} (${previous})`);
	return delay;
}
/** Events of the types the source applies; the rest are not sent (the organization did not bind them). */
function onlyApplied(events, applied) {
	return {
		upsert: (type, payload, options) => {
			if (applied().has(type)) events.upsert(type, payload, options);
		},
		delete: (type, payload, options) => {
			if (applied().has(type)) events.delete(type, payload, options);
		},
		flush: () => events.flush(),
		close: () => events.close()
	};
}
const isAsyncIterable = (value) => Symbol.asyncIterator in value;
/**
* Hands every record to `visit`, one at a time, until the listing ends or
* `visit` answers `false`. Each record waits for the one before it (a
* flush included), in constant memory. The listing is closed when it is
* left early or throws, as a `for await` would close it.
*/
function eachRecord(records, visit) {
	const iterator = isAsyncIterable(records) ? records[Symbol.asyncIterator]() : records[Symbol.iterator]();
	const close = () => Promise.resolve().then(() => iterator.return?.()).catch(() => void 0);
	return new Promise((resolve, reject) => {
		const fail = (error) => {
			close().then(() => reject(error));
		};
		const next = () => {
			Promise.resolve().then(() => iterator.next()).then((step) => {
				if (step.done) {
					resolve();
					return;
				}
				Promise.resolve().then(() => visit(step.value)).then((more) => {
					if (more) next();
					else close().then(() => resolve());
				}, fail);
			}, fail);
		};
		next();
	});
}
/**
* Takes one full snapshot of the collector's system of record into its
* source: upserts the source and its own mappings, opens a run of the types
* the source applies, streams every record the snapshot yields (pausing on a
* flush every full batch), and finalizes. A snapshot that throws, yields a
* record of a type it does not declare, or is cancelled is aborted: nothing
* is deleted. A dry run is reported, then closed.
* @returns The run as the API closed it.
* @throws {Error} what made the snapshot fail, after aborting its run.
* @example
* const ingest = new ClientIngest(new IngestClient({ apiKey }));
* const result = await runSnapshot(collector, ingest, { source: { slug: 'eu-cluster' }, log });
* if (result.reconciliation?.guardTripped) {
*   log.error('nothing deleted: a guard tripped');
* }
*/
async function runSnapshot(definition, port, options, finalizeOptions = {}) {
	validateDefinition(definition);
	const { log } = options;
	const { types, ...source } = await prepareSource(definition, port, options);
	options.applied?.(types);
	const declared = declaredTypes(definition);
	const run = await port.openRun(source.id, types);
	log.info(`snapshot ${run.id} of ${source.slug}`);
	const controller = new AbortController();
	const stop = () => controller.abort();
	options.signal?.addEventListener("abort", stop, { once: true });
	if (options.signal?.aborted) stop();
	const ctx = {
		source,
		log,
		signal: controller.signal,
		observedAt: /* @__PURE__ */ new Date()
	};
	let records = 0;
	let unbound = 0;
	try {
		await eachRecord(await definition.snapshot(ctx), (record) => {
			if (controller.signal.aborted) return false;
			if (!declared.includes(record.type)) throw new Error(`record type '${record.type}' is not one this collector declares`);
			if (!types.includes(record.type)) {
				unbound += 1;
				return true;
			}
			run.add({
				...record,
				observedAt: record.observedAt ?? ctx.observedAt
			});
			records += 1;
			return records % 500 === 0 ? run.flush().then(() => true) : true;
		});
		if (controller.signal.aborted) throw new Error("the snapshot was cancelled");
	} catch (error) {
		await run.abort().catch(() => void 0);
		log.error(`snapshot ${run.id} aborted after ${records} record(s): ${messageOf(error)}`);
		throw error;
	} finally {
		options.signal?.removeEventListener("abort", stop);
	}
	log.info(`${records} record(s) sent${unbound ? ` (${unbound} of types not bound, not sent)` : ""}, reconciling`);
	let result;
	try {
		result = await run.finalize(finalizeOptions);
	} catch (error) {
		await run.abort().catch(() => void 0);
		log.error(`snapshot ${run.id} aborted, not finalized: ${messageOf(error)}`);
		throw error;
	}
	const { reconciliation } = result;
	if (reconciliation?.dryRun) {
		await run.abort().catch((error) => log.error(`snapshot ${run.id}: could not close the dry run: ${messageOf(error)}`));
		log.info(`snapshot ${run.id} dry run: ${reconciliation.seen} seen, ${reconciliation.stale} stale (would be deleted); nothing deleted`);
		return {
			...result,
			status: "aborted"
		};
	}
	if (reconciliation?.guardTripped) log.warn(`snapshot ${run.id}: nothing deleted, ${reconciliation.guardReason ?? "a guard tripped"}`);
	else {
		const outcome = reconciliation ? `${reconciliation.seen} seen, ${reconciliation.stale} stale, ${reconciliation.deleted} deleted` : `${records} record(s)`;
		log.info(`snapshot ${run.id} ${result.status}: ${outcome}`);
	}
	return result;
}
/**
* Runs a collector until `options.signal` aborts: sets its source up
* (retrying with a backoff), then a snapshot every `intervalSeconds` (never
* two at once; `0`: one, on start) and, when the collector watches, its
* watch, which starts at once. The first snapshot is due by the source's last
* run (the API's runs, any status): at once when it has none or it started
* more than `intervalSeconds` ago, else when the interval since it is over, so
* a restart or a crash loop does not backfill again; a last run that cannot
* be read is logged and the snapshot runs at once. The watch
* sends only the types the source applies and is restarted with a backoff
* when it fails or ends. A watch that failed and has then run `retryMaxMs`
* without failing makes a snapshot due at once (after the one running, if
* any): only a snapshot deletes what vanished while it was down. One per
* recovered outage, however many restarts it took, and none with an
* `intervalSeconds` of 0; the schedule continues from it. A failed snapshot
* is logged and the next one runs on schedule. Every scheduled snapshot finalizes with `finalizeOptions`
* (`{ dryRun: true }`: each is assessed and closed, nothing deleted).
* @returns Once everything in flight has stopped.
* @example
* const stop = new AbortController();
* process.on('SIGTERM', () => stop.abort());
* await runCollector(collector, new ClientIngest(new IngestClient({ apiKey })), {
*   source: { slug: 'eu-cluster' },
*   log: console,
*   signal: stop.signal,
*   intervalSeconds: 86400,
* });
*/
async function runCollector(definition, port, options, finalizeOptions = {}) {
	validateDefinition(definition);
	const { signal, log } = options;
	const retryMinMs = options.retryMinMs ?? 1e3;
	const retryMaxMs = options.retryMaxMs ?? 6e4;
	const setUp = async (backoff) => {
		if (signal.aborted) return;
		try {
			return await prepareSource(definition, port, options);
		} catch (error) {
			log.error(`could not set up source ${options.source.slug}: ${messageOf(error)}; retrying`);
			await pause(backoff, signal);
			return setUp(Math.min(backoff * 2, retryMaxMs));
		}
	};
	const prepared = await setUp(retryMinMs);
	if (!prepared) return;
	const { types: appliedTypes, ...source } = prepared;
	let applied = new Set(appliedTypes);
	const snapshotOptions = {
		...options,
		applied: (types) => {
			applied = new Set(types);
		}
	};
	let resyncDue = false;
	let wake;
	const resync = (failures) => {
		if (signal.aborted) return;
		log.info(`snapshot due now (watch recovered after ${failures} failure(s))`);
		resyncDue = true;
		wake?.();
	};
	const untilDue = async (ms) => {
		if (resyncDue || signal.aborted) return;
		const sleeping = new AbortController();
		const stop = () => sleeping.abort();
		signal.addEventListener("abort", stop, { once: true });
		wake = stop;
		await pause(ms, sleeping.signal);
		wake = void 0;
		signal.removeEventListener("abort", stop);
	};
	const snapshots = async () => {
		if (signal.aborted) return;
		resyncDue = false;
		const started = Date.now();
		try {
			await runSnapshot(definition, port, snapshotOptions, finalizeOptions);
		} catch (error) {
			if (!signal.aborted) log.error(`snapshot failed: ${messageOf(error)}`);
		}
		if (options.intervalSeconds <= 0) return;
		await untilDue(Math.max(0, options.intervalSeconds * 1e3 - (Date.now() - started)));
		await snapshots();
	};
	const watching = async (delay, failures) => {
		if (!definition.watch || signal.aborted) return;
		const events = onlyApplied(port.events(source.id), () => applied);
		const ctx = {
			source,
			log,
			signal,
			events
		};
		const started = Date.now();
		let outage = failures;
		const recovery = failures > 0 && options.intervalSeconds > 0 ? setTimeout(() => {
			outage = 0;
			resync(failures);
		}, retryMaxMs) : void 0;
		try {
			await definition.watch(ctx);
			await events.close();
			if (signal.aborted) return;
			log.info("watch ended; restarting");
		} catch (error) {
			await events.close().catch(() => void 0);
			if (signal.aborted) return;
			log.error(`watch failed: ${messageOf(error)}; restarting`);
			outage += 1;
		} finally {
			clearTimeout(recovery);
		}
		const wait = Date.now() - started > retryMaxMs ? retryMinMs : delay;
		await pause(wait, signal);
		await watching(Math.min(wait * 2, retryMaxMs), outage);
	};
	const scheduled = async () => {
		if (options.intervalSeconds > 0) {
			const delay = await firstSnapshotDelay(port, source, options.intervalSeconds, log);
			if (delay > 0) await untilDue(delay);
		}
		await snapshots();
	};
	await Promise.all([scheduled(), watching(retryMinMs, 0)]);
}
//#endregion
//#region src/collector/client-ingest.ts
const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, field]) => field !== void 0));
const iso = (value) => {
	if (value === void 0) return;
	return value instanceof Date ? value.toISOString() : value;
};
/** The event options the client takes: the observation time as ISO text, and the id. */
const eventOptions = (options = {}) => compact({
	id: options.id,
	observedAt: iso(options.observedAt)
});
/** Where the public API serves the ingest API. */
const INGEST_PATH = "/catalog/ingest";
/**
* The `IngestPort` of the real API, through an `IngestClient`: what a
* collector feeds outside tests and local runs.
* @example
* const ingest = new ClientIngest(new IngestClient({ apiKey: process.env.NP_API_KEY }));
* await runCollector(collector, ingest, { source: { slug: 'eu-cluster' }, log, signal, intervalSeconds: 86400 });
*/
var ClientIngest = class ClientIngest {
	#client;
	constructor(client) {
		this.#client = client;
	}
	/**
	* The port of the ingest API under `authBaseURL` (or at `baseURL`),
	* authenticated by a token when given, else by the API key, its client
	* tuned by the rest of `options`.
	* @throws {Error} when neither an API key nor a token is given.
	* @example
	* const ingest = ClientIngest.connect({ apiKey: process.env.NP_API_KEY, timeoutMs: 60_000 });
	*/
	static connect(options) {
		const { authBaseURL: authBaseURLOption, baseURL: baseURLOption, apiKey, token, ...tuning } = options;
		const authBaseURL = (authBaseURLOption ?? "https://api.nullplatform.com").replace(/\/+$/, "");
		const baseURL = baseURLOption || `${authBaseURL}${INGEST_PATH}`;
		if (token) return new ClientIngest(new IngestClient({
			...tuning,
			baseURL,
			token
		}));
		if (!apiKey) throw new Error("an API key or a token is required to feed the ingest API");
		return new ClientIngest(new IngestClient({
			...tuning,
			baseURL,
			apiKey,
			authBaseURL
		}));
	}
	async upsertSource(source) {
		const [upserted] = await this.#client.sources.upsert([compact({
			slug: source.slug,
			nrn: source.nrn,
			name: source.name,
			type: source.type,
			description: source.description,
			attributes: source.attributes,
			runs: source.runs && compact({ ...source.runs })
		})]);
		return {
			id: upserted.id,
			slug: upserted.slug
		};
	}
	/**
	* The client's two upserts: the source's own mapping of each record type,
	* then its destination at the target and endpoint it names. A destination
	* of the mapping to another endpoint is left alone (a record type may go to
	* several). What was written is what the upserts say they did: a mapping or
	* destination created or updated.
	*/
	async upsertMappings(sourceId, mappings) {
		const entries = Object.entries(mappings);
		const upserted = await this.#client.mappings.upsertForSource(sourceId, entries.map(([recordType, mapping]) => ({
			recordType,
			engine: mapping.engine,
			expression: mapping.expression
		})));
		const bound = await this.#client.destinations.upsertForSource(sourceId, upserted.map((mapping, index) => {
			const { target, endpoint, enabled } = entries[index][1];
			return compact({
				mappingId: mapping.id,
				target: target ?? "catalog",
				endpoint,
				enabled
			});
		}));
		const written = (resource) => resource.upserted !== "unchanged";
		return entries.filter((_, index) => written(upserted[index]) || written(bound[index])).map(([recordType]) => recordType);
	}
	/** The types of `types` the source applies: what it applies (enabled only), queried by those types. */
	async appliedTypes(sourceId, types) {
		const applied = await everyPageFor(types, (recordType, page) => this.#client.destinations.listForSource(sourceId, {
			recordType,
			...page
		}));
		const bound = new Set(applied.map((destination) => destination.recordType));
		return types.filter((type) => bound.has(type));
	}
	/** The source's newest run, of any status: one run, asked newest first. */
	async lastRun(sourceId) {
		const [latest] = (await this.#client.runs.list(sourceId, {
			limit: 1,
			sort: "createdAt:desc"
		})).results;
		return latest ? {
			id: latest.id,
			createdAt: latest.createdAt
		} : null;
	}
	async openRun(sourceId, types) {
		const handle = await this.#client.runs.open(sourceId, {
			types,
			onConflict: "abort"
		});
		let records = 0;
		return {
			id: handle.id,
			add: (record) => {
				records += 1;
				handle.add(compact({
					id: record.id,
					type: record.type,
					observedAt: iso(record.observedAt),
					payload: record.payload
				}));
			},
			flush: () => handle.flush(),
			finalize: async (options = {}) => {
				const run = await handle.finalize(compact({
					dryRun: options.dryRun,
					allowFailures: options.allowFailures,
					allowRejections: options.allowRejections,
					maxDeleteRatio: options.maxDeleteRatio
				}));
				return {
					runId: run.id,
					status: run.status,
					records,
					counters: run.counters,
					reconciliation: run.reconciliation
				};
			},
			abort: async () => {
				await handle.abort();
			}
		};
	}
	events(sourceId) {
		const batcher = this.#client.events.batcher(sourceId);
		return {
			upsert: (type, payload, options) => {
				batcher.upsert(type, payload, eventOptions(options));
			},
			delete: (type, payload, options) => {
				batcher.delete(type, payload, eventOptions(options));
			},
			flush: () => batcher.flush(),
			close: () => batcher.close()
		};
	}
};
//#endregion
exports.AdoptPolicy = AdoptPolicy;
exports.ApiKeyToken = ApiKeyToken;
exports.AssignedBy = AssignedBy;
exports.Batcher = Batcher;
exports.CallbackToken = CallbackToken;
exports.ClearSemantics = ClearSemantics;
exports.ClientIngest = ClientIngest;
exports.DEFAULT_AUTH_BASE_URL = DEFAULT_AUTH_BASE_URL;
exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
exports.DEFAULT_MAPPING_TARGET = require_types.DEFAULT_MAPPING_TARGET;
exports.DeletePolicy = DeletePolicy;
exports.DestinationRevisionAction = DestinationRevisionAction;
exports.DriftCheckStatus = DriftCheckStatus;
exports.DriftPolicy = DriftPolicy;
exports.DriftType = DriftType;
exports.EmptyLinkSet = EmptyLinkSet;
exports.Engine = Engine;
exports.EntityOrigin = EntityOrigin;
exports.EventBatcher = EventBatcher;
exports.EventOp = EventOp;
exports.FLUSH_EVERY = FLUSH_EVERY;
exports.FieldComparison = FieldComparison;
exports.FieldRule = FieldRule;
exports.HttpMethod = HttpMethod;
exports.IngestClient = IngestClient;
exports.IngestError = IngestError;
exports.IngestErrorCode = IngestErrorCode;
exports.InputStatus = InputStatus;
exports.MAX_FILTER_VALUES = MAX_FILTER_VALUES;
exports.MappingRevisionAction = MappingRevisionAction;
exports.OnConflict = OnConflict;
exports.OnDelete = OnDelete;
exports.OperationBody = OperationBody;
exports.OperationName = OperationName;
exports.Outcome = Outcome;
exports.PagingStyle = PagingStyle;
exports.ReplayStatus = ReplayStatus;
exports.RunHandle = RunHandle;
exports.RunStatus = RunStatus;
exports.SourceRevisionAction = SourceRevisionAction;
exports.SourceTypeRevisionAction = SourceTypeRevisionAction;
exports.StaticToken = StaticToken;
exports.TargetDeletePolicy = TargetDeletePolicy;
exports.TargetErrorOutcome = TargetErrorOutcome;
exports.TimeoutError = TimeoutError;
exports.UpsertOutcome = UpsertOutcome;
exports.declaredTypes = declaredTypes;
exports.isUuidV7 = require_types.isUuidV7;
exports.pause = pause;
exports.prepareSource = prepareSource;
exports.runCollector = runCollector;
exports.runSnapshot = runSnapshot;
exports.uuidv7 = require_types.uuidv7;
exports.validateDefinition = validateDefinition;

//# sourceMappingURL=index.cjs.map