@anythingai/cli 0.0.1 → 0.0.2

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.
Files changed (2) hide show
  1. package/dist/js/bin.mjs +2361 -2158
  2. package/package.json +1 -1
package/dist/js/bin.mjs CHANGED
@@ -2,12 +2,12 @@
2
2
  import { createRequire } from "node:module";
3
3
  import { hideBin } from "yargs/helpers";
4
4
  import yargs from "yargs";
5
+ import { exec, execSync } from "node:child_process";
5
6
  import fs, { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
6
7
  import path, { basename, dirname, extname, join, resolve } from "node:path";
8
+ import Conf from "conf";
7
9
  import { err, ok } from "neverthrow";
8
10
  import { z } from "zod";
9
- import { exec, execSync } from "node:child_process";
10
- import Conf from "conf";
11
11
  import { styleText } from "node:util";
12
12
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
13
13
  import { createInterface } from "node:readline";
@@ -20,1435 +20,638 @@ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).export
20
20
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
21
 
22
22
  //#endregion
23
- //#region package.json
24
- var version = "0.0.1";
23
+ //#region ../../node_modules/dotenv/package.json
24
+ var require_package$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
25
+ module.exports = {
26
+ "name": "dotenv",
27
+ "version": "16.5.0",
28
+ "description": "Loads environment variables from .env file",
29
+ "main": "lib/main.js",
30
+ "types": "lib/main.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./lib/main.d.ts",
34
+ "require": "./lib/main.js",
35
+ "default": "./lib/main.js"
36
+ },
37
+ "./config": "./config.js",
38
+ "./config.js": "./config.js",
39
+ "./lib/env-options": "./lib/env-options.js",
40
+ "./lib/env-options.js": "./lib/env-options.js",
41
+ "./lib/cli-options": "./lib/cli-options.js",
42
+ "./lib/cli-options.js": "./lib/cli-options.js",
43
+ "./package.json": "./package.json"
44
+ },
45
+ "scripts": {
46
+ "dts-check": "tsc --project tests/types/tsconfig.json",
47
+ "lint": "standard",
48
+ "pretest": "npm run lint && npm run dts-check",
49
+ "test": "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
50
+ "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
51
+ "prerelease": "npm test",
52
+ "release": "standard-version"
53
+ },
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git://github.com/motdotla/dotenv.git"
57
+ },
58
+ "homepage": "https://github.com/motdotla/dotenv#readme",
59
+ "funding": "https://dotenvx.com",
60
+ "keywords": [
61
+ "dotenv",
62
+ "env",
63
+ ".env",
64
+ "environment",
65
+ "variables",
66
+ "config",
67
+ "settings"
68
+ ],
69
+ "readmeFilename": "README.md",
70
+ "license": "BSD-2-Clause",
71
+ "devDependencies": {
72
+ "@types/node": "^18.11.3",
73
+ "decache": "^4.6.2",
74
+ "sinon": "^14.0.1",
75
+ "standard": "^17.0.0",
76
+ "standard-version": "^9.5.0",
77
+ "tap": "^19.2.0",
78
+ "typescript": "^4.8.4"
79
+ },
80
+ "engines": { "node": ">=12" },
81
+ "browser": { "fs": false }
82
+ };
83
+ }));
25
84
 
26
85
  //#endregion
