@telia-ace/alliance-internal-node-utilities 1.0.6 → 1.1.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,737 +1,4 @@
1
- import jwt from 'jsonwebtoken';
2
- import { createPublicKey } from 'node:crypto';
3
- import { z } from 'zod';
4
- import { validate } from 'jsonschema';
5
- import { existsSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
6
- import { resolve } from 'node:path';
7
- import _slugify from 'slugify';
8
- import pino from 'pino';
9
-
10
- // src/auth/tokens.ts
11
- var zBooleanEnum = z.enum(["true", "false"]).transform((strBool) => strBool === "true");
12
- var zNonEmptyString = z.string().min(1);
13
- var zSharedConfig = z.object({
14
- /**
15
- * Name for the cookie storing the user session
16
- *
17
- * Optional, defaults to "alliance-auth"
18
- */
19
- AUTH_COOKIE_NAME: zNonEmptyString.default("alliance-auth"),
20
- /**
21
- * Secret to use when signing the user session cookie
22
- *
23
- * Optional, defaults to "zlLZBlk7wt8lypP5lA4D"
24
- */
25
- AUTH_COOKIE_SECRET: zNonEmptyString.default("zlLZBlk7wt8lypP5lA4D"),
26
- /**
27
- * Endpoint to use when communicating with the Data API
28
- */
29
- DB_ENDPOINT: zNonEmptyString,
30
- /**
31
- * Private key to use when signing JWT tokens
32
- *
33
- * Optional, defaults to "MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="
34
- */
35
- JWT_PRIVATE_KEY: zNonEmptyString.default(
36
- "MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="
37
- ),
38
- /**
39
- * Public key type used by old versions of .NET.
40
- *
41
- * Optional, defaults to "BgIAAACkAABSU0ExAAgAAAEAAQDFBQ9thkQ01wvaRFcDRPpOrbd6hsXHAAiEdjof2NPPY02VZZMTW3MXxYJZkMm4suCbyeqc6FUI2kZ4DzUBHCQY/pQYRk3SiBhCYbvFvMNrxAmRzqk22FLAHedKEnJPgZpU9J6LCrfgw/do/d5YFk2vE/PYWD8rqev+LaegJ2DCwkklOMoaBByPGQj+0BoXZVRx7qLYRdq1IgNk/yHvDu5OkLyt97E/G2l7zdW04i9SiPF+yaEKJ8NEjViowY0tAdNYpLFsezhrLU3ev0rVeUrDEq+8f8uPUaYnAT8t+tmgcgkFi+SzQr2YQmrZ7SMKTuIqJ2CAoTqUmNBC3znOjmqw"
42
- */
43
- JWT_PUBLIC_CSP_KEY: z.string().min(1).default(
44
- "BgIAAACkAABSU0ExAAgAAAEAAQDFBQ9thkQ01wvaRFcDRPpOrbd6hsXHAAiEdjof2NPPY02VZZMTW3MXxYJZkMm4suCbyeqc6FUI2kZ4DzUBHCQY/pQYRk3SiBhCYbvFvMNrxAmRzqk22FLAHedKEnJPgZpU9J6LCrfgw/do/d5YFk2vE/PYWD8rqev+LaegJ2DCwkklOMoaBByPGQj+0BoXZVRx7qLYRdq1IgNk/yHvDu5OkLyt97E/G2l7zdW04i9SiPF+yaEKJ8NEjViowY0tAdNYpLFsezhrLU3ev0rVeUrDEq+8f8uPUaYnAT8t+tmgcgkFi+SzQr2YQmrZ7SMKTuIqJ2CAoTqUmNBC3znOjmqw"
45
- ),
46
- /**
47
- * Log level to output
48
- *
49
- * Supports "silent" | "fatal" | "error" | "warn" | "info" | "debug" | "trace"
50
- *
51
- * Optional, defaults to "trace"
52
- */
53
- SERVICE_LOG_LEVEL: z.enum(["silent", "fatal", "error", "warn", "info", "debug", "trace"]).default("trace"),
54
- /**
55
- * Port to run the service on.
56
- *
57
- * Optional, defaults to "3000"
58
- */
59
- SERVICE_PORT: zNonEmptyString.transform(Number).default("3000"),
60
- /**
61
- * Url to redis server to use when storing / reading user session information.
62
- */
63
- REDIS_HOST: zNonEmptyString,
64
- /**
65
- * Password to redis server to use when storing / reading user session information.
66
- *
67
- * Optional
68
- */
69
- REDIS_PASSWORD: zNonEmptyString.optional()
70
- });
71
-
72
- // src/constants/headers.ts
73
- var AllianceHeaders = /* @__PURE__ */ ((AllianceHeaders2) => {
74
- AllianceHeaders2["TargetUrl"] = "alliance-target-url";
75
- AllianceHeaders2["TargetApp"] = "alliance-target-app";
76
- AllianceHeaders2["TargetWorkspace"] = "alliance-target-workspace";
77
- return AllianceHeaders2;
78
- })(AllianceHeaders || {});
79
-
80
- // src/auth/tokens.ts
81
- zSharedConfig.pick({ JWT_PRIVATE_KEY: true, JWT_PUBLIC_CSP_KEY: true });
82
- function createBearerToken({
83
- privateKey,
84
- aud,
85
- sub,
86
- name,
87
- user,
88
- workspace,
89
- expiration = "1h"
90
- }) {
91
- const token = jwt.sign(
92
- {
93
- iss: "Alliance",
94
- aud,
95
- sub,
96
- name,
97
- "https://alliance.teliacompany.net/user_type": user.type,
98
- "https://alliance.teliacompany.net/user_email": user.email,
99
- "https://alliance.teliacompany.net/user_privileges": user.permissions,
100
- "https://alliance.teliacompany.net/workspace": workspace.slug,
101
- "https://alliance.teliacompany.net/workspace_name": workspace.name,
102
- "https://alliance.teliacompany.net/tenant": workspace.slug,
103
- "https://alliance.teliacompany.net/tenant_name": workspace.name
104
- },
105
- privateKey,
106
- {
107
- expiresIn: expiration,
108
- algorithm: "RS256"
109
- }
110
- );
111
- return `Bearer ${token}`;
112
- }
113
- function getPrivateKey(config) {
114
- return "-----BEGIN RSA PRIVATE KEY-----\n" + config.JWT_PRIVATE_KEY + "\n-----END RSA PRIVATE KEY-----";
115
- }
116
- function createSystemUserToken(config) {
117
- return createBearerToken({
118
- aud: "system",
119
- sub: "system",
120
- name: "system",
121
- workspace: {
122
- slug: "system",
123
- name: "system"
124
- },
125
- user: {
126
- type: "system",
127
- permissions: [],
128
- email: "system"
129
- },
130
- privateKey: getPrivateKey(config)
131
- });
132
- }
133
- function createPublicKeys(config) {
134
- const priv = getPrivateKey(config);
135
- const generatedKey = createPublicKey(priv);
136
- return {
137
- pkcs: generatedKey.export({ type: "pkcs1", format: "pem" }).toString().trim(),
138
- spki: generatedKey.export({ type: "spki", format: "pem" }).toString().trim(),
139
- csp: config.JWT_PUBLIC_CSP_KEY
140
- };
141
- }
142
- function getCleanPublicKey(type, keys) {
143
- return keys[type].replace("-----BEGIN RSA PUBLIC KEY-----", "").replace("-----END RSA PUBLIC KEY-----", "").replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "").trim().replaceAll("\n", "");
144
- }
145
-
146
- // src/distribution/cookie-policy.ts
147
- function generateCookiePolicyHtml(appManifests) {
148
- const cookiePolicyTableRows = [];
149
- for (const appName in appManifests) {
150
- const manifest = appManifests[appName];
151
- if (!manifest.storage) {
152
- continue;
153
- }
154
- for (const [key, value] of Object.entries(manifest.storage)) {
155
- const tableRow = createCookiePolicyTableRow(key, value);
156
- cookiePolicyTableRows.push(tableRow);
157
- }
158
- }
159
- return cookiePolicyHtml.replace("{APP_COOKIES}", cookiePolicyTableRows.join(""));
160
- }
161
- function createCookiePolicyTableRow(key, claimEntry) {
162
- const rows = ["<tr>"];
163
- const { category, purpose, lifespan } = claimEntry;
164
- rows.push(`<td>${key}</td>`);
165
- rows.push(`<td>${category}</td>`);
166
- rows.push(`<td>${purpose}</td>`);
167
- rows.push(`<td>${lifespan}</td>`);
168
- rows.push("</tr>");
169
- return rows.join("");
170
- }
171
- var cookiePolicyHtml = `
172
- <!DOCTYPE html>
173
- <html lang="en">
174
- <head>
175
- <meta charset="UTF-8" />
176
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
177
- <title>ACE Alliance - Cookie Policy</title>
178
- <link
179
- rel="icon"
180
- href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAGcElEQVRYha2Xe4xUVx3HP7/fPTOzDLO7sw8RlzWlZEtp2dCy0qIVWltKU/UPDZH6ijXWEK2odPcPa2qbhpi2kSa7blSStsFUjNq0lWCMaVMx8rAm22IJMJRHCqFC6BJ22eEx+5p7z88/7sywC7uwgCe5mXsz5/y+j/M753eOcJ2tK5sDyBrME2gBmkBq43/tnMERgXdAjrbn518yXq4RNA3cB/J54HNiMhfEicm4oAYghmHexN4Dew5k01giUybQlc1h0CbI9zC+Imi9mCAIYhoHsnI4KcNjYoDhxWPxsxFY1Z5vHQVwVwSu3Qdid4E8rSb3i6mqKYwBjpWX1V/QZBiYYWIIiifCw8Mm/vS7L/W237FqJno58M5srgmxP4npjsAHDwTeaeAdagGBdwQWoBYgFqCmqGlMqvTE3+U+ipbeE+ngB42Lde6kDnRmcwisAHlBfdBYCYxStp3y7xjTJ51RA0XxgGCkasQFSfkW8NQlBDqzORVYK6ZPqAU6ThUyqd0TN7mQDRZ/CULzvVVeRO68xIGubE6BbjH9oVqA+thaQccpvjLwRDTit2RG/fxVGR3sLc4ELuRAV90+gJ/G4K4EHpRs1wr7qwW/uH36uaxPzwz0xNZhHUfAzJZgsjZWrqXEiTP9WlRP1Bb+pCacs2KaCwvmD/5+cLhCoCubU0G61QJXyWYkVv9/Av/UEzVh2+PVDmDPr875ob4oD6UcMLhfTdqU8dket+sDD6rwS7vrfMs30i4qRhzfMhwe3FhwQG+FgMDKytIyKe1o1zffZlB3swvve7mehgVJZ95zatdouG31gHpvoHYUwHVmc4AsqoCXYK9HtzhYsDoTLnqyRl1a1QxOvjMavrmyT4sFr6hhsA/AZUbqKKTy9ZfCXhuFpntS4WfWZWloTcTTa8bh14fCrY/2a3E4UlOLt2jYCeCGE+cBBuPhdk2gZjDjjmS46KkampelnEhMPhwy3/PkGb/vhXPO4zGJ60KyTo5nPpk8wg5wPz57M13Z3PuGzRtTxEovV3BBoXlZKrytvZqmpSknKhVCJ3tGwu2rBxjYHzrEymUZw9Py0LQtD6yb7aG8CoR/mNgKs1LHEomJ4M2M9McDf9PX0n7eI9OpbXEVxQCFE5F/d+0Zf+iPgy7e/GPDjVj9rGXJcO7D6b+yLu7vABavrd10/O8jz5/cFqXNFBGr1HYzQ0SoviEIm5dXceOXpvGJpSkNEjJuGy+ciPzu7nN+/4aCRkM2vsaUrM/coH7ed9Ond3WffbPyF8CxQ/1Y5F8b/C9fHthlFPvFB05JNzqtvSnBxxYmmN4UVCwe60b/7mK4d/15Dr82qH50fHkva/fiSc00v/SlGr97fX79ytdb1owjAHDwX71tVbWuJ9OQdMl0gmTKESQUVWGsxQDD/ZE/snnIH/xdgVP/KU5yqCnBi2f6bPF3b6jxe17Mhx9sKizsyLceKPeqDP7bF/rfa2xLvHrLN6sfmr08o0GDqAaCIYRD3g/sD/1Hb49w7K1hev89otEoTi6To+V5n3l3Mryru1r3vpjn8KbCZjU5MLbfuBCd2VyzIHsTgauZ3pAkkXIanScc6Tf1RfRiJyYHN4Iq/O2PZ/zc71Rpz89P+30bz4QmdltHvvXQpARKJB5R0w0XSvL4cjwV+FnLU+HiZ2tUpxtbf9Tnj20vOJPo2fZ8688u7n3pmdB42Yt/xUuESVQ+yVJexZNtVmbQ2JYIH9zcGC5/pd71Hxjxm5f1cnzboDPx7xs8M9G4CSV1ZnOZICE7GNXbKweTMU7EA6USoemeVLhgTYame1Nu4MBI2PN0ng+3DDovIZFG5w37bEe+dc+UCQC8/ZtjzX07i/88saU4J8yLXiAhaCC+fn7Sz/7iNFq+mqZ6TuD6do+Gu7vPcuQvBRf62LlIQ2/Y1zvyra9OhnPZSf1g58k5I6ftDSnqnNFTaOACqmclfP0tSa3KBjrc5/2Hbwz7Q38ocHLniDM8XjxeIrxG3rA16vXXj529dVKMK2bVL2fkmhrmJ/9cPy91Z2ZGwhMqQx95TudC8gdCZx4obbMVAhqNGvaoCr99bKD1svGntK4647vg84J8X021PBXlK5gJGJWr11GDb3fkW7dPJfaUi3539iARxSUCz4AsERMVpHwDxMTyhq0HftGRbz071bhXfeooXVJvBR4EbgSGgR6Bt9qvArjc/gfZzPoCTDB+AgAAAABJRU5ErkJggg=="
181
- />
182
- <style>
183
- @charset "UTF-8";
184
- @import 'https://cdn.voca.teliacompany.com/fonts/TeliaSansV10/TeliaSans.css';
185
- @import 'https://fonts.googleapis.com/css?family=Reenie+Beanie';
186
-
187
- body {
188
- font-family: TeliaSans, Helvetica, Arial, Lucida Grande, sans-serif;
189
- }
190
-
191
- body > div {
192
- max-width: 1000px;
193
- margin: 0 auto;
194
- padding: 0 40px 40px;
195
- }
196
- </style>
197
- </head>
198
-
199
- <body>
200
- <div>
201
- <h1>Cookie Policy</h1>
202
- <p>
203
- On our websites, we use cookies and other similar technologies. You can choose
204
- whether you want to allow our websites to store cookies on your computer or not. You
205
- can change your choices at any time.
206
- </p>
207
-
208
- <h2>Your consent is required</h2>
209
- <p>
210
- You choose whether you want to accept cookies on your device or not. Your consent is
211
- required for the use of cookies, but not for such cookies that are necessary to
212
- enable the service that you as a user have requested. If you do not accept our use
213
- of cookies, or if you have previously approved our use and have changed your mind,
214
- you can return to your cookie settings at any time and change your choices. You do
215
- this by clicking on the cookie button/link. You may also need to change the settings
216
- in your browser and manually delete cookies to clear your device of previously
217
- stored cookies.
218
- </p>
219
-
220
- <h2>What are cookies?</h2>
221
- <p>
222
- A cookie is a small text file that is stored on your computer by the web browser
223
- while browsing a website. When we refer to cookies (\u201Ccookies\u201D) in this policy, other
224
- similar technologies and tools that retrieve and store information in your browser,
225
- and in some cases forward such information to third parties, in a manner similar to
226
- cookies. Examples are pixels, local storage, session storage and fingerprinting.
227
- </p>
228
- <p>
229
- The websites will \u201Cremember\u201D and \u201Crecognize\u201D you. This can be done by placing
230
- cookies in three different ways;
231
- </p>
232
- <ul>
233
- <li>The session ends, ie until you close the window in your browser.</li>
234
- <li>
235
- Time-limited, ie the cookie has a predetermined lifespan. The time may vary
236
- between different cookies.
237
- </li>
238
- <li>
239
- Until further notice, ie the information remains until you choose to delete it
240
- yourself. This applies to local storage.
241
- </li>
242
- </ul>
243
- <p>You can always go into your browser and delete already stored cookies yourself.</p>
244
-
245
- <h3>Third Party Cookies</h3>
246
- <p>
247
- We use third-party cookies on our websites. Third-party cookies are stored by
248
- someone other than the person responsible for the website, in this case by a company
249
- other than Telia.
250
- </p>
251
- <p>
252
- Telia uses external platforms to communicate digitally, these include the Google
253
- Marketing Platform and others. The platforms use both first- and third-party cookies
254
- as well as similar techniques to advertise and follow up the results of the
255
- advertising.
256
- </p>
257
- <p>
258
- A third-party cookie can be used by several websites to understand and track how you
259
- browse between different websites. Telia receives information from these cookies,
260
- but the information can also be used for other purposes determined by third parties.
261
- Third-party cookies found on our website are covered by each third-party privacy
262
- policy. Feel free to read these to understand what other purposes the information
263
- can be used for. Links are in our Cookie Table.
264
- </p>
265
- <p>
266
- For information about which third-party cookies are used on our websites, see our
267
- Cookie Table. For more information on how Telia handles personal data in connection
268
- with transfers to third parties, read our Privacy Policy.
269
- </p>
270
-
271
- <h2>Cookies on our websites</h2>
272
- <p>
273
- In order for you to have better control over which cookies are used on the websites,
274
- and thus be able to more easily decide how cookies should be used when you visit our
275
- websites, we have identified four different categories of cookies. These categories
276
- are defined based on the purposes for the use of the cookies.
277
- </p>
278
- <p>
279
- In our Cookie Table, you can also see which category each cookie belongs to, for
280
- what purposes it is used and for how long it is active.
281
- </p>
282
- <p>
283
- We have identified the following four categories of cookies. All categories contain
284
- cookies which means that data is shared with third parties.
285
- </p>
286
-
287
- <h3>Necessary</h3>
288
- <p>
289
- These cookies are needed for our app to work in a secure and correct way. Necessary
290
- cookies enable you to use our app and us to provide the service you request.
291
- Necessary cookies make basic functions of the app possible, for example, identifying
292
- you when you log into My Telia, detecting repeated failed login attempts,
293
- identifying where you are in the buying process and remembering the items put into
294
- your shopping basket.
295
- </p>
296
-
297
- <h3>Functionality</h3>
298
- <p>
299
- These cookies let us to enable some useful functionalities to make the user
300
- experience better, for example, to remember your login details and settings.
301
- </p>
302
-
303
- <h3>Analytics</h3>
304
- <p>
305
- These cookies give us information about how you use our app and allow us to improve
306
- the user experience.
307
- </p>
308
-
309
- <h3>Marketing</h3>
310
- <p>
311
- These cookies help us and our partners to display personalized and relevant ads
312
- based on your browsing behavior on our website and in our app, even when you later
313
- visit other (third parties\u2019) websites. These cookies are used to evaluate the
314
- effectiveness of our marketingcampaigns, as well as for targeted marketing and
315
- profiling, regardless of which device(s) you have used. Information collected for
316
- this purpose may also be combined with other customer and traffic data we have about
317
- you, if you have given your consent that we may use your traffic data for marketing
318
- purpose and have not objected to the use of your customer data for marketing
319
- purposes.
320
- </p>
321
-
322
- <h2>Manage settings</h2>
323
- <p>
324
- We save your cookie consent for 12 months. Then we will ask you again. Please note
325
- that some cookies have a lifespan that exceeds these 12 months. You may therefore
326
- need to change the settings in your browser and manually delete all cookies.
327
- </p>
328
- <p>
329
- More information on how to turn off cookies can be found in the instructions for
330
- your browser.
331
- </p>
332
- <ul>
333
- <li>
334
- <a
335
- href="https://support.google.com/accounts/answer/61416?co=GENIE.Platform%3DDesktop&amp;hl=en"
336
- target="_blank"
337
- rel="noopener noreferrer"
338
- >Google Chrome</a
339
- >
340
- </li>
341
- <li>
342
- <a
343
- href="https://privacy.microsoft.com/en-us/windows-10-microsoft-edge-and-privacy"
344
- target="_blank"
345
- rel="noopener noreferrer"
346
- >Microsoft Edge</a
347
- >
348
- </li>
349
- <li>
350
- <a
351
- href="https://support.mozilla.org/en-US/kb/enable-and-disable-cookies-website-preferences"
352
- target="_blank"
353
- rel="noopener noreferrer"
354
- >Mozilla Firefox</a
355
- >
356
- </li>
357
- <li>
358
- <a
359
- href="https://support.microsoft.com/en-gb/help/17442/windows-internet-explorer-delete-manage-cookies"
360
- target="_blank"
361
- rel="noopener noreferrer"
362
- >Microsoft Internet Explorer</a
363
- >
364
- </li>
365
- <li>
366
- <a
367
- href="https://www.opera.com/help/tutorials/security/privacy/"
368
- target="_blank"
369
- rel="noopener noreferrer"
370
- >Opera</a
371
- >
372
- </li>
373
- <li>
374
- <a
375
- href="https://support.apple.com/guide/safari/manage-cookies-and-website-data-sfri11471/mac"
376
- target="_blank"
377
- rel="noopener noreferrer"
378
- >Apple Safari</a
379
- >
380
- </li>
381
- </ul>
382
-
383
- <h3>Do Not Track-signals</h3>
384
- <p>
385
- If you have chosen to turn on the Do Not Track function in your browser, we will not
386
- automatically place cookies for marketing on your device. You make other choices in
387
- your cookie settings.
388
- </p>
389
-
390
- <h3>If you block cookies</h3>
391
- <p>
392
- If you choose not to accept our use of cookies, the functionality and performance of
393
- our websites may deteriorate as certain functions are dependent on cookies. A
394
- blocking of cookies can therefore mean that the websites\u2019 services do not work as
395
- they should.
396
- </p>
397
-
398
- <h3>Your security with us</h3>
399
- <p>
400
- If you want to read more about your rights and how we protect your privacy, go to
401
- our privacy policy for
402
- <a
403
- href="https://www.telia.se/dam/jcr:df2eeb83-50ce-4383-89fc-0613f7615796/Integritetspolicy-privatkunder.pdf"
404
- >private customers</a
405
- >
406
- (C2B) or
407
- <a
408
- href="https://www.telia.se/dam/jcr:95b2b4a5-82ca-436b-90e0-873e0a864118/Telia-integritetspolicy-foretag.pdf"
409
- >corporate customers</a
410
- >
411
- (B2B). You are always welcome to contact us at
412
- <a href="mailto:dpo-se@teliacompany.com">dpo-se@teliacompany.com</a> if you have any
413
- questions.
414
- </p>
415
- <p>Our cookie policy may change in the future.</p>
416
- <p>
417
- More information about cookies can be found at the Swedish Post and Telecom
418
- Authority (PTS).
419
- </p>
420
-
421
- <h2>Our Cookie Table</h2>
422
- <p>
423
- Below, you will find a list of the cookies and similar technologies that we use on
424
- this website. These cookies are stored on your device by us.
425
- </p>
426
- <table>
427
- <thead>
428
- <tr>
429
- <th>Cookie</th>
430
- <th>Category</th>
431
- <th>Purpose</th>
432
- <th>Lifespan</th>
433
- </tr>
434
- </thead>
435
- <tbody>
436
- <tr>
437
- <td>alliance-session-v1</td>
438
- <td>necessary</td>
439
- <td>Contains the authenticated user.</td>
440
- <td>1 day</td>
441
- </tr>
442
- {APP_COOKIES}
443
- </tbody>
444
- </table>
445
- <style>
446
- table {
447
- width: 100%;
448
- border: 1px solid rgba(0, 0, 0, 0.15);
449
- }
450
- th, td {
451
- text-align: left;
452
- padding: 3px;
453
- }
454
- </style>
455
- </div>
456
- </body>
457
- </html>
458
- `;
459
- function getJsonSchemas() {
460
- const frameworkDistDirPath = resolve(
461
- process.cwd(),
462
- "node_modules",
463
- "@telia-ace/alliance-framework",
464
- "dist"
465
- );
466
- const appConfigSchemaPath = resolve(frameworkDistDirPath, "config.schema.json");
467
- const appManifestSchemaPath = resolve(frameworkDistDirPath, "manifest.schema.json");
468
- const appConfigSchemaFile = readFileSync(appConfigSchemaPath).toString();
469
- const appManifestSchemaFile = readFileSync(appManifestSchemaPath).toString();
470
- const appConfig = JSON.parse(appConfigSchemaFile);
471
- const appManifest = JSON.parse(appManifestSchemaFile);
472
- return {
473
- appConfig,
474
- appManifest
475
- };
476
- }
477
- async function createTempModuleAndImport(moduleString, fileName) {
478
- const file = resolve(process.cwd(), `${fileName}.mjs`);
479
- writeFileSync(file, moduleString);
480
- const importedModule = await import(`file:///${file}`);
481
- rmSync(file, { force: true });
482
- return importedModule;
483
- }
484
- async function getAppManifests(apps) {
485
- const moduleStringParts = [];
486
- const manifestImportVariables = [];
487
- for (const packageName of apps) {
488
- const manifestImportVariable = `app${apps.indexOf(packageName)}`;
489
- manifestImportVariables.push(manifestImportVariable);
490
- moduleStringParts.push(`import ${manifestImportVariable} from '${packageName}/manifest';`);
491
- }
492
- moduleStringParts.push(`export default [${manifestImportVariables.join(", ")}];`);
493
- const result = await createTempModuleAndImport(
494
- moduleStringParts.join("\n"),
495
- "app-manifests"
496
- );
497
- return result.default;
498
- }
499
-
500
- // src/distribution/pkg-json.ts
501
- function getPkgJson() {
502
- const packageJson = resolve(process.cwd(), "package.json");
503
- const pkgJsonFile = readFileSync(packageJson).toString();
504
- return JSON.parse(pkgJsonFile);
505
- }
506
- async function getManifests(pkgJson) {
507
- if (!pkgJson || !pkgJson.alliance || !pkgJson.alliance.apps) {
508
- throw new Error("Alliance apps not defined in package.json.");
509
- }
510
- const manifestArray = await getAppManifests(pkgJson.alliance.apps);
511
- return manifestArray.reduce((acc, curr) => {
512
- acc[curr.name] = curr;
513
- return acc;
514
- }, {});
515
- }
516
-
517
- // src/distribution/create-public-files.ts
518
- var PUBLIC_DIR_NAME = "public";
519
- var MANIFESTS_FILE_NAME = "manifests.json";
520
- var COOKIE_POLICY_FILE_NAME = "cookie-policy.html";
521
- var APP_CONFIG_SCHEMA_FILE_NAME = "config.schema.json";
522
- var APP_MANIFEST_SCHEMA_FILE_NAME = "manifest.schema.json";
523
- async function createPublicDistributionFiles() {
524
- const pkgJson = getPkgJson();
525
- const manifests = await getManifests(pkgJson);
526
- const schemas = getJsonSchemas();
527
- for (const appName in manifests) {
528
- const manifest = manifests[appName];
529
- const validationResult = validate(manifest, schemas.appManifest);
530
- if (validationResult.errors.length) {
531
- const errors2 = validationResult.errors.map((e) => JSON.stringify(e, null, 2));
532
- throw new Error(
533
- `Validation of app manifest for app '${appName}' failed with the following errors:
534
- ${errors2.join(
535
- "\n"
536
- )}`
537
- );
538
- }
539
- }
540
- const publicDirPath = resolve(process.cwd(), PUBLIC_DIR_NAME);
541
- if (!existsSync(publicDirPath)) {
542
- mkdirSync(publicDirPath);
543
- }
544
- const manifestsFilePath = resolve(publicDirPath, MANIFESTS_FILE_NAME);
545
- writeFileSync(manifestsFilePath, JSON.stringify(manifests));
546
- const cookiePolicyFilePath = resolve(publicDirPath, COOKIE_POLICY_FILE_NAME);
547
- writeFileSync(cookiePolicyFilePath, generateCookiePolicyHtml(manifests));
548
- const appConfigSchemaFilePath = resolve(publicDirPath, APP_CONFIG_SCHEMA_FILE_NAME);
549
- const appManifestSchemaFilePath = resolve(publicDirPath, APP_MANIFEST_SCHEMA_FILE_NAME);
550
- writeFileSync(appConfigSchemaFilePath, JSON.stringify(schemas.appConfig));
551
- writeFileSync(appManifestSchemaFilePath, JSON.stringify(schemas.appManifest));
552
- }
553
- function slugify(value, replacement = "-") {
554
- return _slugify(value, { strict: true, replacement, lower: true });
555
- }
556
- function logFn(instance) {
557
- return (level) => {
558
- return (msg, data) => instance[level]({ ...data, msg });
559
- };
560
- }
561
- function createLogger(config) {
562
- const instance = pino({
563
- level: config.SERVICE_LOG_LEVEL,
564
- redact: [
565
- "authorization",
566
- "headers.authorization",
567
- "req.headers.authorization",
568
- "res.headers.authorization",
569
- "req.headers.cookie",
570
- 'res.headers["set-cookie"]'
571
- ]
572
- });
573
- return {
574
- fatal: logFn(instance)("fatal"),
575
- error: logFn(instance)("error"),
576
- warn: logFn(instance)("warn"),
577
- info: logFn(instance)("info"),
578
- debug: logFn(instance)("debug"),
579
- trace: logFn(instance)("trace"),
580
- silent: logFn(instance)("silent"),
581
- child: () => createLogger(config),
582
- level: config.SERVICE_LOG_LEVEL
583
- };
584
- }
585
- function requestLoggerHandler(logger) {
586
- return (req, _, next) => {
587
- logger.trace("received request", {
588
- url: req.url,
589
- params: req.params,
590
- query: req.query,
591
- body: req.body
592
- });
593
- return next();
594
- };
595
- }
596
-
597
- // src/errors/codes.ts
598
- var GatewayErrorCode = /* @__PURE__ */ ((GatewayErrorCode2) => {
599
- GatewayErrorCode2[GatewayErrorCode2["NoObjectId"] = 10001] = "NoObjectId";
600
- GatewayErrorCode2[GatewayErrorCode2["NoTargetAppHeader"] = 10002] = "NoTargetAppHeader";
601
- GatewayErrorCode2[GatewayErrorCode2["NoTargetWorkspaceHeader"] = 10003] = "NoTargetWorkspaceHeader";
602
- GatewayErrorCode2[GatewayErrorCode2["NoManifestsInCache"] = 10004] = "NoManifestsInCache";
603
- GatewayErrorCode2[GatewayErrorCode2["NoDevSessionInCache"] = 10005] = "NoDevSessionInCache";
604
- GatewayErrorCode2[GatewayErrorCode2["NoManifest"] = 10006] = "NoManifest";
605
- GatewayErrorCode2[GatewayErrorCode2["NoRequestContext"] = 10007] = "NoRequestContext";
606
- GatewayErrorCode2[GatewayErrorCode2["NoUserInRequestContext"] = 10008] = "NoUserInRequestContext";
607
- GatewayErrorCode2[GatewayErrorCode2["NoAppInRequestContext"] = 10009] = "NoAppInRequestContext";
608
- GatewayErrorCode2[GatewayErrorCode2["NoWorkspaceInRequestContext"] = 10010] = "NoWorkspaceInRequestContext";
609
- GatewayErrorCode2[GatewayErrorCode2["NoUserPermissionsInRequestContext"] = 10012] = "NoUserPermissionsInRequestContext";
610
- GatewayErrorCode2[GatewayErrorCode2["WorkspacePermissionDenied"] = 10013] = "WorkspacePermissionDenied";
611
- GatewayErrorCode2[GatewayErrorCode2["NoTargetUrlHeader"] = 10014] = "NoTargetUrlHeader";
612
- GatewayErrorCode2[GatewayErrorCode2["NoSessionInRedisCache"] = 10015] = "NoSessionInRedisCache";
613
- return GatewayErrorCode2;
614
- })(GatewayErrorCode || {});
615
- var DataErrorCode = /* @__PURE__ */ ((DataErrorCode2) => {
616
- DataErrorCode2[DataErrorCode2["NoPublicKey"] = 11e3] = "NoPublicKey";
617
- DataErrorCode2[DataErrorCode2["NoAuthHeader"] = 11001] = "NoAuthHeader";
618
- DataErrorCode2[DataErrorCode2["FailedFileUpload"] = 11002] = "FailedFileUpload";
619
- DataErrorCode2[DataErrorCode2["FailedFileDownload"] = 11003] = "FailedFileDownload";
620
- return DataErrorCode2;
621
- })(DataErrorCode || {});
622
- var errors = {
623
- [10001 /* NoObjectId */]: {
624
- statusCode: 401,
625
- msg: "No object id available on authenticated user."
626
- },
627
- [10002 /* NoTargetAppHeader */]: {
628
- statusCode: 400,
629
- msg: `Request missing header '${"alliance-target-app" /* TargetApp */}'.`
630
- },
631
- [10003 /* NoTargetWorkspaceHeader */]: {
632
- statusCode: 400,
633
- msg: `Request missing header '${"alliance-target-workspace" /* TargetWorkspace */}'.`
634
- },
635
- [10014 /* NoTargetUrlHeader */]: {
636
- statusCode: 400,
637
- msg: `Request missing header '${"alliance-target-url" /* TargetUrl */}'.`
638
- },
639
- [10004 /* NoManifestsInCache */]: {
640
- statusCode: 500,
641
- msg: "App manifests missing in cache."
642
- },
643
- [10005 /* NoDevSessionInCache */]: {
644
- statusCode: 500,
645
- msg: "No dev session in memory cache."
646
- },
647
- [10015 /* NoSessionInRedisCache */]: {
648
- statusCode: 401,
649
- msg: "Could not find user session in Redis server."
650
- },
651
- [10006 /* NoManifest */]: {
652
- statusCode: 500,
653
- msg: "Could not find manifest for app '{{appSlug}}'."
654
- },
655
- [10007 /* NoRequestContext */]: {
656
- statusCode: 500,
657
- msg: "No request context."
658
- },
659
- [10008 /* NoUserInRequestContext */]: {
660
- statusCode: 500,
661
- msg: "No user in request context."
662
- },
663
- [10009 /* NoAppInRequestContext */]: {
664
- statusCode: 500,
665
- msg: "No app in request context."
666
- },
667
- [10010 /* NoWorkspaceInRequestContext */]: {
668
- statusCode: 500,
669
- msg: "No workspace in request context."
670
- },
671
- [10012 /* NoUserPermissionsInRequestContext */]: {
672
- statusCode: 500,
673
- msg: "No user permissions in request context."
674
- },
675
- [10013 /* WorkspacePermissionDenied */]: {
676
- statusCode: 403,
677
- msg: "User does not have access to the current workspace."
678
- },
679
- [11e3 /* NoPublicKey */]: {
680
- statusCode: 401,
681
- msg: "No public key available to decode JWT."
682
- },
683
- [11001 /* NoAuthHeader */]: {
684
- statusCode: 401,
685
- msg: "No authorization header found."
686
- },
687
- [11002 /* FailedFileUpload */]: {
688
- statusCode: 500,
689
- msg: "Something went wrong when trying to upload a file to the S3 storage."
690
- },
691
- [11003 /* FailedFileDownload */]: {
692
- statusCode: 500,
693
- msg: "Something went wrong when trying to download a file to the S3 storage."
694
- },
695
- [12e3 /* NoObjectId */]: {
696
- statusCode: 401,
697
- msg: "No object id found in user claims."
698
- }
699
- };
700
-
701
- // src/errors/errors.ts
702
- var AllianceError = class extends Error {
703
- constructor(errorCode, variables = {}) {
704
- const { msg, statusCode } = errors[errorCode];
705
- const message = parseTemplates(msg, variables);
706
- super(message);
707
- this.errorCode = errorCode;
708
- this.info = `https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${this.errorCode}`;
709
- this.message = message;
710
- this.statusCode = statusCode;
711
- }
712
- };
713
- function parseTemplates(message, variables) {
714
- return Object.entries(variables).reduce((acc, [key, value]) => {
715
- return acc.replaceAll(`{{${key}}}`, value);
716
- }, message);
717
- }
718
- function requestErrorHandler(logger) {
719
- return (err, req, res, _next) => {
720
- const error = {
721
- cause: err.cause,
722
- message: err.message,
723
- status: err.status || err.statusCode || err.code,
724
- info: err.info
725
- };
726
- logger.error("error when processing request", {
727
- url: req.url,
728
- body: req.body,
729
- error
730
- });
731
- return res.status(error.status).json(error);
732
- };
733
- }
734
-
735
- export { AllianceError, AllianceHeaders, DataErrorCode, GatewayErrorCode, createBearerToken, createLogger, createPublicDistributionFiles, createPublicKeys, createSystemUserToken, getCleanPublicKey, getPrivateKey, requestErrorHandler, requestLoggerHandler, slugify, zBooleanEnum, zNonEmptyString, zSharedConfig };
736
- //# sourceMappingURL=out.js.map
737
- //# sourceMappingURL=index.js.map
1
+ import{a as It,b as Et,c as Ct}from"./chunk-RKK7CWA6.js";import"./chunk-26VIM55J.js";import"./chunk-JG7V63GM.js";import Cr from"jsonwebtoken";import{createPublicKey as Sr}from"node:crypto";var k;(function(t){t.assertEqual=s=>s;function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let a={};for(let o of s)a[o]=o;return a},t.getValidEnumValues=s=>{let a=t.objectKeys(s).filter(c=>typeof s[s[c]]!="number"),o={};for(let c of a)o[c]=s[c];return t.objectValues(o)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let o in s)Object.prototype.hasOwnProperty.call(s,o)&&a.push(o);return a},t.find=(s,a)=>{for(let o of s)if(a(o))return o},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(o=>typeof o=="string"?`'${o}'`:o).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(k||(k={}));var je;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(je||(je={}));var p=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),z=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}},d=k.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),St=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),N=class extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){let r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let o of a.issues)if(o.code==="invalid_union")o.unionErrors.map(s);else if(o.code==="invalid_return_type")s(o.returnTypeError);else if(o.code==="invalid_arguments")s(o.argumentsError);else if(o.path.length===0)n._errors.push(r(o));else{let c=n,h=0;for(;h<o.path.length;){let i=o.path[h];h===o.path.length-1?(c[i]=c[i]||{_errors:[]},c[i]._errors.push(r(o))):c[i]=c[i]||{_errors:[]},c=c[i],h++}}};return s(this),n}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)s.path.length>0?(r[s.path[0]]=r[s.path[0]]||[],r[s.path[0]].push(e(s))):n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};N.create=t=>new N(t);var ge=(t,e)=>{let r;switch(t.code){case d.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case d.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,k.jsonStringifyReplacer)}`;break;case d.unrecognized_keys:r=`Unrecognized key(s) in object: ${k.joinValues(t.keys,", ")}`;break;case d.invalid_union:r="Invalid input";break;case d.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${k.joinValues(t.options)}`;break;case d.invalid_enum_value:r=`Invalid enum value. Expected ${k.joinValues(t.options)}, received '${t.received}'`;break;case d.invalid_arguments:r="Invalid function arguments";break;case d.invalid_return_type:r="Invalid function return type";break;case d.invalid_date:r="Invalid date";break;case d.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:k.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case d.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case d.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case d.custom:r="Invalid input";break;case d.invalid_intersection_types:r="Intersection results could not be merged";break;case d.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case d.not_finite:r="Number must be finite";break;default:r=e.defaultError,k.assertNever(t)}return{message:r}},Qe=ge;function Nt(t){Qe=t}function ke(){return Qe}var Te=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],o={...s,path:a},c="",h=n.filter(i=>!!i).slice().reverse();for(let i of h)c=i(o,{data:e,defaultError:c}).message;return{...s,path:a,message:s.message||c}},Rt=[];function m(t,e){let r=Te({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ke(),ge].filter(n=>!!n)});t.common.issues.push(r)}var I=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return v;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r)n.push({key:await s.key,value:await s.value});return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:a,value:o}=s;if(a.status==="aborted"||o.status==="aborted")return v;a.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof o.value<"u"||s.alwaysSet)&&(n[a.value]=o.value)}return{status:e.value,value:n}}},v=Object.freeze({status:"aborted"}),Xe=t=>({status:"dirty",value:t}),E=t=>({status:"valid",value:t}),Pe=t=>t.status==="aborted",Ze=t=>t.status==="dirty",ye=t=>t.status==="valid",Ie=t=>typeof Promise<"u"&&t instanceof Promise,g;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(g||(g={}));var O=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},He=(t,e)=>{if(ye(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new N(t.common.issues);return this._error=r,this._error}}};function _(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(o,c)=>o.code!=="invalid_type"?{message:c.defaultError}:typeof c.data>"u"?{message:n??c.defaultError}:{message:r??c.defaultError},description:s}}var x=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return z(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:z(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new I,ctx:{common:e.parent.common,data:e.data,parsedType:z(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ie(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;let s={common:{issues:[],async:(n=r?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)},a=this._parseSync({data:e,path:s.path,parent:s});return He(s,a)}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:z(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Ie(s)?s:Promise.resolve(s));return He(n,a)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,a)=>{let o=e(s),c=()=>a.addIssue({code:d.custom,...n(s)});return typeof Promise<"u"&&o instanceof Promise?o.then(h=>h?!0:(c(),!1)):o?!0:(c(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new R({schema:this,typeName:y.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return j.create(this,this._def)}nullable(){return V.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return M.create(this,this._def)}promise(){return U.create(this,this._def)}or(e){return G.create([this,e],this._def)}and(e){return Q.create(this,e,this._def)}transform(e){return new R({..._(this._def),schema:this,typeName:y.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ne({..._(this._def),innerType:this,defaultValue:r,typeName:y.ZodDefault})}brand(){return new Ne({typeName:y.ZodBranded,type:this,..._(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new le({..._(this._def),innerType:this,catchValue:r,typeName:y.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return ve.create(this,e)}readonly(){return pe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Ot=/^c[^\s-]{8,}$/i,At=/^[a-z][a-z0-9]*$/,jt=/^[0-9A-HJKMNP-TV-Z]{26}$/,Pt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Zt=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Lt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ae,Mt=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,Vt=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,zt=t=>t.precision?t.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${t.precision}}Z$`):t.precision===0?t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):t.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function Bt(t,e){return!!((e==="v4"||!e)&&Mt.test(t)||(e==="v6"||!e)&&Vt.test(t))}var B=class t extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let a=this._getOrReturnCtx(e);return m(a,{code:d.invalid_type,expected:p.string,received:a.parsedType}),v}let n=new I,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let o=e.data.length>a.value,c=e.data.length<a.value;(o||c)&&(s=this._getOrReturnCtx(e,s),o?m(s,{code:d.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):c&&m(s,{code:d.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Zt.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"email",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Ae||(Ae=new RegExp(Lt,"u")),Ae.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"emoji",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Pt.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"uuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Ot.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")At.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"cuid2",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")jt.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ulid",code:d.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),m(s,{validation:"url",code:d.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"regex",code:d.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?zt(a).test(e.data)||(s=this._getOrReturnCtx(e,s),m(s,{code:d.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="ip"?Bt(e.data,a.version)||(s=this._getOrReturnCtx(e,s),m(s,{validation:"ip",code:d.invalid_string,message:a.message}),n.dirty()):k.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:d.invalid_string,...g.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...g.errToObj(e)})}url(e){return this._addCheck({kind:"url",...g.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...g.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...g.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...g.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...g.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...g.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...g.errToObj(e)})}datetime(e){var r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(r=e?.offset)!==null&&r!==void 0?r:!1,...g.errToObj(e?.message)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...g.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...g.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...g.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...g.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...g.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...g.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...g.errToObj(r)})}nonempty(e){return this.min(1,g.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};B.create=t=>{var e;return new B({checks:[],typeName:y.ZodString,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,..._(t)})};function Kt(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=parseInt(t.toFixed(s).replace(".","")),o=parseInt(e.toFixed(s).replace(".",""));return a%o/Math.pow(10,s)}var $=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let a=this._getOrReturnCtx(e);return m(a,{code:d.invalid_type,expected:p.number,received:a.parsedType}),v}let n,s=new I;for(let a of this._def.checks)a.kind==="int"?k.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Kt(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_finite,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:g.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:g.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:g.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&k.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};$.create=t=>new $({checks:[],typeName:y.ZodNumber,coerce:t?.coerce||!1,..._(t)});var W=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==p.bigint){let a=this._getOrReturnCtx(e);return m(a,{code:d.invalid_type,expected:p.bigint,received:a.parsedType}),v}let n,s=new I;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),m(n,{code:d.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,g.toString(r))}gt(e,r){return this.setLimit("min",e,!1,g.toString(r))}lte(e,r){return this.setLimit("max",e,!0,g.toString(r))}lt(e,r){return this.setLimit("max",e,!1,g.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:g.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:g.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};W.create=t=>{var e;return new W({checks:[],typeName:y.ZodBigInt,coerce:(e=t?.coerce)!==null&&e!==void 0?e:!1,..._(t)})};var F=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.boolean,received:n.parsedType}),v}return E(e.data)}};F.create=t=>new F({typeName:y.ZodBoolean,coerce:t?.coerce||!1,..._(t)});var Y=class t extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let a=this._getOrReturnCtx(e);return m(a,{code:d.invalid_type,expected:p.date,received:a.parsedType}),v}if(isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return m(a,{code:d.invalid_date}),v}let n=new I,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),m(s,{code:d.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):k.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:g.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:g.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Y.create=t=>new Y({checks:[],coerce:t?.coerce||!1,typeName:y.ZodDate,..._(t)});var oe=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.symbol,received:n.parsedType}),v}return E(e.data)}};oe.create=t=>new oe({typeName:y.ZodSymbol,..._(t)});var J=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.undefined,received:n.parsedType}),v}return E(e.data)}};J.create=t=>new J({typeName:y.ZodUndefined,..._(t)});var H=class extends x{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.null,received:n.parsedType}),v}return E(e.data)}};H.create=t=>new H({typeName:y.ZodNull,..._(t)});var K=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return E(e.data)}};K.create=t=>new K({typeName:y.ZodAny,..._(t)});var L=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return E(e.data)}};L.create=t=>new L({typeName:y.ZodUnknown,..._(t)});var P=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return m(r,{code:d.invalid_type,expected:p.never,received:r.parsedType}),v}};P.create=t=>new P({typeName:y.ZodNever,..._(t)});var ce=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.void,received:n.parsedType}),v}return E(e.data)}};ce.create=t=>new ce({typeName:y.ZodVoid,..._(t)});var M=class t extends x{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return m(r,{code:d.invalid_type,expected:p.array,received:r.parsedType}),v;if(s.exactLength!==null){let o=r.data.length>s.exactLength.value,c=r.data.length<s.exactLength.value;(o||c)&&(m(r,{code:o?d.too_big:d.too_small,minimum:c?s.exactLength.value:void 0,maximum:o?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(m(r,{code:d.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(m(r,{code:d.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((o,c)=>s.type._parseAsync(new O(r,o,r.path,c)))).then(o=>I.mergeArray(n,o));let a=[...r.data].map((o,c)=>s.type._parseSync(new O(r,o,r.path,c)));return I.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:g.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:g.toString(r)}})}nonempty(e){return this.min(1,e)}};M.create=(t,e)=>new M({type:t,minLength:null,maxLength:null,exactLength:null,typeName:y.ZodArray,..._(e)});function ie(t){if(t instanceof S){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=j.create(ie(n))}return new S({...t._def,shape:()=>e})}else return t instanceof M?new M({...t._def,type:ie(t.element)}):t instanceof j?j.create(ie(t.unwrap())):t instanceof V?V.create(ie(t.unwrap())):t instanceof Z?Z.create(t.items.map(e=>ie(e))):t}var S=class t extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=k.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==p.object){let i=this._getOrReturnCtx(e);return m(i,{code:d.invalid_type,expected:p.object,received:i.parsedType}),v}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:o}=this._getCached(),c=[];if(!(this._def.catchall instanceof P&&this._def.unknownKeys==="strip"))for(let i in s.data)o.includes(i)||c.push(i);let h=[];for(let i of o){let u=a[i],f=s.data[i];h.push({key:{status:"valid",value:i},value:u._parse(new O(s,f,s.path,i)),alwaysSet:i in s.data})}if(this._def.catchall instanceof P){let i=this._def.unknownKeys;if(i==="passthrough")for(let u of c)h.push({key:{status:"valid",value:u},value:{status:"valid",value:s.data[u]}});else if(i==="strict")c.length>0&&(m(s,{code:d.unrecognized_keys,keys:c}),n.dirty());else if(i!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let i=this._def.catchall;for(let u of c){let f=s.data[u];h.push({key:{status:"valid",value:u},value:i._parse(new O(s,f,s.path,u)),alwaysSet:u in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let i=[];for(let u of h){let f=await u.key;i.push({key:f,value:await u.value,alwaysSet:u.alwaysSet})}return i}).then(i=>I.mergeObjectSync(n,i)):I.mergeObjectSync(n,h)}get shape(){return this._def.shape()}strict(e){return g.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var s,a,o,c;let h=(o=(a=(s=this._def).errorMap)===null||a===void 0?void 0:a.call(s,r,n).message)!==null&&o!==void 0?o:n.defaultError;return r.code==="unrecognized_keys"?{message:(c=g.errToObj(e).message)!==null&&c!==void 0?c:h}:{message:h}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:y.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};return k.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}omit(e){let r={};return k.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new t({...this._def,shape:()=>r})}deepPartial(){return ie(this)}partial(e){let r={};return k.objectKeys(this.shape).forEach(n=>{let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}),new t({...this._def,shape:()=>r})}required(e){let r={};return k.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof j;)a=a._def.innerType;r[n]=a}}),new t({...this._def,shape:()=>r})}keyof(){return et(k.objectKeys(this.shape))}};S.create=(t,e)=>new S({shape:()=>t,unknownKeys:"strip",catchall:P.create(),typeName:y.ZodObject,..._(e)});S.strictCreate=(t,e)=>new S({shape:()=>t,unknownKeys:"strict",catchall:P.create(),typeName:y.ZodObject,..._(e)});S.lazycreate=(t,e)=>new S({shape:t,unknownKeys:"strip",catchall:P.create(),typeName:y.ZodObject,..._(e)});var G=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(let c of a)if(c.result.status==="valid")return c.result;for(let c of a)if(c.result.status==="dirty")return r.common.issues.push(...c.ctx.common.issues),c.result;let o=a.map(c=>new N(c.ctx.common.issues));return m(r,{code:d.invalid_union,unionErrors:o}),v}if(r.common.async)return Promise.all(n.map(async a=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(s);{let a,o=[];for(let h of n){let i={...r,common:{...r.common,issues:[]},parent:null},u=h._parseSync({data:r.data,path:r.path,parent:i});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:i}),i.common.issues.length&&o.push(i.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let c=o.map(h=>new N(h));return m(r,{code:d.invalid_union,unionErrors:c}),v}}get options(){return this._def.options}};G.create=(t,e)=>new G({options:t,typeName:y.ZodUnion,..._(e)});var be=t=>t instanceof X?be(t.schema):t instanceof R?be(t.innerType()):t instanceof ee?[t.value]:t instanceof te?t.options:t instanceof re?Object.keys(t.enum):t instanceof ne?be(t._def.innerType):t instanceof J?[void 0]:t instanceof H?[null]:null,Ee=class t extends x{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return m(r,{code:d.invalid_type,expected:p.object,received:r.parsedType}),v;let n=this.discriminator,s=r.data[n],a=this.optionsMap.get(s);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(m(r,{code:d.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),v)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let a of r){let o=be(a.shape[e]);if(!o)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of o){if(s.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);s.set(c,a)}}return new t({typeName:y.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,..._(n)})}};function Le(t,e){let r=z(t),n=z(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=k.objectKeys(e),a=k.objectKeys(t).filter(c=>s.indexOf(c)!==-1),o={...t,...e};for(let c of a){let h=Le(t[c],e[c]);if(!h.valid)return{valid:!1};o[c]=h.data}return{valid:!0,data:o}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<t.length;a++){let o=t[a],c=e[a],h=Le(o,c);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Q=class extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(a,o)=>{if(Pe(a)||Pe(o))return v;let c=Le(a.value,o.value);return c.valid?((Ze(a)||Ze(o))&&r.dirty(),{status:r.value,value:c.data}):(m(n,{code:d.invalid_intersection_types}),v)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,o])=>s(a,o)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Q.create=(t,e,r)=>new Q({left:t,right:e,typeName:y.ZodIntersection,..._(r)});var Z=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return m(n,{code:d.invalid_type,expected:p.array,received:n.parsedType}),v;if(n.data.length<this._def.items.length)return m(n,{code:d.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:d.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((o,c)=>{let h=this._def.items[c]||this._def.rest;return h?h._parse(new O(n,o,n.path,c)):null}).filter(o=>!!o);return n.common.async?Promise.all(a).then(o=>I.mergeArray(r,o)):I.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Z.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Z({items:t,typeName:y.ZodTuple,rest:null,..._(e)})};var Ce=class t extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return m(n,{code:d.invalid_type,expected:p.object,received:n.parsedType}),v;let s=[],a=this._def.keyType,o=this._def.valueType;for(let c in n.data)s.push({key:a._parse(new O(n,c,n.path,c)),value:o._parse(new O(n,n.data[c],n.path,c))});return n.common.async?I.mergeObjectAsync(r,s):I.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof x?new t({keyType:e,valueType:r,typeName:y.ZodRecord,..._(n)}):new t({keyType:B.create(),valueType:e,typeName:y.ZodRecord,..._(r)})}},ue=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return m(n,{code:d.invalid_type,expected:p.map,received:n.parsedType}),v;let s=this._def.keyType,a=this._def.valueType,o=[...n.data.entries()].map(([c,h],i)=>({key:s._parse(new O(n,c,n.path,[i,"key"])),value:a._parse(new O(n,h,n.path,[i,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let h of o){let i=await h.key,u=await h.value;if(i.status==="aborted"||u.status==="aborted")return v;(i.status==="dirty"||u.status==="dirty")&&r.dirty(),c.set(i.value,u.value)}return{status:r.value,value:c}})}else{let c=new Map;for(let h of o){let i=h.key,u=h.value;if(i.status==="aborted"||u.status==="aborted")return v;(i.status==="dirty"||u.status==="dirty")&&r.dirty(),c.set(i.value,u.value)}return{status:r.value,value:c}}}};ue.create=(t,e,r)=>new ue({valueType:e,keyType:t,typeName:y.ZodMap,..._(r)});var de=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return m(n,{code:d.invalid_type,expected:p.set,received:n.parsedType}),v;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(m(n,{code:d.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(m(n,{code:d.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let a=this._def.valueType;function o(h){let i=new Set;for(let u of h){if(u.status==="aborted")return v;u.status==="dirty"&&r.dirty(),i.add(u.value)}return{status:r.value,value:i}}let c=[...n.data.values()].map((h,i)=>a._parse(new O(n,h,n.path,i)));return n.common.async?Promise.all(c).then(h=>o(h)):o(c)}min(e,r){return new t({...this._def,minSize:{value:e,message:g.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:g.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};de.create=(t,e)=>new de({valueType:t,minSize:null,maxSize:null,typeName:y.ZodSet,..._(e)});var Se=class t extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return m(r,{code:d.invalid_type,expected:p.function,received:r.parsedType}),v;function n(c,h){return Te({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ke(),ge].filter(i=>!!i),issueData:{code:d.invalid_arguments,argumentsError:h}})}function s(c,h){return Te({data:c,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ke(),ge].filter(i=>!!i),issueData:{code:d.invalid_return_type,returnTypeError:h}})}let a={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof U){let c=this;return E(async function(...h){let i=new N([]),u=await c._def.args.parseAsync(h,a).catch(b=>{throw i.addIssue(n(h,b)),i}),f=await Reflect.apply(o,this,u);return await c._def.returns._def.type.parseAsync(f,a).catch(b=>{throw i.addIssue(s(f,b)),i})})}else{let c=this;return E(function(...h){let i=c._def.args.safeParse(h,a);if(!i.success)throw new N([n(h,i.error)]);let u=Reflect.apply(o,this,i.data),f=c._def.returns.safeParse(u,a);if(!f.success)throw new N([s(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Z.create(e).rest(L.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Z.create([]).rest(L.create()),returns:r||L.create(),typeName:y.ZodFunction,..._(n)})}},X=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};X.create=(t,e)=>new X({getter:t,typeName:y.ZodLazy,..._(e)});var ee=class extends x{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return m(r,{received:r.data,code:d.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:e.data}}get value(){return this._def.value}};ee.create=(t,e)=>new ee({value:t,typeName:y.ZodLiteral,..._(e)});function et(t,e){return new te({values:t,typeName:y.ZodEnum,..._(e)})}var te=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{expected:k.joinValues(n),received:r.parsedType,code:d.invalid_type}),v}if(this._def.values.indexOf(e.data)===-1){let r=this._getOrReturnCtx(e),n=this._def.values;return m(r,{received:r.data,code:d.invalid_enum_value,options:n}),v}return E(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e){return t.create(e)}exclude(e){return t.create(this.options.filter(r=>!e.includes(r)))}};te.create=et;var re=class extends x{_parse(e){let r=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=k.objectValues(r);return m(n,{expected:k.joinValues(s),received:n.parsedType,code:d.invalid_type}),v}if(r.indexOf(e.data)===-1){let s=k.objectValues(r);return m(n,{received:n.data,code:d.invalid_enum_value,options:s}),v}return E(e.data)}get enum(){return this._def.values}};re.create=(t,e)=>new re({values:t,typeName:y.ZodNativeEnum,..._(e)});var U=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return m(r,{code:d.invalid_type,expected:p.promise,received:r.parsedType}),v;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return E(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};U.create=(t,e)=>new U({type:t,typeName:y.ZodPromise,..._(e)});var R=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:o=>{m(n,o),o.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let o=s.transform(n.data,a);return n.common.issues.length?{status:"dirty",value:n.data}:n.common.async?Promise.resolve(o).then(c=>this._def.schema._parseAsync({data:c,path:n.path,parent:n})):this._def.schema._parseSync({data:o,path:n.path,parent:n})}if(s.type==="refinement"){let o=c=>{let h=s.refinement(c,a);if(n.common.async)return Promise.resolve(h);if(h instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?v:(c.status==="dirty"&&r.dirty(),o(c.value),{status:r.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?v:(c.status==="dirty"&&r.dirty(),o(c.value).then(()=>({status:r.value,value:c.value}))))}if(s.type==="transform")if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ye(o))return o;let c=s.transform(o.value,a);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>ye(o)?Promise.resolve(s.transform(o.value,a)).then(c=>({status:r.value,value:c})):o);k.assertNever(s)}};R.create=(t,e,r)=>new R({schema:t,typeName:y.ZodEffects,effect:e,..._(r)});R.createWithPreprocess=(t,e,r)=>new R({schema:e,effect:{type:"preprocess",transform:t},typeName:y.ZodEffects,..._(r)});var j=class extends x{_parse(e){return this._getType(e)===p.undefined?E(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};j.create=(t,e)=>new j({innerType:t,typeName:y.ZodOptional,..._(e)});var V=class extends x{_parse(e){return this._getType(e)===p.null?E(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};V.create=(t,e)=>new V({innerType:t,typeName:y.ZodNullable,..._(e)});var ne=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ne.create=(t,e)=>new ne({innerType:t,typeName:y.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var le=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ie(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new N(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new N(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};le.create=(t,e)=>new le({innerType:t,typeName:y.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var fe=class extends x{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return m(n,{code:d.invalid_type,expected:p.nan,received:n.parsedType}),v}return{status:"valid",value:e.data}}};fe.create=t=>new fe({typeName:y.ZodNaN,..._(t)});var Ut=Symbol("zod_brand"),Ne=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},ve=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?v:a.status==="dirty"?(r.dirty(),Xe(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?v:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:y.ZodPipeline})}},pe=class extends x{_parse(e){let r=this._def.innerType._parse(e);return ye(r)&&(r.value=Object.freeze(r.value)),r}};pe.create=(t,e)=>new pe({innerType:t,typeName:y.ZodReadonly,..._(e)});var tt=(t,e={},r)=>t?K.create().superRefine((n,s)=>{var a,o;if(!t(n)){let c=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,h=(o=(a=c.fatal)!==null&&a!==void 0?a:r)!==null&&o!==void 0?o:!0,i=typeof c=="string"?{message:c}:c;s.addIssue({code:"custom",...i,fatal:h})}}):K.create(),Dt={object:S.lazycreate},y;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(y||(y={}));var qt=(t,e={message:`Input not instance of ${t.name}`})=>tt(r=>r instanceof t,e),rt=B.create,nt=$.create,$t=fe.create,Wt=W.create,st=F.create,Ft=Y.create,Yt=oe.create,Jt=J.create,Ht=H.create,Gt=K.create,Qt=L.create,Xt=P.create,er=ce.create,tr=M.create,rr=S.create,nr=S.strictCreate,sr=G.create,ar=Ee.create,ir=Q.create,or=Z.create,cr=Ce.create,ur=ue.create,dr=de.create,lr=Se.create,fr=X.create,pr=ee.create,mr=te.create,hr=re.create,gr=U.create,Ge=R.create,yr=j.create,vr=V.create,_r=R.createWithPreprocess,xr=ve.create,wr=()=>rt().optional(),br=()=>nt().optional(),kr=()=>st().optional(),Tr={string:t=>B.create({...t,coerce:!0}),number:t=>$.create({...t,coerce:!0}),boolean:t=>F.create({...t,coerce:!0}),bigint:t=>W.create({...t,coerce:!0}),date:t=>Y.create({...t,coerce:!0})},Ir=v,me=Object.freeze({__proto__:null,defaultErrorMap:ge,setErrorMap:Nt,getErrorMap:ke,makeIssue:Te,EMPTY_PATH:Rt,addIssueToContext:m,ParseStatus:I,INVALID:v,DIRTY:Xe,OK:E,isAborted:Pe,isDirty:Ze,isValid:ye,isAsync:Ie,get util(){return k},get objectUtil(){return je},ZodParsedType:p,getParsedType:z,ZodType:x,ZodString:B,ZodNumber:$,ZodBigInt:W,ZodBoolean:F,ZodDate:Y,ZodSymbol:oe,ZodUndefined:J,ZodNull:H,ZodAny:K,ZodUnknown:L,ZodNever:P,ZodVoid:ce,ZodArray:M,ZodObject:S,ZodUnion:G,ZodDiscriminatedUnion:Ee,ZodIntersection:Q,ZodTuple:Z,ZodRecord:Ce,ZodMap:ue,ZodSet:de,ZodFunction:Se,ZodLazy:X,ZodLiteral:ee,ZodEnum:te,ZodNativeEnum:re,ZodPromise:U,ZodEffects:R,ZodTransformer:R,ZodOptional:j,ZodNullable:V,ZodDefault:ne,ZodCatch:le,ZodNaN:fe,BRAND:Ut,ZodBranded:Ne,ZodPipeline:ve,ZodReadonly:pe,custom:tt,Schema:x,ZodSchema:x,late:Dt,get ZodFirstPartyTypeKind(){return y},coerce:Tr,any:Gt,array:tr,bigint:Wt,boolean:st,date:Ft,discriminatedUnion:ar,effect:Ge,enum:mr,function:lr,instanceof:qt,intersection:ir,lazy:fr,literal:pr,map:ur,nan:$t,nativeEnum:hr,never:Xt,null:Ht,nullable:vr,number:nt,object:rr,oboolean:kr,onumber:br,optional:yr,ostring:wr,pipeline:xr,preprocess:_r,promise:gr,record:cr,set:dr,strictObject:nr,string:rt,symbol:Yt,transformer:Ge,tuple:or,undefined:Jt,union:sr,unknown:Qt,void:er,NEVER:Ir,ZodIssueCode:d,quotelessJson:St,ZodError:N});var Er=me.enum(["true","false"]).transform(t=>t==="true"),D=me.string().min(1),Me=me.object({AUTH_COOKIE_NAME:D.default("alliance-auth"),AUTH_COOKIE_SECRET:D.default("zlLZBlk7wt8lypP5lA4D"),DB_ENDPOINT:D,JWT_PRIVATE_KEY:D.default("MIIEogIBAAKCAQEAsGqOzjnfQtCYlDqhgGAnKuJOCiPt2WpCmL1Cs+SLBQlyoNn6LT8BJ6ZRj8t/vK8Sw0p51Uq/3k0tazh7bLGkWNMBLY3BqFiNRMMnCqHJfvGIUi/itNXNe2kbP7H3rbyQTu4O7yH/ZAMitdpF2KLucVRlFxrQ/ggZjxwEGso4JUnCwmAnoKct/uupKz9Y2PMTr00WWN79aPfD4LcKi570VJqBT3ISSucdwFLYNqnOkQnEa8O8xbthQhiI0k1GGJT+GCQcATUPeEbaCFXonOrJm+CyuMmQWYLFF3NbE5NllU1jz9PYHzp2hAgAx8WGeretTvpEA1dE2gvXNESGbQ8FxQIDAQABAoIBAAjTJmud1348eGAfLV8CRaij2MAxxenJ9/ozVXfcPIa2+fCelsuBSv8pwbYODvNoVT7xpcs2nwccGI6JgnBl09EhqlMWCT7w7GLT2aBy3A/T6JF76xJICQGzDfWPYygMtlyhv0YqZDUjjFlJHun+/ysqIUMY81AR0FLUAEc6yw41ChcdSvTgIqBM9f5PsBRK7zOgdW1vcVQiZbf2Vqr+7wTJ+6b9A4rWnnAqesGDXqYupx3UJEu3x0wRNQB8FeiG9iJrw4cyD9SmM95doTyKosQ2PWWnUO1NMgmWCR/mWcKZAUcfZUpnQ8rz75WAWept8ZIOOdha8UZ1B/kw3EsVdEECgYEA3iN0BRUqMN0J69bazvlNOWtI+Chc1lYMt/tZ4p78pIJpAZvc3rQ9lAp6JvOEno2IglULA4I+ZLUmpz+lfu7XxKMNOI3cnG7WdiGbiIlwOSwuxzeO1FJqhtnc0U6mNkIjptV8b2etj8U2/SXAC3CC8XgsawAj9A/I7awlCL3NXdECgYEAy07gun3rcd3Y0ISmd3+SbAn/MbGf8uRLcfSc2ls9B6m3pXj25prXJWIrB6DyGuL/HQmHzffQkOeXmwFGHFXyiIFOIITX4z8b9lMnavgUZoPDY+ZFsxp6I7vMn75AetB8wYXpOFFeCG/Ck/VSIYP7oAN8kLw8EHdOuNbZYbu34bUCgYBYd14ZOBiZZS4yUlrJ2tc6atOgoNJ4OcTO8LcXXaHYEmenUF9iAf4UGygSoyDJ1CvtW9kLCK+4g7xlFx/dsVkU4qq9PyIA2tNmMHQ0qCedXU8z35huTnRGSDV81gmzyhtQsezgoTWp8Cy6HHKjG6fKasWlx2SKKk8m+Eu3c396QQKBgBMY2asq4M7VU+RiUXCwHwTe+4Wjda7PGvcdTw6Du3vYyVNVxXtr2AG+8uPIjnVQFT6ZApSqToEOAAOjXv6SZDHGU5xiXhUOfIXq0a0OmHv4rIXZv3pPZmGs5k+rA0uGAfH7riiIHBkWxmQ3ivty9lPVgAHobIvvaQmbxNeVVnRxAoGAUzUmcBiUAiODfjulrpYvWG0tCn5B//yk7g1Tm3Chrh9huA1qGEN3jDoqSsTd5k4Yi5foyAZt5ORgoiUVm4IsfS56aoxIco1CtFG3zeMQRy4uKzTsvUTOdsJ4RlQdjNwpngXR44VL0WelgCDqTqJwn5ubzPvuIHuTj3cBpmJCjOo="),JWT_PUBLIC_CSP_KEY:me.string().min(1).default("BgIAAACkAABSU0ExAAgAAAEAAQDFBQ9thkQ01wvaRFcDRPpOrbd6hsXHAAiEdjof2NPPY02VZZMTW3MXxYJZkMm4suCbyeqc6FUI2kZ4DzUBHCQY/pQYRk3SiBhCYbvFvMNrxAmRzqk22FLAHedKEnJPgZpU9J6LCrfgw/do/d5YFk2vE/PYWD8rqev+LaegJ2DCwkklOMoaBByPGQj+0BoXZVRx7qLYRdq1IgNk/yHvDu5OkLyt97E/G2l7zdW04i9SiPF+yaEKJ8NEjViowY0tAdNYpLFsezhrLU3ev0rVeUrDEq+8f8uPUaYnAT8t+tmgcgkFi+SzQr2YQmrZ7SMKTuIqJ2CAoTqUmNBC3znOjmqw"),SERVICE_LOG_LEVEL:me.enum(["silent","fatal","error","warn","info","debug","trace"]).default("trace"),SERVICE_PORT:D.transform(Number).default("3000"),REDIS_HOST:D,REDIS_PASSWORD:D.optional()});var Ve=(n=>(n.TargetUrl="alliance-target-url",n.TargetApp="alliance-target-app",n.TargetWorkspace="alliance-target-workspace",n))(Ve||{});var hn=Me.pick({JWT_PRIVATE_KEY:!0,JWT_PUBLIC_CSP_KEY:!0});function at({privateKey:t,aud:e,sub:r,name:n,user:s,workspace:a,expiration:o="1h"}){return`Bearer ${Cr.sign({iss:"Alliance",aud:e,sub:r,name:n,"https://alliance.teliacompany.net/user_type":s.type,"https://alliance.teliacompany.net/user_email":s.email,"https://alliance.teliacompany.net/user_privileges":s.permissions,"https://alliance.teliacompany.net/workspace":a.slug,"https://alliance.teliacompany.net/workspace_name":a.name,"https://alliance.teliacompany.net/tenant":a.slug,"https://alliance.teliacompany.net/tenant_name":a.name},t,{expiresIn:o,algorithm:"RS256"})}`}function ze(t){return`-----BEGIN RSA PRIVATE KEY-----
2
+ `+t.JWT_PRIVATE_KEY+`
3
+ -----END RSA PRIVATE KEY-----`}function Nr(t){return at({aud:"system",sub:"system",name:"system",workspace:{slug:"system",name:"system"},user:{type:"system",permissions:[],email:"system"},privateKey:ze(t)})}function Rr(t){let e=ze(t),r=Sr(e);return{pkcs:r.export({type:"pkcs1",format:"pem"}).toString().trim(),spki:r.export({type:"spki",format:"pem"}).toString().trim(),csp:t.JWT_PUBLIC_CSP_KEY}}function Or(t,e){return e[t].replace("-----BEGIN RSA PUBLIC KEY-----","").replace("-----END RSA PUBLIC KEY-----","").replace("-----BEGIN PUBLIC KEY-----","").replace("-----END PUBLIC KEY-----","").trim().replaceAll(`
4
+ `,"")}import{homedir as Jr,tmpdir as Hr}from"node:os";import{resolve as Gr}from"node:path";var Ar=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,jr=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,Pr=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Zr(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Lr(t);return}return e}function Lr(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function _e(t,e={}){if(typeof t!="string")return t;let r=t.trim();if(t[0]==='"'&&t.at(-1)==='"'&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){let n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!Pr.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Ar.test(t)||jr.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Zr)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}function Mr(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function T(t,...e){try{return Mr(t(...e))}catch(r){return Promise.reject(r)}}function Vr(t){let e=typeof t;return t===null||e!=="object"&&e!=="function"}function zr(t){let e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function xe(t){if(Vr(t))return String(t);if(zr(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return xe(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function it(){if(typeof Buffer===void 0)throw new TypeError("[unstorage] Buffer is not supported!")}var Be="base64:";function ot(t){if(typeof t=="string")return t;it();let e=Buffer.from(t).toString("base64");return Be+e}function ct(t){return typeof t!="string"||!t.startsWith(Be)?t:(it(),Buffer.from(t.slice(Be.length),"base64"))}var Br=["hasItem","getItem","getItemRaw","setItem","setItemRaw","removeItem","getMeta","setMeta","removeMeta","getKeys","clear","mount","unmount"];function Ke(t,e){if(e=he(e),!e)return t;let r={...t};for(let n of Br)r[n]=(s="",...a)=>t[n](e+s,...a);return r.getKeys=(n="",...s)=>t.getKeys(e+n,...s).then(a=>a.map(o=>o.slice(e.length))),r}function C(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function ut(...t){return C(t.join(":"))}function he(t){return t=C(t),t?t+":":""}var Kr="memory",Ur=()=>{let t=new Map;return{name:Kr,options:{},hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return Array.from(t.keys())},clear(){t.clear()},dispose(){t.clear()}}};function ft(t={}){let e={mounts:{"":t.driver||Ur()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=i=>{for(let u of e.mountpoints)if(i.startsWith(u))return{base:u,relativeKey:i.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:i,driver:e.mounts[""]}},n=(i,u)=>e.mountpoints.filter(f=>f.startsWith(i)||u&&i.startsWith(f)).map(f=>({relativeBase:i.length>f.length?i.slice(f.length):void 0,mountpoint:f,driver:e.mounts[f]})),s=(i,u)=>{if(e.watching){u=C(u);for(let f of e.watchListeners)f(i,u)}},a=async()=>{if(!e.watching){e.watching=!0;for(let i in e.mounts)e.unwatch[i]=await dt(e.mounts[i],s,i)}},o=async()=>{if(e.watching){for(let i in e.unwatch)await e.unwatch[i]();e.unwatch={},e.watching=!1}},c=(i,u,f)=>{let l=new Map,b=w=>{let A=l.get(w.base);return A||(A={driver:w.driver,base:w.base,items:[]},l.set(w.base,A)),A};for(let w of i){let A=typeof w=="string",we=C(A?w:w.key),q=A?void 0:w.value,Oe=A||!w.options?u:{...u,...w.options},Je=r(we);b(Je).items.push({key:we,value:q,relativeKey:Je.relativeKey,options:Oe})}return Promise.all([...l.values()].map(w=>f(w))).then(w=>w.flat())},h={hasItem(i,u={}){i=C(i);let{relativeKey:f,driver:l}=r(i);return T(l.hasItem,f,u)},getItem(i,u={}){i=C(i);let{relativeKey:f,driver:l}=r(i);return T(l.getItem,f,u).then(b=>_e(b))},getItems(i,u){return c(i,u,f=>f.driver.getItems?T(f.driver.getItems,f.items.map(l=>({key:l.relativeKey,options:l.options})),u).then(l=>l.map(b=>({key:ut(f.base,b.key),value:_e(b.value)}))):Promise.all(f.items.map(l=>T(f.driver.getItem,l.relativeKey,l.options).then(b=>({key:l.key,value:_e(b)})))))},getItemRaw(i,u={}){i=C(i);let{relativeKey:f,driver:l}=r(i);return l.getItemRaw?T(l.getItemRaw,f,u):T(l.getItem,f,u).then(b=>ct(b))},async setItem(i,u,f={}){if(u===void 0)return h.removeItem(i);i=C(i);let{relativeKey:l,driver:b}=r(i);b.setItem&&(await T(b.setItem,l,xe(u),f),b.watch||s("update",i))},async setItems(i,u){await c(i,u,async f=>{f.driver.setItems&&await T(f.driver.setItems,f.items.map(l=>({key:l.relativeKey,value:xe(l.value),options:l.options})),u),f.driver.setItem&&await Promise.all(f.items.map(l=>T(f.driver.setItem,l.relativeKey,xe(l.value),l.options)))})},async setItemRaw(i,u,f={}){if(u===void 0)return h.removeItem(i,f);i=C(i);let{relativeKey:l,driver:b}=r(i);if(b.setItemRaw)await T(b.setItemRaw,l,u,f);else if(b.setItem)await T(b.setItem,l,ot(u),f);else return;b.watch||s("update",i)},async removeItem(i,u={}){typeof u=="boolean"&&(u={removeMeta:u}),i=C(i);let{relativeKey:f,driver:l}=r(i);l.removeItem&&(await T(l.removeItem,f,u),(u.removeMeta||u.removeMata)&&await T(l.removeItem,f+"$",u),l.watch||s("remove",i))},async getMeta(i,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),i=C(i);let{relativeKey:f,driver:l}=r(i),b=Object.create(null);if(l.getMeta&&Object.assign(b,await T(l.getMeta,f,u)),!u.nativeOnly){let w=await T(l.getItem,f+"$",u).then(A=>_e(A));w&&typeof w=="object"&&(typeof w.atime=="string"&&(w.atime=new Date(w.atime)),typeof w.mtime=="string"&&(w.mtime=new Date(w.mtime)),Object.assign(b,w))}return b},setMeta(i,u,f={}){return this.setItem(i+"$",u,f)},removeMeta(i,u={}){return this.removeItem(i+"$",u)},async getKeys(i,u={}){i=he(i);let f=n(i,!0),l=[],b=[];for(let w of f){let we=(await T(w.driver.getKeys,w.relativeBase,u)).map(q=>w.mountpoint+C(q)).filter(q=>!l.some(Oe=>q.startsWith(Oe)));b.push(...we),l=[w.mountpoint,...l.filter(q=>!q.startsWith(w.mountpoint))]}return i?b.filter(w=>w.startsWith(i)&&!w.endsWith("$")):b.filter(w=>!w.endsWith("$"))},async clear(i,u={}){i=he(i),await Promise.all(n(i,!1).map(async f=>{if(f.driver.clear)return T(f.driver.clear,f.relativeBase,u);if(f.driver.removeItem){let l=await f.driver.getKeys(f.relativeBase||"",u);return Promise.all(l.map(b=>f.driver.removeItem(b,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(i=>lt(i)))},async watch(i){return await a(),e.watchListeners.push(i),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==i),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(i,u){if(i=he(i),i&&e.mounts[i])throw new Error(`already mounted at ${i}`);return i&&(e.mountpoints.push(i),e.mountpoints.sort((f,l)=>l.length-f.length)),e.mounts[i]=u,e.watching&&Promise.resolve(dt(u,s,i)).then(f=>{e.unwatch[i]=f}).catch(console.error),h},async unmount(i,u=!0){i=he(i),!(!i||!e.mounts[i])&&(e.watching&&i in e.unwatch&&(e.unwatch[i](),delete e.unwatch[i]),u&&await lt(e.mounts[i]),e.mountpoints=e.mountpoints.filter(f=>f!==i),delete e.mounts[i])},getMount(i=""){i=C(i)+":";let u=r(i);return{driver:u.driver,base:u.base}},getMounts(i="",u={}){return i=C(i),n(i,u.parents).map(l=>({driver:l.driver,base:l.mountpoint}))}};return h}function dt(t,e,r){return t.watch?t.watch((n,s)=>e(n,r+s)):()=>{}}async function lt(t){typeof t.dispose=="function"&&await T(t.dispose)}import{existsSync as qr,promises as $r}from"fs";import{resolve as Wr,join as Fr}from"path";function Re(t,e,r){return new Error(`[unstorage] [${t}] ${e}`,r)}function pt(t,e){return Array.isArray(e)?Re(t,`Missing some of the required options ${e.map(r=>"`"+r+"`").join(", ")}`):Re(t,`Missing required option \`${e}\`.`)}import{existsSync as Dr,promises as se}from"fs";import{resolve as ht,dirname as gt}from"path";function Ue(t){return t.code==="ENOENT"||t.code==="EISDIR"?null:t}function mt(t){return t.code==="EEXIST"?null:t}async function De(t,e,r){return await _t(gt(t)),se.writeFile(t,e,r)}function qe(t,e){return se.readFile(t,e).catch(Ue)}function yt(t){return se.unlink(t).catch(Ue)}function vt(t){return se.readdir(t,{withFileTypes:!0}).catch(Ue).then(e=>e||[])}async function _t(t){Dr(t)||(await _t(gt(t)).catch(mt),await se.mkdir(t).catch(mt))}async function $e(t,e){if(e&&e(t))return[];let r=await vt(t),n=[];return await Promise.all(r.map(async s=>{let a=ht(t,s.name);if(s.isDirectory()){let o=await $e(a,e);n.push(...o.map(c=>s.name+"/"+c))}else e&&e(s.name)||n.push(s.name)})),n}async function We(t){let e=await vt(t);await Promise.all(e.map(r=>{let n=ht(t,r.name);return r.isDirectory()?We(n).then(()=>se.rmdir(n)):se.unlink(n)}))}var Yr=/\.\.\:|\.\.$/,Fe="fs-lite",xt=(t={})=>{if(!t.base)throw pt(Fe,"base");t.base=Wr(t.base);let e=r=>{if(Yr.test(r))throw Re(Fe,`Invalid key: ${JSON.stringify(r)}. It should not contain .. segments`);return Fr(t.base,r.replace(/:/g,"/"))};return{name:Fe,options:t,hasItem(r){return qr(e(r))},getItem(r){return qe(e(r),"utf8")},getItemRaw(r){return qe(e(r))},async getMeta(r){let{atime:n,mtime:s,size:a,birthtime:o,ctime:c}=await $r.stat(e(r)).catch(()=>({}));return{atime:n,mtime:s,size:a,birthtime:o,ctime:c}},setItem(r,n){if(!t.readOnly)return De(e(r),n,"utf8")},setItemRaw(r,n){if(!t.readOnly)return De(e(r),n)},removeItem(r){if(!t.readOnly)return yt(e(r))},getKeys(){return $e(e("."),t.ignore)},async clear(){t.readOnly||t.noClear||await We(e("."))}}};function Qr({prefix:t,logger:e}){return Ke(ft({driver:xt({base:Xr({logger:e})})}),t)}function Xr({logger:t}){let e="";try{e=Jr()}catch(r){t.error("could not use homedir, trying tmpdir",{error:r?.message})}if(!e)try{e=Hr()}catch(r){t.error("could not use tmpdir, trying process.cwd",{error:r?.message})}if(!e)try{e=process.cwd()}catch(r){t.error("could not use process.cwd, exiting",{error:r?.message}),process.exit(1)}return Gr(e,".alliance")}import en from"pino";function ae(t){return e=>(r,n)=>t[e]({...n,msg:r})}function wt(t){let e=en({level:t.SERVICE_LOG_LEVEL,redact:["authorization","headers.authorization","req.headers.authorization","res.headers.authorization","req.headers.cookie",'res.headers["set-cookie"]']});return{fatal:ae(e)("fatal"),error:ae(e)("error"),warn:ae(e)("warn"),info:ae(e)("info"),debug:ae(e)("debug"),trace:ae(e)("trace"),silent:ae(e)("silent"),child:()=>wt(t),level:t.SERVICE_LOG_LEVEL}}function tn(t){return(e,r,n)=>(t.trace("received request",{url:e.url,params:e.params,query:e.query,body:e.body}),n())}var bt=(l=>(l[l.NoObjectId=10001]="NoObjectId",l[l.NoTargetAppHeader=10002]="NoTargetAppHeader",l[l.NoTargetWorkspaceHeader=10003]="NoTargetWorkspaceHeader",l[l.NoManifest=10006]="NoManifest",l[l.NoRequestContext=10007]="NoRequestContext",l[l.NoUserInRequestContext=10008]="NoUserInRequestContext",l[l.NoAppInRequestContext=10009]="NoAppInRequestContext",l[l.NoWorkspaceInRequestContext=10010]="NoWorkspaceInRequestContext",l[l.NoUserPermissionsInRequestContext=10012]="NoUserPermissionsInRequestContext",l[l.WorkspacePermissionDenied=10013]="WorkspacePermissionDenied",l[l.NoTargetUrlHeader=10014]="NoTargetUrlHeader",l[l.NoSessionInRedisCache=10015]="NoSessionInRedisCache",l))(bt||{}),kt=(s=>(s[s.NoPublicKey=11e3]="NoPublicKey",s[s.NoAuthHeader=11001]="NoAuthHeader",s[s.FailedFileUpload=11002]="FailedFileUpload",s[s.FailedFileDownload=11003]="FailedFileDownload",s))(kt||{});var Tt={10001:{statusCode:401,msg:"No object id available on authenticated user."},10002:{statusCode:400,msg:"Request missing header 'alliance-target-app'."},10003:{statusCode:400,msg:"Request missing header 'alliance-target-workspace'."},10014:{statusCode:400,msg:"Request missing header 'alliance-target-url'."},10015:{statusCode:401,msg:"Could not find user session in Redis server."},10006:{statusCode:500,msg:"Could not find manifest for app '{{appSlug}}'."},10007:{statusCode:500,msg:"No request context."},10008:{statusCode:500,msg:"No user in request context."},10009:{statusCode:500,msg:"No app in request context."},10010:{statusCode:500,msg:"No workspace in request context."},10012:{statusCode:500,msg:"No user permissions in request context."},10013:{statusCode:403,msg:"User does not have access to the current workspace."},11e3:{statusCode:401,msg:"No public key available to decode JWT."},11001:{statusCode:401,msg:"No authorization header found."},11002:{statusCode:500,msg:"Something went wrong when trying to upload a file to the S3 storage."},11003:{statusCode:500,msg:"Something went wrong when trying to download a file to the S3 storage."},12e3:{statusCode:401,msg:"No object id found in user claims."}};var Ye=class extends Error{constructor(r,n={}){let{msg:s,statusCode:a}=Tt[r],o=rn(s,n);super(o);this.errorCode=r;this.message=o,this.statusCode=a,this.info=`https://github.com/telia-company/ace-alliance-sdk/wiki/error-codes#${this.errorCode}`}info;statusCode};function rn(t,e){return Object.entries(e).reduce((r,[n,s])=>r.replaceAll(`{{${n}}}`,s),t)}function nn(t){return(e,r,n,s)=>{let a={cause:e.cause,message:e.message,status:e.status||e.statusCode||e.code,info:e.info};return t.error("error when processing request",{url:r.url,body:r.body,error:a}),n.status(a.status).json(a)}}export{Ye as AllianceError,Ve as AllianceHeaders,kt as DataErrorCode,bt as GatewayErrorCode,at as createBearerToken,Qr as createFileStorage,Et as createIndexHtml,wt as createLogger,Rr as createPublicKeys,Nr as createSystemUserToken,Ct as getAppManifests,Or as getCleanPublicKey,ze as getPrivateKey,nn as requestErrorHandler,tn as requestLoggerHandler,It as slugify,Er as zBooleanEnum,D as zNonEmptyString,Me as zSharedConfig};