dotsec 4.0.0-alpha.4 → 4.0.0-alpha.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,4 +1,445 @@
1
- var je=Object.create;var J=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,He=Object.prototype.hasOwnProperty;var Le=(n,o,a,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let e of Ae(o))!He.call(n,e)&&e!==a&&J(n,e,{get:()=>o[e],enumerable:!(t=Ve(o,e))||t.enumerable});return n};var w=(n,o,a)=>(a=n!=null?je(ke(n)):{},Le(o||!n||!n.__esModule?J(a,"default",{value:n,enumerable:!0}):a,n));var Te=require("commander");var Re="dotsec.config.ts",B=[Re],q=".sec",G=".env",_={defaults:{}};var Y=w(require("fs")),z=w(require("path"));function Me(n){try{return new Function(`return ${n.trim()}`)()}catch{return{}}}var Q=async n=>{try{return Me(await Y.default.promises.readFile(n,"utf8"))}catch(o){throw o instanceof Error?new Error(`Failed to parse ${z.default.relative(process.cwd(),n)}: ${o.message}`):o}};var X=require("bundle-require"),Z=w(require("joycon")),ee=w(require("path")),ne=async n=>{let o=process.cwd(),t=await new Z.default().resolve({files:n?[n]:[...B,"package.json"],cwd:o,stopDir:ee.default.parse(o).root,packageKey:"dotsec"});if(n&&t===null)throw new Error(`Could not find config file ${n}`);if(t){if(t.endsWith(".json")){let e=await Q(t),i;return t.endsWith("package.json")&&e.dotsec!==void 0?i=e.dotsec:i=e,{source:"json",contents:{..._,...i,defaults:{...i?.defaults,..._.defaults,plugins:{...i?.defaults?.plugins,..._.defaults?.plugins}},push:{...i?.push}}}}else if(t.endsWith(".ts")){let e=await(0,X.bundleRequire)({filepath:t}),i=e.mod.dotsec||e.mod.default||e.mod;return{source:"ts",contents:{..._,...i,defaults:{...i?.defaults,..._.defaults,plugins:{...i?.defaults?.plugins,..._.defaults?.plugins}},push:{...i?.push}}}}}return{source:"defaultConfig",contents:_}};var W=async n=>import(n.name).then(o=>o.default);var te=require("commander"),x=(n,o,a)=>{n&&Object.values(n).map(t=>{let e;if(Array.isArray(t)){let[i,c,l]=t;e={flags:i,description:c,defaultValue:l}}else{let{flags:i,description:c,defaultValue:l,choices:s,env:r,fn:f}=t;e={flags:i,description:c,defaultValue:l,choices:s,env:r,fn:f}}if(e){let i=new te.Option(e.flags,e.description);e.fn&&i.argParser(e.fn),e.defaultValue&&i.default(e.defaultValue),e.env&&i.env(e.env),a&&i.makeOptionMandatory(!0),e.choices&&i.choices(e.choices),o.addOption(i)}})};var k=w(require("fs/promises")),oe=w(require("path")),ie=w(require("prompts")),V=async n=>await k.default.readFile(n,"utf-8"),I=async(n,o)=>await k.default.writeFile(n,o,"utf-8"),qe=async n=>{try{return await(0,k.stat)(n),!0}catch{return!1}},A=async({filePath:n,skip:o})=>{let a;return await qe(n)&&o!==!0?a=await(0,ie.default)({type:"confirm",name:"overwrite",message:()=>`Overwrite './${oe.default.relative(process.cwd(),n)}' ?`}):a=void 0,a};var re=w(require("chalk")),Ge=w(require("cli-table"));var C=n=>re.default.yellow.bold(n);var ye=require("commander");var S={option:["--env-file <envFile>",`Path to .env file. If not provided, will look for value in 'ENV_FILE' environment variable. If not provided, will look for '${G}' file in current directory.`,G],env:"ENV_FILE"},N={option:["--sec-file, <secFile>",`Path to .sec file. If not provided, will look for value in 'SEC_FILE' environment variable. If not provided, will look for '${q}' file in current directory.`,q],env:"SEC_FILE"},L={flags:"--using <using>",description:"Wether to use a dot env file or a dot sec file",choices:["env","sec"],env:"DOTSEC_USING"},se={flags:"--using <using>",description:"Wether to use a dot env file or a dot sec file",choices:["env"],env:"DOTSEC_USING"},$={option:["--yes","Skip confirmation prompts"]};var F={option:["-c, --config-file, --configFile <configFile>","Config file"],env:"DOTSEC_CONFIG_FILE"},ae={option:["--plugin <plugin>","Comma-separated list of plugins to use"],env:"DOTSEC_PLUGIN"},ce={option:["--engine <engine>","Encryption engine to use"],env:"DOTSEC_ENGINE"},R={option:["--create-manifest","Create a markdown manifest file. See the --manifest-file option for more information."],env:"CREATE_MANIFEST"},M={option:["--manifest-file <manifestFile>","Specify the name of the manifest file to create."],env:"ENCRYPTION_MANIFEST_FILE"};var We={decrypt:{options:{configFile:F,envFile:S,secFile:N,createManifest:R,manifestFile:M,yes:$},description:"Decrypt a sec file",helpText:`Examples:
1
+ 'use strict';
2
+
3
+ var commander = require('commander');
4
+ var fs3 = require('fs');
5
+ var path = require('path');
6
+ var bundleRequire = require('bundle-require');
7
+ var JoyCon = require('joycon');
8
+ var fs2 = require('fs/promises');
9
+ var prompts = require('prompts');
10
+ var chalk2 = require('chalk');
11
+ require('cli-table');
12
+ var dotenvExpand = require('dotenv-expand');
13
+ var camelCase = require('camel-case');
14
+ var child_process = require('child_process');
15
+ var Ajv = require('ajv');
16
+ var yargsParser = require('yargs-parser');
17
+
18
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
19
+
20
+ var fs3__default = /*#__PURE__*/_interopDefault(fs3);
21
+ var path__default = /*#__PURE__*/_interopDefault(path);
22
+ var JoyCon__default = /*#__PURE__*/_interopDefault(JoyCon);
23
+ var fs2__default = /*#__PURE__*/_interopDefault(fs2);
24
+ var prompts__default = /*#__PURE__*/_interopDefault(prompts);
25
+ var chalk2__default = /*#__PURE__*/_interopDefault(chalk2);
26
+ var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
27
+ var yargsParser__default = /*#__PURE__*/_interopDefault(yargsParser);
28
+
29
+ // src/cli/index.ts
30
+
31
+ // src/constants.ts
32
+ var DOTSEC_DEFAULT_CONFIG_FILE = "dotsec.config.ts";
33
+ var DOTSEC_CONFIG_FILES = [DOTSEC_DEFAULT_CONFIG_FILE];
34
+ var DOTSEC_DEFAULT_DOTSEC_FILENAME = ".sec";
35
+ var DOTSEC_DEFAULT_DOTENV_FILENAME = ".env";
36
+ var defaultConfig = {
37
+ defaults: {
38
+ // encryptionEngine: "pke",
39
+ // plugins: {
40
+ // pke: {},
41
+ // },
42
+ options: {
43
+ showRedacted: false
44
+ }
45
+ }
46
+ };
47
+ function jsoncParse(data) {
48
+ try {
49
+ return new Function(`return ${data.trim()}`)();
50
+ } catch {
51
+ return {};
52
+ }
53
+ }
54
+ var loadJson = async (filepath) => {
55
+ try {
56
+ return jsoncParse(await fs3__default.default.promises.readFile(filepath, "utf8"));
57
+ } catch (error) {
58
+ if (error instanceof Error) {
59
+ throw new Error(
60
+ `Failed to parse ${path__default.default.relative(process.cwd(), filepath)}: ${error.message}`
61
+ );
62
+ } else {
63
+ throw error;
64
+ }
65
+ }
66
+ };
67
+ var getMagicalConfig = async (filename) => {
68
+ const cwd = process.cwd();
69
+ const configJoycon = new JoyCon__default.default();
70
+ const configPath = await configJoycon.resolve({
71
+ files: filename ? [filename] : [...DOTSEC_CONFIG_FILES, "package.json"],
72
+ cwd,
73
+ stopDir: path__default.default.parse(cwd).root,
74
+ packageKey: "dotsec"
75
+ });
76
+ if (filename && configPath === null) {
77
+ throw new Error(`Could not find config file ${filename}`);
78
+ }
79
+ if (configPath) {
80
+ if (configPath.endsWith(".json")) {
81
+ const rawData = await loadJson(configPath);
82
+ let data;
83
+ if (configPath.endsWith("package.json") && rawData.dotsec !== void 0) {
84
+ data = rawData.dotsec;
85
+ } else {
86
+ data = rawData;
87
+ }
88
+ return {
89
+ source: "json",
90
+ contents: {
91
+ ...defaultConfig,
92
+ ...data,
93
+ defaults: {
94
+ ...data?.defaults,
95
+ ...defaultConfig.defaults,
96
+ options: {
97
+ ...data?.defaults?.options,
98
+ ...defaultConfig.defaults?.options
99
+ },
100
+ plugins: {
101
+ ...data?.defaults?.plugins,
102
+ ...defaultConfig.defaults?.plugins
103
+ }
104
+ },
105
+ push: {
106
+ ...data?.push
107
+ }
108
+ }
109
+ };
110
+ } else if (configPath.endsWith(".ts")) {
111
+ const bundleRequireResult = await bundleRequire.bundleRequire({
112
+ filepath: configPath
113
+ });
114
+ const data = bundleRequireResult.mod.dotsec || bundleRequireResult.mod.default || bundleRequireResult.mod;
115
+ return {
116
+ source: "ts",
117
+ contents: {
118
+ ...defaultConfig,
119
+ ...data,
120
+ defaults: {
121
+ ...data?.defaults,
122
+ ...defaultConfig.defaults,
123
+ plugins: {
124
+ ...data?.defaults?.plugins,
125
+ ...defaultConfig.defaults?.plugins
126
+ },
127
+ options: {
128
+ ...data?.defaults?.options,
129
+ ...defaultConfig.defaults?.options
130
+ }
131
+ },
132
+ push: {
133
+ ...data?.push
134
+ }
135
+ }
136
+ };
137
+ }
138
+ }
139
+ return { source: "defaultConfig", contents: defaultConfig };
140
+ };
141
+
142
+ // src/lib/loadDotsecPlugin.ts
143
+ var loadDotsecPlugin = async (options) => {
144
+ return import(options.name).then((imported) => {
145
+ return imported.default;
146
+ });
147
+ };
148
+ var addPluginOptions = (options, command, mandatory) => {
149
+ if (options) {
150
+ Object.values(options).map((option) => {
151
+ let optionProps;
152
+ if (Array.isArray(option)) {
153
+ const [flags, description, defaultValue] = option;
154
+ optionProps = {
155
+ flags,
156
+ description,
157
+ defaultValue
158
+ };
159
+ } else {
160
+ const { flags, description, defaultValue, choices, env, fn } = option;
161
+ optionProps = {
162
+ flags,
163
+ description,
164
+ defaultValue,
165
+ choices,
166
+ env,
167
+ fn
168
+ };
169
+ }
170
+ if (optionProps) {
171
+ const newOption = new commander.Option(
172
+ optionProps.flags,
173
+ optionProps.description
174
+ );
175
+ if (optionProps.fn) {
176
+ newOption.argParser(optionProps.fn);
177
+ }
178
+ if (optionProps.defaultValue) {
179
+ newOption.default(optionProps.defaultValue);
180
+ }
181
+ if (optionProps.env) {
182
+ newOption.env(optionProps.env);
183
+ }
184
+ if (mandatory) {
185
+ newOption.makeOptionMandatory(true);
186
+ }
187
+ if (optionProps.choices) {
188
+ newOption.choices(optionProps.choices);
189
+ }
190
+ command.addOption(newOption);
191
+ }
192
+ });
193
+ }
194
+ };
195
+ var readContentsFromFile = async (filePath) => {
196
+ return await fs2__default.default.readFile(filePath, "utf-8");
197
+ };
198
+ var writeContentsToFile = async (filePath, contents) => {
199
+ return await fs2__default.default.writeFile(filePath, contents, "utf-8");
200
+ };
201
+ var fileExists = async (source) => {
202
+ try {
203
+ await fs2.stat(source);
204
+ return true;
205
+ } catch {
206
+ return false;
207
+ }
208
+ };
209
+ var promptOverwriteIfFileExists = async ({
210
+ filePath,
211
+ skip
212
+ }) => {
213
+ let overwriteResponse;
214
+ if (await fileExists(filePath) && skip !== true) {
215
+ overwriteResponse = await prompts__default.default({
216
+ type: "confirm",
217
+ name: "overwrite",
218
+ message: () => {
219
+ return `Overwrite './${path__default.default.relative(process.cwd(), filePath)}' ?`;
220
+ }
221
+ });
222
+ } else {
223
+ overwriteResponse = void 0;
224
+ }
225
+ return overwriteResponse;
226
+ };
227
+
228
+ // src/lib/parse.ts
229
+ var LINE = /^(#.*)|(\s?\r?\n)|(?:^|^)\s*(?:export\s+)?([\w.-]*)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?(\s*)(#.*)?(?:$|$)/gm;
230
+ var parse = (src) => {
231
+ const obj = {};
232
+ const blocks = [];
233
+ let lines = src.toString();
234
+ lines = lines.replace(/\r\n?/gm, "\n");
235
+ let match;
236
+ while ((match = LINE.exec(lines)) != null) {
237
+ const key = match[3];
238
+ if (match?.[1]?.[0] === "#") {
239
+ blocks.push({ type: "comment", raw: match[1] });
240
+ } else if (match?.[2]) {
241
+ blocks.push({ type: "whitespace", raw: match[2] });
242
+ } else {
243
+ let value = match[4] || "";
244
+ value = value.trim();
245
+ const maybeQuote = value[0];
246
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
247
+ if (maybeQuote === '"') {
248
+ value = value.replace(/\\n/g, "\n");
249
+ value = value.replace(/\\r/g, "\r");
250
+ }
251
+ obj[key] = value;
252
+ blocks.push({
253
+ type: "value",
254
+ key,
255
+ value,
256
+ raw: value + (match[5] ? match[5] : "") + (match[6] ? match[6] : "")
257
+ });
258
+ }
259
+ }
260
+ return { blocks, obj };
261
+ };
262
+ if (undefined) {
263
+ const { it, expect } = undefined;
264
+ it("parse", () => {
265
+ const input1 = "KEY=value";
266
+ const input2 = 'KEY="value"';
267
+ const input3 = "KEY='value'";
268
+ const input4 = "KEY=value # this is a comment";
269
+ expect(parse(input1)).toMatchInlineSnapshot(`
270
+ {
271
+ "blocks": [
272
+ {
273
+ "key": "KEY",
274
+ "raw": "value",
275
+ "type": "value",
276
+ "value": "value",
277
+ },
278
+ ],
279
+ "obj": {
280
+ "KEY": "value",
281
+ },
282
+ }
283
+ `);
284
+ expect(parse(input2)).toMatchInlineSnapshot(`
285
+ {
286
+ "blocks": [
287
+ {
288
+ "key": "KEY",
289
+ "raw": "value",
290
+ "type": "value",
291
+ "value": "value",
292
+ },
293
+ ],
294
+ "obj": {
295
+ "KEY": "value",
296
+ },
297
+ }
298
+ `);
299
+ expect(parse(input3)).toMatchInlineSnapshot(`
300
+ {
301
+ "blocks": [
302
+ {
303
+ "key": "KEY",
304
+ "raw": "value",
305
+ "type": "value",
306
+ "value": "value",
307
+ },
308
+ ],
309
+ "obj": {
310
+ "KEY": "value",
311
+ },
312
+ }
313
+ `);
314
+ expect(parse(input4)).toMatchInlineSnapshot(`
315
+ {
316
+ "blocks": [
317
+ {
318
+ "key": "KEY",
319
+ "raw": "value# this is a comment",
320
+ "type": "value",
321
+ "value": "value",
322
+ },
323
+ ],
324
+ "obj": {
325
+ "KEY": "value",
326
+ },
327
+ }
328
+ `);
329
+ });
330
+ }
331
+ var strong = (str) => chalk2__default.default.yellow.bold(str);
332
+
333
+ // src/types/colors.ts
334
+ var backgroundColors = [
335
+ "black",
336
+ "red",
337
+ "green",
338
+ "yellow",
339
+ "blue",
340
+ "magenta",
341
+ "cyan",
342
+ "white",
343
+ "black-bright",
344
+ "gray",
345
+ "grey",
346
+ "red-bright",
347
+ "green-bright",
348
+ "yellow-bright",
349
+ "blue-bright",
350
+ "magenta-bright",
351
+ "cyan-bright",
352
+ "white-bright"
353
+ ];
354
+
355
+ // src/cli/options/sharedOptions.ts
356
+ var envFileOption = {
357
+ option: [
358
+ "--env-file <envFile>",
359
+ `Path to .env file. If not provided, will look for value in 'ENV_FILE' environment variable. If not provided, will look for '${DOTSEC_DEFAULT_DOTENV_FILENAME}' file in current directory.`,
360
+ DOTSEC_DEFAULT_DOTENV_FILENAME
361
+ ],
362
+ env: "ENV_FILE"
363
+ };
364
+ var secFileOption = {
365
+ option: [
366
+ "--sec-file, <secFile>",
367
+ `Path to .sec file. If not provided, will look for value in 'SEC_FILE' environment variable. If not provided, will look for '${DOTSEC_DEFAULT_DOTSEC_FILENAME}' file in current directory.`,
368
+ DOTSEC_DEFAULT_DOTSEC_FILENAME
369
+ ],
370
+ env: "SEC_FILE"
371
+ };
372
+ var usingOption = {
373
+ flags: "--using <using>",
374
+ description: "Wether to use a dot env file or a dot sec file",
375
+ choices: ["env", "sec"],
376
+ env: "DOTSEC_USING"
377
+ };
378
+ var usingNoEncryptionEngineOption = {
379
+ flags: "--using <using>",
380
+ description: "Wether to use a dot env file or a dot sec file",
381
+ choices: ["env"],
382
+ env: "DOTSEC_USING"
383
+ };
384
+ var showOutputPrefixOption = {
385
+ flags: "--show-output-prefix",
386
+ description: "Show output prefix",
387
+ env: "DOTSEC_SHOW_OUTPUT_PREFIX"
388
+ };
389
+ var outputPrefixOption = {
390
+ flags: "--output-prefix <outputPrefix>",
391
+ description: "Output prefix",
392
+ env: "DOTSEC_OUTPUT_PREFIX"
393
+ };
394
+ var outputBackgroundColorOption = {
395
+ flags: "--output-background-color <outputBackgroundColor>",
396
+ description: "Background color of the output.",
397
+ env: "DOTSEC_OUTPUT_BACKGROUND_COLOR",
398
+ choices: [...backgroundColors, true]
399
+ };
400
+ var yesOption = {
401
+ option: ["--yes", "Skip confirmation prompts"]
402
+ };
403
+ var configFileOption = {
404
+ option: ["-c, --config-file, --configFile <configFile>", "Config file"],
405
+ env: "DOTSEC_CONFIG_FILE"
406
+ };
407
+ var pluginOption = {
408
+ option: ["--plugin <plugin>", "Comma-separated list of plugins to use"],
409
+ env: "DOTSEC_PLUGIN"
410
+ };
411
+ var engineOption = {
412
+ option: ["--engine <engine>", "Encryption engine to use"],
413
+ env: "DOTSEC_ENGINE"
414
+ };
415
+ var createManifestOption = {
416
+ option: [
417
+ "--create-manifest",
418
+ "Create a markdown manifest file. See the --manifest-file option for more information."
419
+ ],
420
+ env: "CREATE_MANIFEST"
421
+ };
422
+ var manifestFilePrefixOption = {
423
+ option: [
424
+ "--manifest-file-prefix <manifestFilePrefix>",
425
+ "Mmanifest file prefix"
426
+ ],
427
+ env: "ENCRYPTION_MANIFEST_FILE"
428
+ };
429
+
430
+ // src/cli/options/decrypt.ts
431
+ var decryptCommandDefaults = {
432
+ decrypt: {
433
+ options: {
434
+ configFile: configFileOption,
435
+ envFile: envFileOption,
436
+ secFile: secFileOption,
437
+ createManifest: createManifestOption,
438
+ manifestFilePrefix: manifestFilePrefixOption,
439
+ yes: yesOption
440
+ },
441
+ description: "Decrypt a sec file",
442
+ helpText: `Examples:
2
443
 
3
444
 
4
445
  Decrypt .sec file to .env file
@@ -16,7 +457,7 @@ Specify a different .env file
16
457
  $ npx dotsec decrypt --env-file .env.dev
17
458
  $ ENV_FILE=.env.dev npx dotsec decrypt
18
459
 
19
- Write a manifest file
460
+ Write a manifest markdown file
20
461
 
21
462
  $ npx dotsec decrypt --create-manifest
22
463
  $ CREATE_MANIFEST=true npx dotsec decrypt
@@ -24,8 +465,36 @@ $ CREATE_MANIFEST=true npx dotsec decrypt
24
465
  Specify a different manifest file
25
466
 
26
467
  $ npx dotsec decrypt --manifest-file .manifest.dev
27
- $ MANIFEST_FILE=.manifest.dev npx dotsec decrypt
28
- `}},pe=We;var Ue={dotsec:{options:{configFile:F,plugin:ae}}},le=Ue;var Ke={encrypt:{options:{configFile:F,envFile:S,secFile:N,createManifest:R,manifestFile:M,yes:$},description:"Encrypt an env file",helpText:`Examples:
468
+ $ MANIFEST_FILE=decryption-manifest.md npx dotsec decrypt
469
+ `
470
+ }
471
+ };
472
+ var decrypt_default = decryptCommandDefaults;
473
+
474
+ // src/cli/options/dotsec.ts
475
+ var dotsecCommandDefaults = {
476
+ dotsec: {
477
+ options: {
478
+ configFile: configFileOption,
479
+ plugin: pluginOption
480
+ }
481
+ }
482
+ };
483
+ var dotsec_default = dotsecCommandDefaults;
484
+
485
+ // src/cli/options/encrypt.ts
486
+ var encryptCommandDefaults = {
487
+ encrypt: {
488
+ options: {
489
+ configFile: configFileOption,
490
+ envFile: envFileOption,
491
+ secFile: secFileOption,
492
+ createManifest: createManifestOption,
493
+ manifestFile: manifestFilePrefixOption,
494
+ yes: yesOption
495
+ },
496
+ description: "Encrypt an env file",
497
+ helpText: `Examples:
29
498
 
30
499
 
31
500
  Encrypt .env file to .sec file
@@ -38,13 +507,14 @@ Specify a different .env file
38
507
  $ npx dotsec encrypt --env-file .env.dev
39
508
  $ ENV_FILE=.env.dev npx dotsec encrypt
40
509
 
510
+
41
511
  Specify a different .sec file
42
512
 
43
513
  $ npx dotsec encrypt --sec-file .sec.dev
44
514
  $ SEC_FILE=.sec.dev npx dotsec encrypt
45
515
 
46
516
 
47
- Write a manifest file
517
+ Write a manifest markdown file
48
518
 
49
519
  $ npx dotsec encrypt --create-manifest
50
520
  $ CREATE_MANIFEST=true npx dotsec encrypt
@@ -52,9 +522,22 @@ $ CREATE_MANIFEST=true npx dotsec encrypt
52
522
 
53
523
  Specify a different manifest file
54
524
 
55
- $ npx dotsec encrypt --manifest-file .manifest.dev
56
- $ MANIFEST_FILE=.manifest.dev npx dotsec encrypt
57
- `}},de=Ke;var Je={init:{options:{configFile:F,yes:$},description:"Initialize a dotsec project by creating a dotsec.config.ts file.",helpText:`Examples:
525
+ $ npx dotsec encrypt --manifest-file manifest.dev
526
+ $ MANIFEST_FILE=encryption-manifest.md npx dotsec encrypt
527
+ `
528
+ }
529
+ };
530
+ var encrypt_default = encryptCommandDefaults;
531
+
532
+ // src/cli/options/init.ts
533
+ var initCommandDefaults = {
534
+ init: {
535
+ options: {
536
+ configFile: configFileOption,
537
+ yes: yesOption
538
+ },
539
+ description: "Initialize a dotsec project by creating a dotsec.config.ts file.",
540
+ helpText: `Examples:
58
541
 
59
542
  Create a dotsec.config.ts file in the current directory
60
543
 
@@ -73,7 +556,25 @@ By specifying the --config-file option, you can create a dotsec config file with
73
556
  $ npx dotsec init --config-file dotsec.config.ts
74
557
 
75
558
  $ DOTSEC_CONFIG_FILE=my.config.ts npx dotsec init
76
- `}},fe=Je;var Be={push:{options:{configFile:F,envFile:S,secFile:N,yes:$},requiredOptions:{using:L},description:"Push variables from env or sec file to a remote",helpText:`Examples:
559
+ `
560
+ }
561
+ };
562
+ var init_default = initCommandDefaults;
563
+
564
+ // src/cli/options/push.ts
565
+ var pushCommandDefaults = {
566
+ push: {
567
+ options: {
568
+ configFile: configFileOption,
569
+ envFile: envFileOption,
570
+ secFile: secFileOption,
571
+ yes: yesOption
572
+ },
573
+ requiredOptions: {
574
+ using: usingOption
575
+ },
576
+ description: "Push variables from env or sec file to a remote",
577
+ helpText: `Examples:
77
578
 
78
579
  Push variables from .env file to remote
79
580
 
@@ -85,7 +586,29 @@ Push variables from .sec file to remote
85
586
 
86
587
  $ npx dotsec push --using sec
87
588
  $ DOTSEC_USING=sec npx dotsec push
88
- `}},me=Be;var Ye={runEnvOnly:{usage:"--using env [commandArgs...]",options:{configFile:F,envFile:S,yes:$,engine:ce},requiredOptions:{using:se},description:"Run a command in a separate process and populate env with contents of a dotenv file.",helpText:`Examples:
589
+ `
590
+ }
591
+ };
592
+ var push_default = pushCommandDefaults;
593
+
594
+ // src/cli/options/run.ts
595
+ var runCommandDefaults = {
596
+ runEnvOnly: {
597
+ usage: "--using env [commandArgs...]",
598
+ options: {
599
+ configFile: configFileOption,
600
+ envFile: envFileOption,
601
+ yes: yesOption,
602
+ engine: engineOption,
603
+ outputBackgroundColor: outputBackgroundColorOption,
604
+ showOutputPrefix: showOutputPrefixOption,
605
+ outputPrefix: outputPrefixOption
606
+ },
607
+ requiredOptions: {
608
+ using: usingNoEncryptionEngineOption
609
+ },
610
+ description: "Run a command in a separate process and populate env with contents of a dotenv file.",
611
+ helpText: `Examples:
89
612
 
90
613
  Run a command with a .env file
91
614
 
@@ -105,63 +628,877 @@ $ ENV_FILE=.env.dev npx dotsec run --using env node -e "console.log(process.env)
105
628
  You can also specify 'using' as an environment variable
106
629
 
107
630
  $ DOTSEC_USING=env npx dotsec run node -e "console.log(process.env)"
108
- `},run:{options:{configFile:F,envFile:S,secFile:N,yes:$},requiredOptions:{using:L},usage:"[--using env] [--using sec] [commandArgs...]",description:`Run a command in a separate process and populate env with either
631
+ `
632
+ },
633
+ run: {
634
+ options: {
635
+ configFile: configFileOption,
636
+ envFile: envFileOption,
637
+ secFile: secFileOption,
638
+ yes: yesOption,
639
+ outputBackgroundColor: outputBackgroundColorOption,
640
+ hideOutputPrefix: showOutputPrefixOption,
641
+ outputPrefix: outputPrefixOption
642
+ },
643
+ requiredOptions: {
644
+ using: usingOption
645
+ },
646
+ usage: "[--using env] [--using sec] [commandArgs...]",
647
+ description: `Run a command in a separate process and populate env with either
109
648
  - contents of a dotenv file
110
649
  - decrypted values of a dotsec file.
111
650
 
112
- The --withEnv option will take precedence over the --withSec option. If neither are specified, the --withEnv option will be used by default.`,helpText:`Examples:
651
+ The --withEnv option will take precedence over the --withSec option. If neither are specified, the --withEnv option will be used by default.`,
652
+ helpText: `${"Examples:"}
113
653
 
114
- Run a command with a .env file
654
+ ${"Run a command with a .env file"}
115
655
 
116
656
  $ dotsec run echo "hello world"
117
657
 
118
658
 
119
- Run a command with a specific .env file
659
+ ${"Run a command with a specific .env file"}
120
660
 
121
661
  $ dotsec run --with-env --env-file .env.dev echo "hello world"
122
662
 
123
663
 
124
- Run a command with a .sec file
664
+ ${"Run a command with a .sec file"}
125
665
 
126
666
  $ dotsec run --with-sec echo "hello world"
127
667
 
128
668
 
129
- Run a command with a specific .sec file
669
+ ${"Run a command with a specific .sec file"}
130
670
 
131
671
  $ dotsec run --with-sec --sec-file .sec.dev echo "hello world"
132
- `}},ge=Ye;var ze={...le,...fe,...de,...pe,...ge,...me},Qe=n=>{if(Array.isArray(n)){let[o,a,t]=n;return{flags:o,description:a,defaultValue:t}}else{if("option"in n){let[o,a,t]=n.option;return{flags:o,description:a,defaultValue:t,env:n.env}}return n}},ue=(n,o)=>{let a=o?.dotsecConfig?.defaults?.options?.[o?.optionKey],t=Qe(n),e=new ye.Option(t.flags,t.description);return t.fn&&e.argParser(t.fn),t.defaultValue&&e.default(a||t.defaultValue),t.env&&e.env(t.env),o.required&&e.makeOptionMandatory(!0),t.choices&&e.choices(t.choices),e},P=n=>{let{program:o,commandName:a,dotsecConfig:t}=n,e=ze[a||o.name()];if(e){let{options:i,requiredOptions:c,description:l,usage:s,helpText:r}=e;i&&Object.keys(i).forEach(f=>{let m=i[f],d=ue(m,{dotsecConfig:t,optionKey:f});o.addOption(d)}),c&&Object.keys(c).forEach(f=>{let m=c[f],d=ue(m,{required:!0,dotsecConfig:t,optionKey:f});o.addOption(d)}),l&&o.description(l),s&&o.usage(s),r&&o.description(r)}};var Oe=require("dotenv"),Xe=async(n,o)=>{let{dotsecConfig:a,decryptHandlers:t}=o,e=n.enablePositionalOptions().passThroughOptions().command("decrypt").action(async(c,l)=>{try{let{envFile:s,secFile:r,engine:f,createManifest:m,manifestFile:d,yes:p}=l.optsWithGlobals(),O=f||a?.defaults?.encryptionEngine,u=(t||[]).find(h=>h.triggerOptionValue===O);if(!u)throw new Error(`No decryption plugin found, available decryption engine(s): ${o.decryptHandlers.map(h=>`--${h.triggerOptionValue}`).join(", ")}`);console.log("Decrypting with",C(u.encryptionEngineName||u.triggerOptionValue),"engine");let g=[...Object.keys(u.options||{}),...Object.keys(u.requiredOptions||{})],D=Object.fromEntries(g.map(h=>[h,c[h]])),v=await V(r),E=await u.handler({ciphertext:v,...D}),j=await A({filePath:s,skip:p});if((j===void 0||j.overwrite===!0)&&(await I(s,E),console.log(`Wrote plaintext contents of ${C(r)} file to ${C(s)}`)),m){let h=(0,Oe.parse)(E),y=`# Dotsec decryption manifest
672
+ `
673
+ }
674
+ // push: {
675
+ // options: {
676
+ // ...dotsecCommandDefaults.dotsec.options,
677
+ // withEnv: withEnvOption,
678
+ // withSec: withSecOption,
679
+ // envFile: envFileOption,
680
+ // secFile: secFileOption,
681
+ // yes: yesOption,
682
+ // },
683
+ // requiredOptions: {
684
+ // ...dotsecCommandDefaults.dotsec.requiredOptions,
685
+ // },
686
+ // },
687
+ };
688
+ var run_default = runCommandDefaults;
689
+
690
+ // src/cli/options/index.ts
691
+ var commandOptions = {
692
+ ...dotsec_default,
693
+ ...init_default,
694
+ ...encrypt_default,
695
+ ...decrypt_default,
696
+ ...run_default,
697
+ ...push_default
698
+ };
699
+ var expandCommandOption = (commandOption) => {
700
+ if (Array.isArray(commandOption)) {
701
+ const [flags, description, defaultValue] = commandOption;
702
+ const optionProps = {
703
+ flags,
704
+ description,
705
+ defaultValue
706
+ };
707
+ return optionProps;
708
+ } else {
709
+ if ("option" in commandOption) {
710
+ const [flags, description, defaultValue] = commandOption.option;
711
+ const optionProps = {
712
+ flags,
713
+ description,
714
+ defaultValue,
715
+ env: commandOption.env
716
+ };
717
+ return optionProps;
718
+ }
719
+ return commandOption;
720
+ }
721
+ };
722
+ var createOption = (commandOption, options) => {
723
+ const defaultOptionValueFromConfig = options?.dotsecConfig?.defaults?.options?.[options?.optionKey];
724
+ const optionProps = expandCommandOption(commandOption);
725
+ const newOption = new commander.Option(optionProps.flags, optionProps.description);
726
+ if (optionProps.fn) {
727
+ newOption.argParser(optionProps.fn);
728
+ }
729
+ if (optionProps.defaultValue) {
730
+ newOption.default(defaultOptionValueFromConfig || optionProps.defaultValue);
731
+ }
732
+ if (optionProps.env) {
733
+ newOption.env(optionProps.env);
734
+ }
735
+ if (options.required) {
736
+ newOption.makeOptionMandatory(true);
737
+ }
738
+ if (optionProps.choices) {
739
+ newOption.choices(optionProps.choices);
740
+ }
741
+ return newOption;
742
+ };
743
+ var setProgramOptions = (params) => {
744
+ const { program: program2, commandName, dotsecConfig } = params;
745
+ const programOptions = commandOptions[commandName || program2.name()];
746
+ if (programOptions) {
747
+ const { options, requiredOptions, description, usage, helpText } = programOptions;
748
+ if (options) {
749
+ Object.keys(options).forEach((optionKey) => {
750
+ const commandOption = options[optionKey];
751
+ const newOption = createOption(commandOption, {
752
+ dotsecConfig,
753
+ optionKey
754
+ });
755
+ program2.addOption(newOption);
756
+ });
757
+ }
758
+ if (requiredOptions) {
759
+ Object.keys(requiredOptions).forEach((requiredOptionKey) => {
760
+ const requiredOption = requiredOptions[requiredOptionKey];
761
+ const newOption = createOption(requiredOption, {
762
+ required: true,
763
+ dotsecConfig,
764
+ optionKey: requiredOptionKey
765
+ });
766
+ program2.addOption(newOption);
767
+ });
768
+ }
769
+ if (description) {
770
+ program2.description(description);
771
+ }
772
+ if (usage) {
773
+ program2.usage(usage);
774
+ }
775
+ if (helpText) {
776
+ program2.description(helpText);
777
+ }
778
+ }
779
+ };
780
+
781
+ // src/cli/commands/decrypt.ts
782
+ var addEncryptProgram = async (program2, options) => {
783
+ const { dotsecConfig, decryptHandlers } = options;
784
+ const subProgram = program2.enablePositionalOptions().passThroughOptions().command("decrypt").action(async (_options, command) => {
785
+ try {
786
+ const {
787
+ // verbose,
788
+ envFile,
789
+ secFile,
790
+ engine,
791
+ createManifest,
792
+ manifestFile,
793
+ yes
794
+ } = command.optsWithGlobals();
795
+ const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
796
+ const pluginCliDecrypt = (decryptHandlers || []).find((handler) => {
797
+ return handler.triggerOptionValue === encryptionEngine;
798
+ });
799
+ if (!pluginCliDecrypt) {
800
+ throw new Error(
801
+ `No decryption plugin found, available decryption engine(s): ${options.decryptHandlers.map((e) => `--${e.triggerOptionValue}`).join(", ")}`
802
+ );
803
+ }
804
+ console.log(
805
+ "Decrypting with",
806
+ strong(
807
+ pluginCliDecrypt.encryptionEngineName || pluginCliDecrypt.triggerOptionValue
808
+ ),
809
+ "engine"
810
+ );
811
+ const allOptionKeys = [
812
+ ...Object.keys(pluginCliDecrypt.options || {}),
813
+ ...Object.keys(pluginCliDecrypt.requiredOptions || {})
814
+ ];
815
+ const allOptionsValues = Object.fromEntries(
816
+ allOptionKeys.map((key) => {
817
+ return [key, _options[key]];
818
+ })
819
+ );
820
+ const dotsecString = await readContentsFromFile(secFile);
821
+ const plaintext = await pluginCliDecrypt.handler({
822
+ ciphertext: dotsecString,
823
+ ...allOptionsValues
824
+ });
825
+ const dotenvOverwriteResponse = await promptOverwriteIfFileExists({
826
+ filePath: envFile,
827
+ skip: yes
828
+ });
829
+ if (dotenvOverwriteResponse === void 0 || dotenvOverwriteResponse.overwrite === true) {
830
+ await writeContentsToFile(envFile, plaintext);
831
+ console.log(
832
+ `Wrote plaintext contents of ${strong(secFile)} file to ${strong(
833
+ envFile
834
+ )}`
835
+ );
836
+ }
837
+ if (createManifest || dotsecConfig?.defaults?.options?.createManifest) {
838
+ const dotenvVars = parse(plaintext).obj;
839
+ const markdownManifest = `# Dotsec decryption manifest
133
840
 
134
841
  ## Overview
135
842
 
136
- - plaintext source: ${s}
137
- - ciphertext target: ${r}
138
- - created: ${new Date().toUTCString()}
139
- - Decryption engine: ${u.encryptionEngineName||u.triggerOptionValue}
140
- - Decryption engine options: ${JSON.stringify(D)}
843
+ - plaintext source: ${envFile}
844
+ - ciphertext target: ${secFile}
845
+ - created: ${( new Date()).toUTCString()}
846
+ - Decryption engine: ${pluginCliDecrypt.encryptionEngineName || pluginCliDecrypt.triggerOptionValue}
847
+ - Decryption engine options: ${JSON.stringify(allOptionsValues)}
141
848
 
142
849
  ## Variables
143
850
 
144
- | Key |
145
- | --- |
146
- ${Object.keys(h).map(H=>`| \`${H} \`| `).join(`
147
- `)}
148
- `,b=d||`${s}.decryption-manifest.md`;await I(b,y),console.log(`Wrote manifest of ${C(s)} file to ${C(b)}`)}}catch(s){console.error(C(s.message)),l.help()}});o.decryptHandlers.map(c=>{let{options:l,requiredOptions:s}=c;x(l,e),x(s,e,!0)});let i=o.decryptHandlers.map(c=>c.triggerOptionValue);return e.option("--engine <engine>",`Encryption engine${i.length>0?"s":""} to use: ${i.length===1?i[0]:i.join(", ")}`,i.length===1?i[0]:void 0),P({program:e,dotsecConfig:a}),e},Ce=Xe;var he=require("dotenv"),Ze=async(n,o)=>{let{encryptHandlers:a,dotsecConfig:t}=o,e=n.enablePositionalOptions().passThroughOptions().command("encrypt").action(async(l,s)=>{try{let{envFile:r,secFile:f,engine:m,createManifest:d,manifestFile:p,yes:O}=s.optsWithGlobals(),u=m||t?.defaults?.encryptionEngine,g=(a||[]).find(y=>y.triggerOptionValue===u);if(!g)throw new Error(`No encryption plugin found, available encryption engine(s): ${o.encryptHandlers.map(y=>y.triggerOptionValue).join(", ")}`);let D=[...Object.keys(g.options||{}),...Object.keys(g.requiredOptions||{})],v=Object.fromEntries(D.map(y=>[y,l[y]])),E=await V(r),j=await g.handler({plaintext:E,...v}),h=await A({filePath:f,skip:O});if((h===void 0||h.overwrite===!0)&&(await I(f,j),console.log(`Wrote encrypted contents of ${C(r)} file to ${C(f)}`),d)){let y=(0,he.parse)(E),b=`# Dotsec encryption manifest
851
+ | Key |
852
+ | --- |
853
+ ${Object.keys(dotenvVars).map((key) => {
854
+ return `| \`${key} \`| `;
855
+ }).join("\n")}
856
+ `;
857
+ const manifestTargetFile = manifestFile || `${envFile}.decryption-manifest.md`;
858
+ await writeContentsToFile(manifestTargetFile, markdownManifest);
859
+ console.log(
860
+ `Wrote manifest of ${strong(envFile)} file to ${strong(
861
+ manifestTargetFile
862
+ )}`
863
+ );
864
+ }
865
+ } catch (e) {
866
+ console.error(strong(e.message));
867
+ command.help();
868
+ }
869
+ });
870
+ options.decryptHandlers.map((decryption) => {
871
+ const { options: options2, requiredOptions } = decryption;
872
+ addPluginOptions(options2, subProgram);
873
+ addPluginOptions(requiredOptions, subProgram, true);
874
+ });
875
+ const engines = options.decryptHandlers.map((e) => e.triggerOptionValue);
876
+ subProgram.option(
877
+ "--engine <engine>",
878
+ `Encryption engine${engines.length > 0 ? "s" : ""} to use: ${engines.length === 1 ? engines[0] : engines.join(", ")}`,
879
+ engines.length === 1 ? engines[0] : void 0
880
+ );
881
+ setProgramOptions({ program: subProgram, dotsecConfig });
882
+ return subProgram;
883
+ };
884
+ var decrypt_default2 = addEncryptProgram;
885
+
886
+ // src/cli/commands/encrypt.ts
887
+ var addEncryptProgram2 = async (program2, options) => {
888
+ const { encryptHandlers, dotsecConfig } = options;
889
+ const subProgram = program2.enablePositionalOptions().passThroughOptions().command("encrypt").action(async (_options, command) => {
890
+ try {
891
+ const {
892
+ // verbose,
893
+ envFile,
894
+ secFile,
895
+ engine,
896
+ createManifest,
897
+ manifestFile,
898
+ yes
899
+ } = command.optsWithGlobals();
900
+ const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
901
+ const pluginCliEncrypt = (encryptHandlers || []).find((handler) => {
902
+ return handler.triggerOptionValue === encryptionEngine;
903
+ });
904
+ if (!pluginCliEncrypt) {
905
+ throw new Error(
906
+ `No encryption plugin found, available encryption engine(s): ${options.encryptHandlers.map((e) => e.triggerOptionValue).join(", ")}`
907
+ );
908
+ }
909
+ const allOptionKeys = [
910
+ ...Object.keys(pluginCliEncrypt.options || {}),
911
+ ...Object.keys(pluginCliEncrypt.requiredOptions || {})
912
+ ];
913
+ const allOptionsValues = Object.fromEntries(
914
+ allOptionKeys.map((key) => {
915
+ return [key, _options[key]];
916
+ })
917
+ );
918
+ const dotenvString = await readContentsFromFile(envFile);
919
+ let dotsecString;
920
+ try {
921
+ dotsecString = await readContentsFromFile(secFile);
922
+ } catch (e) {
923
+ }
924
+ const cipherText = await pluginCliEncrypt.handler({
925
+ plaintext: dotenvString,
926
+ ciphertext: dotsecString,
927
+ ...allOptionsValues
928
+ });
929
+ const dotsecOverwriteResponse = await promptOverwriteIfFileExists({
930
+ filePath: secFile,
931
+ skip: yes
932
+ });
933
+ if (dotsecOverwriteResponse === void 0 || dotsecOverwriteResponse.overwrite === true) {
934
+ await writeContentsToFile(secFile, cipherText);
935
+ console.log(
936
+ `Wrote encrypted contents of ${strong(envFile)} file to ${strong(
937
+ secFile
938
+ )}`
939
+ );
940
+ if (createManifest || dotsecConfig?.defaults?.options?.createManifest) {
941
+ const dotenvVars = parse(dotenvString).obj;
942
+ const markdownManifest = `# Dotsec encryption manifest
149
943
 
150
944
  ## Overview
151
945
 
152
- - plaintext source: ${r}
153
- - ciphertext target: ${f}
154
- - created: ${new Date().toUTCString()}
155
- - encryption engine: ${g.encryptionEngineName||g.triggerOptionValue}
156
- - encryption engine options: ${JSON.stringify(v)}
946
+ - plaintext source: ${envFile}
947
+ - ciphertext target: ${secFile}
948
+ - created: ${( new Date()).toUTCString()}
949
+ - encryption engine: ${pluginCliEncrypt.encryptionEngineName || pluginCliEncrypt.triggerOptionValue}
950
+ - encryption engine options: ${JSON.stringify(allOptionsValues)}
157
951
 
158
952
  ## Variables
159
953
 
160
954
  | Key |
161
955
  | --- |
162
- ${Object.keys(y).map(Ne=>`| \`${Ne} \`| `).join(`
163
- `)}
164
- `,H=p||`${f}.encryption-manifest.md`;await I(H,b),console.log(`Wrote manifest of ${C(r)} file to ${C(H)}`)}}catch(r){console.error(C(r.message)),s.help()}});o.encryptHandlers.map(l=>{let{options:s,requiredOptions:r}=l;x(s,e),x(r,e,!0)});let i=o.encryptHandlers.map(l=>l.triggerOptionValue),c=o.encryptHandlers.map(l=>l.encryptionEngineName);return e.option("--engine <engine>",`Encryption engine${i.length>0?"s":""}: ${i.length===1?i[0]:i.join(", ")}`,i.length===1?i[0]:void 0),P({program:e,dotsecConfig:t}),e.description(`Encrypt .env file using ${c.join(", ")}`),e},ve=Ze;var Ee=w(require("path")),en=async(n,o)=>{let{dotsecConfig:a}=o,t=n.enablePositionalOptions().passThroughOptions().command("init").action(async(e,i)=>{let{configFile:c="dotsec.config.ts",yes:l}=i.optsWithGlobals();try{let s=await V(Ee.default.resolve(__dirname,"../../src/templates/dotsec.config.ts")),r=await A({filePath:c,skip:l});(r===void 0||r.overwrite===!0)&&(await I(c,s),console.log(`Wrote config file to ${C(c)}`))}catch(s){i.error(s)}});return P({program:t,dotsecConfig:a}),t},we=en;var De=require("dotenv"),Fe=require("dotenv-expand"),U=w(require("fs")),nn=async(n,o)=>{let{dotsecConfig:a,handlers:t}=o,e=n.enablePositionalOptions().passThroughOptions().command("push").action(async(r,f)=>{try{let{using:m,envFile:d,secFile:p,engine:O,yes:u}=f.optsWithGlobals(),g=O||a?.defaults?.encryptionEngine,D=(t||[]).find(y=>y.decrypt?.triggerOptionValue===g)?.decrypt,v=(t||[]).find(y=>y.push?.triggerOptionValue===g)?.push;if(!v)throw new Error("No push plugin found!");let E=[...Object.keys(D?.options||{}),...Object.keys(D?.requiredOptions||{}),...Object.keys(v?.options||{}),...Object.keys(v?.requiredOptions||{})],j=Object.fromEntries(E.map(y=>[y,r[y]])),h;if(m==="env"){if(!d)throw new Error("No dotenv file specified in --env-file option");h=U.default.readFileSync(d,"utf8")}else{if(!p)throw new Error("No dotsec file specified in --sec-file option");if(!D)throw new Error(`No decryption plugin found, available decryption engine(s): ${t.map(b=>`--${b.decrypt?.triggerOptionValue}`).join(", ")}`);let y=U.default.readFileSync(p,"utf8");h=await D.handler({ciphertext:y,...j})}if(h){let y=(0,De.parse)(h),b=(0,Fe.expand)({ignoreProcessEnv:!0,parsed:{...process.env,...y}});b.parsed&&await v.handler({push:b.parsed,yes:u,...j})}else throw new Error("No .env or .sec file provided")}catch(m){console.error(m),process.exit(1)}});P({program:e,dotsecConfig:a});let i=o.handlers.map(({decrypt:r})=>r.triggerOptionValue);e.option("--engine <engine>",`Encryption engine${i.length>0?"s":""} to use: ${i.length===1?i[0]:i.join(", ")}`,i.length===1?i[0]:void 0);let c={};o.handlers.forEach(r=>{Object.keys(r).map(f=>{let{options:m,requiredOptions:d}=r[f];Object.keys(m||{}).forEach(p=>{c[p]=Array.isArray(m[p])?m[p]:{...c[p],...m[p]}}),Object.keys(d||{}).forEach(p=>{c[p]=Array.isArray(d[p])?d[p]:{...c[p],...d[p],required:!0}})})});let l=[],s=[];return t.forEach(r=>{r.push?.description&&s.push(r.push.description),r.push?.usage&&l.push(r.push.usage)}),s.length>0&&e.description(s.join(`
165
- `)),l.length>0&&e.usage(l.join(`
166
- `)),x(Object.fromEntries(Object.entries(c).filter(([r,f])=>f.required!==!0)),e),x(Object.fromEntries(Object.entries(c).filter(([r,f])=>f.required===!0)),e,!0),e},xe=nn;var K=w(require("fs")),Pe=require("dotenv"),$e=require("dotenv-expand");var be=require("child_process"),tn=(n,o)=>{let{dotsecConfig:a,decryptHandlers:t}=o||{},e=t!==void 0&&t.length>0,i=n.command("run <command...>").allowUnknownOption(!0).enablePositionalOptions().passThroughOptions().showHelpAfterError(!0).action(async(c,l,s)=>{try{let{envFile:r,using:f,secFile:m,engine:d}=s.optsWithGlobals(),p;if(f==="env"||e===!1){if(!r)throw new Error("No dotenv file specified in --env-file option");p=K.default.readFileSync(r,"utf8")}else if(f==="sec"){if(!m)throw new Error("No dotsec file specified in --sec-file option");let O=d||a?.defaults?.encryptionEngine,u=(t||[]).find(E=>E.triggerOptionValue===O);if(!u)throw new Error(`No decryption plugin found, available decryption engine(s): ${(t||[]).map(E=>`--${E.triggerOptionValue}`).join(", ")}`);let g=[...Object.keys(u.options||{}),...Object.keys(u.requiredOptions||{})],D=Object.fromEntries(g.map(E=>[E,l[E]])),v=K.default.readFileSync(m,"utf8");p=await u.handler({ciphertext:v,...D})}if(p){let O=(0,Pe.parse)(p),u=(0,$e.expand)({ignoreProcessEnv:!0,parsed:{...process.env,...O}}),[g,...D]=c,v=(0,be.spawnSync)(g,[...D],{stdio:"inherit",shell:!1,encoding:"utf-8",env:{...u.parsed,...process.env,__DOTSEC_ENV__:JSON.stringify(Object.keys(O))}});v.status!==0&&process.exit(v.status||1)}else throw new Error("No .env or .sec file provided")}catch(r){console.error(C(r.message)),s.help()}});if(P({program:i,commandName:e?"run":"runEnvOnly",dotsecConfig:a}),e){t?.map(l=>{let{options:s,requiredOptions:r}=l;x(s,i),x(r,i,!0)});let c=t?.map(l=>l.triggerOptionValue);i.option("--engine <engine>",`Encryption engine${c.length>0?"s":""}: ${c.join(", "),c.length===1?c[0]:void 0}`)}return i},Se=tn;var _e=w(require("ajv")),Ie=w(require("yargs-parser")),on={keyword:"separator",type:"string",metaSchema:{type:"string",description:"value separator"},modifying:!0,valid:!0,errors:!1,compile:n=>(o,a)=>{if(a){let{parentData:t,parentDataProperty:e}=a;return t[e]=o===""?[]:o.split(n),!0}else return!1}},T=new Te.Command;(async()=>{let n=(0,Ie.default)(process.argv),o=[];n.plugin&&(Array.isArray(n.plugin)?o.push(...n.plugin):o.push(n.plugin));let a=[...Array.isArray(n.configFile)?n.configFile:[n.configFile],...Array.isArray(n.c)?n.c:[n.c]][0]||process.env.DOTSEC_CONFIG_FILE,{contents:t={}}=await ne(a),{defaults:e={},push:i,plugins:c}=t;T.name("dotsec").description(".env, but secure").version("1.0.0").enablePositionalOptions().action((d,p)=>{p.help()}),P({program:T,dotsecConfig:t});let l=new _e.default({allErrors:!0,removeAdditional:!0,useDefaults:!0,coerceTypes:!0,allowUnionTypes:!0,addUsedSchema:!1,keywords:[on]}),s={};if(c)for(let d of c)e?.plugins?.[d]||(e.plugins={...e.plugins,[d]:{}});if(o.length>0)for(let d of o){let O=await(await W({name:d}))({dotsecConfig:t,ajv:l,configFile:a});s[O.name]=d,o.length===1&&(t.defaults={...t.defaults,encryptionEngine:String(O.name),plugins:{...t.defaults?.plugins,[O.name]:{...t.defaults?.plugins?.[O.name]}}})}e?.encryptionEngine&&(e?.plugins?.[e.encryptionEngine]||(e.plugins={...e.plugins,[e.encryptionEngine]:{}})),e?.plugins&&Object.entries(e?.plugins).forEach(([d,p])=>{p?.name?s[d]=p?.name:s[d]=`@dotsec/plugin-${d}`}),Object.values(i||{}).forEach(d=>{Object.keys(d).forEach(p=>{s[p]||(s[p]=`@dotsec/plugin-${p}`)})});let r=[],f=[],m=[];for(let d of Object.keys(s)){let p=s[d],O=await W({name:p}),{addCliCommand:u,cliHandlers:g}=await O({ajv:l,dotsecConfig:t,configFile:a});g?.encrypt&&r.push(g.encrypt),g?.decrypt&&(f.push(g.decrypt),g?.push&&m.push({push:g.push,decrypt:g.decrypt})),u&&u({program:T})}r.length&&await ve(T,{dotsecConfig:t,encryptHandlers:r}),f.length&&await Ce(T,{dotsecConfig:t,decryptHandlers:f}),m.length&&await xe(T,{dotsecConfig:t,handlers:m}),await we(T,{dotsecConfig:t}),await Se(T,{dotsecConfig:t,decryptHandlers:f}),await T.parse()})();
956
+ ${Object.keys(dotenvVars).map((key) => {
957
+ return `| \`${key} \`| `;
958
+ }).join("\n")}
959
+ `;
960
+ const manifestTargetFile = manifestFile || `${secFile}.encryption-manifest.md`;
961
+ await writeContentsToFile(manifestTargetFile, markdownManifest);
962
+ console.log(
963
+ `Wrote manifest of ${strong(envFile)} file to ${strong(
964
+ manifestTargetFile
965
+ )}`
966
+ );
967
+ }
968
+ }
969
+ } catch (e) {
970
+ console.error(strong(e.message));
971
+ command.help();
972
+ }
973
+ });
974
+ options.encryptHandlers.map((encryptionHandler) => {
975
+ const { options: options2, requiredOptions } = encryptionHandler;
976
+ addPluginOptions(options2, subProgram);
977
+ addPluginOptions(requiredOptions, subProgram, true);
978
+ });
979
+ const engines = options.encryptHandlers.map((e) => e.triggerOptionValue);
980
+ const encryptionEngineNames = options.encryptHandlers.map(
981
+ (e) => e.encryptionEngineName
982
+ );
983
+ subProgram.option(
984
+ "--engine <engine>",
985
+ `Encryption engine${engines.length > 0 ? "s" : ""}: ${engines.length === 1 ? engines[0] : engines.join(", ")}`,
986
+ engines.length === 1 ? engines[0] : void 0
987
+ );
988
+ setProgramOptions({ program: subProgram, dotsecConfig });
989
+ subProgram.description(
990
+ `Encrypt .env file using ${encryptionEngineNames.join(", ")}`
991
+ );
992
+ return subProgram;
993
+ };
994
+ var encrypt_default2 = addEncryptProgram2;
995
+ var addInitProgram = async (program2, options) => {
996
+ const { dotsecConfig } = options;
997
+ const subProgram = program2.enablePositionalOptions().passThroughOptions().command("init").action(async (_options, command) => {
998
+ const { configFile = "dotsec.config.ts", yes } = command.optsWithGlobals();
999
+ try {
1000
+ const configTemplate = await readContentsFromFile(
1001
+ path__default.default.resolve(__dirname, "../../src/templates/dotsec.config.ts")
1002
+ );
1003
+ const dotsecConfigOverwriteResponse = await promptOverwriteIfFileExists(
1004
+ {
1005
+ filePath: configFile,
1006
+ skip: yes
1007
+ }
1008
+ );
1009
+ if (dotsecConfigOverwriteResponse === void 0 || dotsecConfigOverwriteResponse.overwrite === true) {
1010
+ await writeContentsToFile(configFile, configTemplate);
1011
+ console.log(`Wrote config file to ${strong(configFile)}`);
1012
+ }
1013
+ } catch (e) {
1014
+ command.error(e);
1015
+ }
1016
+ });
1017
+ setProgramOptions({ program: subProgram, dotsecConfig });
1018
+ return subProgram;
1019
+ };
1020
+ var init_default2 = addInitProgram;
1021
+ var addPushProgram = async (program2, options) => {
1022
+ const { dotsecConfig, handlers } = options;
1023
+ const subProgram = program2.enablePositionalOptions().passThroughOptions().command("push").action(async (_options, command) => {
1024
+ try {
1025
+ const {
1026
+ // verbose,
1027
+ using,
1028
+ envFile,
1029
+ secFile,
1030
+ engine,
1031
+ yes
1032
+ } = command.optsWithGlobals();
1033
+ const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
1034
+ const pluginCliDecrypt = (handlers || []).find((handler) => {
1035
+ return handler.decrypt?.triggerOptionValue === encryptionEngine;
1036
+ })?.decrypt;
1037
+ const pluginCliPush = (handlers || []).find((handler) => {
1038
+ return handler.push?.triggerOptionValue === encryptionEngine;
1039
+ })?.push;
1040
+ if (!pluginCliPush) {
1041
+ throw new Error("No push plugin found!");
1042
+ }
1043
+ const allOptionKeys = [
1044
+ ...Object.keys(pluginCliDecrypt?.options || {}),
1045
+ ...Object.keys(pluginCliDecrypt?.requiredOptions || {}),
1046
+ ...Object.keys(pluginCliPush?.options || {}),
1047
+ ...Object.keys(pluginCliPush?.requiredOptions || {})
1048
+ ];
1049
+ const allOptionsValues = Object.fromEntries(
1050
+ allOptionKeys.map((key) => {
1051
+ return [key, _options[key]];
1052
+ })
1053
+ );
1054
+ let envContents;
1055
+ if (using === "env") {
1056
+ if (!envFile) {
1057
+ throw new Error("No dotenv file specified in --env-file option");
1058
+ }
1059
+ envContents = fs3__default.default.readFileSync(envFile, "utf8");
1060
+ } else {
1061
+ if (!secFile) {
1062
+ throw new Error("No dotsec file specified in --sec-file option");
1063
+ }
1064
+ if (!pluginCliDecrypt) {
1065
+ throw new Error(
1066
+ `No decryption plugin found, available decryption engine(s): ${handlers.map((e) => `--${e.decrypt?.triggerOptionValue}`).join(", ")}`
1067
+ );
1068
+ }
1069
+ const dotSecContents = fs3__default.default.readFileSync(secFile, "utf8");
1070
+ envContents = await pluginCliDecrypt.handler({
1071
+ ciphertext: dotSecContents,
1072
+ ...allOptionsValues
1073
+ });
1074
+ }
1075
+ if (envContents) {
1076
+ const dotenvVars = parse(envContents).obj;
1077
+ const expandedEnvVars = dotenvExpand.expand({
1078
+ ignoreProcessEnv: true,
1079
+ parsed: {
1080
+ // add standard env variables
1081
+ ...process.env,
1082
+ // add custom env variables, either from .env or .sec, (or empty object if none)
1083
+ ...dotenvVars
1084
+ }
1085
+ });
1086
+ if (expandedEnvVars.parsed) {
1087
+ await pluginCliPush.handler({
1088
+ push: expandedEnvVars.parsed,
1089
+ yes,
1090
+ ...allOptionsValues
1091
+ });
1092
+ }
1093
+ } else {
1094
+ throw new Error("No .env or .sec file provided");
1095
+ }
1096
+ } catch (e) {
1097
+ console.error(e);
1098
+ process.exit(1);
1099
+ }
1100
+ });
1101
+ setProgramOptions({ program: subProgram, dotsecConfig });
1102
+ const engines = options.handlers.map(
1103
+ ({ decrypt }) => decrypt.triggerOptionValue
1104
+ );
1105
+ subProgram.option(
1106
+ "--engine <engine>",
1107
+ `Encryption engine${engines.length > 0 ? "s" : ""} to use: ${engines.length === 1 ? engines[0] : engines.join(", ")}`,
1108
+ engines.length === 1 ? engines[0] : void 0
1109
+ );
1110
+ const allOptions = {};
1111
+ options.handlers.forEach((handlers2) => {
1112
+ Object.keys(handlers2).map((handlerName) => {
1113
+ const { options: cliOptions, requiredOptions } = handlers2[handlerName];
1114
+ Object.keys(cliOptions || {}).forEach((key) => {
1115
+ allOptions[key] = Array.isArray(cliOptions[key]) ? cliOptions[key] : { ...allOptions[key], ...cliOptions[key] };
1116
+ });
1117
+ Object.keys(requiredOptions || {}).forEach((key) => {
1118
+ allOptions[key] = Array.isArray(requiredOptions[key]) ? requiredOptions[key] : {
1119
+ ...allOptions[key],
1120
+ ...requiredOptions[key],
1121
+ required: true
1122
+ };
1123
+ });
1124
+ });
1125
+ });
1126
+ const usage = [];
1127
+ const descriptions = [];
1128
+ handlers.forEach((handler) => {
1129
+ if (handler.push?.description) {
1130
+ descriptions.push(handler.push.description);
1131
+ }
1132
+ if (handler.push?.usage) {
1133
+ usage.push(handler.push.usage);
1134
+ }
1135
+ });
1136
+ if (descriptions.length > 0) {
1137
+ subProgram.description(descriptions.join("\n"));
1138
+ }
1139
+ if (usage.length > 0) {
1140
+ subProgram.usage(usage.join("\n"));
1141
+ }
1142
+ addPluginOptions(
1143
+ Object.fromEntries(
1144
+ Object.entries(allOptions).filter(
1145
+ ([_key, value]) => value.required !== true
1146
+ )
1147
+ ),
1148
+ subProgram
1149
+ );
1150
+ addPluginOptions(
1151
+ Object.fromEntries(
1152
+ Object.entries(allOptions).filter(
1153
+ ([_key, value]) => value.required === true
1154
+ )
1155
+ ),
1156
+ subProgram,
1157
+ true
1158
+ );
1159
+ return subProgram;
1160
+ };
1161
+ var push_default2 = addPushProgram;
1162
+ var addRunProgam = (program2, options) => {
1163
+ const { dotsecConfig, decryptHandlers } = options || {};
1164
+ const hasDecryptEngine = decryptHandlers !== void 0 && decryptHandlers.length > 0;
1165
+ const subProgram = program2.command("run <command...>").allowUnknownOption(true).enablePositionalOptions().passThroughOptions().showHelpAfterError(true).action(
1166
+ async (commands, _options, command) => {
1167
+ try {
1168
+ const {
1169
+ envFile,
1170
+ using,
1171
+ secFile,
1172
+ engine,
1173
+ outputBackgroundColor,
1174
+ showOutputPrefix,
1175
+ outputPrefix
1176
+ } = command.optsWithGlobals();
1177
+ let envContents;
1178
+ if (using === "env" || hasDecryptEngine === false) {
1179
+ if (!envFile) {
1180
+ throw new Error("No dotenv file specified in --env-file option");
1181
+ }
1182
+ envContents = fs3__default.default.readFileSync(envFile, "utf8");
1183
+ } else if (using === "sec") {
1184
+ if (!secFile) {
1185
+ throw new Error("No dotsec file specified in --sec-file option");
1186
+ }
1187
+ const encryptionEngine = engine || dotsecConfig?.defaults?.encryptionEngine;
1188
+ const pluginCliDecrypt = (decryptHandlers || []).find((handler) => {
1189
+ return handler.triggerOptionValue === encryptionEngine;
1190
+ });
1191
+ if (!pluginCliDecrypt) {
1192
+ throw new Error(
1193
+ `No decryption plugin found, available decryption engine(s): ${(decryptHandlers || []).map((e) => `--${e.triggerOptionValue}`).join(", ")}`
1194
+ );
1195
+ }
1196
+ const allOptionKeys = [
1197
+ ...Object.keys(pluginCliDecrypt.options || {}),
1198
+ ...Object.keys(pluginCliDecrypt.requiredOptions || {})
1199
+ ];
1200
+ const allOptionsValues = Object.fromEntries(
1201
+ allOptionKeys.map((key) => {
1202
+ return [key, _options[key]];
1203
+ })
1204
+ );
1205
+ try {
1206
+ const dotSecContents = fs3__default.default.readFileSync(secFile, "utf8");
1207
+ envContents = await pluginCliDecrypt.handler({
1208
+ ciphertext: dotSecContents,
1209
+ ...allOptionsValues
1210
+ });
1211
+ } catch (e) {
1212
+ console.error("Something bad happened while decrypting.");
1213
+ console.error(`File: ${secFile}`);
1214
+ throw e;
1215
+ }
1216
+ }
1217
+ if (envContents) {
1218
+ const dotenvVars = parse(envContents).obj;
1219
+ const expandedEnvVars = dotenvExpand.expand({
1220
+ ignoreProcessEnv: true,
1221
+ parsed: {
1222
+ // add standard env variables
1223
+ ...process.env,
1224
+ // add custom env variables, either from .env or .sec, (or empty object if none)
1225
+ ...dotenvVars
1226
+ }
1227
+ });
1228
+ const [userCommand, ...userCommandArgs] = commands;
1229
+ const waiter = await new Promise((resolve) => {
1230
+ const cprocess = child_process.spawn(userCommand, [...userCommandArgs], {
1231
+ stdio: "pipe",
1232
+ shell: false,
1233
+ env: {
1234
+ ...expandedEnvVars.parsed,
1235
+ ...process.env,
1236
+ __DOTSEC_ENV__: JSON.stringify(Object.keys(dotenvVars))
1237
+ }
1238
+ });
1239
+ const expandedEnvVarsWithoutEnv = dotenvExpand.expand({
1240
+ ignoreProcessEnv: true,
1241
+ parsed: {
1242
+ // add standard env variables
1243
+ // add custom env variables, either from .env or .sec, (or empty object if none)
1244
+ ...dotenvVars
1245
+ }
1246
+ });
1247
+ cprocess.stdout.setEncoding("utf8");
1248
+ let backgroundColor = outputBackgroundColor || dotsecConfig.defaults?.options?.outputBackgroundColor;
1249
+ if (typeof backgroundColor === "boolean" && backgroundColor === true) {
1250
+ backgroundColor = "red-bright";
1251
+ }
1252
+ let addBackgroundColor = (str) => str;
1253
+ if (backgroundColor) {
1254
+ if (!backgroundColors.includes(backgroundColor)) {
1255
+ throw new Error(
1256
+ `Invalid background color: ${backgroundColor}`
1257
+ );
1258
+ }
1259
+ const backgroundColorFnName = camelCase.camelCase(
1260
+ `bg-${backgroundColor}`
1261
+ );
1262
+ if (chalk2__default.default[backgroundColorFnName]) {
1263
+ addBackgroundColor = chalk2__default.default[backgroundColorFnName];
1264
+ } else {
1265
+ console.warn(
1266
+ `Invalid background color: ${backgroundColorFnName}, using default: red`
1267
+ );
1268
+ addBackgroundColor = chalk2__default.default.bgRedBright;
1269
+ }
1270
+ }
1271
+ const prefix = showOutputPrefix || dotsecConfig?.defaults?.options?.showOutputPrefix ? `${dotsecConfig?.defaults?.options?.outputPrefix || outputPrefix || "(dotsec) "}` : "";
1272
+ let lineBuffer = "";
1273
+ cprocess.stdout.on("data", function(data) {
1274
+ lineBuffer += data.toString();
1275
+ const lines = lineBuffer.split("\n");
1276
+ for (let i = 0; i < lines.length - 1; i++) {
1277
+ const line = lines[i];
1278
+ const redactedLines = Object.entries(
1279
+ expandedEnvVarsWithoutEnv.parsed || {}
1280
+ ).sort(([, a], [, b]) => {
1281
+ if (a.length > b.length) {
1282
+ return -1;
1283
+ } else if (a.length < b.length) {
1284
+ return 1;
1285
+ } else {
1286
+ return 0;
1287
+ }
1288
+ }).reduce((acc, [key, value]) => {
1289
+ if (dotsecConfig?.redaction?.show?.includes(key)) {
1290
+ return acc;
1291
+ } else {
1292
+ const redactedValue = value.replace(/./g, "*");
1293
+ return acc.replace(value, redactedValue);
1294
+ }
1295
+ }, line);
1296
+ console.log(prefix + addBackgroundColor(redactedLines));
1297
+ }
1298
+ lineBuffer = lines[lines.length - 1];
1299
+ });
1300
+ cprocess.stdout.on("end", function() {
1301
+ console.log(prefix + addBackgroundColor(lineBuffer));
1302
+ });
1303
+ cprocess.stderr.setEncoding("utf8");
1304
+ cprocess.stderr.on("data", function(data) {
1305
+ process.stderr.write(data.toString());
1306
+ });
1307
+ cprocess.on("exit", (code) => {
1308
+ resolve(code);
1309
+ });
1310
+ });
1311
+ if (waiter !== 0) {
1312
+ process.exit(waiter || 1);
1313
+ }
1314
+ } else {
1315
+ throw new Error("No .env or .sec file provided");
1316
+ }
1317
+ } catch (e) {
1318
+ console.error(strong(e.message));
1319
+ command.help();
1320
+ }
1321
+ }
1322
+ );
1323
+ setProgramOptions({
1324
+ program: subProgram,
1325
+ commandName: hasDecryptEngine ? "run" : "runEnvOnly",
1326
+ dotsecConfig
1327
+ });
1328
+ if (hasDecryptEngine) {
1329
+ decryptHandlers?.map((run) => {
1330
+ const { options: options2, requiredOptions } = run;
1331
+ addPluginOptions(options2, subProgram);
1332
+ addPluginOptions(requiredOptions, subProgram, true);
1333
+ });
1334
+ const engines = decryptHandlers?.map((e) => e.triggerOptionValue);
1335
+ subProgram.option(
1336
+ "--engine <engine>",
1337
+ `Encryption engine${engines.length > 0 ? "s" : ""}: ${engines.join(", "), engines.length === 1 ? engines[0] : void 0}`
1338
+ // engines.length === 1 ? engines[0] : undefined,
1339
+ );
1340
+ }
1341
+ return subProgram;
1342
+ };
1343
+ var run_default2 = addRunProgam;
1344
+ var separator = {
1345
+ keyword: "separator",
1346
+ type: "string",
1347
+ metaSchema: {
1348
+ type: "string",
1349
+ description: "value separator"
1350
+ },
1351
+ modifying: true,
1352
+ valid: true,
1353
+ errors: false,
1354
+ compile: (schema) => (data, ctx) => {
1355
+ if (ctx) {
1356
+ const { parentData, parentDataProperty } = ctx;
1357
+ parentData[parentDataProperty] = data === "" ? [] : data.split(schema);
1358
+ return true;
1359
+ } else {
1360
+ return false;
1361
+ }
1362
+ }
1363
+ };
1364
+ var program = new commander.Command();
1365
+ (async () => {
1366
+ const parsedOptions = yargsParser__default.default(process.argv);
1367
+ const argvPluginModules = [];
1368
+ if (parsedOptions.plugin) {
1369
+ if (Array.isArray(parsedOptions.plugin)) {
1370
+ argvPluginModules.push(...parsedOptions.plugin);
1371
+ } else {
1372
+ argvPluginModules.push(parsedOptions.plugin);
1373
+ }
1374
+ }
1375
+ const someConfigFile = parsedOptions.configFile || parsedOptions.c;
1376
+ const configFile = [
1377
+ ...Array.isArray(someConfigFile) ? someConfigFile : [someConfigFile]
1378
+ ]?.[0] || process.env.DOTSEC_CONFIG_FILE;
1379
+ const { contents: dotsecConfig = {} } = await getMagicalConfig(configFile);
1380
+ const { defaults = {}, push: pushVariables, plugins } = dotsecConfig;
1381
+ program.name("dotsec").description(".env, but secure").version("1.0.0").passThroughOptions().action((_options, other) => {
1382
+ other.help();
1383
+ });
1384
+ setProgramOptions({ program, dotsecConfig });
1385
+ const ajv = new Ajv__default.default({
1386
+ allErrors: true,
1387
+ removeAdditional: true,
1388
+ useDefaults: true,
1389
+ coerceTypes: true,
1390
+ allowUnionTypes: true,
1391
+ addUsedSchema: false,
1392
+ keywords: [separator]
1393
+ });
1394
+ const pluginModules = {};
1395
+ if (plugins) {
1396
+ for (const pluginName of plugins) {
1397
+ if (!defaults?.plugins?.[pluginName]) {
1398
+ defaults.plugins = {
1399
+ ...defaults.plugins,
1400
+ [pluginName]: {}
1401
+ };
1402
+ }
1403
+ }
1404
+ }
1405
+ if (argvPluginModules.length > 0) {
1406
+ for (const pluginModule of argvPluginModules) {
1407
+ const plugin = await loadDotsecPlugin({ name: pluginModule });
1408
+ const loadedPlugin = await plugin({
1409
+ dotsecConfig,
1410
+ ajv,
1411
+ configFile
1412
+ });
1413
+ pluginModules[loadedPlugin.name] = pluginModule;
1414
+ if (argvPluginModules.length === 1) {
1415
+ dotsecConfig.defaults = {
1416
+ ...dotsecConfig.defaults,
1417
+ encryptionEngine: String(loadedPlugin.name),
1418
+ plugins: {
1419
+ ...dotsecConfig.defaults?.plugins,
1420
+ [loadedPlugin.name]: {
1421
+ ...dotsecConfig.defaults?.plugins?.[loadedPlugin.name]
1422
+ }
1423
+ }
1424
+ };
1425
+ }
1426
+ }
1427
+ }
1428
+ if (defaults?.encryptionEngine) {
1429
+ if (!defaults?.plugins?.[defaults.encryptionEngine]) {
1430
+ defaults.plugins = {
1431
+ ...defaults.plugins,
1432
+ [defaults.encryptionEngine]: {}
1433
+ };
1434
+ }
1435
+ }
1436
+ if (defaults?.plugins) {
1437
+ Object.entries(defaults?.plugins).forEach(
1438
+ ([pluginName, pluginModule]) => {
1439
+ if (pluginModule?.name) {
1440
+ pluginModules[pluginName] = pluginModule?.name;
1441
+ } else {
1442
+ pluginModules[pluginName] = `@dotsec/plugin-${pluginName}`;
1443
+ }
1444
+ }
1445
+ );
1446
+ }
1447
+ Object.values(pushVariables || {}).forEach((pushVariable) => {
1448
+ Object.keys(pushVariable).forEach((pluginName) => {
1449
+ if (!pluginModules[pluginName]) {
1450
+ pluginModules[pluginName] = `@dotsec/plugin-${pluginName}`;
1451
+ }
1452
+ });
1453
+ });
1454
+ const cliPluginEncryptHandlers = [];
1455
+ const cliPluginDecryptHandlers = [];
1456
+ const cliPluginPushHandlers = [];
1457
+ for (const pluginName of Object.keys(pluginModules)) {
1458
+ const pluginModule = pluginModules[pluginName];
1459
+ const initDotsecPlugin = await loadDotsecPlugin({ name: pluginModule });
1460
+ const { addCliCommand, cliHandlers: cli } = await initDotsecPlugin({
1461
+ ajv,
1462
+ dotsecConfig,
1463
+ configFile
1464
+ });
1465
+ if (cli?.encrypt) {
1466
+ cliPluginEncryptHandlers.push(cli.encrypt);
1467
+ }
1468
+ if (cli?.decrypt) {
1469
+ cliPluginDecryptHandlers.push(cli.decrypt);
1470
+ if (cli?.push) {
1471
+ cliPluginPushHandlers.push({ push: cli.push, decrypt: cli.decrypt });
1472
+ }
1473
+ }
1474
+ if (addCliCommand) {
1475
+ addCliCommand({ program });
1476
+ }
1477
+ }
1478
+ if (cliPluginEncryptHandlers.length) {
1479
+ await encrypt_default2(program, {
1480
+ dotsecConfig,
1481
+ encryptHandlers: cliPluginEncryptHandlers
1482
+ });
1483
+ }
1484
+ if (cliPluginDecryptHandlers.length) {
1485
+ await decrypt_default2(program, {
1486
+ dotsecConfig,
1487
+ decryptHandlers: cliPluginDecryptHandlers
1488
+ });
1489
+ }
1490
+ if (cliPluginPushHandlers.length) {
1491
+ await push_default2(program, {
1492
+ dotsecConfig,
1493
+ handlers: cliPluginPushHandlers
1494
+ });
1495
+ }
1496
+ await init_default2(program, { dotsecConfig });
1497
+ await run_default2(program, {
1498
+ dotsecConfig,
1499
+ decryptHandlers: cliPluginDecryptHandlers
1500
+ });
1501
+ await program.parse();
1502
+ })();
1503
+ //# sourceMappingURL=out.js.map
167
1504
  //# sourceMappingURL=index.js.map