27
- //#region src/api-client.ts
28
- const USER_AGENT = `anything-cli/${version}`;
29
- function parseRetryAfter(response) {
30
- if (response.status !== 429) return null;
31
- const header = response.headers.get("retry-after");
32
- if (!header) return null;
33
- const seconds = Number(header);
34
- if (Number.isFinite(seconds)) return seconds >= 0 ? Math.ceil(seconds) : null;
35
- const dateMs = Date.parse(header);
36
- if (!Number.isNaN(dateMs)) {
37
- const delta = Math.ceil((dateMs - Date.now()) / 1e3);
38
- return delta > 0 ? delta : 0;
86
+ //#region ../../node_modules/dotenv/lib/main.js
87
+ var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
88
+ const fs$2 = __require("fs");
89
+ const path$1 = __require("path");
90
+ const os$1 = __require("os");
91
+ const crypto = __require("crypto");
92
+ const version = require_package$1().version;
93
+ const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
94
+ function parse(src) {
95
+ const obj = {};
96
+ let lines = src.toString();
97
+ lines = lines.replace(/\r\n?/gm, "\n");
98
+ let match;
99
+ while ((match = LINE.exec(lines)) != null) {
100
+ const key = match[1];
101
+ let value = match[2] || "";
102
+ value = value.trim();
103
+ const maybeQuote = value[0];
104
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
105
+ if (maybeQuote === "\"") {
106
+ value = value.replace(/\\n/g, "\n");
107
+ value = value.replace(/\\r/g, "\r");
108
+ }
109
+ obj[key] = value;
110
+ }
111
+ return obj;
39
112
  }
40
- return null;
41
- }
42
- const AuthProviderSchema = z.enum([
43
- "google",
44
- "email",
45
- "facebook",
46
- "twitter",
47
- "apple"
48
- ]);
49
- const CreateEnvironmentSchema = z.enum([
50
- "development",
51
- "preview",
52
- "production"
53
- ]);
54
- const CreateProjectResponseSchema = z.object({
55
- projectGroupId: z.string(),
56
- revisionId: z.string()
57
- });
58
- const DuplicateProjectGroupResponseSchema = z.object({
59
- projectGroupId: z.string(),
60
- name: z.string()
61
- });
62
- const GenerateResponseSchema = z.object({
63
- revisionId: z.string(),
64
- threadId: z.string().nullable()
65
- });
66
- const MessageSchema = z.object({
67
- id: z.string(),
68
- userMessage: z.string().nullable(),
69
- assistantMessage: z.string().nullable(),
70
- action: z.string(),
71
- status: z.string(),
72
- threadId: z.string().nullable(),
73
- createdAt: z.string()
74
- });
75
- const MessagesResponseSchema = z.object({ messages: z.array(MessageSchema) });
76
- const ProjectFileSchema = z.object({
77
- path: z.string(),
78
- content: z.string().optional()
79
- });
80
- const ProjectFilesResponseSchema = z.object({ files: z.array(ProjectFileSchema.omit({ content: true })) });
81
- const ProjectFileResponseSchema = z.object({ file: ProjectFileSchema.extend({ content: z.string() }) });
82
- const ProjectLogSchema = z.object({
83
- id: z.string(),
84
- message: z.string(),
85
- level: z.enum([
86
- "info",
87
- "warn",
88
- "error"
89
- ]),
90
- timestamp: z.string(),
91
- source: z.string().nullable(),
92
- devServerId: z.string().nullable()
93
- });
94
- const ProjectAuthProviderSecretSchema = z.object({
95
- id: z.string(),
96
- envKey: z.string(),
97
- displayName: z.string(),
98
- environment: z.string()
99
- });
100
- const ProjectAuthProvidersProviderSchema = z.object({
101
- provider: AuthProviderSchema,
102
- enabled: z.boolean(),
103
- secrets: z.array(ProjectAuthProviderSecretSchema)
104
- });
105
- const ProjectAuthProvidersResponseSchema = z.object({
106
- authEnabled: z.boolean(),
107
- providers: z.array(ProjectAuthProvidersProviderSchema)
108
- });
109
- const ProjectLogsResponseSchema = z.object({ logs: z.array(ProjectLogSchema) });
110
- const ProjectAuthSettingsProviderSchema = z.object({
111
- provider: AuthProviderSchema,
112
- enabled: z.boolean(),
113
- configured: z.boolean(),
114
- expectedSecretKeys: z.array(z.string()),
115
- configuredSecretKeys: z.array(z.string()),
116
- helpUrl: z.string()
117
- });
118
- const ProjectAuthSettingsResponseSchema = z.object({
119
- authEnabled: z.boolean(),
120
- providers: z.array(ProjectAuthSettingsProviderSchema)
121
- });
122
- z.object({
123
- envKey: z.string(),
124
- displayName: z.string(),
125
- value: z.string(),
126
- environment: CreateEnvironmentSchema
127
- });
128
- const ProjectModuleSchema = z.object({
129
- id: z.string(),
130
- name: z.string(),
131
- slug: z.string().nullable(),
132
- moduleType: z.string(),
133
- pathSegment: z.string().nullable()
134
- });
135
- const ProjectInfoResponseSchema = z.object({
136
- id: z.string(),
137
- name: z.string(),
138
- slug: z.string().nullable(),
139
- filesystemVersion: z.string().nullable(),
140
- createdAt: z.string(),
141
- updatedAt: z.string(),
142
- devServerUrl: z.string().nullable(),
143
- publishedUrls: z.array(z.string()),
144
- latestPublishedUrl: z.string().nullable(),
145
- projects: z.array(ProjectModuleSchema)
146
- });
147
- const ProjectStatusResponseSchema = z.object({
148
- projectGroupId: z.string(),
149
- latestRevisionId: z.string().nullable(),
150
- status: z.string().nullable(),
151
- deployment: z.object({
152
- id: z.string(),
153
- status: z.string(),
154
- url: z.string().nullable()
155
- }).nullable(),
156
- updatedAt: z.string()
157
- });
158
- const RenameProjectGroupResponseSchema = z.object({
159
- success: z.boolean(),
160
- projectGroupId: z.string().uuid(),
161
- name: z.string(),
162
- slug: z.string().nullable(),
163
- updatedAt: z.string()
164
- });
165
- const ProjectListItemSchema = z.object({
166
- id: z.string(),
167
- name: z.string(),
168
- slug: z.string().nullable(),
169
- organizationId: z.string(),
170
- organizationName: z.string(),
171
- createdAt: z.string(),
172
- updatedAt: z.string()
173
- });
174
- const ListProjectsResponseSchema = z.object({ projects: z.array(ProjectListItemSchema) });
175
- const DatabaseListItemSchema = z.object({
176
- id: z.string(),
177
- name: z.string(),
178
- status: z.enum([
179
- "CREATING",
180
- "COMPLETED",
181
- "FAILED"
182
- ]),
183
- organizationId: z.string(),
184
- organizationName: z.string(),
185
- createdAt: z.string(),
186
- updatedAt: z.string(),
187
- pointInTimeRestoreEnabled: z.boolean()
188
- });
189
- const ListDatabasesResponseSchema = z.object({ databases: z.array(DatabaseListItemSchema) });
190
- const SecretSchema = z.object({
191
- id: z.string(),
192
- envKey: z.string(),
193
- displayName: z.string(),
194
- environment: z.string()
195
- });
196
- const AddSecretResponseSchema = z.object({ secret: SecretSchema });
197
- const SecretListItemSchema = SecretSchema.extend({
198
- createdAt: z.string(),
199
- updatedAt: z.string()
200
- });
201
- const ListSecretsResponseSchema = z.object({ secrets: z.array(SecretListItemSchema) });
202
- const PublishResponseSchema = z.object({
203
- success: z.boolean(),
204
- projectGroupId: z.string(),
205
- slug: z.string().nullable(),
206
- deploymentId: z.string()
207
- });
208
- const ProjectSubmissionSchema = z.object({
209
- id: z.string(),
210
- projectGroupId: z.string(),
211
- status: z.enum([
212
- "PENDING",
213
- "CREATED",
214
- "FAILED"
215
- ]),
216
- launchUrl: z.string().nullable(),
217
- authUrl: z.string().nullable(),
218
- errorMessage: z.string().nullable(),
219
- expiresAt: z.string().nullable()
220
- });
221
- const SubmitProjectResponseSchema = z.object({
222
- success: z.boolean(),
223
- submission: ProjectSubmissionSchema
224
- });
225
- const UnpublishResponseSchema = z.object({
226
- success: z.boolean(),
227
- projectGroupId: z.string()
228
- });
229
- const OrganizationSchema = z.object({
230
- id: z.string(),
231
- name: z.string(),
232
- plan: z.string(),
233
- planDisplayName: z.string(),
234
- isPaid: z.boolean(),
235
- creditBalance: z.string()
236
- });
237
- const MeResponseSchema = z.object({
238
- id: z.string(),
239
- email: z.string().nullable(),
240
- name: z.string().nullable(),
241
- organizations: z.array(OrganizationSchema)
242
- });
243
- const OrganizationMembersResponseSchema = z.object({
244
- organization: z.object({
245
- id: z.string(),
246
- name: z.string(),
247
- role: z.string().nullable()
248
- }),
249
- collaborators: z.array(z.object({
250
- userId: z.string(),
251
- email: z.string().nullable(),
252
- displayName: z.string(),
253
- role: z.string(),
254
- isMe: z.boolean()
255
- })),
256
- pendingInvites: z.array(z.object({
257
- id: z.string(),
258
- toEmail: z.string(),
259
- expiresAt: z.string(),
260
- status: z.enum(["pending", "expired"])
261
- }))
262
- });
263
- const AssetSchema = z.object({
264
- id: z.string(),
265
- name: z.string(),
266
- url: z.string(),
267
- mimeType: z.string(),
268
- createdAt: z.string()
269
- });
270
- const UploadAssetResponseSchema = AssetSchema;
271
- const ListAssetsResponseSchema = z.object({
272
- assets: z.array(AssetSchema),
273
- total: z.number().optional()
274
- });
275
- const DomainProjectGroupSchema = z.object({
276
- id: z.string(),
277
- name: z.string()
278
- });
279
- const DomainSchema = z.object({
280
- id: z.string(),
281
- domain: z.string(),
282
- vercelVerified: z.boolean(),
283
- vercelVerification: z.unknown().nullable(),
284
- projectGroup: DomainProjectGroupSchema.nullable()
285
- });
286
- const ListDomainsResponseSchema = z.object({ domains: z.array(DomainSchema) });
287
- const DatabaseDetailSchema = DatabaseListItemSchema.extend({
288
- connectionString: z.string().nullable().optional(),
289
- projectGroupId: z.string().nullable().optional()
290
- });
291
- const DatabaseDetailResponseSchema = z.object({ database: DatabaseDetailSchema });
292
- const CreateDatabaseResponseSchema = z.object({ database: DatabaseListItemSchema });
293
- const DatabaseQueryResultSchema = z.object({
294
- columns: z.array(z.string()),
295
- rows: z.array(z.array(z.unknown())),
296
- rowCount: z.number()
297
- });
298
- const DatabaseConnectionResponseSchema = z.object({ connectionString: z.string() });
299
- const AddDomainResponseSchema = z.object({ domain: DomainSchema });
300
- const DomainVerificationSchema = z.object({
301
- domain: z.string(),
302
- verified: z.boolean(),
303
- vercelVerification: z.unknown().nullable()
304
- });
305
- const DeploymentSchema = z.object({
306
- id: z.string(),
307
- projectGroupId: z.string(),
308
- status: z.string(),
309
- url: z.string().nullable().optional(),
310
- createdAt: z.string(),
311
- completedAt: z.string().nullable()
312
- });
313
- const ListDeploymentsResponseSchema = z.object({ deployments: z.array(DeploymentSchema) });
314
- const DeploymentDetailSchema = DeploymentSchema.extend({
315
- buildLogs: z.string().nullable().optional(),
316
- failureReason: z.string().nullable().optional()
317
- });
318
- const DeploymentDetailResponseSchema = z.object({ deployment: DeploymentDetailSchema });
319
- const DeploymentLogsResponseSchema = z.object({
320
- logs: z.string(),
321
- status: z.string().optional(),
322
- failureReason: z.string().nullable().optional()
323
- });
324
- const RollbackResponseSchema = z.object({
325
- success: z.boolean(),
326
- deployment: DeploymentSchema.optional()
327
- });
328
- const InviteMemberResponseSchema = z.object({
329
- success: z.boolean(),
330
- invite: z.object({
331
- id: z.string(),
332
- toEmail: z.string(),
333
- expiresAt: z.string()
334
- })
335
- });
336
- const RemoveMemberResponseSchema = z.object({ success: z.boolean() });
337
- const UpdateMemberRoleResponseSchema = z.object({
338
- success: z.boolean(),
339
- userId: z.string(),
340
- role: z.string()
341
- });
342
- var AnythingApiClient = class {
343
- baseUrl;
344
- authHeader;
345
- constructor(config) {
346
- this.baseUrl = `${config.apiUrl.replace(/\/$/, "")}/v0/api`;
347
- this.authHeader = config.apiKey.startsWith("anything_") || config.apiKey.startsWith("create_") ? `Basic ${Buffer.from(`${config.apiKey}:`).toString("base64")}` : config.apiKey;
113
+ function _parseVault(options) {
114
+ const vaultPath = _vaultPath(options);
115
+ const result = DotenvModule.configDotenv({ path: vaultPath });
116
+ if (!result.parsed) {
117
+ const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
118
+ err.code = "MISSING_DATA";
119
+ throw err;
120
+ }
121
+ const keys = _dotenvKey(options).split(",");
122
+ const length = keys.length;
123
+ let decrypted;
124
+ for (let i = 0; i < length; i++) try {
125
+ const attrs = _instructions(result, keys[i].trim());
126
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
127
+ break;
128
+ } catch (error) {
129
+ if (i + 1 >= length) throw error;
130
+ }
131
+ return DotenvModule.parse(decrypted);
348
132
  }
349
- async getMe() {
350
- return this.request({
351
- method: "GET",
352
- path: "/me",
353
- schema: MeResponseSchema
354
- });
133
+ function _warn(message) {
134
+ console.log(`[dotenv@${version}][WARN] ${message}`);
355
135
  }
356
- async getOrganizationMembers({ organizationId }) {
357
- return this.request({
358
- method: "GET",
359
- path: `/organizations/${organizationId}/members`,
360
- schema: OrganizationMembersResponseSchema
361
- });
136
+ function _debug(message) {
137
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
362
138
  }
363
- async createProject({ prompt, organizationId, name }) {
364
- return this.request({
365
- method: "POST",
366
- path: "/projects",
367
- body: {
368
- prompt,
369
- organizationId,
370
- ...name !== null ? { name } : {}
371
- },
372
- schema: CreateProjectResponseSchema
373
- });
139
+ function _dotenvKey(options) {
140
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
141
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
142
+ return "";
374
143
  }
375
- async duplicateProjectGroup({ projectGroupId, name }) {
376
- return this.request({
377
- method: "POST",
378
- path: `/projects/${projectGroupId}/duplicate`,
379
- body: name !== null ? { name } : {},
380
- schema: DuplicateProjectGroupResponseSchema
381
- });
144
+ function _instructions(result, dotenvKey) {
145
+ let uri;
146
+ try {
147
+ uri = new URL(dotenvKey);
148
+ } catch (error) {
149
+ if (error.code === "ERR_INVALID_URL") {
150
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
151
+ err.code = "INVALID_DOTENV_KEY";
152
+ throw err;
153
+ }
154
+ throw error;
155
+ }
156
+ const key = uri.password;
157
+ if (!key) {
158
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
159
+ err.code = "INVALID_DOTENV_KEY";
160
+ throw err;
161
+ }
162
+ const environment = uri.searchParams.get("environment");
163
+ if (!environment) {
164
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
165
+ err.code = "INVALID_DOTENV_KEY";
166
+ throw err;
167
+ }
168
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
169
+ const ciphertext = result.parsed[environmentKey];
170
+ if (!ciphertext) {
171
+ const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
172
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
173
+ throw err;
174
+ }
175
+ return {
176
+ ciphertext,
177
+ key
178
+ };
382
179
  }
383
- async listProjects({ organizationId, query, limit }) {
384
- const params = new URLSearchParams();
385
- if (organizationId !== null) params.set("organizationId", organizationId);
386
- if (query !== null) params.set("query", query);
387
- params.set("limit", String(limit));
388
- return this.request({
389
- method: "GET",
390
- path: `/projects?${params.toString()}`,
391
- schema: ListProjectsResponseSchema
392
- });
393
- }
394
- async listDatabases({ organizationId, limit }) {
395
- const params = new URLSearchParams();
396
- params.set("organizationId", organizationId);
397
- params.set("limit", String(limit));
398
- return this.request({
399
- method: "GET",
400
- path: `/databases?${params.toString()}`,
401
- schema: ListDatabasesResponseSchema
402
- });
403
- }
404
- async generate({ projectGroupId, prompt, threadId, createNewThread }) {
405
- return this.request({
406
- method: "POST",
407
- path: `/projects/${projectGroupId}/generate`,
408
- body: {
409
- prompt,
410
- ...threadId !== null ? { threadId } : {},
411
- ...createNewThread ? { createNewThread: true } : {}
412
- },
413
- schema: GenerateResponseSchema
414
- });
415
- }
416
- async getMessages({ projectGroupId, threadId, limit }) {
417
- const params = new URLSearchParams();
418
- if (threadId !== null) params.set("threadId", threadId);
419
- if (limit !== null) params.set("limit", String(limit));
420
- const query = params.toString();
421
- const path = `/projects/${projectGroupId}/messages${query ? `?${query}` : ""}`;
422
- return this.request({
423
- method: "GET",
424
- path,
425
- schema: MessagesResponseSchema
426
- });
427
- }
428
- async getProjectLogs({ projectGroupId, level, search, limit }) {
429
- const params = new URLSearchParams();
430
- if (level !== null) params.set("level", level);
431
- if (search !== null) params.set("search", search);
432
- if (limit !== null) params.set("limit", String(limit));
433
- const query = params.toString();
434
- const path = `/projects/${projectGroupId}/logs${query ? `?${query}` : ""}`;
435
- return this.request({
436
- method: "GET",
437
- path,
438
- schema: ProjectLogsResponseSchema
439
- });
440
- }
441
- async getProjectAuthProviders({ projectGroupId }) {
442
- return this.request({
443
- method: "GET",
444
- path: `/projects/${projectGroupId}/auth/providers`,
445
- schema: ProjectAuthProvidersResponseSchema
446
- });
447
- }
448
- async getProjectAuthSettings({ projectGroupId }) {
449
- return this.request({
450
- method: "GET",
451
- path: `/projects/${projectGroupId}/settings/auth`,
452
- schema: ProjectAuthSettingsResponseSchema
453
- });
180
+ function _vaultPath(options) {
181
+ let possibleVaultPath = null;
182
+ if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
183
+ for (const filepath of options.path) if (fs$2.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
184
+ } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
185
+ else possibleVaultPath = path$1.resolve(process.cwd(), ".env.vault");
186
+ if (fs$2.existsSync(possibleVaultPath)) return possibleVaultPath;
187
+ return null;
454
188
  }
455
- async updateProjectAuthSettings({ projectGroupId, provider, enabled, secrets, enableForAllModules }) {
456
- return this.request({
457
- method: "POST",
458
- path: `/projects/${projectGroupId}/settings/auth`,
459
- body: {
460
- provider,
461
- enabled,
462
- ...secrets.length > 0 ? { secrets } : {},
463
- ...enableForAllModules ? { enableForAllModules } : {}
464
- },
465
- schema: ProjectAuthSettingsResponseSchema
466
- });
189
+ function _resolveHome(envPath) {
190
+ return envPath[0] === "~" ? path$1.join(os$1.homedir(), envPath.slice(1)) : envPath;
467
191
  }
468
- async getProject({ projectGroupId }) {
469
- return this.request({
470
- method: "GET",
471
- path: `/projects/${projectGroupId}`,
472
- schema: ProjectInfoResponseSchema
473
- });
192
+ function _configVault(options) {
193
+ if (Boolean(options && options.debug)) _debug("Loading env from encrypted .env.vault");
194
+ const parsed = DotenvModule._parseVault(options);
195
+ let processEnv = process.env;
196
+ if (options && options.processEnv != null) processEnv = options.processEnv;
197
+ DotenvModule.populate(processEnv, parsed, options);
198
+ return { parsed };
474
199
  }
475
- async getProjectStatus({ projectGroupId }) {
476
- return this.request({
477
- method: "GET",
478
- path: `/projects/${projectGroupId}/status`,
479
- schema: ProjectStatusResponseSchema
480
- });
200
+ function configDotenv(options) {
201
+ const dotenvPath = path$1.resolve(process.cwd(), ".env");
202
+ let encoding = "utf8";
203
+ const debug = Boolean(options && options.debug);
204
+ if (options && options.encoding) encoding = options.encoding;
205
+ else if (debug) _debug("No encoding is specified. UTF-8 is used by default");
206
+ let optionPaths = [dotenvPath];
207
+ if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
208
+ else {
209
+ optionPaths = [];
210
+ for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
211
+ }
212
+ let lastError;
213
+ const parsedAll = {};
214
+ for (const path of optionPaths) try {
215
+ const parsed = DotenvModule.parse(fs$2.readFileSync(path, { encoding }));
216
+ DotenvModule.populate(parsedAll, parsed, options);
217
+ } catch (e) {
218
+ if (debug) _debug(`Failed to load ${path} ${e.message}`);
219
+ lastError = e;
220
+ }
221
+ let processEnv = process.env;
222
+ if (options && options.processEnv != null) processEnv = options.processEnv;
223
+ DotenvModule.populate(processEnv, parsedAll, options);
224
+ if (lastError) return {
225
+ parsed: parsedAll,
226
+ error: lastError
227
+ };
228
+ else return { parsed: parsedAll };
481
229
  }
482
- async renameProjectGroup({ projectGroupId, name }) {
483
- return this.request({
484
- method: "POST",
485
- path: `/projects/${projectGroupId}/rename`,
486
- body: { name },
487
- schema: RenameProjectGroupResponseSchema
488
- });
230
+ function config(options) {
231
+ if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
232
+ const vaultPath = _vaultPath(options);
233
+ if (!vaultPath) {
234
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
235
+ return DotenvModule.configDotenv(options);
236
+ }
237
+ return DotenvModule._configVault(options);
489
238
  }
490
- async listProjectFiles({ projectGroupId }) {
491
- return this.request({
492
- method: "GET",
493
- path: `/projects/${projectGroupId}/files`,
494
- schema: ProjectFilesResponseSchema
495
- });
239
+ function decrypt(encrypted, keyStr) {
240
+ const key = Buffer.from(keyStr.slice(-64), "hex");
241
+ let ciphertext = Buffer.from(encrypted, "base64");
242
+ const nonce = ciphertext.subarray(0, 12);
243
+ const authTag = ciphertext.subarray(-16);
244
+ ciphertext = ciphertext.subarray(12, -16);
245
+ try {
246
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
247
+ aesgcm.setAuthTag(authTag);
248
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
249
+ } catch (error) {
250
+ const isRange = error instanceof RangeError;
251
+ const invalidKeyLength = error.message === "Invalid key length";
252
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
253
+ if (isRange || invalidKeyLength) {
254
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
255
+ err.code = "INVALID_DOTENV_KEY";
256
+ throw err;
257
+ } else if (decryptionFailed) {
258
+ const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
259
+ err.code = "DECRYPTION_FAILED";
260
+ throw err;
261
+ } else throw error;
262
+ }
496
263
  }
497
- async getProjectFile({ projectGroupId, path }) {
498
- const params = new URLSearchParams({ path });
499
- return this.request({
500
- method: "GET",
501
- path: `/projects/${projectGroupId}/files?${params.toString()}`,
502
- schema: ProjectFileResponseSchema
503
- });
264
+ function populate(processEnv, parsed, options = {}) {
265
+ const debug = Boolean(options && options.debug);
266
+ const override = Boolean(options && options.override);
267
+ if (typeof parsed !== "object") {
268
+ const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
269
+ err.code = "OBJECT_REQUIRED";
270
+ throw err;
271
+ }
272
+ for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
273
+ if (override === true) processEnv[key] = parsed[key];
274
+ if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
275
+ else _debug(`"${key}" is already defined and was NOT overwritten`);
276
+ } else processEnv[key] = parsed[key];
504
277
  }
505
- async addSecret({ projectGroupId, displayName, value, environment }) {
506
- return this.request({
507
- method: "POST",
508
- path: `/projects/${projectGroupId}/secrets`,
509
- body: {
510
- displayName,
511
- value,
512
- ...environment !== null ? { environment } : {}
278
+ const DotenvModule = {
279
+ configDotenv,
280
+ _configVault,
281
+ _parseVault,
282
+ config,
283
+ decrypt,
284
+ parse,
285
+ populate
286
+ };
287
+ module.exports.configDotenv = DotenvModule.configDotenv;
288
+ module.exports._configVault = DotenvModule._configVault;
289
+ module.exports._parseVault = DotenvModule._parseVault;
290
+ module.exports.config = DotenvModule.config;
291
+ module.exports.decrypt = DotenvModule.decrypt;
292
+ module.exports.parse = DotenvModule.parse;
293
+ module.exports.populate = DotenvModule.populate;
294
+ module.exports = DotenvModule;
295
+ }));
296
+
297
+ //#endregion
298
+ //#region ../../node_modules/dotenv-flow/package.json
299
+ var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
300
+ module.exports = {
301
+ "name": "dotenv-flow",
302
+ "version": "4.1.0",
303
+ "description": "Loads environment variables from `.env.[development|test|production][.local]` files",
304
+ "keywords": [
305
+ "dotenv",
306
+ "node_env",
307
+ "development",
308
+ "test",
309
+ "production",
310
+ "local",
311
+ "env",
312
+ "environment",
313
+ "variables"
314
+ ],
315
+ "homepage": "https://github.com/kerimdzhanov/dotenv-flow#readme",
316
+ "repository": {
317
+ "type": "git",
318
+ "url": "git+https://github.com/kerimdzhanov/dotenv-flow.git"
319
+ },
320
+ "bugs": { "url": "https://github.com/kerimdzhanov/dotenv-flow/issues" },
321
+ "main": "lib/dotenv-flow.js",
322
+ "types": "lib/dotenv-flow.d.ts",
323
+ "exports": {
324
+ ".": "./lib/dotenv-flow.js",
325
+ "./config": {
326
+ "require": "./config.js",
327
+ "node": "./config.js"
513
328
  },
514
- schema: AddSecretResponseSchema
515
- });
516
- }
517
- async listSecrets({ projectGroupId }) {
518
- return this.request({
519
- method: "GET",
520
- path: `/projects/${projectGroupId}/secrets`,
521
- schema: ListSecretsResponseSchema
522
- });
523
- }
524
- async deleteSecret({ projectGroupId, secretId }) {
525
- return this.request({
526
- method: "DELETE",
527
- path: `/projects/${projectGroupId}/secrets/${secretId}`
528
- });
529
- }
530
- async publish({ projectGroupId, slug }) {
531
- return this.request({
532
- method: "POST",
533
- path: `/projects/${projectGroupId}/publish`,
534
- body: slug !== null ? { slug } : {},
535
- schema: PublishResponseSchema
536
- });
537
- }
538
- async submitProject({ projectGroupId, store }) {
539
- return this.request({
540
- method: "POST",
541
- path: `/projects/${projectGroupId}/submit`,
542
- body: { store },
543
- schema: SubmitProjectResponseSchema
544
- });
545
- }
546
- async getProjectSubmission({ projectGroupId, submissionId }) {
547
- return this.request({
548
- method: "GET",
549
- path: `/projects/${projectGroupId}/submit/${submissionId}`,
550
- schema: SubmitProjectResponseSchema
551
- });
552
- }
553
- async unpublish({ projectGroupId }) {
554
- return this.request({
555
- method: "POST",
556
- path: `/projects/${projectGroupId}/unpublish`,
557
- schema: UnpublishResponseSchema
558
- });
329
+ "./package.json": "./package.json"
330
+ },
331
+ "files": [
332
+ "lib/cli-options.js",
333
+ "lib/dotenv-flow.d.ts",
334
+ "lib/env-options.js",
335
+ "config.d.ts",
336
+ "config.js"
337
+ ],
338
+ "dependencies": { "dotenv": "^16.0.0" },
339
+ "devDependencies": {
340
+ "@types/node": "^20.6.2",
341
+ "chai": "^4.3.7",
342
+ "conventional-changelog-cli": "^2.0.35",
343
+ "mocha": "^10.2.0",
344
+ "sinon": "^15.2.0",
345
+ "sinon-chai": "^3.7.0",
346
+ "tmp": "^0.2.1",
347
+ "typescript": "^5.2.2"
348
+ },
349
+ "engines": { "node": ">= 12.0.0" },
350
+ "scripts": {
351
+ "test": "yarn run test:unit && yarn run test:integration && yarn run test:types",
352
+ "test:unit": "mocha -r mocha.conf.js test/unit/*.spec.js",
353
+ "test:integration": "mocha -r mocha.conf.js test/integration/*.spec.{m,}js",
354
+ "test:types": "tsc",
355
+ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
356
+ },
357
+ "author": "Dan Kerimdzhanov",
358
+ "license": "MIT"
359
+ };
360
+ }));
361
+
362
+ //#endregion
363
+ //#region ../../node_modules/dotenv-flow/lib/dotenv-flow.js
364
+ var require_dotenv_flow = /* @__PURE__ */ __commonJSMin(((exports, module) => {
365
+ const fs$1 = __require("fs");
366
+ const p = __require("path");
367
+ const dotenv = require_main();
368
+ const { version } = require_package();
369
+ const DEFAULT_PATTERN = ".env[.node_env][.local]";
370
+ const LOCAL_PLACEHOLDER_REGEX = /\[(\W*\blocal\b\W*)]/g;
371
+ const NODE_ENV_PLACEHOLDER_REGEX = /\[(\W*\b)node_env(\b\W*)]/g;
372
+ /**
373
+ * Compose a filename from a given `patten`.
374
+ *
375
+ * @param {string} pattern
376
+ * @param {object} [options]
377
+ * @param {boolean} [options.local]
378
+ * @param {string} [options.node_env]
379
+ * @return {string} filename
380
+ */
381
+ function composeFilename(pattern, options) {
382
+ let filename = pattern;
383
+ filename = filename.replace(LOCAL_PLACEHOLDER_REGEX, options && options.local ? "$1" : "");
384
+ filename = filename.replace(NODE_ENV_PLACEHOLDER_REGEX, options && options.node_env ? `$1${options.node_env}$2` : "");
385
+ return filename;
559
386
  }
560
- async uploadAsset({ projectGroupId, filePath, name }) {
561
- const url = `${this.baseUrl}/projects/${projectGroupId}/assets`;
562
- let fileBuffer;
563
- try {
564
- const { readFileSync } = await import("node:fs");
565
- fileBuffer = readFileSync(filePath);
566
- } catch (cause) {
567
- return err({
568
- message: `Failed to read file: ${cause instanceof Error ? cause.message : String(cause)}`,
569
- status: null
570
- });
387
+ /**
388
+ * Returns a list of existing `.env*` filenames depending on the given `options`.
389
+ *
390
+ * The resulting list is ordered by the env files'
391
+ * variables overwriting priority from lowest to highest.
392
+ *
393
+ * This can also be referenced as "env files' environment cascade"
394
+ * or "order of ascending priority."
395
+ *
396
+ * ⚠️ Note that the `.env.local` file is not listed for "test" environment,
397
+ * since normally you expect tests to produce the same results for everyone.
398
+ *
399
+ * @param {object} [options] - `.env*` files listing options
400
+ * @param {string} [options.node_env] - node environment (development/test/production/etc.)
401
+ * @param {string} [options.path] - path to the working directory (default: `process.cwd()`)
402
+ * @param {string} [options.pattern] - `.env*` files' naming convention pattern
403
+ * (default: ".env[.node_env][.local]")
404
+ * @param {boolean} [options.debug] - turn on debug messages
405
+ * @return {string[]}
406
+ */
407
+ function listFiles(options = {}) {
408
+ options.debug && debug("listing effective `.env*` files…");
409
+ const { node_env, path = process.cwd(), pattern = DEFAULT_PATTERN } = options;
410
+ const hasLocalPlaceholder = LOCAL_PLACEHOLDER_REGEX.test(pattern);
411
+ const filenames = {};
412
+ if (pattern === DEFAULT_PATTERN) filenames[".env.defaults"] = ".env.defaults";
413
+ filenames[".env"] = composeFilename(pattern);
414
+ if (hasLocalPlaceholder) {
415
+ const envlocal = composeFilename(pattern, { local: true });
416
+ if (node_env !== "test") filenames[".env.local"] = envlocal;
417
+ else if (options.debug && fs$1.existsSync(p.resolve(path, envlocal))) debug("[!] note that `%s` is being skipped for \"test\" environment", envlocal);
571
418
  }
572
- const fileName = basename(filePath);
573
- const formData = new FormData();
574
- formData.append("file", new Blob([new Uint8Array(fileBuffer)]), fileName);
575
- if (name !== null) formData.append("name", name);
576
- let response;
577
- try {
578
- response = await fetch(url, {
579
- method: "POST",
580
- headers: {
581
- authorization: this.authHeader,
582
- "user-agent": USER_AGENT
583
- },
584
- body: formData
585
- });
586
- } catch (cause) {
587
- return err({
588
- message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,
589
- status: null
419
+ if (node_env && NODE_ENV_PLACEHOLDER_REGEX.test(pattern)) {
420
+ filenames[".env.node_env"] = composeFilename(pattern, { node_env });
421
+ if (hasLocalPlaceholder) filenames[".env.node_env.local"] = composeFilename(pattern, {
422
+ node_env,
423
+ local: true
590
424
  });
591
425
  }
592
- if (!response.ok) {
593
- const text = await response.text().catch(() => "");
594
- let details;
595
- try {
596
- details = JSON.parse(text);
597
- } catch {
598
- details = text || void 0;
426
+ return [
427
+ ".env.defaults",
428
+ ".env",
429
+ ".env.local",
430
+ ".env.node_env",
431
+ ".env.node_env.local"
432
+ ].reduce((list, basename) => {
433
+ if (!filenames[basename]) return list;
434
+ const filename = p.resolve(path, filenames[basename]);
435
+ if (fs$1.existsSync(filename)) {
436
+ options.debug && debug(">> %s", filename);
437
+ list.push(filename);
599
438
  }
600
- const retryAfter = parseRetryAfter(response);
601
- return err({
602
- message: `API error (${response.status})`,
603
- status: response.status,
604
- details,
605
- ...retryAfter !== null ? { retryAfter } : {}
606
- });
607
- }
608
- const json = await response.json();
609
- const parsed = UploadAssetResponseSchema.safeParse(json);
610
- if (!parsed.success) return err({
611
- message: "Unexpected API response format",
612
- status: response.status,
613
- details: parsed.error.errors
614
- });
615
- return ok(parsed.data);
616
- }
617
- async listAssets({ projectGroupId, query, limit, offset }) {
618
- const params = new URLSearchParams();
619
- if (query !== null) params.set("query", query);
620
- if (limit !== null) params.set("limit", String(limit));
621
- if (offset !== null) params.set("offset", String(offset));
622
- const qs = params.toString();
623
- const path = `/projects/${projectGroupId}/assets${qs ? `?${qs}` : ""}`;
624
- return this.request({
625
- method: "GET",
626
- path,
627
- schema: ListAssetsResponseSchema
628
- });
629
- }
630
- async listDomains({ organizationId }) {
631
- const params = new URLSearchParams({ organizationId });
632
- return this.request({
633
- method: "GET",
634
- path: `/domains?${params.toString()}`,
635
- schema: ListDomainsResponseSchema
636
- });
439
+ return list;
440
+ }, []);
637
441
  }
638
- async deleteAsset({ projectGroupId, assetId }) {
639
- return this.request({
640
- method: "DELETE",
641
- path: `/projects/${projectGroupId}/assets/${assetId}`
642
- });
442
+ /**
443
+ * Parses a given file or a list of files.
444
+ *
445
+ * When a list of filenames is given, the files will be parsed and merged in the same order as given.
446
+ *
447
+ * @param {string|string[]} filenames - filename or a list of filenames to parse and merge
448
+ * @param {{ encoding?: string, debug?: boolean }} [options] - parse options
449
+ * @return {Object<string, string>} the resulting map of `{ env_var: value }` as an object
450
+ */
451
+ function parse(filenames, options = {}) {
452
+ if (typeof filenames === "string") {
453
+ options.debug && debug("parsing \"%s\"…", filenames);
454
+ const parsed = dotenv.parse(fs$1.readFileSync(filenames, options.encoding && { encoding: options.encoding }));
455
+ if (options.debug) Object.keys(parsed).forEach((varname) => debug(">> %s", varname));
456
+ return parsed;
457
+ }
458
+ return filenames.reduce((result, filename) => {
459
+ const parsed = parse(filename, options);
460
+ if (options.debug) Object.keys(parsed).filter((varname) => result.hasOwnProperty(varname)).forEach((varname) => debug("`%s` is being overwritten by merge from \"%s\"", varname, filename));
461
+ return Object.assign(result, parsed);
462
+ }, {});
643
463
  }
644
- async getDatabase({ databaseId }) {
645
- return this.request({
646
- method: "GET",
647
- path: `/databases/${databaseId}`,
648
- schema: DatabaseDetailResponseSchema
649
- });
650
- }
651
- async createDatabase({ organizationId, projectGroupId, name }) {
652
- return this.request({
653
- method: "POST",
654
- path: "/databases",
655
- body: {
656
- organizationId,
657
- ...projectGroupId !== null ? { projectGroupId } : {},
658
- ...name !== null ? { name } : {}
659
- },
660
- schema: CreateDatabaseResponseSchema
661
- });
662
- }
663
- async queryDatabase({ databaseId, sql }) {
664
- return this.request({
665
- method: "POST",
666
- path: `/databases/${databaseId}/query`,
667
- body: { sql },
668
- schema: DatabaseQueryResultSchema
669
- });
670
- }
671
- async getDatabaseConnection({ databaseId }) {
672
- return this.request({
673
- method: "GET",
674
- path: `/databases/${databaseId}/connection`,
675
- schema: DatabaseConnectionResponseSchema
676
- });
677
- }
678
- async resetDatabase({ databaseId }) {
679
- return this.request({
680
- method: "POST",
681
- path: `/databases/${databaseId}/reset`
682
- });
683
- }
684
- async addDomain({ organizationId, domain, projectGroupId }) {
685
- return this.request({
686
- method: "POST",
687
- path: "/domains",
688
- body: {
689
- organizationId,
690
- domain,
691
- ...projectGroupId !== null ? { projectGroupId } : {}
692
- },
693
- schema: AddDomainResponseSchema
694
- });
695
- }
696
- async removeDomain({ domainId }) {
697
- return this.request({
698
- method: "DELETE",
699
- path: `/domains/${domainId}`
700
- });
464
+ /**
465
+ * Parses variables defined in given file(s) and assigns them to `process.env`.
466
+ *
467
+ * Variables that are already defined in `process.env` will not be overwritten,
468
+ * thus giving a higher priority to environment variables predefined by the shell.
469
+ *
470
+ * If the loading is successful, an object with `parsed` property is returned.
471
+ * The `parsed` property contains parsed variables' `key => value` pairs merged in order using
472
+ * the "overwrite merge" strategy.
473
+ *
474
+ * If parsing fails for any of the given files, `process.env` is being left untouched,
475
+ * and an object with `error` property is returned.
476
+ * The `error` property, if present, references to the occurred error.
477
+ *
478
+ * @param {string|string[]} filenames - filename or a list of filenames to parse and merge
479
+ * @param {object} [options] - file loading options
480
+ * @param {string} [options.encoding="utf8"] - encoding of `.env*` files
481
+ * @param {boolean} [options.debug=false] - turn on debug messages
482
+ * @param {boolean} [options.silent=false] - suppress console errors and warnings
483
+ * @return {{ error: Error } | { parsed: Object<string, string> }}
484
+ */
485
+ function load(filenames, options = {}) {
486
+ try {
487
+ const parsed = parse(filenames, {
488
+ encoding: options.encoding,
489
+ debug: options.debug
490
+ });
491
+ options.debug && debug("safe-merging parsed environment variables into `process.env`…");
492
+ for (const varname of Object.keys(parsed)) if (!process.env.hasOwnProperty(varname)) {
493
+ options.debug && debug(">> process.env.%s", varname);
494
+ process.env[varname] = parsed[varname];
495
+ } else if (options.debug && process.env[varname] !== parsed[varname]) debug("environment variable `%s` is predefined and not being overwritten", varname);
496
+ return { parsed };
497
+ } catch (error) {
498
+ return failure(error, options);
499
+ }
701
500
  }
702
- async verifyDomain({ domainId }) {
703
- return this.request({
704
- method: "POST",
705
- path: `/domains/${domainId}/verify`,
706
- schema: DomainVerificationSchema
501
+ /**
502
+ * Unload variables defined in a given file(s) from `process.env`.
503
+ *
504
+ * This function can gracefully resolve the following issue:
505
+ *
506
+ * In some cases, the original "dotenv" library can be used by one of the dependent npm modules.
507
+ * It causes calling the original `dotenv.config()` that loads the `.env` file from your project before you can call `dotenv-flow.config()`.
508
+ * Such cases break `.env*` files priority because the previously loaded environment variables are treated as shell-defined thus having a higher priority.
509
+ *
510
+ * Unloading the previously loaded `.env` file can be activated when using the `dotenv-flow.config()` with the `purge_dotenv` option set to `true`.
511
+ *
512
+ * @param {string|string[]} filenames - filename or a list of filenames to unload
513
+ * @param {object} [options] - `fs.readFileSync` options
514
+ */
515
+ function unload(filenames, options = {}) {
516
+ const parsed = parse(filenames, options);
517
+ Object.keys(parsed).forEach((key) => {
518
+ if (process.env[key] === parsed[key]) delete process.env[key];
707
519
  });
708
520
  }
709
- async listDeployments({ projectGroupId, limit }) {
710
- const params = new URLSearchParams();
711
- if (limit !== null) params.set("limit", String(limit));
712
- const query = params.toString();
713
- const path = `/projects/${projectGroupId}/deployments${query ? `?${query}` : ""}`;
714
- return this.request({
715
- method: "GET",
716
- path,
717
- schema: ListDeploymentsResponseSchema
718
- });
521
+ /**
522
+ * Returns effective (computed) `node_env`.
523
+ *
524
+ * @param {object} [options]
525
+ * @param {string} [options.node_env]
526
+ * @param {string} [options.default_node_env]
527
+ * @param {boolean} [options.debug]
528
+ * @return {string|undefined} node_env
529
+ */
530
+ function getEffectiveNodeEnv(options = {}) {
531
+ if (options.node_env) {
532
+ options.debug && debug(`operating in "${options.node_env}" environment (set by \`options.node_env\`)`);
533
+ return options.node_env;
534
+ }
535
+ if (process.env.NODE_ENV) {
536
+ options.debug && debug(`operating in "${process.env.NODE_ENV}" environment (as per \`process.env.NODE_ENV\`)`);
537
+ return process.env.NODE_ENV;
538
+ }
539
+ if (options.default_node_env) {
540
+ options.debug && debug(`operating in "${options.default_node_env}" environment (taken from \`options.default_node_env\`)`);
541
+ return options.default_node_env;
542
+ }
543
+ options.debug && debug("operating in \"no environment\" mode (no environment-related options are set)");
719
544
  }
720
- async getDeployment({ deploymentId }) {
721
- return this.request({
722
- method: "GET",
723
- path: `/deployments/${deploymentId}`,
724
- schema: DeploymentDetailResponseSchema
725
- });
545
+ const CONFIG_OPTION_KEYS = [
546
+ "node_env",
547
+ "default_node_env",
548
+ "path",
549
+ "pattern",
550
+ "files",
551
+ "encoding",
552
+ "purge_dotenv",
553
+ "silent"
554
+ ];
555
+ /**
556
+ * "dotenv-flow" initialization function (API entry point).
557
+ *
558
+ * Allows configuring dotenv-flow programmatically.
559
+ *
560
+ * @param {object} [options] - configuration options
561
+ * @param {string} [options.node_env=process.env.NODE_ENV] - node environment (development/test/production/etc.)
562
+ * @param {string} [options.default_node_env] - the default node environment
563
+ * @param {string} [options.path=process.cwd()] - path to `.env*` files directory
564
+ * @param {string} [options.pattern=".env[.node_env][.local]"] - `.env*` files' naming convention pattern
565
+ * @param {string[]} [options.files] - an explicit list of `.env*` files to load (note that `options.[default_]node_env` and `options.pattern` are ignored in this case)
566
+ * @param {string} [options.encoding="utf8"] - encoding of `.env*` files
567
+ * @param {boolean} [options.purge_dotenv=false] - perform the `.env` file {@link unload}
568
+ * @param {boolean} [options.debug=false] - turn on detailed logging to help debug why certain variables are not being set as you expect
569
+ * @param {boolean} [options.silent=false] - suppress all kinds of warnings including ".env*" files' loading errors
570
+ * @return {{ parsed?: object, error?: Error }} with a `parsed` key containing the loaded content or an `error` key with an error that is occurred
571
+ */
572
+ function config(options = {}) {
573
+ if (options.debug) {
574
+ debug("initializing…");
575
+ CONFIG_OPTION_KEYS.filter((key) => key in options).forEach((key) => debug(`| options.${key} =`, options[key]));
576
+ }
577
+ const { path = process.cwd(), pattern = DEFAULT_PATTERN } = options;
578
+ if (options.purge_dotenv) {
579
+ options.debug && debug("`options.purge_dotenv` is enabled, unloading potentially pre-loaded `.env`…");
580
+ const dotenvFile = p.resolve(path, ".env");
581
+ try {
582
+ fs$1.existsSync(dotenvFile) && unload(dotenvFile, { encoding: options.encoding });
583
+ } catch (error) {
584
+ !options.silent && warn("unloading failed: ", error);
585
+ }
586
+ }
587
+ try {
588
+ let filenames;
589
+ if (options.files) {
590
+ options.debug && debug("using explicit list of `.env*` files: %s…", options.files.join(", "));
591
+ filenames = options.files.reduce((list, basename) => {
592
+ const filename = p.resolve(path, basename);
593
+ if (fs$1.existsSync(filename)) list.push(filename);
594
+ else if (options.debug) debug(">> %s does not exist, skipping…", filename);
595
+ return list;
596
+ }, []);
597
+ } else {
598
+ const node_env = getEffectiveNodeEnv(options);
599
+ filenames = listFiles({
600
+ node_env,
601
+ path,
602
+ pattern,
603
+ debug: options.debug
604
+ });
605
+ if (filenames.length === 0) {
606
+ const _pattern = node_env ? pattern.replace(NODE_ENV_PLACEHOLDER_REGEX, `[$1${node_env}$2]`) : pattern;
607
+ return failure(/* @__PURE__ */ new Error(`no ".env*" files matching pattern "${_pattern}" in "${path}" dir`), options);
608
+ }
609
+ }
610
+ const result = load(filenames, {
611
+ encoding: options.encoding,
612
+ debug: options.debug,
613
+ silent: options.silent
614
+ });
615
+ options.debug && debug("initialization completed.");
616
+ return result;
617
+ } catch (error) {
618
+ return failure(error, options);
619
+ }
726
620
  }
727
- async getDeploymentLogs({ deploymentId }) {
728
- return this.request({
729
- method: "GET",
730
- path: `/deployments/${deploymentId}/logs`,
731
- schema: DeploymentLogsResponseSchema
732
- });
621
+ function failure(error, options) {
622
+ if (!options.silent) warn(`".env*" files loading failed: ${error.message || error}`);
623
+ return { error };
733
624
  }
734
- async rollbackDeployment({ projectGroupId, deploymentId }) {
735
- return this.request({
736
- method: "POST",
737
- path: `/projects/${projectGroupId}/deployments/rollback`,
738
- body: deploymentId !== null ? { deploymentId } : {},
739
- schema: RollbackResponseSchema
740
- });
625
+ function warn(message, error) {
626
+ if (error) message += ": %s";
627
+ console.warn(`[dotenv-flow@${version}]: ${message}`, error);
741
628
  }
742
- async inviteMember({ organizationId, email, role }) {
743
- return this.request({
744
- method: "POST",
745
- path: `/organizations/${organizationId}/invites`,
746
- body: {
747
- email,
748
- ...role !== null ? { role } : {}
749
- },
750
- schema: InviteMemberResponseSchema
751
- });
629
+ function debug(message, ...values) {
630
+ console.debug(`[dotenv-flow@${version}]: ${message}`, ...values);
752
631
  }
753
- async removeMember({ organizationId, email }) {
754
- return this.request({
755
- method: "POST",
756
- path: `/organizations/${organizationId}/members/remove`,
757
- body: { email },
758
- schema: RemoveMemberResponseSchema
759
- });
760
- }
761
- async updateMemberRole({ organizationId, email, role }) {
762
- return this.request({
763
- method: "POST",
764
- path: `/organizations/${organizationId}/members/role`,
765
- body: {
766
- email,
767
- role
768
- },
769
- schema: UpdateMemberRoleResponseSchema
770
- });
771
- }
772
- async request(params) {
773
- const url = `${this.baseUrl}${params.path}`;
774
- let response;
775
- try {
776
- response = await fetch(url, {
777
- method: params.method,
778
- headers: {
779
- authorization: this.authHeader,
780
- "user-agent": USER_AGENT,
781
- ...params.body ? { "Content-Type": "application/json" } : {}
782
- },
783
- ...params.body ? { body: JSON.stringify(params.body) } : {}
784
- });
785
- } catch (cause) {
786
- return err({
787
- message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,
788
- status: null
789
- });
790
- }
791
- if (!response.ok) {
792
- const text = await response.text().catch(() => "");
793
- let details;
794
- try {
795
- details = JSON.parse(text);
796
- } catch {
797
- details = text || void 0;
798
- }
799
- const retryAfter = parseRetryAfter(response);
800
- return err({
801
- message: `API error (${response.status})`,
802
- status: response.status,
803
- details,
804
- ...retryAfter !== null ? { retryAfter } : {}
805
- });
806
- }
807
- if (response.status === 204 || !params.schema) return ok(void 0);
808
- const json = await response.json();
809
- const parsed = params.schema.safeParse(json);
810
- if (!parsed.success) return err({
811
- message: "Unexpected API response format",
812
- status: response.status,
813
- details: parsed.error.errors
814
- });
815
- return ok(parsed.data);
816
- }
817
- };
818
-
819
- //#endregion
820
- //#region ../../node_modules/dotenv/package.json
821
- var require_package$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
822
632
  module.exports = {
823
- "name": "dotenv",
824
- "version": "16.5.0",
825
- "description": "Loads environment variables from .env file",
826
- "main": "lib/main.js",
827
- "types": "lib/main.d.ts",
828
- "exports": {
829
- ".": {
830
- "types": "./lib/main.d.ts",
831
- "require": "./lib/main.js",
832
- "default": "./lib/main.js"
833
- },
834
- "./config": "./config.js",
835
- "./config.js": "./config.js",
836
- "./lib/env-options": "./lib/env-options.js",
837
- "./lib/env-options.js": "./lib/env-options.js",
838
- "./lib/cli-options": "./lib/cli-options.js",
839
- "./lib/cli-options.js": "./lib/cli-options.js",
840
- "./package.json": "./package.json"
841
- },
842
- "scripts": {
843
- "dts-check": "tsc --project tests/types/tsconfig.json",
844
- "lint": "standard",
845
- "pretest": "npm run lint && npm run dts-check",
846
- "test": "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
847
- "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
848
- "prerelease": "npm test",
849
- "release": "standard-version"
850
- },
851
- "repository": {
852
- "type": "git",
853
- "url": "git://github.com/motdotla/dotenv.git"
854
- },
855
- "homepage": "https://github.com/motdotla/dotenv#readme",
856
- "funding": "https://dotenvx.com",
857
- "keywords": [
858
- "dotenv",
859
- "env",
860
- ".env",
861
- "environment",
862
- "variables",
863
- "config",
864
- "settings"
865
- ],
866
- "readmeFilename": "README.md",
867
- "license": "BSD-2-Clause",
868
- "devDependencies": {
869
- "@types/node": "^18.11.3",
870
- "decache": "^4.6.2",
871
- "sinon": "^14.0.1",
872
- "standard": "^17.0.0",
873
- "standard-version": "^9.5.0",
874
- "tap": "^19.2.0",
875
- "typescript": "^4.8.4"
876
- },
877
- "engines": { "node": ">=12" },
878
- "browser": { "fs": false }
633
+ DEFAULT_PATTERN,
634
+ listFiles,
635
+ parse,
636
+ load,
637
+ unload,
638
+ config
879
639
  };
880
640
  }));
881
641
 
882
642
  //#endregion
883
- //#region ../../node_modules/dotenv/lib/main.js
884
- var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
885
- const fs$2 = __require("fs");
886
- const path$1 = __require("path");
887
- const os$1 = __require("os");
888
- const crypto = __require("crypto");
889
- const version = require_package$1().version;
890
- const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
891
- function parse(src) {
892
- const obj = {};
893
- let lines = src.toString();
894
- lines = lines.replace(/\r\n?/gm, "\n");
895
- let match;
896
- while ((match = LINE.exec(lines)) != null) {
897
- const key = match[1];
898
- let value = match[2] || "";
899
- value = value.trim();
900
- const maybeQuote = value[0];
901
- value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
902
- if (maybeQuote === "\"") {
903
- value = value.replace(/\\n/g, "\n");
904
- value = value.replace(/\\r/g, "\r");
905
- }
906
- obj[key] = value;
907
- }
908
- return obj;
909
- }
910
- function _parseVault(options) {
911
- const vaultPath = _vaultPath(options);
912
- const result = DotenvModule.configDotenv({ path: vaultPath });
913
- if (!result.parsed) {
914
- const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
915
- err.code = "MISSING_DATA";
916
- throw err;
917
- }
918
- const keys = _dotenvKey(options).split(",");
919
- const length = keys.length;
920
- let decrypted;
921
- for (let i = 0; i < length; i++) try {
922
- const attrs = _instructions(result, keys[i].trim());
923
- decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
924
- break;
925
- } catch (error) {
926
- if (i + 1 >= length) throw error;
927
- }
928
- return DotenvModule.parse(decrypted);
929
- }
930
- function _warn(message) {
931
- console.log(`[dotenv@${version}][WARN] ${message}`);
932
- }
933
- function _debug(message) {
934
- console.log(`[dotenv@${version}][DEBUG] ${message}`);
935
- }
936
- function _dotenvKey(options) {
937
- if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
938
- if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
939
- return "";
940
- }
941
- function _instructions(result, dotenvKey) {
942
- let uri;
943
- try {
944
- uri = new URL(dotenvKey);
945
- } catch (error) {
946
- if (error.code === "ERR_INVALID_URL") {
947
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
948
- err.code = "INVALID_DOTENV_KEY";
949
- throw err;
950
- }
951
- throw error;
952
- }
953
- const key = uri.password;
954
- if (!key) {
955
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
956
- err.code = "INVALID_DOTENV_KEY";
957
- throw err;
958
- }
959
- const environment = uri.searchParams.get("environment");
960
- if (!environment) {
961
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
962
- err.code = "INVALID_DOTENV_KEY";
963
- throw err;
964
- }
965
- const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
966
- const ciphertext = result.parsed[environmentKey];
967
- if (!ciphertext) {
968
- const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
969
- err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
970
- throw err;
971
- }
972
- return {
973
- ciphertext,
974
- key
975
- };
976
- }
977
- function _vaultPath(options) {
978
- let possibleVaultPath = null;
979
- if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
980
- for (const filepath of options.path) if (fs$2.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
981
- } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
982
- else possibleVaultPath = path$1.resolve(process.cwd(), ".env.vault");
983
- if (fs$2.existsSync(possibleVaultPath)) return possibleVaultPath;
984
- return null;
985
- }
986
- function _resolveHome(envPath) {
987
- return envPath[0] === "~" ? path$1.join(os$1.homedir(), envPath.slice(1)) : envPath;
988
- }
989
- function _configVault(options) {
990
- if (Boolean(options && options.debug)) _debug("Loading env from encrypted .env.vault");
991
- const parsed = DotenvModule._parseVault(options);
992
- let processEnv = process.env;
993
- if (options && options.processEnv != null) processEnv = options.processEnv;
994
- DotenvModule.populate(processEnv, parsed, options);
995
- return { parsed };
996
- }
997
- function configDotenv(options) {
998
- const dotenvPath = path$1.resolve(process.cwd(), ".env");
999
- let encoding = "utf8";
1000
- const debug = Boolean(options && options.debug);
1001
- if (options && options.encoding) encoding = options.encoding;
1002
- else if (debug) _debug("No encoding is specified. UTF-8 is used by default");
1003
- let optionPaths = [dotenvPath];
1004
- if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
1005
- else {
1006
- optionPaths = [];
1007
- for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
1008
- }
1009
- let lastError;
1010
- const parsedAll = {};
1011
- for (const path of optionPaths) try {
1012
- const parsed = DotenvModule.parse(fs$2.readFileSync(path, { encoding }));
1013
- DotenvModule.populate(parsedAll, parsed, options);
1014
- } catch (e) {
1015
- if (debug) _debug(`Failed to load ${path} ${e.message}`);
1016
- lastError = e;
1017
- }
1018
- let processEnv = process.env;
1019
- if (options && options.processEnv != null) processEnv = options.processEnv;
1020
- DotenvModule.populate(processEnv, parsedAll, options);
1021
- if (lastError) return {
1022
- parsed: parsedAll,
1023
- error: lastError
1024
- };
1025
- else return { parsed: parsedAll };
1026
- }
1027
- function config(options) {
1028
- if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
1029
- const vaultPath = _vaultPath(options);
1030
- if (!vaultPath) {
1031
- _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
1032
- return DotenvModule.configDotenv(options);
1033
- }
1034
- return DotenvModule._configVault(options);
1035
- }
1036
- function decrypt(encrypted, keyStr) {
1037
- const key = Buffer.from(keyStr.slice(-64), "hex");
1038
- let ciphertext = Buffer.from(encrypted, "base64");
1039
- const nonce = ciphertext.subarray(0, 12);
1040
- const authTag = ciphertext.subarray(-16);
1041
- ciphertext = ciphertext.subarray(12, -16);
1042
- try {
1043
- const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
1044
- aesgcm.setAuthTag(authTag);
1045
- return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
1046
- } catch (error) {
1047
- const isRange = error instanceof RangeError;
1048
- const invalidKeyLength = error.message === "Invalid key length";
1049
- const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
1050
- if (isRange || invalidKeyLength) {
1051
- const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
1052
- err.code = "INVALID_DOTENV_KEY";
1053
- throw err;
1054
- } else if (decryptionFailed) {
1055
- const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
1056
- err.code = "DECRYPTION_FAILED";
1057
- throw err;
1058
- } else throw error;
1059
- }
1060
- }
1061
- function populate(processEnv, parsed, options = {}) {
1062
- const debug = Boolean(options && options.debug);
1063
- const override = Boolean(options && options.override);
1064
- if (typeof parsed !== "object") {
1065
- const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
1066
- err.code = "OBJECT_REQUIRED";
1067
- throw err;
1068
- }
1069
- for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
1070
- if (override === true) processEnv[key] = parsed[key];
1071
- if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
1072
- else _debug(`"${key}" is already defined and was NOT overwritten`);
1073
- } else processEnv[key] = parsed[key];
1074
- }
1075
- const DotenvModule = {
1076
- configDotenv,
1077
- _configVault,
1078
- _parseVault,
1079
- config,
1080
- decrypt,
1081
- parse,
1082
- populate
1083
- };
1084
- module.exports.configDotenv = DotenvModule.configDotenv;
1085
- module.exports._configVault = DotenvModule._configVault;
1086
- module.exports._parseVault = DotenvModule._parseVault;
1087
- module.exports.config = DotenvModule.config;
1088
- module.exports.decrypt = DotenvModule.decrypt;
1089
- module.exports.parse = DotenvModule.parse;
1090
- module.exports.populate = DotenvModule.populate;
1091
- module.exports = DotenvModule;
1092
- }));
1093
-
1094
- //#endregion
1095
- //#region ../../node_modules/dotenv-flow/package.json
1096
- var require_package = /* @__PURE__ */ __commonJSMin(((exports, module) => {
643
+ //#region ../../node_modules/color-name/index.js
644
+ var require_color_name = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1097
645
  module.exports = {
1098
- "name": "dotenv-flow",
1099
- "version": "4.1.0",
1100
- "description": "Loads environment variables from `.env.[development|test|production][.local]` files",
1101
- "keywords": [
1102
- "dotenv",
1103
- "node_env",
1104
- "development",
1105
- "test",
1106
- "production",
1107
- "local",
1108
- "env",
1109
- "environment",
1110
- "variables"
646
+ "aliceblue": [
647
+ 240,
648
+ 248,
649
+ 255
1111
650
  ],
1112
- "homepage": "https://github.com/kerimdzhanov/dotenv-flow#readme",
1113
- "repository": {
1114
- "type": "git",
1115
- "url": "git+https://github.com/kerimdzhanov/dotenv-flow.git"
1116
- },
1117
- "bugs": { "url": "https://github.com/kerimdzhanov/dotenv-flow/issues" },
1118
- "main": "lib/dotenv-flow.js",
1119
- "types": "lib/dotenv-flow.d.ts",
1120
- "exports": {
1121
- ".": "./lib/dotenv-flow.js",
1122
- "./config": {
1123
- "require": "./config.js",
1124
- "node": "./config.js"
1125
- },
1126
- "./package.json": "./package.json"
1127
- },
1128
- "files": [
1129
- "lib/cli-options.js",
1130
- "lib/dotenv-flow.d.ts",
1131
- "lib/env-options.js",
1132
- "config.d.ts",
1133
- "config.js"
1134
- ],
1135
- "dependencies": { "dotenv": "^16.0.0" },
1136
- "devDependencies": {
1137
- "@types/node": "^20.6.2",
1138
- "chai": "^4.3.7",
1139
- "conventional-changelog-cli": "^2.0.35",
1140
- "mocha": "^10.2.0",
1141
- "sinon": "^15.2.0",
1142
- "sinon-chai": "^3.7.0",
1143
- "tmp": "^0.2.1",
1144
- "typescript": "^5.2.2"
1145
- },
1146
- "engines": { "node": ">= 12.0.0" },
1147
- "scripts": {
1148
- "test": "yarn run test:unit && yarn run test:integration && yarn run test:types",
1149
- "test:unit": "mocha -r mocha.conf.js test/unit/*.spec.js",
1150
- "test:integration": "mocha -r mocha.conf.js test/integration/*.spec.{m,}js",
1151
- "test:types": "tsc",
1152
- "changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"
1153
- },
1154
- "author": "Dan Kerimdzhanov",
1155
- "license": "MIT"
1156
- };
1157
- }));
1158
-
1159
- //#endregion
1160
- //#region ../../node_modules/dotenv-flow/lib/dotenv-flow.js
1161
- var require_dotenv_flow = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1162
- const fs$1 = __require("fs");
1163
- const p = __require("path");
1164
- const dotenv = require_main();
1165
- const { version } = require_package();
1166
- const DEFAULT_PATTERN = ".env[.node_env][.local]";
1167
- const LOCAL_PLACEHOLDER_REGEX = /\[(\W*\blocal\b\W*)]/g;
1168
- const NODE_ENV_PLACEHOLDER_REGEX = /\[(\W*\b)node_env(\b\W*)]/g;
1169
- /**
1170
- * Compose a filename from a given `patten`.
1171
- *
1172
- * @param {string} pattern
1173
- * @param {object} [options]
1174
- * @param {boolean} [options.local]
1175
- * @param {string} [options.node_env]
1176
- * @return {string} filename
1177
- */
1178
- function composeFilename(pattern, options) {
1179
- let filename = pattern;
1180
- filename = filename.replace(LOCAL_PLACEHOLDER_REGEX, options && options.local ? "$1" : "");
1181
- filename = filename.replace(NODE_ENV_PLACEHOLDER_REGEX, options && options.node_env ? `$1${options.node_env}$2` : "");
1182
- return filename;
1183
- }
1184
- /**
1185
- * Returns a list of existing `.env*` filenames depending on the given `options`.
1186
- *
1187
- * The resulting list is ordered by the env files'
1188
- * variables overwriting priority from lowest to highest.
1189
- *
1190
- * This can also be referenced as "env files' environment cascade"
1191
- * or "order of ascending priority."
1192
- *
1193
- * ⚠️ Note that the `.env.local` file is not listed for "test" environment,
1194
- * since normally you expect tests to produce the same results for everyone.
1195
- *
1196
- * @param {object} [options] - `.env*` files listing options
1197
- * @param {string} [options.node_env] - node environment (development/test/production/etc.)
1198
- * @param {string} [options.path] - path to the working directory (default: `process.cwd()`)
1199
- * @param {string} [options.pattern] - `.env*` files' naming convention pattern
1200
- * (default: ".env[.node_env][.local]")
1201
- * @param {boolean} [options.debug] - turn on debug messages
1202
- * @return {string[]}
1203
- */
1204
- function listFiles(options = {}) {
1205
- options.debug && debug("listing effective `.env*` files…");
1206
- const { node_env, path = process.cwd(), pattern = DEFAULT_PATTERN } = options;
1207
- const hasLocalPlaceholder = LOCAL_PLACEHOLDER_REGEX.test(pattern);
1208
- const filenames = {};
1209
- if (pattern === DEFAULT_PATTERN) filenames[".env.defaults"] = ".env.defaults";
1210
- filenames[".env"] = composeFilename(pattern);
1211
- if (hasLocalPlaceholder) {
1212
- const envlocal = composeFilename(pattern, { local: true });
1213
- if (node_env !== "test") filenames[".env.local"] = envlocal;
1214
- else if (options.debug && fs$1.existsSync(p.resolve(path, envlocal))) debug("[!] note that `%s` is being skipped for \"test\" environment", envlocal);
1215
- }
1216
- if (node_env && NODE_ENV_PLACEHOLDER_REGEX.test(pattern)) {
1217
- filenames[".env.node_env"] = composeFilename(pattern, { node_env });
1218
- if (hasLocalPlaceholder) filenames[".env.node_env.local"] = composeFilename(pattern, {
1219
- node_env,
1220
- local: true
1221
- });
1222
- }
1223
- return [
1224
- ".env.defaults",
1225
- ".env",
1226
- ".env.local",
1227
- ".env.node_env",
1228
- ".env.node_env.local"
1229
- ].reduce((list, basename) => {
1230
- if (!filenames[basename]) return list;
1231
- const filename = p.resolve(path, filenames[basename]);
1232
- if (fs$1.existsSync(filename)) {
1233
- options.debug && debug(">> %s", filename);
1234
- list.push(filename);
1235
- }
1236
- return list;
1237
- }, []);
1238
- }
1239
- /**
1240
- * Parses a given file or a list of files.
1241
- *
1242
- * When a list of filenames is given, the files will be parsed and merged in the same order as given.
1243
- *
1244
- * @param {string|string[]} filenames - filename or a list of filenames to parse and merge
1245
- * @param {{ encoding?: string, debug?: boolean }} [options] - parse options
1246
- * @return {Object<string, string>} the resulting map of `{ env_var: value }` as an object
1247
- */
1248
- function parse(filenames, options = {}) {
1249
- if (typeof filenames === "string") {
1250
- options.debug && debug("parsing \"%s\"…", filenames);
1251
- const parsed = dotenv.parse(fs$1.readFileSync(filenames, options.encoding && { encoding: options.encoding }));
1252
- if (options.debug) Object.keys(parsed).forEach((varname) => debug(">> %s", varname));
1253
- return parsed;
1254
- }
1255
- return filenames.reduce((result, filename) => {
1256
- const parsed = parse(filename, options);
1257
- if (options.debug) Object.keys(parsed).filter((varname) => result.hasOwnProperty(varname)).forEach((varname) => debug("`%s` is being overwritten by merge from \"%s\"", varname, filename));
1258
- return Object.assign(result, parsed);
1259
- }, {});
1260
- }
1261
- /**
1262
- * Parses variables defined in given file(s) and assigns them to `process.env`.
1263
- *
1264
- * Variables that are already defined in `process.env` will not be overwritten,
1265
- * thus giving a higher priority to environment variables predefined by the shell.
1266
- *
1267
- * If the loading is successful, an object with `parsed` property is returned.
1268
- * The `parsed` property contains parsed variables' `key => value` pairs merged in order using
1269
- * the "overwrite merge" strategy.
1270
- *
1271
- * If parsing fails for any of the given files, `process.env` is being left untouched,
1272
- * and an object with `error` property is returned.
1273
- * The `error` property, if present, references to the occurred error.
1274
- *
1275
- * @param {string|string[]} filenames - filename or a list of filenames to parse and merge
1276
- * @param {object} [options] - file loading options
1277
- * @param {string} [options.encoding="utf8"] - encoding of `.env*` files
1278
- * @param {boolean} [options.debug=false] - turn on debug messages
1279
- * @param {boolean} [options.silent=false] - suppress console errors and warnings
1280
- * @return {{ error: Error } | { parsed: Object<string, string> }}
1281
- */
1282
- function load(filenames, options = {}) {
1283
- try {
1284
- const parsed = parse(filenames, {
1285
- encoding: options.encoding,
1286
- debug: options.debug
1287
- });
1288
- options.debug && debug("safe-merging parsed environment variables into `process.env`…");
1289
- for (const varname of Object.keys(parsed)) if (!process.env.hasOwnProperty(varname)) {
1290
- options.debug && debug(">> process.env.%s", varname);
1291
- process.env[varname] = parsed[varname];
1292
- } else if (options.debug && process.env[varname] !== parsed[varname]) debug("environment variable `%s` is predefined and not being overwritten", varname);
1293
- return { parsed };
1294
- } catch (error) {
1295
- return failure(error, options);
1296
- }
1297
- }
1298
- /**
1299
- * Unload variables defined in a given file(s) from `process.env`.
1300
- *
1301
- * This function can gracefully resolve the following issue:
1302
- *
1303
- * In some cases, the original "dotenv" library can be used by one of the dependent npm modules.
1304
- * It causes calling the original `dotenv.config()` that loads the `.env` file from your project before you can call `dotenv-flow.config()`.
1305
- * Such cases break `.env*` files priority because the previously loaded environment variables are treated as shell-defined thus having a higher priority.
1306
- *
1307
- * Unloading the previously loaded `.env` file can be activated when using the `dotenv-flow.config()` with the `purge_dotenv` option set to `true`.
1308
- *
1309
- * @param {string|string[]} filenames - filename or a list of filenames to unload
1310
- * @param {object} [options] - `fs.readFileSync` options
1311
- */
1312
- function unload(filenames, options = {}) {
1313
- const parsed = parse(filenames, options);
1314
- Object.keys(parsed).forEach((key) => {
1315
- if (process.env[key] === parsed[key]) delete process.env[key];
1316
- });
1317
- }
1318
- /**
1319
- * Returns effective (computed) `node_env`.
1320
- *
1321
- * @param {object} [options]
1322
- * @param {string} [options.node_env]
1323
- * @param {string} [options.default_node_env]
1324
- * @param {boolean} [options.debug]
1325
- * @return {string|undefined} node_env
1326
- */
1327
- function getEffectiveNodeEnv(options = {}) {
1328
- if (options.node_env) {
1329
- options.debug && debug(`operating in "${options.node_env}" environment (set by \`options.node_env\`)`);
1330
- return options.node_env;
1331
- }
1332
- if (process.env.NODE_ENV) {
1333
- options.debug && debug(`operating in "${process.env.NODE_ENV}" environment (as per \`process.env.NODE_ENV\`)`);
1334
- return process.env.NODE_ENV;
1335
- }
1336
- if (options.default_node_env) {
1337
- options.debug && debug(`operating in "${options.default_node_env}" environment (taken from \`options.default_node_env\`)`);
1338
- return options.default_node_env;
1339
- }
1340
- options.debug && debug("operating in \"no environment\" mode (no environment-related options are set)");
1341
- }
1342
- const CONFIG_OPTION_KEYS = [
1343
- "node_env",
1344
- "default_node_env",
1345
- "path",
1346
- "pattern",
1347
- "files",
1348
- "encoding",
1349
- "purge_dotenv",
1350
- "silent"
1351
- ];
1352
- /**
1353
- * "dotenv-flow" initialization function (API entry point).
1354
- *
1355
- * Allows configuring dotenv-flow programmatically.
1356
- *
1357
- * @param {object} [options] - configuration options
1358
- * @param {string} [options.node_env=process.env.NODE_ENV] - node environment (development/test/production/etc.)
1359
- * @param {string} [options.default_node_env] - the default node environment
1360
- * @param {string} [options.path=process.cwd()] - path to `.env*` files directory
1361
- * @param {string} [options.pattern=".env[.node_env][.local]"] - `.env*` files' naming convention pattern
1362
- * @param {string[]} [options.files] - an explicit list of `.env*` files to load (note that `options.[default_]node_env` and `options.pattern` are ignored in this case)
1363
- * @param {string} [options.encoding="utf8"] - encoding of `.env*` files
1364
- * @param {boolean} [options.purge_dotenv=false] - perform the `.env` file {@link unload}
1365
- * @param {boolean} [options.debug=false] - turn on detailed logging to help debug why certain variables are not being set as you expect
1366
- * @param {boolean} [options.silent=false] - suppress all kinds of warnings including ".env*" files' loading errors
1367
- * @return {{ parsed?: object, error?: Error }} with a `parsed` key containing the loaded content or an `error` key with an error that is occurred
1368
- */
1369
- function config(options = {}) {
1370
- if (options.debug) {
1371
- debug("initializing…");
1372
- CONFIG_OPTION_KEYS.filter((key) => key in options).forEach((key) => debug(`| options.${key} =`, options[key]));
1373
- }
1374
- const { path = process.cwd(), pattern = DEFAULT_PATTERN } = options;
1375
- if (options.purge_dotenv) {
1376
- options.debug && debug("`options.purge_dotenv` is enabled, unloading potentially pre-loaded `.env`…");
1377
- const dotenvFile = p.resolve(path, ".env");
1378
- try {
1379
- fs$1.existsSync(dotenvFile) && unload(dotenvFile, { encoding: options.encoding });
1380
- } catch (error) {
1381
- !options.silent && warn("unloading failed: ", error);
1382
- }
1383
- }
1384
- try {
1385
- let filenames;
1386
- if (options.files) {
1387
- options.debug && debug("using explicit list of `.env*` files: %s…", options.files.join(", "));
1388
- filenames = options.files.reduce((list, basename) => {
1389
- const filename = p.resolve(path, basename);
1390
- if (fs$1.existsSync(filename)) list.push(filename);
1391
- else if (options.debug) debug(">> %s does not exist, skipping…", filename);
1392
- return list;
1393
- }, []);
1394
- } else {
1395
- const node_env = getEffectiveNodeEnv(options);
1396
- filenames = listFiles({
1397
- node_env,
1398
- path,
1399
- pattern,
1400
- debug: options.debug
1401
- });
1402
- if (filenames.length === 0) {
1403
- const _pattern = node_env ? pattern.replace(NODE_ENV_PLACEHOLDER_REGEX, `[$1${node_env}$2]`) : pattern;
1404
- return failure(/* @__PURE__ */ new Error(`no ".env*" files matching pattern "${_pattern}" in "${path}" dir`), options);
1405
- }
1406
- }
1407
- const result = load(filenames, {
1408
- encoding: options.encoding,
1409
- debug: options.debug,
1410
- silent: options.silent
1411
- });
1412
- options.debug && debug("initialization completed.");
1413
- return result;
1414
- } catch (error) {
1415
- return failure(error, options);
1416
- }
1417
- }
1418
- function failure(error, options) {
1419
- if (!options.silent) warn(`".env*" files loading failed: ${error.message || error}`);
1420
- return { error };
1421
- }
1422
- function warn(message, error) {
1423
- if (error) message += ": %s";
1424
- console.warn(`[dotenv-flow@${version}]: ${message}`, error);
1425
- }
1426
- function debug(message, ...values) {
1427
- console.debug(`[dotenv-flow@${version}]: ${message}`, ...values);
1428
- }
1429
- module.exports = {
1430
- DEFAULT_PATTERN,
1431
- listFiles,
1432
- parse,
1433
- load,
1434
- unload,
1435
- config
1436
- };
1437
- }));
1438
-
1439
- //#endregion
1440
- //#region ../../node_modules/color-name/index.js
1441
- var require_color_name = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1442
- module.exports = {
1443
- "aliceblue": [
1444
- 240,
1445
- 248,
1446
- 255
1447
- ],
1448
- "antiquewhite": [
1449
- 250,
1450
- 235,
1451
- 215
651
+ "antiquewhite": [
652
+ 250,
653
+ 235,
654
+ 215
1452
655
  ],
1453
656
  "aqua": [
1454
657
  0,
@@ -3002,793 +2205,1648 @@ var require_route = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3002
2205
  }
3003
2206
  return graph;
3004
2207
  }
3005
- function link(from, to) {
3006
- return function(args) {
3007
- return to(from(args));
3008
- };
2208
+ function link(from, to) {
2209
+ return function(args) {
2210
+ return to(from(args));
2211
+ };
2212
+ }
2213
+ function wrapConversion(toModel, graph) {
2214
+ const path = [graph[toModel].parent, toModel];
2215
+ let fn = conversions[graph[toModel].parent][toModel];
2216
+ let cur = graph[toModel].parent;
2217
+ while (graph[cur].parent) {
2218
+ path.unshift(graph[cur].parent);
2219
+ fn = link(conversions[graph[cur].parent][cur], fn);
2220
+ cur = graph[cur].parent;
2221
+ }
2222
+ fn.conversion = path;
2223
+ return fn;
2224
+ }
2225
+ module.exports = function(fromModel) {
2226
+ const graph = deriveBFS(fromModel);
2227
+ const conversion = {};
2228
+ const models = Object.keys(graph);
2229
+ for (let len = models.length, i = 0; i < len; i++) {
2230
+ const toModel = models[i];
2231
+ if (graph[toModel].parent === null) continue;
2232
+ conversion[toModel] = wrapConversion(toModel, graph);
2233
+ }
2234
+ return conversion;
2235
+ };
2236
+ }));
2237
+
2238
+ //#endregion
2239
+ //#region ../../node_modules/color-convert/index.js
2240
+ var require_color_convert = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2241
+ const conversions = require_conversions();
2242
+ const route = require_route();
2243
+ const convert = {};
2244
+ const models = Object.keys(conversions);
2245
+ function wrapRaw(fn) {
2246
+ const wrappedFn = function(...args) {
2247
+ const arg0 = args[0];
2248
+ if (arg0 === void 0 || arg0 === null) return arg0;
2249
+ if (arg0.length > 1) args = arg0;
2250
+ return fn(args);
2251
+ };
2252
+ if ("conversion" in fn) wrappedFn.conversion = fn.conversion;
2253
+ return wrappedFn;
2254
+ }
2255
+ function wrapRounded(fn) {
2256
+ const wrappedFn = function(...args) {
2257
+ const arg0 = args[0];
2258
+ if (arg0 === void 0 || arg0 === null) return arg0;
2259
+ if (arg0.length > 1) args = arg0;
2260
+ const result = fn(args);
2261
+ if (typeof result === "object") for (let len = result.length, i = 0; i < len; i++) result[i] = Math.round(result[i]);
2262
+ return result;
2263
+ };
2264
+ if ("conversion" in fn) wrappedFn.conversion = fn.conversion;
2265
+ return wrappedFn;
2266
+ }
2267
+ models.forEach((fromModel) => {
2268
+ convert[fromModel] = {};
2269
+ Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels });
2270
+ Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels });
2271
+ const routes = route(fromModel);
2272
+ Object.keys(routes).forEach((toModel) => {
2273
+ const fn = routes[toModel];
2274
+ convert[fromModel][toModel] = wrapRounded(fn);
2275
+ convert[fromModel][toModel].raw = wrapRaw(fn);
2276
+ });
2277
+ });
2278
+ module.exports = convert;
2279
+ }));
2280
+
2281
+ //#endregion
2282
+ //#region ../../node_modules/ansi-styles/index.js
2283
+ var require_ansi_styles = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2284
+ const wrapAnsi16 = (fn, offset) => (...args) => {
2285
+ return `\u001B[${fn(...args) + offset}m`;
2286
+ };
2287
+ const wrapAnsi256 = (fn, offset) => (...args) => {
2288
+ const code = fn(...args);
2289
+ return `\u001B[${38 + offset};5;${code}m`;
2290
+ };
2291
+ const wrapAnsi16m = (fn, offset) => (...args) => {
2292
+ const rgb = fn(...args);
2293
+ return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
2294
+ };
2295
+ const ansi2ansi = (n) => n;
2296
+ const rgb2rgb = (r, g, b) => [
2297
+ r,
2298
+ g,
2299
+ b
2300
+ ];
2301
+ const setLazyProperty = (object, property, get) => {
2302
+ Object.defineProperty(object, property, {
2303
+ get: () => {
2304
+ const value = get();
2305
+ Object.defineProperty(object, property, {
2306
+ value,
2307
+ enumerable: true,
2308
+ configurable: true
2309
+ });
2310
+ return value;
2311
+ },
2312
+ enumerable: true,
2313
+ configurable: true
2314
+ });
2315
+ };
2316
+ /** @type {typeof import('color-convert')} */
2317
+ let colorConvert;
2318
+ const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
2319
+ if (colorConvert === void 0) colorConvert = require_color_convert();
2320
+ const offset = isBackground ? 10 : 0;
2321
+ const styles = {};
2322
+ for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
2323
+ const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
2324
+ if (sourceSpace === targetSpace) styles[name] = wrap(identity, offset);
2325
+ else if (typeof suite === "object") styles[name] = wrap(suite[targetSpace], offset);
2326
+ }
2327
+ return styles;
2328
+ };
2329
+ function assembleStyles() {
2330
+ const codes = /* @__PURE__ */ new Map();
2331
+ const styles = {
2332
+ modifier: {
2333
+ reset: [0, 0],
2334
+ bold: [1, 22],
2335
+ dim: [2, 22],
2336
+ italic: [3, 23],
2337
+ underline: [4, 24],
2338
+ inverse: [7, 27],
2339
+ hidden: [8, 28],
2340
+ strikethrough: [9, 29]
2341
+ },
2342
+ color: {
2343
+ black: [30, 39],
2344
+ red: [31, 39],
2345
+ green: [32, 39],
2346
+ yellow: [33, 39],
2347
+ blue: [34, 39],
2348
+ magenta: [35, 39],
2349
+ cyan: [36, 39],
2350
+ white: [37, 39],
2351
+ blackBright: [90, 39],
2352
+ redBright: [91, 39],
2353
+ greenBright: [92, 39],
2354
+ yellowBright: [93, 39],
2355
+ blueBright: [94, 39],
2356
+ magentaBright: [95, 39],
2357
+ cyanBright: [96, 39],
2358
+ whiteBright: [97, 39]
2359
+ },
2360
+ bgColor: {
2361
+ bgBlack: [40, 49],
2362
+ bgRed: [41, 49],
2363
+ bgGreen: [42, 49],
2364
+ bgYellow: [43, 49],
2365
+ bgBlue: [44, 49],
2366
+ bgMagenta: [45, 49],
2367
+ bgCyan: [46, 49],
2368
+ bgWhite: [47, 49],
2369
+ bgBlackBright: [100, 49],
2370
+ bgRedBright: [101, 49],
2371
+ bgGreenBright: [102, 49],
2372
+ bgYellowBright: [103, 49],
2373
+ bgBlueBright: [104, 49],
2374
+ bgMagentaBright: [105, 49],
2375
+ bgCyanBright: [106, 49],
2376
+ bgWhiteBright: [107, 49]
2377
+ }
2378
+ };
2379
+ styles.color.gray = styles.color.blackBright;
2380
+ styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
2381
+ styles.color.grey = styles.color.blackBright;
2382
+ styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
2383
+ for (const [groupName, group] of Object.entries(styles)) {
2384
+ for (const [styleName, style] of Object.entries(group)) {
2385
+ styles[styleName] = {
2386
+ open: `\u001B[${style[0]}m`,
2387
+ close: `\u001B[${style[1]}m`
2388
+ };
2389
+ group[styleName] = styles[styleName];
2390
+ codes.set(style[0], style[1]);
2391
+ }
2392
+ Object.defineProperty(styles, groupName, {
2393
+ value: group,
2394
+ enumerable: false
2395
+ });
2396
+ }
2397
+ Object.defineProperty(styles, "codes", {
2398
+ value: codes,
2399
+ enumerable: false
2400
+ });
2401
+ styles.color.close = "\x1B[39m";
2402
+ styles.bgColor.close = "\x1B[49m";
2403
+ setLazyProperty(styles.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false));
2404
+ setLazyProperty(styles.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false));
2405
+ setLazyProperty(styles.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false));
2406
+ setLazyProperty(styles.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true));
2407
+ setLazyProperty(styles.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true));
2408
+ setLazyProperty(styles.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true));
2409
+ return styles;
2410
+ }
2411
+ Object.defineProperty(module, "exports", {
2412
+ enumerable: true,
2413
+ get: assembleStyles
2414
+ });
2415
+ }));
2416
+
2417
+ //#endregion
2418
+ //#region ../../node_modules/has-flag/index.js
2419
+ var require_has_flag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2420
+ module.exports = (flag, argv = process.argv) => {
2421
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
2422
+ const position = argv.indexOf(prefix + flag);
2423
+ const terminatorPosition = argv.indexOf("--");
2424
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
2425
+ };
2426
+ }));
2427
+
2428
+ //#endregion
2429
+ //#region ../../node_modules/chalk/node_modules/supports-color/index.js
2430
+ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2431
+ const os = __require("os");
2432
+ const tty = __require("tty");
2433
+ const hasFlag = require_has_flag();
2434
+ const { env } = process;
2435
+ let forceColor;
2436
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) forceColor = 0;
2437
+ else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) forceColor = 1;
2438
+ if ("FORCE_COLOR" in env) if (env.FORCE_COLOR === "true") forceColor = 1;
2439
+ else if (env.FORCE_COLOR === "false") forceColor = 0;
2440
+ else forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
2441
+ function translateLevel(level) {
2442
+ if (level === 0) return false;
2443
+ return {
2444
+ level,
2445
+ hasBasic: true,
2446
+ has256: level >= 2,
2447
+ has16m: level >= 3
2448
+ };
2449
+ }
2450
+ function supportsColor(haveStream, streamIsTTY) {
2451
+ if (forceColor === 0) return 0;
2452
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
2453
+ if (hasFlag("color=256")) return 2;
2454
+ if (haveStream && !streamIsTTY && forceColor === void 0) return 0;
2455
+ const min = forceColor || 0;
2456
+ if (env.TERM === "dumb") return min;
2457
+ if (process.platform === "win32") {
2458
+ const osRelease = os.release().split(".");
2459
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
2460
+ return 1;
2461
+ }
2462
+ if ("CI" in env) {
2463
+ if ([
2464
+ "TRAVIS",
2465
+ "CIRCLECI",
2466
+ "APPVEYOR",
2467
+ "GITLAB_CI",
2468
+ "GITHUB_ACTIONS",
2469
+ "BUILDKITE"
2470
+ ].some((sign) => sign in env) || env.CI_NAME === "codeship") return 1;
2471
+ return min;
2472
+ }
2473
+ if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2474
+ if (env.COLORTERM === "truecolor") return 3;
2475
+ if ("TERM_PROGRAM" in env) {
2476
+ const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2477
+ switch (env.TERM_PROGRAM) {
2478
+ case "iTerm.app": return version >= 3 ? 3 : 2;
2479
+ case "Apple_Terminal": return 2;
2480
+ }
2481
+ }
2482
+ if (/-256(color)?$/i.test(env.TERM)) return 2;
2483
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
2484
+ if ("COLORTERM" in env) return 1;
2485
+ return min;
2486
+ }
2487
+ function getSupportLevel(stream) {
2488
+ return translateLevel(supportsColor(stream, stream && stream.isTTY));
2489
+ }
2490
+ module.exports = {
2491
+ supportsColor: getSupportLevel,
2492
+ stdout: translateLevel(supportsColor(true, tty.isatty(1))),
2493
+ stderr: translateLevel(supportsColor(true, tty.isatty(2)))
2494
+ };
2495
+ }));
2496
+
2497
+ //#endregion
2498
+ //#region ../../node_modules/chalk/source/util.js
2499
+ var require_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2500
+ const stringReplaceAll = (string, substring, replacer) => {
2501
+ let index = string.indexOf(substring);
2502
+ if (index === -1) return string;
2503
+ const substringLength = substring.length;
2504
+ let endIndex = 0;
2505
+ let returnValue = "";
2506
+ do {
2507
+ returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
2508
+ endIndex = index + substringLength;
2509
+ index = string.indexOf(substring, endIndex);
2510
+ } while (index !== -1);
2511
+ returnValue += string.substr(endIndex);
2512
+ return returnValue;
2513
+ };
2514
+ const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
2515
+ let endIndex = 0;
2516
+ let returnValue = "";
2517
+ do {
2518
+ const gotCR = string[index - 1] === "\r";
2519
+ returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
2520
+ endIndex = index + 1;
2521
+ index = string.indexOf("\n", endIndex);
2522
+ } while (index !== -1);
2523
+ returnValue += string.substr(endIndex);
2524
+ return returnValue;
2525
+ };
2526
+ module.exports = {
2527
+ stringReplaceAll,
2528
+ stringEncaseCRLFWithFirstIndex
2529
+ };
2530
+ }));
2531
+
2532
+ //#endregion
2533
+ //#region ../../node_modules/chalk/source/templates.js
2534
+ var require_templates = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2535
+ const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
2536
+ const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
2537
+ const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
2538
+ const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
2539
+ const ESCAPES = new Map([
2540
+ ["n", "\n"],
2541
+ ["r", "\r"],
2542
+ ["t", " "],
2543
+ ["b", "\b"],
2544
+ ["f", "\f"],
2545
+ ["v", "\v"],
2546
+ ["0", "\0"],
2547
+ ["\\", "\\"],
2548
+ ["e", "\x1B"],
2549
+ ["a", "\x07"]
2550
+ ]);
2551
+ function unescape(c) {
2552
+ const u = c[0] === "u";
2553
+ const bracket = c[1] === "{";
2554
+ if (u && !bracket && c.length === 5 || c[0] === "x" && c.length === 3) return String.fromCharCode(parseInt(c.slice(1), 16));
2555
+ if (u && bracket) return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
2556
+ return ESCAPES.get(c) || c;
2557
+ }
2558
+ function parseArguments(name, arguments_) {
2559
+ const results = [];
2560
+ const chunks = arguments_.trim().split(/\s*,\s*/g);
2561
+ let matches;
2562
+ for (const chunk of chunks) {
2563
+ const number = Number(chunk);
2564
+ if (!Number.isNaN(number)) results.push(number);
2565
+ else if (matches = chunk.match(STRING_REGEX)) results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
2566
+ else throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
2567
+ }
2568
+ return results;
2569
+ }
2570
+ function parseStyle(style) {
2571
+ STYLE_REGEX.lastIndex = 0;
2572
+ const results = [];
2573
+ let matches;
2574
+ while ((matches = STYLE_REGEX.exec(style)) !== null) {
2575
+ const name = matches[1];
2576
+ if (matches[2]) {
2577
+ const args = parseArguments(name, matches[2]);
2578
+ results.push([name].concat(args));
2579
+ } else results.push([name]);
2580
+ }
2581
+ return results;
2582
+ }
2583
+ function buildStyle(chalk, styles) {
2584
+ const enabled = {};
2585
+ for (const layer of styles) for (const style of layer.styles) enabled[style[0]] = layer.inverse ? null : style.slice(1);
2586
+ let current = chalk;
2587
+ for (const [styleName, styles] of Object.entries(enabled)) {
2588
+ if (!Array.isArray(styles)) continue;
2589
+ if (!(styleName in current)) throw new Error(`Unknown Chalk style: ${styleName}`);
2590
+ current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
2591
+ }
2592
+ return current;
2593
+ }
2594
+ module.exports = (chalk, temporary) => {
2595
+ const styles = [];
2596
+ const chunks = [];
2597
+ let chunk = [];
2598
+ temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
2599
+ if (escapeCharacter) chunk.push(unescape(escapeCharacter));
2600
+ else if (style) {
2601
+ const string = chunk.join("");
2602
+ chunk = [];
2603
+ chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
2604
+ styles.push({
2605
+ inverse,
2606
+ styles: parseStyle(style)
2607
+ });
2608
+ } else if (close) {
2609
+ if (styles.length === 0) throw new Error("Found extraneous } in Chalk template literal");
2610
+ chunks.push(buildStyle(chalk, styles)(chunk.join("")));
2611
+ chunk = [];
2612
+ styles.pop();
2613
+ } else chunk.push(character);
2614
+ });
2615
+ chunks.push(chunk.join(""));
2616
+ if (styles.length > 0) {
2617
+ const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? "" : "s"} (\`}\`)`;
2618
+ throw new Error(errMessage);
2619
+ }
2620
+ return chunks.join("");
2621
+ };
2622
+ }));
2623
+
2624
+ //#endregion
2625
+ //#region ../../node_modules/chalk/source/index.js
2626
+ var require_source = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2627
+ const ansiStyles = require_ansi_styles();
2628
+ const { stdout: stdoutColor, stderr: stderrColor } = require_supports_color();
2629
+ const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = require_util();
2630
+ const { isArray } = Array;
2631
+ const levelMapping = [
2632
+ "ansi",
2633
+ "ansi",
2634
+ "ansi256",
2635
+ "ansi16m"
2636
+ ];
2637
+ const styles = Object.create(null);
2638
+ const applyOptions = (object, options = {}) => {
2639
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) throw new Error("The `level` option should be an integer from 0 to 3");
2640
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
2641
+ object.level = options.level === void 0 ? colorLevel : options.level;
2642
+ };
2643
+ var ChalkClass = class {
2644
+ constructor(options) {
2645
+ return chalkFactory(options);
2646
+ }
2647
+ };
2648
+ const chalkFactory = (options) => {
2649
+ const chalk = {};
2650
+ applyOptions(chalk, options);
2651
+ chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
2652
+ Object.setPrototypeOf(chalk, Chalk.prototype);
2653
+ Object.setPrototypeOf(chalk.template, chalk);
2654
+ chalk.template.constructor = () => {
2655
+ throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
2656
+ };
2657
+ chalk.template.Instance = ChalkClass;
2658
+ return chalk.template;
2659
+ };
2660
+ function Chalk(options) {
2661
+ return chalkFactory(options);
2662
+ }
2663
+ for (const [styleName, style] of Object.entries(ansiStyles)) styles[styleName] = { get() {
2664
+ const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
2665
+ Object.defineProperty(this, styleName, { value: builder });
2666
+ return builder;
2667
+ } };
2668
+ styles.visible = { get() {
2669
+ const builder = createBuilder(this, this._styler, true);
2670
+ Object.defineProperty(this, "visible", { value: builder });
2671
+ return builder;
2672
+ } };
2673
+ const usedModels = [
2674
+ "rgb",
2675
+ "hex",
2676
+ "keyword",
2677
+ "hsl",
2678
+ "hsv",
2679
+ "hwb",
2680
+ "ansi",
2681
+ "ansi256"
2682
+ ];
2683
+ for (const model of usedModels) styles[model] = { get() {
2684
+ const { level } = this;
2685
+ return function(...arguments_) {
2686
+ const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
2687
+ return createBuilder(this, styler, this._isEmpty);
2688
+ };
2689
+ } };
2690
+ for (const model of usedModels) {
2691
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
2692
+ styles[bgModel] = { get() {
2693
+ const { level } = this;
2694
+ return function(...arguments_) {
2695
+ const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
2696
+ return createBuilder(this, styler, this._isEmpty);
2697
+ };
2698
+ } };
2699
+ }
2700
+ const proto = Object.defineProperties(() => {}, {
2701
+ ...styles,
2702
+ level: {
2703
+ enumerable: true,
2704
+ get() {
2705
+ return this._generator.level;
2706
+ },
2707
+ set(level) {
2708
+ this._generator.level = level;
2709
+ }
2710
+ }
2711
+ });
2712
+ const createStyler = (open, close, parent) => {
2713
+ let openAll;
2714
+ let closeAll;
2715
+ if (parent === void 0) {
2716
+ openAll = open;
2717
+ closeAll = close;
2718
+ } else {
2719
+ openAll = parent.openAll + open;
2720
+ closeAll = close + parent.closeAll;
2721
+ }
2722
+ return {
2723
+ open,
2724
+ close,
2725
+ openAll,
2726
+ closeAll,
2727
+ parent
2728
+ };
2729
+ };
2730
+ const createBuilder = (self, _styler, _isEmpty) => {
2731
+ const builder = (...arguments_) => {
2732
+ if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) return applyStyle(builder, chalkTag(builder, ...arguments_));
2733
+ return applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
2734
+ };
2735
+ Object.setPrototypeOf(builder, proto);
2736
+ builder._generator = self;
2737
+ builder._styler = _styler;
2738
+ builder._isEmpty = _isEmpty;
2739
+ return builder;
2740
+ };
2741
+ const applyStyle = (self, string) => {
2742
+ if (self.level <= 0 || !string) return self._isEmpty ? "" : string;
2743
+ let styler = self._styler;
2744
+ if (styler === void 0) return string;
2745
+ const { openAll, closeAll } = styler;
2746
+ if (string.indexOf("\x1B") !== -1) while (styler !== void 0) {
2747
+ string = stringReplaceAll(string, styler.close, styler.open);
2748
+ styler = styler.parent;
2749
+ }
2750
+ const lfIndex = string.indexOf("\n");
2751
+ if (lfIndex !== -1) string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
2752
+ return openAll + string + closeAll;
2753
+ };
2754
+ let template;
2755
+ const chalkTag = (chalk, ...strings) => {
2756
+ const [firstString] = strings;
2757
+ if (!isArray(firstString) || !isArray(firstString.raw)) return strings.join(" ");
2758
+ const arguments_ = strings.slice(1);
2759
+ const parts = [firstString.raw[0]];
2760
+ for (let i = 1; i < firstString.length; i++) parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, "\\$&"), String(firstString.raw[i]));
2761
+ if (template === void 0) template = require_templates();
2762
+ return template(chalk, parts.join(""));
2763
+ };
2764
+ Object.defineProperties(Chalk.prototype, styles);
2765
+ const chalk = Chalk();
2766
+ chalk.supportsColor = stdoutColor;
2767
+ chalk.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 });
2768
+ chalk.stderr.supportsColor = stderrColor;
2769
+ module.exports = chalk;
2770
+ }));
2771
+
2772
+ //#endregion
2773
+ //#region ../../packages/env/dist/js/index.node.cjs
2774
+ var require_index_node = /* @__PURE__ */ __commonJSMin(((exports) => {
2775
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2776
+ var __create = Object.create;
2777
+ var __defProp = Object.defineProperty;
2778
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2779
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2780
+ var __getProtoOf = Object.getPrototypeOf;
2781
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
2782
+ var __copyProps = (to, from, except, desc) => {
2783
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
2784
+ key = keys[i];
2785
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
2786
+ get: ((k) => from[k]).bind(null, key),
2787
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
2788
+ });
2789
+ }
2790
+ return to;
2791
+ };
2792
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
2793
+ value: mod,
2794
+ enumerable: true
2795
+ }) : target, mod));
2796
+ let dotenv_flow = require_dotenv_flow();
2797
+ let zod = __require("zod");
2798
+ let chalk = require_source();
2799
+ chalk = __toESM(chalk);
2800
+ function defineEnv(schemaOrShape, options) {
2801
+ const schema = isZodType(schemaOrShape) ? schemaOrShape : zod.z.object(schemaOrShape);
2802
+ const keys = extractKeys(schemaOrShape);
2803
+ const envSource = options?.env ?? process.env;
2804
+ const cleanedInput = {};
2805
+ for (const key of keys) cleanedInput[key] = envSource[key];
2806
+ if (options?.skipValidation) return cleanedInput;
2807
+ const parsed = schema.safeParse(cleanedInput);
2808
+ const { DISABLE_ENV_VALIDATION } = process.env;
2809
+ if (parsed.success === false) {
2810
+ if (!DISABLE_ENV_VALIDATION) throw new Error(`Invalid environment variables:\n${parsed.error.errors.map((error) => `❌ ${chalk.default.red(error.message)}: ${error.path}`).join("\n")}`);
2811
+ return cleanedInput;
2812
+ }
2813
+ return parsed.data;
2814
+ }
2815
+ function isZodType(value) {
2816
+ return value instanceof zod.z.ZodType;
2817
+ }
2818
+ /**
2819
+ * Extract all possible env var keys from either a raw shape or a Zod schema.
2820
+ * For discriminated unions, this collects keys across all variants so that
2821
+ * every potentially-needed variable is picked from `process.env`.
2822
+ */
2823
+ function extractKeys(schemaOrShape) {
2824
+ if (!isZodType(schemaOrShape)) return Object.keys(schemaOrShape);
2825
+ return extractKeysFromSchema(schemaOrShape);
2826
+ }
2827
+ function extractKeysFromSchema(schema) {
2828
+ const keys = /* @__PURE__ */ new Set();
2829
+ if (schema instanceof zod.z.ZodObject) {
2830
+ const shape = schema.shape;
2831
+ for (const key of Object.keys(shape)) keys.add(key);
2832
+ } else if (schema instanceof zod.z.ZodDiscriminatedUnion) {
2833
+ const union = schema;
2834
+ for (const option of union.options) for (const key of extractKeysFromSchema(option)) keys.add(key);
2835
+ } else if (schema instanceof zod.z.ZodUnion) {
2836
+ const union = schema;
2837
+ for (const option of union.options) for (const key of extractKeysFromSchema(option)) keys.add(key);
2838
+ } else if (schema instanceof zod.z.ZodIntersection) {
2839
+ for (const key of extractKeysFromSchema(schema._def.left)) keys.add(key);
2840
+ for (const key of extractKeysFromSchema(schema._def.right)) keys.add(key);
2841
+ } else if (schema instanceof zod.z.ZodEffects) for (const key of extractKeysFromSchema(schema.innerType())) keys.add(key);
2842
+ return [...keys];
2843
+ }
2844
+ function coerceBoolean(input) {
2845
+ if (!input) return false;
2846
+ const x = String(input).toLowerCase();
2847
+ return x === "true" || x === "1" || x === "yes" || x === "t";
2848
+ }
2849
+ const looseBoolean = () => zod.z.preprocess(coerceBoolean, zod.z.boolean());
2850
+ (0, dotenv_flow.config)({ silent: true });
2851
+ exports.coerceBoolean = coerceBoolean;
2852
+ exports.defineEnv = defineEnv;
2853
+ exports.looseBoolean = looseBoolean;
2854
+ Object.keys(zod).forEach(function(k) {
2855
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
2856
+ enumerable: true,
2857
+ get: function() {
2858
+ return zod[k];
2859
+ }
2860
+ });
2861
+ });
2862
+ }));
2863
+
2864
+ //#endregion
2865
+ //#region src/env.ts
2866
+ var import_index_node = require_index_node();
2867
+ const env = (0, import_index_node.defineEnv)({
2868
+ ANYTHING_API_KEY: (0, import_index_node.string)().optional(),
2869
+ ANYTHING_API_URL: (0, import_index_node.string)().optional(),
2870
+ ANYTHING_WEB_URL: (0, import_index_node.string)().optional(),
2871
+ ANYTHING_NO_BROWSER: (0, import_index_node.string)().optional()
2872
+ });
2873
+
2874
+ //#endregion
2875
+ //#region src/config.ts
2876
+ const DEFAULT_API_URL = "https://api.anything.com";
2877
+ const DEV_API_BASE_PORT = 8002;
2878
+ const DEV_PORT_OFFSET = 100;
2879
+ const DEV_API_URL = `http://localhost:${DEV_API_BASE_PORT}`;
2880
+ const DEV_WEB_URL = "http://localhost:3000";
2881
+ const IS_DEV_BUILD = false;
2882
+ function isDevEnvironment() {
2883
+ return IS_DEV_BUILD;
2884
+ }
2885
+ function branchToEnvName(branch) {
2886
+ if (branch === "main" || branch === "master") return "default";
2887
+ return branch.replace(/[^a-zA-Z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-/, "").replace(/-$/, "");
2888
+ }
2889
+ function git(command) {
2890
+ return execSync(command, {
2891
+ encoding: "utf-8",
2892
+ stdio: [
2893
+ "pipe",
2894
+ "pipe",
2895
+ "ignore"
2896
+ ]
2897
+ }).trim();
2898
+ }
2899
+ function detectDevApiUrl() {
2900
+ try {
2901
+ const envName = branchToEnvName(git("git rev-parse --abbrev-ref HEAD"));
2902
+ if (envName === "default") return DEV_API_URL;
2903
+ const commonDir = git("git rev-parse --git-common-dir");
2904
+ const mainRepoDir = path.dirname(path.resolve(process.cwd(), commonDir));
2905
+ const slotFile = path.join(mainRepoDir, ".anything", `${envName}.slot`);
2906
+ if (!fs.existsSync(slotFile)) return null;
2907
+ const slot = Number.parseInt(fs.readFileSync(slotFile, "utf-8").trim(), 10);
2908
+ if (Number.isNaN(slot)) return null;
2909
+ return `http://localhost:${DEV_API_BASE_PORT + slot * DEV_PORT_OFFSET}`;
2910
+ } catch {
2911
+ return null;
2912
+ }
2913
+ }
2914
+ const store = new Conf({
2915
+ projectName: "anything",
2916
+ projectSuffix: "",
2917
+ configFileMode: 384
2918
+ });
2919
+ const PROD_KEYS = {
2920
+ apiKey: "apiKey",
2921
+ apiUrl: "apiUrl",
2922
+ orgId: "orgId",
2923
+ projectGroupId: "projectGroupId"
2924
+ };
2925
+ const DEV_KEYS = {
2926
+ apiKey: "devApiKey",
2927
+ apiUrl: "devApiUrl",
2928
+ orgId: "devOrgId",
2929
+ projectGroupId: "devProjectGroupId"
2930
+ };
2931
+ let devFlagOverride = false;
2932
+ function setDevFlagOverride(value) {
2933
+ devFlagOverride = value;
2934
+ }
2935
+ function isDevModeActive() {
2936
+ if (!isDevEnvironment()) return false;
2937
+ return devFlagOverride || store.get("devMode") === true;
2938
+ }
2939
+ function getDevMode() {
2940
+ return store.get("devMode") === true;
2941
+ }
2942
+ function setDevMode(enabled) {
2943
+ if (enabled) store.set("devMode", true);
2944
+ else store.delete("devMode");
2945
+ }
2946
+ function activeKeys() {
2947
+ return isDevModeActive() ? DEV_KEYS : PROD_KEYS;
2948
+ }
2949
+ function resolveApiUrl({ dev, apiUrl: apiUrlFlag }) {
2950
+ if (env.ANYTHING_API_URL) return env.ANYTHING_API_URL;
2951
+ if (apiUrlFlag) return apiUrlFlag;
2952
+ if (dev === true || isDevModeActive()) return detectDevApiUrl() ?? DEV_API_URL;
2953
+ return store.get(PROD_KEYS.apiUrl) ?? DEFAULT_API_URL;
2954
+ }
2955
+ function resolveConfig({ dev, apiUrl: apiUrlFlag }) {
2956
+ const keys = dev === true || isDevModeActive() ? DEV_KEYS : PROD_KEYS;
2957
+ const apiKey = env.ANYTHING_API_KEY ?? store.get(keys.apiKey);
2958
+ const apiUrl = resolveApiUrl({
2959
+ dev,
2960
+ apiUrl: apiUrlFlag
2961
+ });
2962
+ if (!apiKey) return err({ message: "Not logged in. Run `anything auth login` to authenticate." });
2963
+ return ok({
2964
+ apiKey,
2965
+ apiUrl
2966
+ });
2967
+ }
2968
+ function saveConfig(config) {
2969
+ const keys = activeKeys();
2970
+ store.set(keys.apiKey, config.apiKey);
2971
+ store.set(keys.apiUrl, config.apiUrl);
2972
+ }
2973
+ function deleteConfig() {
2974
+ const keys = activeKeys();
2975
+ store.delete(keys.apiKey);
2976
+ store.delete(keys.apiUrl);
2977
+ store.delete(keys.orgId);
2978
+ store.delete(keys.projectGroupId);
2979
+ }
2980
+ function configExists() {
2981
+ return store.has(activeKeys().apiKey);
2982
+ }
2983
+ function getConfigPath() {
2984
+ return store.path;
2985
+ }
2986
+ function getStoredOrgId() {
2987
+ return store.get(activeKeys().orgId) || void 0;
2988
+ }
2989
+ function setStoredOrgId(orgId) {
2990
+ store.set(activeKeys().orgId, orgId);
2991
+ }
2992
+ function clearStoredOrgId() {
2993
+ store.delete(activeKeys().orgId);
2994
+ }
2995
+ function getStoredProjectGroupId() {
2996
+ return store.get(activeKeys().projectGroupId) || void 0;
2997
+ }
2998
+ function setStoredProjectGroupId(projectGroupId) {
2999
+ store.set(activeKeys().projectGroupId, projectGroupId);
3000
+ }
3001
+ function clearStoredProjectGroupId() {
3002
+ store.delete(activeKeys().projectGroupId);
3003
+ }
3004
+ function getUpdateCheckState() {
3005
+ return {
3006
+ checkedAt: store.get("updateCheckedAt") ?? null,
3007
+ latestKnownVersion: store.get("latestKnownVersion") ?? null,
3008
+ notifiedVersion: store.get("updateNotifiedVersion") ?? null
3009
+ };
3010
+ }
3011
+ function recordUpdateCheck({ checkedAt, latestVersion }) {
3012
+ store.set("updateCheckedAt", checkedAt);
3013
+ if (latestVersion) store.set("latestKnownVersion", latestVersion);
3014
+ }
3015
+ function recordUpdateNotified(version) {
3016
+ store.set("updateNotifiedVersion", version);
3017
+ }
3018
+
3019
+ //#endregion
3020
+ //#region src/exit-codes.ts
3021
+ const EXIT_ERROR = 1;
3022
+ const EXIT_INVALID_ARGS = 2;
3023
+ const EXIT_NOT_FOUND = 3;
3024
+ const EXIT_AUTH_FAILURE = 4;
3025
+ const EXIT_CONFLICT = 5;
3026
+ const EXIT_TIMEOUT = 6;
3027
+ const EXIT_SERVER_ERROR = 7;
3028
+ const EXIT_RATE_LIMITED = 8;
3029
+ function exitCodeFromHttpStatus(status) {
3030
+ if (status === null) return EXIT_ERROR;
3031
+ if (status === 401 || status === 403) return EXIT_AUTH_FAILURE;
3032
+ if (status === 404) return EXIT_NOT_FOUND;
3033
+ if (status === 409) return EXIT_CONFLICT;
3034
+ if (status === 408 || status === 504) return EXIT_TIMEOUT;
3035
+ if (status === 429) return EXIT_RATE_LIMITED;
3036
+ if (status >= 500) return EXIT_SERVER_ERROR;
3037
+ if (status === 422 || status === 400) return EXIT_INVALID_ARGS;
3038
+ return EXIT_ERROR;
3039
+ }
3040
+ function errorCodeFromHttpStatus(status) {
3041
+ if (status === null) return "NETWORK_ERROR";
3042
+ if (status === 401) return "AUTH_FAILURE";
3043
+ if (status === 403) return "FORBIDDEN";
3044
+ if (status === 404) return "NOT_FOUND";
3045
+ if (status === 409) return "CONFLICT";
3046
+ if (status === 408 || status === 504) return "TIMEOUT";
3047
+ if (status === 429) return "RATE_LIMITED";
3048
+ if (status >= 500) return "SERVER_ERROR";
3049
+ if (status === 422) return "VALIDATION_ERROR";
3050
+ if (status === 400) return "BAD_REQUEST";
3051
+ return "ERROR";
3052
+ }
3053
+
3054
+ //#endregion
3055
+ //#region package.json
3056
+ var version = "0.0.2";
3057
+
3058
+ //#endregion
3059
+ //#region src/api-client.ts
3060
+ const USER_AGENT = `anything-cli/${version}`;
3061
+ function parseRetryAfter(response) {
3062
+ if (response.status !== 429) return null;
3063
+ const header = response.headers.get("retry-after");
3064
+ if (!header) return null;
3065
+ const seconds = Number(header);
3066
+ if (Number.isFinite(seconds)) return seconds >= 0 ? Math.ceil(seconds) : null;
3067
+ const dateMs = Date.parse(header);
3068
+ if (!Number.isNaN(dateMs)) {
3069
+ const delta = Math.ceil((dateMs - Date.now()) / 1e3);
3070
+ return delta > 0 ? delta : 0;
3071
+ }
3072
+ return null;
3073
+ }
3074
+ const AuthProviderSchema = z.enum([
3075
+ "google",
3076
+ "email",
3077
+ "facebook",
3078
+ "twitter",
3079
+ "apple"
3080
+ ]);
3081
+ const CreateEnvironmentSchema = z.enum([
3082
+ "development",
3083
+ "preview",
3084
+ "production"
3085
+ ]);
3086
+ const CreateProjectResponseSchema = z.object({
3087
+ projectGroupId: z.string(),
3088
+ revisionId: z.string()
3089
+ });
3090
+ const DuplicateProjectGroupResponseSchema = z.object({
3091
+ projectGroupId: z.string(),
3092
+ name: z.string()
3093
+ });
3094
+ const GenerateResponseSchema = z.object({
3095
+ revisionId: z.string(),
3096
+ threadId: z.string().nullable()
3097
+ });
3098
+ const MessageSchema = z.object({
3099
+ id: z.string(),
3100
+ userMessage: z.string().nullable(),
3101
+ assistantMessage: z.string().nullable(),
3102
+ action: z.string(),
3103
+ status: z.string(),
3104
+ threadId: z.string().nullable(),
3105
+ createdAt: z.string()
3106
+ });
3107
+ const MessagesResponseSchema = z.object({ messages: z.array(MessageSchema) });
3108
+ const ProjectFileSchema = z.object({
3109
+ path: z.string(),
3110
+ content: z.string().optional()
3111
+ });
3112
+ const ProjectFilesResponseSchema = z.object({ files: z.array(ProjectFileSchema.omit({ content: true })) });
3113
+ const ProjectFileResponseSchema = z.object({ file: ProjectFileSchema.extend({ content: z.string() }) });
3114
+ const ProjectLogSchema = z.object({
3115
+ id: z.string(),
3116
+ message: z.string(),
3117
+ level: z.enum([
3118
+ "info",
3119
+ "warn",
3120
+ "error"
3121
+ ]),
3122
+ timestamp: z.string(),
3123
+ source: z.string().nullable(),
3124
+ devServerId: z.string().nullable()
3125
+ });
3126
+ const ProjectAuthProviderSecretSchema = z.object({
3127
+ id: z.string(),
3128
+ envKey: z.string(),
3129
+ displayName: z.string(),
3130
+ environment: z.string()
3131
+ });
3132
+ const ProjectAuthProvidersProviderSchema = z.object({
3133
+ provider: AuthProviderSchema,
3134
+ enabled: z.boolean(),
3135
+ secrets: z.array(ProjectAuthProviderSecretSchema)
3136
+ });
3137
+ const ProjectAuthProvidersResponseSchema = z.object({
3138
+ authEnabled: z.boolean(),
3139
+ providers: z.array(ProjectAuthProvidersProviderSchema)
3140
+ });
3141
+ const ProjectLogsResponseSchema = z.object({ logs: z.array(ProjectLogSchema) });
3142
+ const ProjectAuthSettingsProviderSchema = z.object({
3143
+ provider: AuthProviderSchema,
3144
+ enabled: z.boolean(),
3145
+ configured: z.boolean(),
3146
+ expectedSecretKeys: z.array(z.string()),
3147
+ configuredSecretKeys: z.array(z.string()),
3148
+ helpUrl: z.string()
3149
+ });
3150
+ const ProjectAuthSettingsResponseSchema = z.object({
3151
+ authEnabled: z.boolean(),
3152
+ providers: z.array(ProjectAuthSettingsProviderSchema)
3153
+ });
3154
+ z.object({
3155
+ envKey: z.string(),
3156
+ displayName: z.string(),
3157
+ value: z.string(),
3158
+ environment: CreateEnvironmentSchema
3159
+ });
3160
+ const ProjectModuleSchema = z.object({
3161
+ id: z.string(),
3162
+ name: z.string(),
3163
+ slug: z.string().nullable(),
3164
+ moduleType: z.string(),
3165
+ pathSegment: z.string().nullable()
3166
+ });
3167
+ const ProjectInfoResponseSchema = z.object({
3168
+ id: z.string(),
3169
+ name: z.string(),
3170
+ slug: z.string().nullable(),
3171
+ filesystemVersion: z.string().nullable(),
3172
+ createdAt: z.string(),
3173
+ updatedAt: z.string(),
3174
+ devServerUrl: z.string().nullable(),
3175
+ publishedUrls: z.array(z.string()),
3176
+ latestPublishedUrl: z.string().nullable(),
3177
+ projects: z.array(ProjectModuleSchema)
3178
+ });
3179
+ const ProjectStatusResponseSchema = z.object({
3180
+ projectGroupId: z.string(),
3181
+ latestRevisionId: z.string().nullable(),
3182
+ status: z.string().nullable(),
3183
+ deployment: z.object({
3184
+ id: z.string(),
3185
+ status: z.string(),
3186
+ url: z.string().nullable()
3187
+ }).nullable(),
3188
+ updatedAt: z.string()
3189
+ });
3190
+ const RenameProjectGroupResponseSchema = z.object({
3191
+ success: z.boolean(),
3192
+ projectGroupId: z.string().uuid(),
3193
+ name: z.string(),
3194
+ slug: z.string().nullable(),
3195
+ updatedAt: z.string()
3196
+ });
3197
+ const ProjectListItemSchema = z.object({
3198
+ id: z.string(),
3199
+ name: z.string(),
3200
+ slug: z.string().nullable(),
3201
+ organizationId: z.string(),
3202
+ organizationName: z.string(),
3203
+ createdAt: z.string(),
3204
+ updatedAt: z.string()
3205
+ });
3206
+ const ListProjectsResponseSchema = z.object({ projects: z.array(ProjectListItemSchema) });
3207
+ const DatabaseListItemSchema = z.object({
3208
+ id: z.string(),
3209
+ name: z.string(),
3210
+ status: z.enum([
3211
+ "CREATING",
3212
+ "COMPLETED",
3213
+ "FAILED"
3214
+ ]),
3215
+ organizationId: z.string(),
3216
+ organizationName: z.string(),
3217
+ createdAt: z.string(),
3218
+ updatedAt: z.string(),
3219
+ pointInTimeRestoreEnabled: z.boolean()
3220
+ });
3221
+ const ListDatabasesResponseSchema = z.object({ databases: z.array(DatabaseListItemSchema) });
3222
+ const SecretSchema = z.object({
3223
+ id: z.string(),
3224
+ envKey: z.string(),
3225
+ displayName: z.string(),
3226
+ environment: z.string()
3227
+ });
3228
+ const AddSecretResponseSchema = z.object({ secret: SecretSchema });
3229
+ const SecretListItemSchema = SecretSchema.extend({
3230
+ createdAt: z.string(),
3231
+ updatedAt: z.string()
3232
+ });
3233
+ const ListSecretsResponseSchema = z.object({ secrets: z.array(SecretListItemSchema) });
3234
+ const PublishResponseSchema = z.object({
3235
+ success: z.boolean(),
3236
+ projectGroupId: z.string(),
3237
+ slug: z.string().nullable(),
3238
+ deploymentId: z.string()
3239
+ });
3240
+ const ProjectSubmissionSchema = z.object({
3241
+ id: z.string(),
3242
+ projectGroupId: z.string(),
3243
+ status: z.enum([
3244
+ "PENDING",
3245
+ "CREATED",
3246
+ "FAILED"
3247
+ ]),
3248
+ launchUrl: z.string().nullable(),
3249
+ authUrl: z.string().nullable(),
3250
+ errorMessage: z.string().nullable(),
3251
+ expiresAt: z.string().nullable()
3252
+ });
3253
+ const SubmitProjectResponseSchema = z.object({
3254
+ success: z.boolean(),
3255
+ submission: ProjectSubmissionSchema
3256
+ });
3257
+ const UnpublishResponseSchema = z.object({
3258
+ success: z.boolean(),
3259
+ projectGroupId: z.string()
3260
+ });
3261
+ const OrganizationSchema = z.object({
3262
+ id: z.string(),
3263
+ name: z.string(),
3264
+ plan: z.string(),
3265
+ planDisplayName: z.string(),
3266
+ isPaid: z.boolean(),
3267
+ creditBalance: z.string()
3268
+ });
3269
+ const MeResponseSchema = z.object({
3270
+ id: z.string(),
3271
+ email: z.string().nullable(),
3272
+ name: z.string().nullable(),
3273
+ organizations: z.array(OrganizationSchema)
3274
+ });
3275
+ const OrganizationMembersResponseSchema = z.object({
3276
+ organization: z.object({
3277
+ id: z.string(),
3278
+ name: z.string(),
3279
+ role: z.string().nullable()
3280
+ }),
3281
+ collaborators: z.array(z.object({
3282
+ userId: z.string(),
3283
+ email: z.string().nullable(),
3284
+ displayName: z.string(),
3285
+ role: z.string(),
3286
+ isMe: z.boolean()
3287
+ })),
3288
+ pendingInvites: z.array(z.object({
3289
+ id: z.string(),
3290
+ toEmail: z.string(),
3291
+ expiresAt: z.string(),
3292
+ status: z.enum(["pending", "expired"])
3293
+ }))
3294
+ });
3295
+ const AssetSchema = z.object({
3296
+ id: z.string(),
3297
+ name: z.string(),
3298
+ url: z.string(),
3299
+ mimeType: z.string(),
3300
+ createdAt: z.string()
3301
+ });
3302
+ const UploadAssetResponseSchema = AssetSchema;
3303
+ const ListAssetsResponseSchema = z.object({
3304
+ assets: z.array(AssetSchema),
3305
+ total: z.number().optional()
3306
+ });
3307
+ const DomainProjectGroupSchema = z.object({
3308
+ id: z.string(),
3309
+ name: z.string()
3310
+ });
3311
+ const DomainSchema = z.object({
3312
+ id: z.string(),
3313
+ domain: z.string(),
3314
+ vercelVerified: z.boolean(),
3315
+ vercelVerification: z.unknown().nullable(),
3316
+ projectGroup: DomainProjectGroupSchema.nullable()
3317
+ });
3318
+ const ListDomainsResponseSchema = z.object({ domains: z.array(DomainSchema) });
3319
+ const DatabaseDetailSchema = DatabaseListItemSchema.extend({
3320
+ connectionString: z.string().nullable().optional(),
3321
+ projectGroupId: z.string().nullable().optional()
3322
+ });
3323
+ const DatabaseDetailResponseSchema = z.object({ database: DatabaseDetailSchema });
3324
+ const CreateDatabaseResponseSchema = z.object({ database: DatabaseListItemSchema });
3325
+ const DatabaseQueryResultSchema = z.object({
3326
+ columns: z.array(z.string()),
3327
+ rows: z.array(z.array(z.unknown())),
3328
+ rowCount: z.number()
3329
+ });
3330
+ const DatabaseConnectionResponseSchema = z.object({ connectionString: z.string() });
3331
+ const AddDomainResponseSchema = z.object({ domain: DomainSchema });
3332
+ const DomainVerificationSchema = z.object({
3333
+ domain: z.string(),
3334
+ verified: z.boolean(),
3335
+ vercelVerification: z.unknown().nullable()
3336
+ });
3337
+ const DeploymentSchema = z.object({
3338
+ id: z.string(),
3339
+ projectGroupId: z.string(),
3340
+ status: z.string(),
3341
+ url: z.string().nullable().optional(),
3342
+ createdAt: z.string(),
3343
+ completedAt: z.string().nullable()
3344
+ });
3345
+ const ListDeploymentsResponseSchema = z.object({ deployments: z.array(DeploymentSchema) });
3346
+ const DeploymentDetailSchema = DeploymentSchema.extend({
3347
+ buildLogs: z.string().nullable().optional(),
3348
+ failureReason: z.string().nullable().optional()
3349
+ });
3350
+ const DeploymentDetailResponseSchema = z.object({ deployment: DeploymentDetailSchema });
3351
+ const DeploymentLogsResponseSchema = z.object({
3352
+ logs: z.string(),
3353
+ status: z.string().optional(),
3354
+ failureReason: z.string().nullable().optional()
3355
+ });
3356
+ const RollbackResponseSchema = z.object({
3357
+ success: z.boolean(),
3358
+ deployment: DeploymentSchema.optional()
3359
+ });
3360
+ const InviteMemberResponseSchema = z.object({
3361
+ success: z.boolean(),
3362
+ invite: z.object({
3363
+ id: z.string(),
3364
+ toEmail: z.string(),
3365
+ expiresAt: z.string()
3366
+ })
3367
+ });
3368
+ const RemoveMemberResponseSchema = z.object({ success: z.boolean() });
3369
+ const UpdateMemberRoleResponseSchema = z.object({
3370
+ success: z.boolean(),
3371
+ userId: z.string(),
3372
+ role: z.string()
3373
+ });
3374
+ var AnythingApiClient = class {
3375
+ baseUrl;
3376
+ authHeader;
3377
+ constructor(config) {
3378
+ this.baseUrl = `${config.apiUrl.replace(/\/$/, "")}/v0/api`;
3379
+ this.authHeader = config.apiKey.startsWith("anything_") || config.apiKey.startsWith("create_") ? `Basic ${Buffer.from(`${config.apiKey}:`).toString("base64")}` : config.apiKey;
3380
+ }
3381
+ async getMe() {
3382
+ return this.request({
3383
+ method: "GET",
3384
+ path: "/me",
3385
+ schema: MeResponseSchema
3386
+ });
3009
3387
  }
3010
- function wrapConversion(toModel, graph) {
3011
- const path = [graph[toModel].parent, toModel];
3012
- let fn = conversions[graph[toModel].parent][toModel];
3013
- let cur = graph[toModel].parent;
3014
- while (graph[cur].parent) {
3015
- path.unshift(graph[cur].parent);
3016
- fn = link(conversions[graph[cur].parent][cur], fn);
3017
- cur = graph[cur].parent;
3018
- }
3019
- fn.conversion = path;
3020
- return fn;
3388
+ async getOrganizationMembers({ organizationId }) {
3389
+ return this.request({
3390
+ method: "GET",
3391
+ path: `/organizations/${organizationId}/members`,
3392
+ schema: OrganizationMembersResponseSchema
3393
+ });
3021
3394
  }
3022
- module.exports = function(fromModel) {
3023
- const graph = deriveBFS(fromModel);
3024
- const conversion = {};
3025
- const models = Object.keys(graph);
3026
- for (let len = models.length, i = 0; i < len; i++) {
3027
- const toModel = models[i];
3028
- if (graph[toModel].parent === null) continue;
3029
- conversion[toModel] = wrapConversion(toModel, graph);
3030
- }
3031
- return conversion;
3032
- };
3033
- }));
3034
-
3035
- //#endregion
3036
- //#region ../../node_modules/color-convert/index.js
3037
- var require_color_convert = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3038
- const conversions = require_conversions();
3039
- const route = require_route();
3040
- const convert = {};
3041
- const models = Object.keys(conversions);
3042
- function wrapRaw(fn) {
3043
- const wrappedFn = function(...args) {
3044
- const arg0 = args[0];
3045
- if (arg0 === void 0 || arg0 === null) return arg0;
3046
- if (arg0.length > 1) args = arg0;
3047
- return fn(args);
3048
- };
3049
- if ("conversion" in fn) wrappedFn.conversion = fn.conversion;
3050
- return wrappedFn;
3395
+ async createProject({ prompt, organizationId, name }) {
3396
+ return this.request({
3397
+ method: "POST",
3398
+ path: "/projects",
3399
+ body: {
3400
+ prompt,
3401
+ organizationId,
3402
+ ...name !== null ? { name } : {}
3403
+ },
3404
+ schema: CreateProjectResponseSchema
3405
+ });
3051
3406
  }
3052
- function wrapRounded(fn) {
3053
- const wrappedFn = function(...args) {
3054
- const arg0 = args[0];
3055
- if (arg0 === void 0 || arg0 === null) return arg0;
3056
- if (arg0.length > 1) args = arg0;
3057
- const result = fn(args);
3058
- if (typeof result === "object") for (let len = result.length, i = 0; i < len; i++) result[i] = Math.round(result[i]);
3059
- return result;
3060
- };
3061
- if ("conversion" in fn) wrappedFn.conversion = fn.conversion;
3062
- return wrappedFn;
3407
+ async duplicateProjectGroup({ projectGroupId, name }) {
3408
+ return this.request({
3409
+ method: "POST",
3410
+ path: `/projects/${projectGroupId}/duplicate`,
3411
+ body: name !== null ? { name } : {},
3412
+ schema: DuplicateProjectGroupResponseSchema
3413
+ });
3063
3414
  }
3064
- models.forEach((fromModel) => {
3065
- convert[fromModel] = {};
3066
- Object.defineProperty(convert[fromModel], "channels", { value: conversions[fromModel].channels });
3067
- Object.defineProperty(convert[fromModel], "labels", { value: conversions[fromModel].labels });
3068
- const routes = route(fromModel);
3069
- Object.keys(routes).forEach((toModel) => {
3070
- const fn = routes[toModel];
3071
- convert[fromModel][toModel] = wrapRounded(fn);
3072
- convert[fromModel][toModel].raw = wrapRaw(fn);
3415
+ async listProjects({ organizationId, query, limit }) {
3416
+ const params = new URLSearchParams();
3417
+ if (organizationId !== null) params.set("organizationId", organizationId);
3418
+ if (query !== null) params.set("query", query);
3419
+ params.set("limit", String(limit));
3420
+ return this.request({
3421
+ method: "GET",
3422
+ path: `/projects?${params.toString()}`,
3423
+ schema: ListProjectsResponseSchema
3073
3424
  });
3074
- });
3075
- module.exports = convert;
3076
- }));
3077
-
3078
- //#endregion
3079
- //#region ../../node_modules/ansi-styles/index.js
3080
- var require_ansi_styles = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3081
- const wrapAnsi16 = (fn, offset) => (...args) => {
3082
- return `\u001B[${fn(...args) + offset}m`;
3083
- };
3084
- const wrapAnsi256 = (fn, offset) => (...args) => {
3085
- const code = fn(...args);
3086
- return `\u001B[${38 + offset};5;${code}m`;
3087
- };
3088
- const wrapAnsi16m = (fn, offset) => (...args) => {
3089
- const rgb = fn(...args);
3090
- return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
3091
- };
3092
- const ansi2ansi = (n) => n;
3093
- const rgb2rgb = (r, g, b) => [
3094
- r,
3095
- g,
3096
- b
3097
- ];
3098
- const setLazyProperty = (object, property, get) => {
3099
- Object.defineProperty(object, property, {
3100
- get: () => {
3101
- const value = get();
3102
- Object.defineProperty(object, property, {
3103
- value,
3104
- enumerable: true,
3105
- configurable: true
3106
- });
3107
- return value;
3108
- },
3109
- enumerable: true,
3110
- configurable: true
3425
+ }
3426
+ async listDatabases({ organizationId, limit }) {
3427
+ const params = new URLSearchParams();
3428
+ params.set("organizationId", organizationId);
3429
+ params.set("limit", String(limit));
3430
+ return this.request({
3431
+ method: "GET",
3432
+ path: `/databases?${params.toString()}`,
3433
+ schema: ListDatabasesResponseSchema
3111
3434
  });
3112
- };
3113
- /** @type {typeof import('color-convert')} */
3114
- let colorConvert;
3115
- const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
3116
- if (colorConvert === void 0) colorConvert = require_color_convert();
3117
- const offset = isBackground ? 10 : 0;
3118
- const styles = {};
3119
- for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
3120
- const name = sourceSpace === "ansi16" ? "ansi" : sourceSpace;
3121
- if (sourceSpace === targetSpace) styles[name] = wrap(identity, offset);
3122
- else if (typeof suite === "object") styles[name] = wrap(suite[targetSpace], offset);
3123
- }
3124
- return styles;
3125
- };
3126
- function assembleStyles() {
3127
- const codes = /* @__PURE__ */ new Map();
3128
- const styles = {
3129
- modifier: {
3130
- reset: [0, 0],
3131
- bold: [1, 22],
3132
- dim: [2, 22],
3133
- italic: [3, 23],
3134
- underline: [4, 24],
3135
- inverse: [7, 27],
3136
- hidden: [8, 28],
3137
- strikethrough: [9, 29]
3138
- },
3139
- color: {
3140
- black: [30, 39],
3141
- red: [31, 39],
3142
- green: [32, 39],
3143
- yellow: [33, 39],
3144
- blue: [34, 39],
3145
- magenta: [35, 39],
3146
- cyan: [36, 39],
3147
- white: [37, 39],
3148
- blackBright: [90, 39],
3149
- redBright: [91, 39],
3150
- greenBright: [92, 39],
3151
- yellowBright: [93, 39],
3152
- blueBright: [94, 39],
3153
- magentaBright: [95, 39],
3154
- cyanBright: [96, 39],
3155
- whiteBright: [97, 39]
3435
+ }
3436
+ async generate({ projectGroupId, prompt, threadId, createNewThread }) {
3437
+ return this.request({
3438
+ method: "POST",
3439
+ path: `/projects/${projectGroupId}/generate`,
3440
+ body: {
3441
+ prompt,
3442
+ ...threadId !== null ? { threadId } : {},
3443
+ ...createNewThread ? { createNewThread: true } : {}
3156
3444
  },
3157
- bgColor: {
3158
- bgBlack: [40, 49],
3159
- bgRed: [41, 49],
3160
- bgGreen: [42, 49],
3161
- bgYellow: [43, 49],
3162
- bgBlue: [44, 49],
3163
- bgMagenta: [45, 49],
3164
- bgCyan: [46, 49],
3165
- bgWhite: [47, 49],
3166
- bgBlackBright: [100, 49],
3167
- bgRedBright: [101, 49],
3168
- bgGreenBright: [102, 49],
3169
- bgYellowBright: [103, 49],
3170
- bgBlueBright: [104, 49],
3171
- bgMagentaBright: [105, 49],
3172
- bgCyanBright: [106, 49],
3173
- bgWhiteBright: [107, 49]
3174
- }
3175
- };
3176
- styles.color.gray = styles.color.blackBright;
3177
- styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
3178
- styles.color.grey = styles.color.blackBright;
3179
- styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
3180
- for (const [groupName, group] of Object.entries(styles)) {
3181
- for (const [styleName, style] of Object.entries(group)) {
3182
- styles[styleName] = {
3183
- open: `\u001B[${style[0]}m`,
3184
- close: `\u001B[${style[1]}m`
3185
- };
3186
- group[styleName] = styles[styleName];
3187
- codes.set(style[0], style[1]);
3188
- }
3189
- Object.defineProperty(styles, groupName, {
3190
- value: group,
3191
- enumerable: false
3192
- });
3193
- }
3194
- Object.defineProperty(styles, "codes", {
3195
- value: codes,
3196
- enumerable: false
3445
+ schema: GenerateResponseSchema
3197
3446
  });
3198
- styles.color.close = "\x1B[39m";
3199
- styles.bgColor.close = "\x1B[49m";
3200
- setLazyProperty(styles.color, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, false));
3201
- setLazyProperty(styles.color, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, false));
3202
- setLazyProperty(styles.color, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, false));
3203
- setLazyProperty(styles.bgColor, "ansi", () => makeDynamicStyles(wrapAnsi16, "ansi16", ansi2ansi, true));
3204
- setLazyProperty(styles.bgColor, "ansi256", () => makeDynamicStyles(wrapAnsi256, "ansi256", ansi2ansi, true));
3205
- setLazyProperty(styles.bgColor, "ansi16m", () => makeDynamicStyles(wrapAnsi16m, "rgb", rgb2rgb, true));
3206
- return styles;
3207
3447
  }
3208
- Object.defineProperty(module, "exports", {
3209
- enumerable: true,
3210
- get: assembleStyles
3211
- });
3212
- }));
3213
-
3214
- //#endregion
3215
- //#region ../../node_modules/has-flag/index.js
3216
- var require_has_flag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3217
- module.exports = (flag, argv = process.argv) => {
3218
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
3219
- const position = argv.indexOf(prefix + flag);
3220
- const terminatorPosition = argv.indexOf("--");
3221
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
3222
- };
3223
- }));
3224
-
3225
- //#endregion
3226
- //#region ../../node_modules/chalk/node_modules/supports-color/index.js
3227
- var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3228
- const os = __require("os");
3229
- const tty = __require("tty");
3230
- const hasFlag = require_has_flag();
3231
- const { env } = process;
3232
- let forceColor;
3233
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) forceColor = 0;
3234
- else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) forceColor = 1;
3235
- if ("FORCE_COLOR" in env) if (env.FORCE_COLOR === "true") forceColor = 1;
3236
- else if (env.FORCE_COLOR === "false") forceColor = 0;
3237
- else forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
3238
- function translateLevel(level) {
3239
- if (level === 0) return false;
3240
- return {
3241
- level,
3242
- hasBasic: true,
3243
- has256: level >= 2,
3244
- has16m: level >= 3
3245
- };
3448
+ async getMessages({ projectGroupId, threadId, limit }) {
3449
+ const params = new URLSearchParams();
3450
+ if (threadId !== null) params.set("threadId", threadId);
3451
+ if (limit !== null) params.set("limit", String(limit));
3452
+ const query = params.toString();
3453
+ const path = `/projects/${projectGroupId}/messages${query ? `?${query}` : ""}`;
3454
+ return this.request({
3455
+ method: "GET",
3456
+ path,
3457
+ schema: MessagesResponseSchema
3458
+ });
3246
3459
  }
3247
- function supportsColor(haveStream, streamIsTTY) {
3248
- if (forceColor === 0) return 0;
3249
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
3250
- if (hasFlag("color=256")) return 2;
3251
- if (haveStream && !streamIsTTY && forceColor === void 0) return 0;
3252
- const min = forceColor || 0;
3253
- if (env.TERM === "dumb") return min;
3254
- if (process.platform === "win32") {
3255
- const osRelease = os.release().split(".");
3256
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
3257
- return 1;
3258
- }
3259
- if ("CI" in env) {
3260
- if ([
3261
- "TRAVIS",
3262
- "CIRCLECI",
3263
- "APPVEYOR",
3264
- "GITLAB_CI",
3265
- "GITHUB_ACTIONS",
3266
- "BUILDKITE"
3267
- ].some((sign) => sign in env) || env.CI_NAME === "codeship") return 1;
3268
- return min;
3269
- }
3270
- if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
3271
- if (env.COLORTERM === "truecolor") return 3;
3272
- if ("TERM_PROGRAM" in env) {
3273
- const version = parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
3274
- switch (env.TERM_PROGRAM) {
3275
- case "iTerm.app": return version >= 3 ? 3 : 2;
3276
- case "Apple_Terminal": return 2;
3277
- }
3278
- }
3279
- if (/-256(color)?$/i.test(env.TERM)) return 2;
3280
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
3281
- if ("COLORTERM" in env) return 1;
3282
- return min;
3460
+ async getProjectLogs({ projectGroupId, level, search, limit }) {
3461
+ const params = new URLSearchParams();
3462
+ if (level !== null) params.set("level", level);
3463
+ if (search !== null) params.set("search", search);
3464
+ if (limit !== null) params.set("limit", String(limit));
3465
+ const query = params.toString();
3466
+ const path = `/projects/${projectGroupId}/logs${query ? `?${query}` : ""}`;
3467
+ return this.request({
3468
+ method: "GET",
3469
+ path,
3470
+ schema: ProjectLogsResponseSchema
3471
+ });
3283
3472
  }
3284
- function getSupportLevel(stream) {
3285
- return translateLevel(supportsColor(stream, stream && stream.isTTY));
3473
+ async getProjectAuthProviders({ projectGroupId }) {
3474
+ return this.request({
3475
+ method: "GET",
3476
+ path: `/projects/${projectGroupId}/auth/providers`,
3477
+ schema: ProjectAuthProvidersResponseSchema
3478
+ });
3286
3479
  }
3287
- module.exports = {
3288
- supportsColor: getSupportLevel,
3289
- stdout: translateLevel(supportsColor(true, tty.isatty(1))),
3290
- stderr: translateLevel(supportsColor(true, tty.isatty(2)))
3291
- };
3292
- }));
3293
-
3294
- //#endregion
3295
- //#region ../../node_modules/chalk/source/util.js
3296
- var require_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3297
- const stringReplaceAll = (string, substring, replacer) => {
3298
- let index = string.indexOf(substring);
3299
- if (index === -1) return string;
3300
- const substringLength = substring.length;
3301
- let endIndex = 0;
3302
- let returnValue = "";
3303
- do {
3304
- returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
3305
- endIndex = index + substringLength;
3306
- index = string.indexOf(substring, endIndex);
3307
- } while (index !== -1);
3308
- returnValue += string.substr(endIndex);
3309
- return returnValue;
3310
- };
3311
- const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
3312
- let endIndex = 0;
3313
- let returnValue = "";
3314
- do {
3315
- const gotCR = string[index - 1] === "\r";
3316
- returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
3317
- endIndex = index + 1;
3318
- index = string.indexOf("\n", endIndex);
3319
- } while (index !== -1);
3320
- returnValue += string.substr(endIndex);
3321
- return returnValue;
3322
- };
3323
- module.exports = {
3324
- stringReplaceAll,
3325
- stringEncaseCRLFWithFirstIndex
3326
- };
3327
- }));
3328
-
3329
- //#endregion
3330
- //#region ../../node_modules/chalk/source/templates.js
3331
- var require_templates = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3332
- const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
3333
- const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
3334
- const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
3335
- const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
3336
- const ESCAPES = new Map([
3337
- ["n", "\n"],
3338
- ["r", "\r"],
3339
- ["t", " "],
3340
- ["b", "\b"],
3341
- ["f", "\f"],
3342
- ["v", "\v"],
3343
- ["0", "\0"],
3344
- ["\\", "\\"],
3345
- ["e", "\x1B"],
3346
- ["a", "\x07"]
3347
- ]);
3348
- function unescape(c) {
3349
- const u = c[0] === "u";
3350
- const bracket = c[1] === "{";
3351
- if (u && !bracket && c.length === 5 || c[0] === "x" && c.length === 3) return String.fromCharCode(parseInt(c.slice(1), 16));
3352
- if (u && bracket) return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
3353
- return ESCAPES.get(c) || c;
3480
+ async getProjectAuthSettings({ projectGroupId }) {
3481
+ return this.request({
3482
+ method: "GET",
3483
+ path: `/projects/${projectGroupId}/settings/auth`,
3484
+ schema: ProjectAuthSettingsResponseSchema
3485
+ });
3354
3486
  }
3355
- function parseArguments(name, arguments_) {
3356
- const results = [];
3357
- const chunks = arguments_.trim().split(/\s*,\s*/g);
3358
- let matches;
3359
- for (const chunk of chunks) {
3360
- const number = Number(chunk);
3361
- if (!Number.isNaN(number)) results.push(number);
3362
- else if (matches = chunk.match(STRING_REGEX)) results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
3363
- else throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
3364
- }
3365
- return results;
3487
+ async updateProjectAuthSettings({ projectGroupId, provider, enabled, secrets, enableForAllModules }) {
3488
+ return this.request({
3489
+ method: "POST",
3490
+ path: `/projects/${projectGroupId}/settings/auth`,
3491
+ body: {
3492
+ provider,
3493
+ enabled,
3494
+ ...secrets.length > 0 ? { secrets } : {},
3495
+ ...enableForAllModules ? { enableForAllModules } : {}
3496
+ },
3497
+ schema: ProjectAuthSettingsResponseSchema
3498
+ });
3366
3499
  }
3367
- function parseStyle(style) {
3368
- STYLE_REGEX.lastIndex = 0;
3369
- const results = [];
3370
- let matches;
3371
- while ((matches = STYLE_REGEX.exec(style)) !== null) {
3372
- const name = matches[1];
3373
- if (matches[2]) {
3374
- const args = parseArguments(name, matches[2]);
3375
- results.push([name].concat(args));
3376
- } else results.push([name]);
3377
- }
3378
- return results;
3500
+ async getProject({ projectGroupId }) {
3501
+ return this.request({
3502
+ method: "GET",
3503
+ path: `/projects/${projectGroupId}`,
3504
+ schema: ProjectInfoResponseSchema
3505
+ });
3379
3506
  }
3380
- function buildStyle(chalk, styles) {
3381
- const enabled = {};
3382
- for (const layer of styles) for (const style of layer.styles) enabled[style[0]] = layer.inverse ? null : style.slice(1);
3383
- let current = chalk;
3384
- for (const [styleName, styles] of Object.entries(enabled)) {
3385
- if (!Array.isArray(styles)) continue;
3386
- if (!(styleName in current)) throw new Error(`Unknown Chalk style: ${styleName}`);
3387
- current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
3388
- }
3389
- return current;
3507
+ async getProjectStatus({ projectGroupId }) {
3508
+ return this.request({
3509
+ method: "GET",
3510
+ path: `/projects/${projectGroupId}/status`,
3511
+ schema: ProjectStatusResponseSchema
3512
+ });
3390
3513
  }
3391
- module.exports = (chalk, temporary) => {
3392
- const styles = [];
3393
- const chunks = [];
3394
- let chunk = [];
3395
- temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
3396
- if (escapeCharacter) chunk.push(unescape(escapeCharacter));
3397
- else if (style) {
3398
- const string = chunk.join("");
3399
- chunk = [];
3400
- chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
3401
- styles.push({
3402
- inverse,
3403
- styles: parseStyle(style)
3404
- });
3405
- } else if (close) {
3406
- if (styles.length === 0) throw new Error("Found extraneous } in Chalk template literal");
3407
- chunks.push(buildStyle(chalk, styles)(chunk.join("")));
3408
- chunk = [];
3409
- styles.pop();
3410
- } else chunk.push(character);
3514
+ async renameProjectGroup({ projectGroupId, name }) {
3515
+ return this.request({
3516
+ method: "POST",
3517
+ path: `/projects/${projectGroupId}/rename`,
3518
+ body: { name },
3519
+ schema: RenameProjectGroupResponseSchema
3411
3520
  });
3412
- chunks.push(chunk.join(""));
3413
- if (styles.length > 0) {
3414
- const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? "" : "s"} (\`}\`)`;
3415
- throw new Error(errMessage);
3416
- }
3417
- return chunks.join("");
3418
- };
3419
- }));
3420
-
3421
- //#endregion
3422
- //#region ../../node_modules/chalk/source/index.js
3423
- var require_source = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3424
- const ansiStyles = require_ansi_styles();
3425
- const { stdout: stdoutColor, stderr: stderrColor } = require_supports_color();
3426
- const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = require_util();
3427
- const { isArray } = Array;
3428
- const levelMapping = [
3429
- "ansi",
3430
- "ansi",
3431
- "ansi256",
3432
- "ansi16m"
3433
- ];
3434
- const styles = Object.create(null);
3435
- const applyOptions = (object, options = {}) => {
3436
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) throw new Error("The `level` option should be an integer from 0 to 3");
3437
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
3438
- object.level = options.level === void 0 ? colorLevel : options.level;
3439
- };
3440
- var ChalkClass = class {
3441
- constructor(options) {
3442
- return chalkFactory(options);
3443
- }
3444
- };
3445
- const chalkFactory = (options) => {
3446
- const chalk = {};
3447
- applyOptions(chalk, options);
3448
- chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
3449
- Object.setPrototypeOf(chalk, Chalk.prototype);
3450
- Object.setPrototypeOf(chalk.template, chalk);
3451
- chalk.template.constructor = () => {
3452
- throw new Error("`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.");
3453
- };
3454
- chalk.template.Instance = ChalkClass;
3455
- return chalk.template;
3456
- };
3457
- function Chalk(options) {
3458
- return chalkFactory(options);
3459
3521
  }
3460
- for (const [styleName, style] of Object.entries(ansiStyles)) styles[styleName] = { get() {
3461
- const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
3462
- Object.defineProperty(this, styleName, { value: builder });
3463
- return builder;
3464
- } };
3465
- styles.visible = { get() {
3466
- const builder = createBuilder(this, this._styler, true);
3467
- Object.defineProperty(this, "visible", { value: builder });
3468
- return builder;
3469
- } };
3470
- const usedModels = [
3471
- "rgb",
3472
- "hex",
3473
- "keyword",
3474
- "hsl",
3475
- "hsv",
3476
- "hwb",
3477
- "ansi",
3478
- "ansi256"
3479
- ];
3480
- for (const model of usedModels) styles[model] = { get() {
3481
- const { level } = this;
3482
- return function(...arguments_) {
3483
- const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
3484
- return createBuilder(this, styler, this._isEmpty);
3485
- };
3486
- } };
3487
- for (const model of usedModels) {
3488
- const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
3489
- styles[bgModel] = { get() {
3490
- const { level } = this;
3491
- return function(...arguments_) {
3492
- const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
3493
- return createBuilder(this, styler, this._isEmpty);
3494
- };
3495
- } };
3522
+ async listProjectFiles({ projectGroupId }) {
3523
+ return this.request({
3524
+ method: "GET",
3525
+ path: `/projects/${projectGroupId}/files`,
3526
+ schema: ProjectFilesResponseSchema
3527
+ });
3496
3528
  }
3497
- const proto = Object.defineProperties(() => {}, {
3498
- ...styles,
3499
- level: {
3500
- enumerable: true,
3501
- get() {
3502
- return this._generator.level;
3529
+ async getProjectFile({ projectGroupId, path }) {
3530
+ const params = new URLSearchParams({ path });
3531
+ return this.request({
3532
+ method: "GET",
3533
+ path: `/projects/${projectGroupId}/files?${params.toString()}`,
3534
+ schema: ProjectFileResponseSchema
3535
+ });
3536
+ }
3537
+ async addSecret({ projectGroupId, displayName, value, environment }) {
3538
+ return this.request({
3539
+ method: "POST",
3540
+ path: `/projects/${projectGroupId}/secrets`,
3541
+ body: {
3542
+ displayName,
3543
+ value,
3544
+ ...environment !== null ? { environment } : {}
3503
3545
  },
3504
- set(level) {
3505
- this._generator.level = level;
3506
- }
3507
- }
3508
- });
3509
- const createStyler = (open, close, parent) => {
3510
- let openAll;
3511
- let closeAll;
3512
- if (parent === void 0) {
3513
- openAll = open;
3514
- closeAll = close;
3515
- } else {
3516
- openAll = parent.openAll + open;
3517
- closeAll = close + parent.closeAll;
3518
- }
3519
- return {
3520
- open,
3521
- close,
3522
- openAll,
3523
- closeAll,
3524
- parent
3525
- };
3526
- };
3527
- const createBuilder = (self, _styler, _isEmpty) => {
3528
- const builder = (...arguments_) => {
3529
- if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) return applyStyle(builder, chalkTag(builder, ...arguments_));
3530
- return applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
3531
- };
3532
- Object.setPrototypeOf(builder, proto);
3533
- builder._generator = self;
3534
- builder._styler = _styler;
3535
- builder._isEmpty = _isEmpty;
3536
- return builder;
3537
- };
3538
- const applyStyle = (self, string) => {
3539
- if (self.level <= 0 || !string) return self._isEmpty ? "" : string;
3540
- let styler = self._styler;
3541
- if (styler === void 0) return string;
3542
- const { openAll, closeAll } = styler;
3543
- if (string.indexOf("\x1B") !== -1) while (styler !== void 0) {
3544
- string = stringReplaceAll(string, styler.close, styler.open);
3545
- styler = styler.parent;
3546
+ schema: AddSecretResponseSchema
3547
+ });
3548
+ }
3549
+ async listSecrets({ projectGroupId }) {
3550
+ return this.request({
3551
+ method: "GET",
3552
+ path: `/projects/${projectGroupId}/secrets`,
3553
+ schema: ListSecretsResponseSchema
3554
+ });
3555
+ }
3556
+ async deleteSecret({ projectGroupId, secretId }) {
3557
+ return this.request({
3558
+ method: "DELETE",
3559
+ path: `/projects/${projectGroupId}/secrets/${secretId}`
3560
+ });
3561
+ }
3562
+ async publish({ projectGroupId, slug }) {
3563
+ return this.request({
3564
+ method: "POST",
3565
+ path: `/projects/${projectGroupId}/publish`,
3566
+ body: slug !== null ? { slug } : {},
3567
+ schema: PublishResponseSchema
3568
+ });
3569
+ }
3570
+ async submitProject({ projectGroupId, store }) {
3571
+ return this.request({
3572
+ method: "POST",
3573
+ path: `/projects/${projectGroupId}/submit`,
3574
+ body: { store },
3575
+ schema: SubmitProjectResponseSchema
3576
+ });
3577
+ }
3578
+ async getProjectSubmission({ projectGroupId, submissionId }) {
3579
+ return this.request({
3580
+ method: "GET",
3581
+ path: `/projects/${projectGroupId}/submit/${submissionId}`,
3582
+ schema: SubmitProjectResponseSchema
3583
+ });
3584
+ }
3585
+ async unpublish({ projectGroupId }) {
3586
+ return this.request({
3587
+ method: "POST",
3588
+ path: `/projects/${projectGroupId}/unpublish`,
3589
+ schema: UnpublishResponseSchema
3590
+ });
3591
+ }
3592
+ async uploadAsset({ projectGroupId, filePath, name }) {
3593
+ const url = `${this.baseUrl}/projects/${projectGroupId}/assets`;
3594
+ let fileBuffer;
3595
+ try {
3596
+ const { readFileSync } = await import("node:fs");
3597
+ fileBuffer = readFileSync(filePath);
3598
+ } catch (cause) {
3599
+ return err({
3600
+ message: `Failed to read file: ${cause instanceof Error ? cause.message : String(cause)}`,
3601
+ status: null
3602
+ });
3546
3603
  }
3547
- const lfIndex = string.indexOf("\n");
3548
- if (lfIndex !== -1) string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
3549
- return openAll + string + closeAll;
3550
- };
3551
- let template;
3552
- const chalkTag = (chalk, ...strings) => {
3553
- const [firstString] = strings;
3554
- if (!isArray(firstString) || !isArray(firstString.raw)) return strings.join(" ");
3555
- const arguments_ = strings.slice(1);
3556
- const parts = [firstString.raw[0]];
3557
- for (let i = 1; i < firstString.length; i++) parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, "\\$&"), String(firstString.raw[i]));
3558
- if (template === void 0) template = require_templates();
3559
- return template(chalk, parts.join(""));
3560
- };
3561
- Object.defineProperties(Chalk.prototype, styles);
3562
- const chalk = Chalk();
3563
- chalk.supportsColor = stdoutColor;
3564
- chalk.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 });
3565
- chalk.stderr.supportsColor = stderrColor;
3566
- module.exports = chalk;
3567
- }));
3568
-
3569
- //#endregion
3570
- //#region ../../packages/env/dist/js/index.node.cjs
3571
- var require_index_node = /* @__PURE__ */ __commonJSMin(((exports) => {
3572
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3573
- var __create = Object.create;
3574
- var __defProp = Object.defineProperty;
3575
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3576
- var __getOwnPropNames = Object.getOwnPropertyNames;
3577
- var __getProtoOf = Object.getPrototypeOf;
3578
- var __hasOwnProp = Object.prototype.hasOwnProperty;
3579
- var __copyProps = (to, from, except, desc) => {
3580
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
3581
- key = keys[i];
3582
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
3583
- get: ((k) => from[k]).bind(null, key),
3584
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
3604
+ const fileName = basename(filePath);
3605
+ const formData = new FormData();
3606
+ formData.append("file", new Blob([new Uint8Array(fileBuffer)]), fileName);
3607
+ if (name !== null) formData.append("name", name);
3608
+ let response;
3609
+ try {
3610
+ response = await fetch(url, {
3611
+ method: "POST",
3612
+ headers: {
3613
+ authorization: this.authHeader,
3614
+ "user-agent": USER_AGENT
3615
+ },
3616
+ body: formData
3617
+ });
3618
+ } catch (cause) {
3619
+ return err({
3620
+ message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,
3621
+ status: null
3585
3622
  });
3586
3623
  }
3587
- return to;
3588
- };
3589
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
3590
- value: mod,
3591
- enumerable: true
3592
- }) : target, mod));
3593
- let dotenv_flow = require_dotenv_flow();
3594
- let zod = __require("zod");
3595
- let chalk = require_source();
3596
- chalk = __toESM(chalk);
3597
- function defineEnv(schemaOrShape, options) {
3598
- const schema = isZodType(schemaOrShape) ? schemaOrShape : zod.z.object(schemaOrShape);
3599
- const keys = extractKeys(schemaOrShape);
3600
- const envSource = options?.env ?? process.env;
3601
- const cleanedInput = {};
3602
- for (const key of keys) cleanedInput[key] = envSource[key];
3603
- if (options?.skipValidation) return cleanedInput;
3604
- const parsed = schema.safeParse(cleanedInput);
3605
- const { DISABLE_ENV_VALIDATION } = process.env;
3606
- if (parsed.success === false) {
3607
- if (!DISABLE_ENV_VALIDATION) throw new Error(`Invalid environment variables:\n${parsed.error.errors.map((error) => `❌ ${chalk.default.red(error.message)}: ${error.path}`).join("\n")}`);
3608
- return cleanedInput;
3624
+ if (!response.ok) {
3625
+ const text = await response.text().catch(() => "");
3626
+ let details;
3627
+ try {
3628
+ details = JSON.parse(text);
3629
+ } catch {
3630
+ details = text || void 0;
3631
+ }
3632
+ const retryAfter = parseRetryAfter(response);
3633
+ return err({
3634
+ message: `API error (${response.status})`,
3635
+ status: response.status,
3636
+ details,
3637
+ ...retryAfter !== null ? { retryAfter } : {}
3638
+ });
3609
3639
  }
3610
- return parsed.data;
3640
+ const json = await response.json();
3641
+ const parsed = UploadAssetResponseSchema.safeParse(json);
3642
+ if (!parsed.success) return err({
3643
+ message: "Unexpected API response format",
3644
+ status: response.status,
3645
+ details: parsed.error.errors
3646
+ });
3647
+ return ok(parsed.data);
3611
3648
  }
3612
- function isZodType(value) {
3613
- return value instanceof zod.z.ZodType;
3649
+ async listAssets({ projectGroupId, query, limit, offset }) {
3650
+ const params = new URLSearchParams();
3651
+ if (query !== null) params.set("query", query);
3652
+ if (limit !== null) params.set("limit", String(limit));
3653
+ if (offset !== null) params.set("offset", String(offset));
3654
+ const qs = params.toString();
3655
+ const path = `/projects/${projectGroupId}/assets${qs ? `?${qs}` : ""}`;
3656
+ return this.request({
3657
+ method: "GET",
3658
+ path,
3659
+ schema: ListAssetsResponseSchema
3660
+ });
3614
3661
  }
3615
- /**
3616
- * Extract all possible env var keys from either a raw shape or a Zod schema.
3617
- * For discriminated unions, this collects keys across all variants so that
3618
- * every potentially-needed variable is picked from `process.env`.
3619
- */
3620
- function extractKeys(schemaOrShape) {
3621
- if (!isZodType(schemaOrShape)) return Object.keys(schemaOrShape);
3622
- return extractKeysFromSchema(schemaOrShape);
3662
+ async listDomains({ organizationId }) {
3663
+ const params = new URLSearchParams({ organizationId });
3664
+ return this.request({
3665
+ method: "GET",
3666
+ path: `/domains?${params.toString()}`,
3667
+ schema: ListDomainsResponseSchema
3668
+ });
3669
+ }
3670
+ async deleteAsset({ projectGroupId, assetId }) {
3671
+ return this.request({
3672
+ method: "DELETE",
3673
+ path: `/projects/${projectGroupId}/assets/${assetId}`
3674
+ });
3675
+ }
3676
+ async getDatabase({ databaseId }) {
3677
+ return this.request({
3678
+ method: "GET",
3679
+ path: `/databases/${databaseId}`,
3680
+ schema: DatabaseDetailResponseSchema
3681
+ });
3682
+ }
3683
+ async createDatabase({ organizationId, projectGroupId, name }) {
3684
+ return this.request({
3685
+ method: "POST",
3686
+ path: "/databases",
3687
+ body: {
3688
+ organizationId,
3689
+ ...projectGroupId !== null ? { projectGroupId } : {},
3690
+ ...name !== null ? { name } : {}
3691
+ },
3692
+ schema: CreateDatabaseResponseSchema
3693
+ });
3694
+ }
3695
+ async queryDatabase({ databaseId, sql }) {
3696
+ return this.request({
3697
+ method: "POST",
3698
+ path: `/databases/${databaseId}/query`,
3699
+ body: { sql },
3700
+ schema: DatabaseQueryResultSchema
3701
+ });
3702
+ }
3703
+ async getDatabaseConnection({ databaseId }) {
3704
+ return this.request({
3705
+ method: "GET",
3706
+ path: `/databases/${databaseId}/connection`,
3707
+ schema: DatabaseConnectionResponseSchema
3708
+ });
3709
+ }
3710
+ async resetDatabase({ databaseId }) {
3711
+ return this.request({
3712
+ method: "POST",
3713
+ path: `/databases/${databaseId}/reset`
3714
+ });
3715
+ }
3716
+ async addDomain({ organizationId, domain, projectGroupId }) {
3717
+ return this.request({
3718
+ method: "POST",
3719
+ path: "/domains",
3720
+ body: {
3721
+ organizationId,
3722
+ domain,
3723
+ ...projectGroupId !== null ? { projectGroupId } : {}
3724
+ },
3725
+ schema: AddDomainResponseSchema
3726
+ });
3727
+ }
3728
+ async removeDomain({ domainId }) {
3729
+ return this.request({
3730
+ method: "DELETE",
3731
+ path: `/domains/${domainId}`
3732
+ });
3733
+ }
3734
+ async verifyDomain({ domainId }) {
3735
+ return this.request({
3736
+ method: "POST",
3737
+ path: `/domains/${domainId}/verify`,
3738
+ schema: DomainVerificationSchema
3739
+ });
3740
+ }
3741
+ async listDeployments({ projectGroupId, limit }) {
3742
+ const params = new URLSearchParams();
3743
+ if (limit !== null) params.set("limit", String(limit));
3744
+ const query = params.toString();
3745
+ const path = `/projects/${projectGroupId}/deployments${query ? `?${query}` : ""}`;
3746
+ return this.request({
3747
+ method: "GET",
3748
+ path,
3749
+ schema: ListDeploymentsResponseSchema
3750
+ });
3751
+ }
3752
+ async getDeployment({ deploymentId }) {
3753
+ return this.request({
3754
+ method: "GET",
3755
+ path: `/deployments/${deploymentId}`,
3756
+ schema: DeploymentDetailResponseSchema
3757
+ });
3758
+ }
3759
+ async getDeploymentLogs({ deploymentId }) {
3760
+ return this.request({
3761
+ method: "GET",
3762
+ path: `/deployments/${deploymentId}/logs`,
3763
+ schema: DeploymentLogsResponseSchema
3764
+ });
3765
+ }
3766
+ async rollbackDeployment({ projectGroupId, deploymentId }) {
3767
+ return this.request({
3768
+ method: "POST",
3769
+ path: `/projects/${projectGroupId}/deployments/rollback`,
3770
+ body: deploymentId !== null ? { deploymentId } : {},
3771
+ schema: RollbackResponseSchema
3772
+ });
3773
+ }
3774
+ async inviteMember({ organizationId, email, role }) {
3775
+ return this.request({
3776
+ method: "POST",
3777
+ path: `/organizations/${organizationId}/invites`,
3778
+ body: {
3779
+ email,
3780
+ ...role !== null ? { role } : {}
3781
+ },
3782
+ schema: InviteMemberResponseSchema
3783
+ });
3623
3784
  }
3624
- function extractKeysFromSchema(schema) {
3625
- const keys = /* @__PURE__ */ new Set();
3626
- if (schema instanceof zod.z.ZodObject) {
3627
- const shape = schema.shape;
3628
- for (const key of Object.keys(shape)) keys.add(key);
3629
- } else if (schema instanceof zod.z.ZodDiscriminatedUnion) {
3630
- const union = schema;
3631
- for (const option of union.options) for (const key of extractKeysFromSchema(option)) keys.add(key);
3632
- } else if (schema instanceof zod.z.ZodUnion) {
3633
- const union = schema;
3634
- for (const option of union.options) for (const key of extractKeysFromSchema(option)) keys.add(key);
3635
- } else if (schema instanceof zod.z.ZodIntersection) {
3636
- for (const key of extractKeysFromSchema(schema._def.left)) keys.add(key);
3637
- for (const key of extractKeysFromSchema(schema._def.right)) keys.add(key);
3638
- } else if (schema instanceof zod.z.ZodEffects) for (const key of extractKeysFromSchema(schema.innerType())) keys.add(key);
3639
- return [...keys];
3785
+ async removeMember({ organizationId, email }) {
3786
+ return this.request({
3787
+ method: "POST",
3788
+ path: `/organizations/${organizationId}/members/remove`,
3789
+ body: { email },
3790
+ schema: RemoveMemberResponseSchema
3791
+ });
3640
3792
  }
3641
- function coerceBoolean(input) {
3642
- if (!input) return false;
3643
- const x = String(input).toLowerCase();
3644
- return x === "true" || x === "1" || x === "yes" || x === "t";
3793
+ async updateMemberRole({ organizationId, email, role }) {
3794
+ return this.request({
3795
+ method: "POST",
3796
+ path: `/organizations/${organizationId}/members/role`,
3797
+ body: {
3798
+ email,
3799
+ role
3800
+ },
3801
+ schema: UpdateMemberRoleResponseSchema
3802
+ });
3645
3803
  }
3646
- const looseBoolean = () => zod.z.preprocess(coerceBoolean, zod.z.boolean());
3647
- (0, dotenv_flow.config)({ silent: true });
3648
- exports.coerceBoolean = coerceBoolean;
3649
- exports.defineEnv = defineEnv;
3650
- exports.looseBoolean = looseBoolean;
3651
- Object.keys(zod).forEach(function(k) {
3652
- if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
3653
- enumerable: true,
3654
- get: function() {
3655
- return zod[k];
3804
+ async request(params) {
3805
+ const url = `${this.baseUrl}${params.path}`;
3806
+ let response;
3807
+ try {
3808
+ response = await fetch(url, {
3809
+ method: params.method,
3810
+ headers: {
3811
+ authorization: this.authHeader,
3812
+ "user-agent": USER_AGENT,
3813
+ ...params.body ? { "Content-Type": "application/json" } : {}
3814
+ },
3815
+ ...params.body ? { body: JSON.stringify(params.body) } : {}
3816
+ });
3817
+ } catch (cause) {
3818
+ return err({
3819
+ message: `Network error: ${cause instanceof Error ? cause.message : String(cause)}`,
3820
+ status: null
3821
+ });
3822
+ }
3823
+ if (!response.ok) {
3824
+ const text = await response.text().catch(() => "");
3825
+ let details;
3826
+ try {
3827
+ details = JSON.parse(text);
3828
+ } catch {
3829
+ details = text || void 0;
3656
3830
  }
3831
+ const retryAfter = parseRetryAfter(response);
3832
+ return err({
3833
+ message: `API error (${response.status})`,
3834
+ status: response.status,
3835
+ details,
3836
+ ...retryAfter !== null ? { retryAfter } : {}
3837
+ });
3838
+ }
3839
+ if (response.status === 204 || !params.schema) return ok(void 0);
3840
+ const json = await response.json();
3841
+ const parsed = params.schema.safeParse(json);
3842
+ if (!parsed.success) return err({
3843
+ message: "Unexpected API response format",
3844
+ status: response.status,
3845
+ details: parsed.error.errors
3657
3846
  });
3658
- });
3659
- }));
3660
-
3661
- //#endregion
3662
- //#region src/env.ts
3663
- var import_index_node = require_index_node();
3664
- const env = (0, import_index_node.defineEnv)({
3665
- ANYTHING_API_KEY: (0, import_index_node.string)().optional(),
3666
- ANYTHING_API_URL: (0, import_index_node.string)().optional(),
3667
- ANYTHING_WEB_URL: (0, import_index_node.string)().optional()
3668
- });
3669
-
3670
- //#endregion
3671
- //#region src/config.ts
3672
- const DEFAULT_API_URL = "https://api.anything.com";
3673
- const DEV_API_BASE_PORT = 8002;
3674
- const DEV_PORT_OFFSET = 100;
3675
- const DEV_API_URL = `http://localhost:${DEV_API_BASE_PORT}`;
3676
- const DEV_WEB_URL = "http://localhost:3000";
3677
- function branchToEnvName(branch) {
3678
- if (branch === "main" || branch === "master") return "default";
3679
- return branch.replace(/[^a-zA-Z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-/, "").replace(/-$/, "");
3680
- }
3681
- function git(command) {
3682
- return execSync(command, {
3683
- encoding: "utf-8",
3684
- stdio: [
3685
- "pipe",
3686
- "pipe",
3687
- "ignore"
3688
- ]
3689
- }).trim();
3690
- }
3691
- function detectDevApiUrl() {
3692
- try {
3693
- const envName = branchToEnvName(git("git rev-parse --abbrev-ref HEAD"));
3694
- if (envName === "default") return DEV_API_URL;
3695
- const commonDir = git("git rev-parse --git-common-dir");
3696
- const mainRepoDir = path.dirname(path.resolve(process.cwd(), commonDir));
3697
- const slotFile = path.join(mainRepoDir, ".anything", `${envName}.slot`);
3698
- if (!fs.existsSync(slotFile)) return null;
3699
- const slot = Number.parseInt(fs.readFileSync(slotFile, "utf-8").trim(), 10);
3700
- if (Number.isNaN(slot)) return null;
3701
- return `http://localhost:${DEV_API_BASE_PORT + slot * DEV_PORT_OFFSET}`;
3702
- } catch {
3703
- return null;
3847
+ return ok(parsed.data);
3704
3848
  }
3705
- }
3706
- const store = new Conf({
3707
- projectName: "anything",
3708
- projectSuffix: "",
3709
- configFileMode: 384
3710
- });
3711
- function resolveApiUrl({ dev, apiUrl: apiUrlFlag }) {
3712
- return env.ANYTHING_API_URL ?? apiUrlFlag ?? store.get("apiUrl") ?? (dev ? detectDevApiUrl() ?? DEV_API_URL : DEFAULT_API_URL);
3713
- }
3714
- function resolveConfig({ dev, apiUrl: apiUrlFlag }) {
3715
- const apiKey = env.ANYTHING_API_KEY ?? store.get("apiKey");
3716
- const apiUrl = resolveApiUrl({
3717
- dev,
3718
- apiUrl: apiUrlFlag
3719
- });
3720
- if (!apiKey) return err({ message: "Not logged in. Run `anything auth login` to authenticate." });
3721
- return ok({
3722
- apiKey,
3723
- apiUrl
3724
- });
3725
- }
3726
- function saveConfig(config) {
3727
- store.set("apiKey", config.apiKey);
3728
- store.set("apiUrl", config.apiUrl);
3729
- }
3730
- function deleteConfig() {
3731
- store.clear();
3732
- }
3733
- function configExists() {
3734
- return store.has("apiKey");
3735
- }
3736
- function getConfigPath() {
3737
- return store.path;
3738
- }
3739
- function getStoredOrgId() {
3740
- return store.get("orgId") || void 0;
3741
- }
3742
- function setStoredOrgId(orgId) {
3743
- store.set("orgId", orgId);
3744
- }
3745
- function clearStoredOrgId() {
3746
- store.delete("orgId");
3747
- }
3748
- function getStoredProjectGroupId() {
3749
- return store.get("projectGroupId") || void 0;
3750
- }
3751
- function setStoredProjectGroupId(projectGroupId) {
3752
- store.set("projectGroupId", projectGroupId);
3753
- }
3754
- function clearStoredProjectGroupId() {
3755
- store.delete("projectGroupId");
3756
- }
3757
-
3758
- //#endregion
3759
- //#region src/exit-codes.ts
3760
- const EXIT_ERROR = 1;
3761
- const EXIT_INVALID_ARGS = 2;
3762
- const EXIT_NOT_FOUND = 3;
3763
- const EXIT_AUTH_FAILURE = 4;
3764
- const EXIT_CONFLICT = 5;
3765
- const EXIT_TIMEOUT = 6;
3766
- const EXIT_SERVER_ERROR = 7;
3767
- const EXIT_RATE_LIMITED = 8;
3768
- function exitCodeFromHttpStatus(status) {
3769
- if (status === null) return EXIT_ERROR;
3770
- if (status === 401 || status === 403) return EXIT_AUTH_FAILURE;
3771
- if (status === 404) return EXIT_NOT_FOUND;
3772
- if (status === 409) return EXIT_CONFLICT;
3773
- if (status === 408 || status === 504) return EXIT_TIMEOUT;
3774
- if (status === 429) return EXIT_RATE_LIMITED;
3775
- if (status >= 500) return EXIT_SERVER_ERROR;
3776
- if (status === 422 || status === 400) return EXIT_INVALID_ARGS;
3777
- return EXIT_ERROR;
3778
- }
3779
- function errorCodeFromHttpStatus(status) {
3780
- if (status === null) return "NETWORK_ERROR";
3781
- if (status === 401) return "AUTH_FAILURE";
3782
- if (status === 403) return "FORBIDDEN";
3783
- if (status === 404) return "NOT_FOUND";
3784
- if (status === 409) return "CONFLICT";
3785
- if (status === 408 || status === 504) return "TIMEOUT";
3786
- if (status === 429) return "RATE_LIMITED";
3787
- if (status >= 500) return "SERVER_ERROR";
3788
- if (status === 422) return "VALIDATION_ERROR";
3789
- if (status === 400) return "BAD_REQUEST";
3790
- return "ERROR";
3791
- }
3849
+ };
3792
3850
 
3793
3851
  //#endregion
3794
3852
  //#region src/output.ts
@@ -4139,6 +4197,40 @@ const assetsCommand = {
4139
4197
  handler: () => {}
4140
4198
  };
4141
4199
 
4200
+ //#endregion
4201
+ //#region src/commands/dev.ts
4202
+ const COMMAND$24 = "dev";
4203
+ const devCommand = {
4204
+ command: "dev [state]",
4205
+ describe: "Toggle local dev mode so commands target your local dev stack",
4206
+ builder: (yargs) => yargs.positional("state", {
4207
+ choices: [
4208
+ "on",
4209
+ "off",
4210
+ "status"
4211
+ ],
4212
+ default: "status",
4213
+ describe: "Turn dev mode on/off, or show the current state"
4214
+ }).example("anything dev on", "Point every command at your local dev stack").example("anything dev off", "Switch back to production").example("anything dev", "Show whether dev mode is on"),
4215
+ handler: (argv) => {
4216
+ if (argv.state === "on") setDevMode(true);
4217
+ else if (argv.state === "off") setDevMode(false);
4218
+ const enabled = getDevMode();
4219
+ const apiUrl = resolveApiUrl({ apiUrl: argv.apiUrl });
4220
+ if (outputSuccess({
4221
+ argv,
4222
+ command: COMMAND$24,
4223
+ data: {
4224
+ devMode: enabled,
4225
+ apiUrl
4226
+ }
4227
+ })) return;
4228
+ printSuccess(`Dev mode ${enabled ? "ON" : "OFF"}`);
4229
+ printLabel("API URL", apiUrl);
4230
+ if (enabled) printLabel("Note", "Dev mode uses a separate login — run `anything auth login` to authenticate against local dev.");
4231
+ }
4232
+ };
4233
+
4142
4234
  //#endregion
4143
4235
  //#region src/input.ts
4144
4236
  async function readStdin() {
@@ -4206,6 +4298,10 @@ const StartCliAuthResponseSchema = z.object({
4206
4298
  code: z.string(),
4207
4299
  pollingId: z.string()
4208
4300
  });
4301
+ const ErrorResponseSchema = z.object({
4302
+ error: z.string(),
4303
+ retryAfter: z.number().optional()
4304
+ });
4209
4305
  const PollResponseSchema = z.object({
4210
4306
  ok: z.boolean(),
4211
4307
  status: z.string().optional(),
@@ -4295,10 +4391,21 @@ async function startCliAuth({ apiUrl }) {
4295
4391
  method: "POST",
4296
4392
  headers: { "user-agent": USER_AGENT }
4297
4393
  });
4298
- if (!response.ok) return {
4299
- ok: false,
4300
- error: `Failed to start auth (${response.status})`
4301
- };
4394
+ if (!response.ok) {
4395
+ const body = await response.json().catch(() => null);
4396
+ const parsed = ErrorResponseSchema.safeParse(body);
4397
+ if (parsed.success) {
4398
+ const retry = parsed.data.retryAfter ? ` Try again in ${parsed.data.retryAfter}s.` : "";
4399
+ return {
4400
+ ok: false,
4401
+ error: `Failed to start auth (${response.status}): ${parsed.data.error}${retry}`
4402
+ };
4403
+ }
4404
+ return {
4405
+ ok: false,
4406
+ error: `Failed to start auth (${response.status})`
4407
+ };
4408
+ }
4302
4409
  const json = await response.json();
4303
4410
  const parsed = StartCliAuthResponseSchema.safeParse(json);
4304
4411
  if (!parsed.success) return {
@@ -4316,6 +4423,12 @@ async function pollForApiKey({ apiUrl, pollingId }) {
4316
4423
  await setTimeout$1(POLL_INTERVAL_MS$1);
4317
4424
  const response = await fetch(`${apiUrl}/v0/auth/cli/poll?id=${encodeURIComponent(pollingId)}`, { headers: { "user-agent": USER_AGENT } }).catch(() => null);
4318
4425
  if (!response) continue;
4426
+ if (response.status === 429) {
4427
+ const body = await response.json().catch(() => null);
4428
+ const parsed = ErrorResponseSchema.safeParse(body);
4429
+ if (parsed.success && parsed.data.retryAfter) await setTimeout$1(parsed.data.retryAfter * 1e3);
4430
+ continue;
4431
+ }
4319
4432
  const json = await response.json().catch(() => null);
4320
4433
  if (!json) continue;
4321
4434
  const parsed = PollResponseSchema.safeParse(json);
@@ -4342,7 +4455,7 @@ const login = {
4342
4455
  describe: "API key for non-interactive login"
4343
4456
  }).example("anything auth login", "Open the browser-based login flow").example("anything auth login --api-key anything_...", "Store an API key directly").example("anything auth login --dev", "Use local dev auto-login"),
4344
4457
  handler: async (argv) => {
4345
- const isDev = argv.dev === true;
4458
+ const isDev = argv.dev === true || isDevModeActive();
4346
4459
  const apiUrl = resolveApiUrl({
4347
4460
  dev: isDev,
4348
4461
  apiUrl: argv.apiUrl
@@ -4437,16 +4550,20 @@ const login = {
4437
4550
  return;
4438
4551
  }
4439
4552
  const loginUrl = `${(env.ANYTHING_WEB_URL ?? (isDev ? DEV_WEB_URL : DEFAULT_WEB_URL)).replace(/\/$/, "")}/auth/cli?code=${startResult.code}`;
4553
+ const skipBrowser = Boolean(env.ANYTHING_NO_BROWSER);
4440
4554
  if (!argv.json) {
4441
4555
  console.log();
4442
4556
  console.log(` Your code: ${startResult.code}`);
4443
4557
  console.log();
4444
- console.log(" Opening browser to confirm...");
4445
- console.log(` If the browser doesn't open, visit: ${loginUrl}`);
4558
+ if (skipBrowser) console.log(` Visit this URL to confirm: ${loginUrl}`);
4559
+ else {
4560
+ console.log(" Opening browser to confirm...");
4561
+ console.log(` If the browser doesn't open, visit: ${loginUrl}`);
4562
+ }
4446
4563
  console.log();
4447
4564
  console.log(" Waiting for confirmation...");
4448
4565
  }
4449
- openBrowser(loginUrl);
4566
+ if (!skipBrowser) openBrowser(loginUrl);
4450
4567
  const pollResult = await pollForApiKey({
4451
4568
  apiUrl,
4452
4569
  pollingId: startResult.pollingId
@@ -10593,6 +10710,72 @@ const userCommand = {
10593
10710
  }
10594
10711
  };
10595
10712
 
10713
+ //#endregion
10714
+ //#region src/update-check.ts
10715
+ const PACKAGE_NAME = "@anythingai/cli";
10716
+ const REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
10717
+ const CHECK_INTERVAL_MS = 1440 * 60 * 1e3;
10718
+ const FETCH_TIMEOUT_MS = 1500;
10719
+ const latestManifestSchema = z.object({ version: z.string() });
10720
+ function isNewerVersion(candidate, current) {
10721
+ const core = (v) => (v.split("-")[0] ?? "").split(".").map((part) => Number.parseInt(part, 10));
10722
+ const a = core(candidate);
10723
+ const b = core(current);
10724
+ if ([...a, ...b].some(Number.isNaN)) return false;
10725
+ for (let i = 0; i < 3; i++) {
10726
+ const left = a[i] ?? 0;
10727
+ const right = b[i] ?? 0;
10728
+ if (left !== right) return left > right;
10729
+ }
10730
+ return false;
10731
+ }
10732
+ async function fetchLatestVersion() {
10733
+ try {
10734
+ const response = await fetch(REGISTRY_URL, {
10735
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
10736
+ headers: { accept: "application/json" }
10737
+ });
10738
+ if (!response.ok) return null;
10739
+ const parsed = latestManifestSchema.safeParse(await response.json());
10740
+ return parsed.success ? parsed.data.version : null;
10741
+ } catch {
10742
+ return null;
10743
+ }
10744
+ }
10745
+ function printUpdateNotice({ current, latest }) {
10746
+ console.error([
10747
+ "",
10748
+ styleText("yellow", `Update available for ${PACKAGE_NAME}: ${current} → ${latest}`),
10749
+ styleText("dim", `Run \`npm install -g ${PACKAGE_NAME}@latest\` to update.`),
10750
+ ""
10751
+ ].join("\n"));
10752
+ }
10753
+ async function notifyIfUpdateAvailable(now) {
10754
+ const state = getUpdateCheckState();
10755
+ let latest = state.latestKnownVersion;
10756
+ if (state.checkedAt === null || now - state.checkedAt >= CHECK_INTERVAL_MS) {
10757
+ const fetched = await fetchLatestVersion();
10758
+ recordUpdateCheck({
10759
+ checkedAt: now,
10760
+ latestVersion: fetched
10761
+ });
10762
+ if (fetched) latest = fetched;
10763
+ }
10764
+ if (!latest || !isNewerVersion(latest, CLI_VERSION)) return;
10765
+ if (state.notifiedVersion === latest) return;
10766
+ printUpdateNotice({
10767
+ current: CLI_VERSION,
10768
+ latest
10769
+ });
10770
+ recordUpdateNotified(latest);
10771
+ }
10772
+ async function maybeNotifyUpdate(argv, now) {
10773
+ if (argv.json || argv.quiet) return;
10774
+ if (isNonInteractive(argv)) return;
10775
+ if (!process.stderr.isTTY) return;
10776
+ await notifyIfUpdateAvailable(now);
10777
+ }
10778
+
10596
10779
  //#endregion
10597
10780
  //#region src/commands/watch.ts
10598
10781
  const IDLE_TIMEOUT_MS = 300 * 1e3;
@@ -10741,7 +10924,7 @@ const watchCommand = {
10741
10924
  //#endregion
10742
10925
  //#region src/cli.ts
10743
10926
  function createCli(argv) {
10744
- return yargs(argv).scriptName("anything").usage("$0 <command> [options]").example("anything auth login", "Log in via browser").example("anything ship --prompt \"Build a todo app\"", "Create + publish in one shot").example("anything domains list org_123", "List domains for one organization").example("anything orgs", "List your organizations").example("anything orgs get <org-id>", "Inspect one organization").example("anything orgs set <org-id>", "Set the active organization").example("anything orgs members <org-id>", "Inspect collaborators and pending invites").example("anything projects create --prompt todo-app", "Create a new app").example("anything projects generate <project-id> --prompt add-auth", "Iterate on an existing app").example("anything projects publish <project-id> --slug my-app", "Publish an app").example("anything projects get <project-id> --json", "Inspect an app in JSON").example("anything projects rename <project-id> --name \"My App\"", "Rename a project").example("anything databases list --org <org-id>", "List databases for an organization").example("anything deployments list <project-id>", "List deployments for a project").example("anything members invite user@example.com --org org_123", "Invite a member").example("anything status", "Show current context").example("anything switch", "Interactive org/project picker").example("anything introspect", "Output command tree as JSON").option("json", {
10927
+ const cli = yargs(argv).scriptName("anything").usage("$0 <command> [options]").example("anything auth login", "Log in via browser").example("anything ship --prompt \"Build a todo app\"", "Create + publish in one shot").example("anything domains list org_123", "List domains for one organization").example("anything orgs", "List your organizations").example("anything orgs get <org-id>", "Inspect one organization").example("anything orgs set <org-id>", "Set the active organization").example("anything orgs members <org-id>", "Inspect collaborators and pending invites").example("anything projects create --prompt todo-app", "Create a new app").example("anything projects generate <project-id> --prompt add-auth", "Iterate on an existing app").example("anything projects publish <project-id> --slug my-app", "Publish an app").example("anything projects get <project-id> --json", "Inspect an app in JSON").example("anything projects rename <project-id> --name \"My App\"", "Rename a project").example("anything databases list --org <org-id>", "List databases for an organization").example("anything deployments list <project-id>", "List deployments for a project").example("anything members invite user@example.com --org org_123", "Invite a member").example("anything status", "Show current context").example("anything switch", "Interactive org/project picker").example("anything introspect", "Output command tree as JSON").option("json", {
10745
10928
  type: "boolean",
10746
10929
  default: false,
10747
10930
  describe: "Output as JSON envelope: { ok, command, data }",
@@ -10775,7 +10958,27 @@ function createCli(argv) {
10775
10958
  type: "string",
10776
10959
  description: "Override the API base URL",
10777
10960
  global: true
10778
- }).command(assetsCommand).command(authCommand).command(databasesCommand).command(deploymentsCommand).command(domainsCommand).command(introspectCommand).command(linkCommand).command(llmContextCommand).command(membersCommand).command(orgsCommand).command(projectsCommand).command(pullCommand).command(shipCommand).command(skillCommand).command(statusCommand).command(switchCommand).command(unlinkCommand).command(userCommand).command(watchCommand).demandCommand(1, "Specify a command. Run --help for usage.").strict().wrap(null).version(CLI_VERSION).help().exitProcess(false);
10961
+ }).middleware(async (args) => {
10962
+ setDevFlagOverride(args.dev === true);
10963
+ await maybeNotifyUpdate({
10964
+ json: args.json === true,
10965
+ quiet: args.quiet === true,
10966
+ "non-interactive": args["non-interactive"] === true,
10967
+ "dry-run": args["dry-run"] === true,
10968
+ dev: args.dev === true
10969
+ }, Date.now());
10970
+ }).command(assetsCommand).command(authCommand).command(databasesCommand).command(deploymentsCommand).command(domainsCommand).command(introspectCommand).command(linkCommand).command(llmContextCommand).command(membersCommand).command(orgsCommand).command(projectsCommand).command(pullCommand).command(shipCommand).command(skillCommand).command(statusCommand).command(switchCommand).command(unlinkCommand).command(userCommand).command(watchCommand).demandCommand(1, "Specify a command. Run --help for usage.").strict().wrap(null).version(CLI_VERSION).help().fail((msg, err, instance) => {
10971
+ if (err) {
10972
+ console.error(err.message || String(err));
10973
+ process.exitCode = EXIT_ERROR;
10974
+ return;
10975
+ }
10976
+ instance.showHelp("error");
10977
+ console.error(`\n${msg}`);
10978
+ process.exitCode = EXIT_INVALID_ARGS;
10979
+ }).exitProcess(false);
10980
+ if (isDevEnvironment()) cli.command(devCommand);
10981
+ return cli;
10779
10982
  }
10780
10983
 
10781
10984
  //#endregion