import { Wt as e, en as t, gn as n } from "./process-statement-common-C3Zo_IH-.js";
import { a as r, o as i, r as a, s as o } from "./statementUtils-CDSNgBCK.js";
import { isArray as s, isObject as c, mapValues as l } from "lodash-es";
import { HttpResponse as u, delay as d, matchRequestUrl as f } from "msw";
import p from "dexie";
//#region src/components-core/interception/Errors.ts
var m = /* @__PURE__ */ function(e) {
	return e[e.Continue = 100] = "Continue", e[e.SwitchingProtocols = 101] = "SwitchingProtocols", e[e.Processing = 102] = "Processing", e[e.EarlyHints = 103] = "EarlyHints", e[e.Ok = 200] = "Ok", e[e.Created = 201] = "Created", e[e.Accepted = 202] = "Accepted", e[e.NonAuthoritativeInformation = 203] = "NonAuthoritativeInformation", e[e.NoContent = 204] = "NoContent", e[e.ResetContent = 205] = "ResetContent", e[e.PartialContent = 206] = "PartialContent", e[e.MultiStatus = 207] = "MultiStatus", e[e.AlreadyReported = 208] = "AlreadyReported", e[e.ImUsed = 226] = "ImUsed", e[e.MultipleChoices = 300] = "MultipleChoices", e[e.MovedPermanently = 301] = "MovedPermanently", e[e.Found = 302] = "Found", e[e.SeeOther = 303] = "SeeOther", e[e.NotModified = 304] = "NotModified", e[e.UseProxy = 305] = "UseProxy", e[e.Unused = 306] = "Unused", e[e.TemporaryRedirect = 307] = "TemporaryRedirect", e[e.PermanentRedirect = 308] = "PermanentRedirect", e[e.BadRequest = 400] = "BadRequest", e[e.Unauthorized = 401] = "Unauthorized", e[e.PaymentRequired = 402] = "PaymentRequired", e[e.Forbidden = 403] = "Forbidden", e[e.NotFound = 404] = "NotFound", e[e.MethodNotAllowed = 405] = "MethodNotAllowed", e[e.NotAcceptable = 406] = "NotAcceptable", e[e.ProxyAuthenticationRequired = 407] = "ProxyAuthenticationRequired", e[e.RequestTimeout = 408] = "RequestTimeout", e[e.Conflict = 409] = "Conflict", e[e.Gone = 410] = "Gone", e[e.LengthRequired = 411] = "LengthRequired", e[e.PreconditionFailed = 412] = "PreconditionFailed", e[e.PayloadTooLarge = 413] = "PayloadTooLarge", e[e.UriTooLong = 414] = "UriTooLong", e[e.UnsupportedMediaType = 415] = "UnsupportedMediaType", e[e.RangeNotSatisfiable = 416] = "RangeNotSatisfiable", e[e.ExpectationFailed = 417] = "ExpectationFailed", e[e.ImATeapot = 418] = "ImATeapot", e[e.MisdirectedRequest = 421] = "MisdirectedRequest", e[e.UnprocessableEntity = 422] = "UnprocessableEntity", e[e.Locked = 423] = "Locked", e[e.FailedDependency = 424] = "FailedDependency", e[e.TooEarly = 425] = "TooEarly", e[e.UpgradeRequired = 426] = "UpgradeRequired", e[e.PreconditionRequired = 428] = "PreconditionRequired", e[e.TooManyRequests = 429] = "TooManyRequests", e[e.RequestHeaderFieldsTooLarge = 431] = "RequestHeaderFieldsTooLarge", e[e.UnavailableForLegalReasons = 451] = "UnavailableForLegalReasons", e[e.InternalServerError = 500] = "InternalServerError", e[e.NotImplemented = 501] = "NotImplemented", e[e.BadGateway = 502] = "BadGateway", e[e.ServiceUnavailable = 503] = "ServiceUnavailable", e[e.GatewayTimeout = 504] = "GatewayTimeout", e[e.HttpVersionNotSupported = 505] = "HttpVersionNotSupported", e[e.VariantAlsoNegotiates = 506] = "VariantAlsoNegotiates", e[e.InsufficientStorage = 507] = "InsufficientStorage", e[e.LoopDetected = 508] = "LoopDetected", e[e.NotExtended = 510] = "NotExtended", e[e.NetworkAuthenticationRequired = 511] = "NetworkAuthenticationRequired", e;
}({}), h = class e extends Error {
	constructor(t, n) {
		super(n?.message || "Not found"), this.details = n, this.status = t, Object.setPrototypeOf(this, e.prototype);
	}
}, g = class e extends h {
	constructor(t) {
		super(m.NotFound, t), Object.setPrototypeOf(this, e.prototype);
	}
}, _ = class e extends h {
	constructor(t) {
		super(m.Unauthorized, t), Object.setPrototypeOf(this, e.prototype);
	}
}, v = class e extends h {
	constructor(t) {
		super(m.Conflict, t), Object.setPrototypeOf(this, e.prototype);
	}
};
function y(e) {
	let t;
	return e && (t = typeof e == "string" ? { message: e } : e), t;
}
var b = {
	NotFound404: (e) => new g(y(e)),
	Unauthorized401: (e) => new _(y(e)),
	HttpError: (e, t) => new h(e, y(t)),
	Conflict409: (e) => new v(y(e))
}, x = { getDate: (e) => e ? new Date(e) : /* @__PURE__ */ new Date() }, S = (e, t) => s(e) ? e.map((e) => S(e, t)) : c(e) ? l(e, (e) => S(e, t)) : t(e), C = class {
	constructor() {
		this.cookies = {};
	}
	setCookie(e, t) {
		this.cookies[e] = t;
	}
	getCookieHeader() {
		let e = [];
		return Object.entries(this.cookies).forEach(([t, n]) => {
			Array.isArray(n) ? n.forEach((n) => e.push(["Set-Cookie", `${t}=${n}`])) : e.push(["Set-Cookie", `${t}=${n}`]);
		}), new Headers(e);
	}
}, w = class {
	constructor() {
		this.headers = {};
	}
	setHeader(e, t) {
		this.headers[e] = t;
	}
	getHeaders() {
		let e = [];
		return Object.entries(this.headers).forEach(([t, n]) => {
			e.push([t, n]);
		}), new Headers(e);
	}
}, T = class {
	constructor(e, t, n) {
		this.definition = e, this.db = t, this.authService = n, this.apiStateHash = {}, this.resolvedHelpers = S(e.helpers, (e) => typeof e == "string" ? (...t) => this.runFn(e, ...t) : e), e.initialize && this.runFn(e.initialize);
	}
	async executeOperation(e, t, n, r) {
		let i = this.definition.operations?.[e];
		if (!i) throw Error(`Unknown backend operation: ${e}`);
		return await this.runFn(i, t, n, r);
	}
	async runFn(t, ...n) {
		let s = E({
			localContext: {
				...this.resolvedHelpers,
				$db: this.db,
				$state: this.apiStateHash,
				$authService: this.authService,
				$env: x,
				$loggedInUser: this.authService.getLoggedInUser(),
				$pathParams: n[0]?.pathParams,
				$queryParams: n[0]?.queryParams,
				$requestBody: n[0]?.requestBody,
				$cookies: n[0]?.cookies,
				$requestHeaders: n[0]?.requestHeaders,
				$cookieService: n[1],
				$headerService: n[2]
			},
			eventArgs: n,
			appContext: {
				...r,
				...o,
				delay: e,
				Errors: b,
				createFile: (...e) => new File(e[0], e[1], e[2]),
				appendBlob: (e, t) => e && t ? new Blob([e, t], { type: e.type || t.type }) : e || t || null,
				getDate: i
			}
		});
		return await a(t, s), s.mainThread?.blocks?.length ? s.mainThread.blocks[s.mainThread.blocks.length - 1].returnValue : void 0;
	}
};
function E(e) {
	return {
		mainThread: {
			childThreads: [],
			blocks: [{ vars: {} }],
			loops: [],
			breakLabelValue: -1
		},
		...e
	};
}
//#endregion
//#region src/components-core/interception/ReadonlyCollection.ts
var D = class e {
	constructor(e) {
		this.list = [];
		for (let t of e) this.list.push(t);
	}
	get length() {
		return this.list.length;
	}
	toArray() {
		return this.list.slice(0);
	}
	at(e) {
		if (e < 0 || e > this.list.length - 1) throw Error(`Index (${e}) is out of range [0..${Math.max(this.list.length - 1, 0)}]`);
		return this.list[e];
	}
	all() {
		return new e(this.list);
	}
	async single(e) {
		let t = await this.where(e);
		if (t.length === 0) throw Error("No items found with the specified predicate");
		if (t.length > 1) throw Error("Multiple items found with the specified predicate");
		return t.at(0);
	}
	async singleOrDefault(e, t) {
		let n = await this.where(e);
		if (n.length === 0) return t;
		if (n.length > 1) throw Error("Multiple items found with the specified predicate");
		return n.at(0);
	}
	async where(t) {
		return new e(await this.whereAsArray(t));
	}
	async whereAsArray(e) {
		let t = await Promise.all(this.list.map(e ?? (async () => !0)));
		return this.list.filter((e, n) => t[n]);
	}
	async orderBy(...n) {
		return new e(await t(this.list, ...n));
	}
	async orderByAsArray(...e) {
		return await t(this.list, ...e);
	}
	async groupBy(t) {
		return new e(await this.groupByAsArray(t));
	}
	async groupByAsArray(e) {
		let t = /* @__PURE__ */ new Map();
		for (let n of this.list) {
			let r = await e(n), i = t.get(r);
			i === void 0 ? t.set(r, [n]) : i.push(n);
		}
		let n = [];
		for (let [e, r] of t.entries()) n.push({
			key: e,
			items: r
		});
		return n;
	}
	async distinct(t) {
		t ??= async (e) => e;
		let n = /* @__PURE__ */ new Set();
		for (let e of this.list) n.add(await t(e));
		return new e(n.values());
	}
	async distinctAsArray(e) {
		return (await this.distinct(e)).toArray();
	}
	async maxValue(n = "id", r) {
		let i = r ? (await new e(this.list).where(r)).toArray() : this.list;
		return i = await t(i, (e) => e[n], !0), i.length === 0 ? void 0 : i[0][n];
	}
	async skip(t) {
		return new e(this.list.slice(t));
	}
	async take(t) {
		return new e(this.list.slice(0, t));
	}
	async skipTake(t, n) {
		return new e(this.list.slice(t, n + t));
	}
}, O = class {
	constructor(e, t = {}, n) {
		this.tables = e, this.initialData = t, this.config = n, this.db = null, this.getItems = (e) => this.getDb().table(e).toArray(), this.findItems = async (e, t) => {
			let n = await this.getItems(e), r = await Promise.all(n.map(t));
			return n.filter((e, t) => r[t]);
		}, this.getItem = async (e, t) => {
			let n = await this.getItems(e), r = await Promise.all(n.map(t));
			return n.find((e, t) => r[t]);
		}, this.getItemById = async (e, t) => await this.getItem(e, (e) => Promise.resolve(e.id + "" == t + "")), this.deleteItems = async (e, t) => {}, this.insertItem = async (e, t) => {
			let n = await this.getDb().table(e).add(t);
			return this.getItemById(e, n);
		}, this.updateItem = async (e, t) => (await this.getDb().table(e).update(t.id, t), await this.getItemById(e, t.id));
	}
	getDb() {
		if (this.db === null) throw Error("Db is not initialized yet");
		return this.db;
	}
	async initialize() {
		let e = typeof this.initialData == "function" ? await this.initialData() : this.initialData, t = {}, n = /* @__PURE__ */ new Set();
		this.tables ? this.tables.forEach((e) => {
			let r = [];
			e.pk.length === 1 ? r.push(e.pk[0]) : r.push(`[${e.pk.join("+")}]`), e.indexes && r.push(...e.indexes), t[e.name] = r.join(", "), n.add(e.name);
		}) : Object.entries(e).forEach(([e]) => {
			t[e] = "++id", n.add(e);
		});
		let r = this.config?.version !== void 0 && typeof this.config?.version == "number" ? this.config?.version : 1, i = await this.dropDbOnVersionChange(r);
		this.db = this.createDbInstance(), this.db.version(r).stores(t), i && await Promise.all(Object.entries(e).map(async ([e, t]) => {
			try {
				await this.getDb().table(e).bulkAdd(t);
			} catch (e) {
				console.error(e);
			}
		})), n.forEach((e) => {
			this[`$${e}`] = k(this.getDb().table(e));
		});
	}
	createDbInstance() {
		return new p(this.config?.database ?? "defaultIndexDb");
	}
	async dropDbOnVersionChange(e) {
		let t = this.createDbInstance();
		return await p.exists(t.name) ? (await t.open(), t.verno === e ? (t.close(), !1) : (await t.delete(), !0)) : !0;
	}
	async transaction(e) {
		if (!this.db) return;
		let t = this.db.tables;
		await this.db.transaction("rw", t, e);
	}
};
function k(e) {
	let t = () => e.db.table(e.name), n = async (t) => {
		let n = await e.toArray(), r = await Promise.all(n.map(t ?? (() => Promise.resolve(!0))));
		return n.filter((e, t) => r[t]);
	};
	return {
		native: t,
		insert: async (n) => {
			let r = await e.add(n);
			return t().get(r);
		},
		update: async (n) => (await e.update(n.id, n), t().get(n.id)),
		save: async (t) => {
			let n = await e.put(t);
			return e.get(n);
		},
		deleteById: async (t) => {
			await e.delete(t);
		},
		byId: async (t) => {
			if (t == null) return null;
			let n = t;
			return e.schema.primKey.src === "++id" && (n = Number(t)), await e.get(n);
		},
		toArray: async () => await e.toArray(),
		single: async (t) => await new D(await e.toArray()).single(t),
		singleOrDefault: async (t, n) => await new D(await e.toArray()).singleOrDefault(t, n),
		where: async (e) => new D(await n(e)),
		whereAsArray: async (e) => await n(e),
		orderBy: async (...t) => await new D(await e.toArray()).orderBy(...t),
		orderByAsArray: async (...t) => await new D(await e.toArray()).orderByAsArray(...t),
		groupBy: async (t) => await new D(await e.toArray()).groupBy(t),
		groupByAsArray: async (t) => await new D(await e.toArray()).groupByAsArray(t),
		distinct: async (t) => await new D(await e.toArray()).distinct(t),
		distinctAsArray: async (t) => await new D(await e.toArray()).distinctAsArray(t),
		maxValue: async (t = "id", n) => await new D(await e.toArray()).maxValue(t, n),
		skip: async (t) => await new D(await e.toArray()).skip(t),
		take: async (t) => await new D(await e.toArray()).take(t),
		skipTake: async (t, n) => await new D(await e.toArray()).skipTake(t, n)
	};
}
//#endregion
//#region src/components-core/utils/request-params.ts
function A(e, t) {
	if (!t) return e;
	let n = { ...e };
	return Object.keys(e).forEach((r) => {
		if (!(r in t)) return;
		let i = e[r], a = typeof i;
		switch (t[r]) {
			case "integer":
				switch (a) {
					case "number":
						n[r] = Math.round(i);
						break;
					case "string":
						n[r] = parseInt(i, 10);
						break;
					case "boolean":
						n[r] = +!!i;
						break;
				}
				break;
			case "float":
			case "real":
			case "double":
				switch (a) {
					case "number":
						n[r] = i;
						break;
					case "string":
						n[r] = parseFloat(i);
						break;
					case "boolean":
						n[r] = +!!i;
						break;
				}
				break;
			case "boolean":
				switch (a) {
					case "string":
						switch (i.toLowerCase()) {
							case "true":
							case "yes":
							case "on":
								n[r] = !0;
								break;
							case "false":
							case "no":
							case "off":
								n[r] = !1;
								break;
						}
						break;
					case "number":
						n[r] = !!i;
						break;
				}
				break;
		}
	}), n;
}
//#endregion
//#region src/components-core/interception/InMemoryDb.ts
var j = class {
	constructor(e, t = {}, n) {
		this.tables = e, this.initialData = t, this.config = n;
	}
	getItems(e) {
		throw Error("Method not implemented.");
	}
	getItem(e, t) {
		throw Error("Method not implemented.");
	}
	getItemById(e, t) {
		throw Error("Method not implemented.");
	}
	deleteItems(e, t) {
		throw Error("Method not implemented.");
	}
	insertItem(e, t) {
		throw Error("Method not implemented.");
	}
	updateItem(e, t) {
		throw Error("Method not implemented.");
	}
	async initialize() {}
};
//#endregion
//#region src/components-core/interception/ApiInterceptor.ts
function M(...e) {
	let t = {};
	for (let n of e) {
		if (!c(n)) throw TypeError("All arguments must be of type object");
		let e = new Headers(n);
		for (let [n, r] of e.entries()) r === void 0 || r === "undefined" ? delete t[n] : t[n] = r;
	}
	return new Headers(t);
}
var N = class {
	constructor(e) {
		let t = JSON.parse(sessionStorage.getItem("session-logged-in-user"));
		this.loggedInUser = t || e?.defaultLoggedInUser;
	}
	login(e) {
		this.loggedInUser = e, sessionStorage.setItem("session-logged-in-user", JSON.stringify(e));
	}
	logout() {
		this.loggedInUser = null, sessionStorage.removeItem("session-logged-in-user");
	}
	getCookieToken() {
		return sessionStorage.getItem("session-anonymous-token");
	}
	setCookieToken(e) {
		sessionStorage.setItem("session-anonymous-token", e);
	}
	getLoggedInUser() {
		return this.loggedInUser;
	}
};
async function P(e) {
	switch (e.type) {
		case "in-memory": return new j(e.schemaDescriptor?.tables, e.initialData, e.config);
		default:
			let t = new O(e.schemaDescriptor?.tables, e.initialData, e.config);
			return await t.initialize(), t;
	}
}
var F = class {
	constructor(e) {
		this.apiDef = e, this.backend = null;
	}
	async initialize() {
		let e = {};
		Object.entries(this.apiDef.operations || {}).forEach(([t, n]) => {
			e[t] = n.handler;
		});
		let t = await P(this.apiDef), n = new N(this.apiDef.auth), r = {
			operations: e,
			initialize: this.apiDef.initialize,
			helpers: this.apiDef.helpers
		};
		this.backend = new T(r, t, n);
	}
	getOperations() {
		return this.apiDef.operations || {};
	}
	getApiUrl() {
		return this.apiDef.apiUrl || "";
	}
	async executeOperation(e, t, r, i) {
		if (this.backend === null) throw Error("Interceptor not initialized");
		let a = this.apiDef.operations?.[e];
		if (!a) throw Error(`Unknown API interceptor operation: ${e}`);
		let o;
		try {
			if (a.requestShape === "formData") {
				let e = await t.formData(), n = {};
				for (let t of e.keys()) {
					let r = e.getAll(t);
					r.length === 1 ? n[t] = r[0] : n[t] = r;
				}
				o = n;
			} else o = a.requestShape === "blob" ? await t.blob() : await t.json();
		} catch {}
		let s = this.convertRequestParams({
			pathParams: i,
			queryParams: Object.fromEntries(new URL(t.url).searchParams),
			requestBody: o,
			cookies: r,
			requestHeaders: Object.fromEntries(t.headers.entries()) || {}
		}, a);
		this.apiDef.artificialDelay === void 0 ? await d("real") : this.apiDef.artificialDelay !== 0 && await d(this.apiDef.artificialDelay);
		let c = new C(), l = new w();
		try {
			let t = await this.backend.executeOperation(e, s, c, l), n = t == null, r = a.successStatusCode ?? (n ? m.NoContent : m.Ok), i = M(c.getCookieHeader(), l.getHeaders());
			if (t instanceof File) {
				i.append("Content-type", t.type), i.append("Content-Length", t.size + "");
				let e = encodeURIComponent(t.name);
				return i.append("Content-Disposition", `attachment; filename*=UTF-8''${e}`), u.arrayBuffer(await t.arrayBuffer(), {
					headers: i,
					status: r
				});
			}
			return n ? new u(null, {
				headers: i,
				status: r
			}) : typeof t == "string" ? u.text(t, {
				headers: i,
				status: r
			}) : u.json(t, {
				headers: i,
				status: r
			});
		} catch (e) {
			return console.error(e), e instanceof n && e.errorObject instanceof h ? u.json(e.errorObject.details, {
				headers: c.getCookieHeader(),
				status: e.errorObject.status
			}) : u.json({ message: e?.message }, {
				headers: c.getCookieHeader(),
				status: m.InternalServerError
			});
		}
	}
	convertRequestParams(e, t) {
		return {
			...e,
			pathParams: A(e.pathParams, t.pathParamTypes),
			queryParams: A(e.queryParams, t.queryParamTypes)
		};
	}
	hasMockForRequest(e, t) {
		return this.getMockForRequest(e, t) !== void 0;
	}
	getMockForRequest(e, t) {
		return Object.entries(this.getOperations()).find(([n, r]) => !!(f(new URL(e, window.location.href), `${this.getApiUrl()}${r.url}`, `${window.location.href}`).matches && (t.method || "get").toLowerCase() === r.method.toLowerCase()));
	}
	executeMockedFetch(e, t) {
		let n = this.getMockForRequest(e, t);
		if (!n) throw Error(`No mock found for request: ${e} with options: ${JSON.stringify(t)}`);
		let [r, i] = n, a = f(new URL(e, window.location.href), `${this.getApiUrl()}${i.url}`, `${window.location.href}`);
		return this.executeOperation(r, new Request(e, t), I(), a.params);
	}
};
function I() {
	let e = document.cookie;
	return e === "" ? {} : e.split("; ").reduce((e, t) => {
		let [n, r] = t.split("=");
		return e[decodeURIComponent(n)] = decodeURIComponent(r), e;
	}, {});
}
//#endregion
//#region src/components-core/interception/initMock.ts
var L = async (e) => {
	let t = new F(e);
	return await t.initialize(), t;
};
//#endregion
export { L as initMock };

//# sourceMappingURL=initMock-CXEnFuSB.js.map