vite-plugin-envka 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +29 -0
  2. package/README.md +97 -0
  3. package/dist/bin/env-cli.d.ts +2 -0
  4. package/dist/bin/env-cli.js +54 -0
  5. package/dist/src/envkaValidator.d.ts +28 -0
  6. package/dist/src/envkaValidator.js +125 -0
  7. package/dist/src/generateEnvTypes.d.ts +2 -0
  8. package/dist/src/generateEnvTypes.js +11 -0
  9. package/dist/src/generateFromArkType.d.ts +1 -0
  10. package/dist/src/generateFromArkType.js +35 -0
  11. package/dist/src/generateFromGeneric.d.ts +1 -0
  12. package/dist/src/generateFromGeneric.js +19 -0
  13. package/dist/src/generateFromValibot.d.ts +9 -0
  14. package/dist/src/generateFromValibot.js +63 -0
  15. package/dist/src/generateFromZod.d.ts +2 -0
  16. package/dist/src/generateFromZod.js +59 -0
  17. package/dist/src/generateType.d.ts +1 -0
  18. package/dist/src/generateType.js +19 -0
  19. package/dist/src/generateTypes.d.ts +2 -0
  20. package/dist/src/generateTypes.js +29 -0
  21. package/dist/src/index.d.ts +12 -0
  22. package/dist/src/index.js +69 -0
  23. package/dist/src/printEnvExample.d.ts +2 -0
  24. package/dist/src/printEnvExample.js +6 -0
  25. package/dist/src/types.d.ts +7 -0
  26. package/dist/src/types.js +1 -0
  27. package/dist/src/utils/isStandardSchema.d.ts +2 -0
  28. package/dist/src/utils/isStandardSchema.js +14 -0
  29. package/dist/src/utils/log.d.ts +3 -0
  30. package/dist/src/utils/log.js +19 -0
  31. package/dist/src/utils/parseEnv.d.ts +1 -0
  32. package/dist/src/utils/parseEnv.js +22 -0
  33. package/dist/src/utils/parser.d.ts +1 -0
  34. package/dist/src/utils/parser.js +22 -0
  35. package/dist/src/utils/renderEnvDts.d.ts +1 -0
  36. package/dist/src/utils/renderEnvDts.js +4 -0
  37. package/dist/src/validate.d.ts +10 -0
  38. package/dist/src/validate.js +10 -0
  39. package/dist/src/validateEnv.d.ts +5 -0
  40. package/dist/src/validateEnv.js +3 -0
  41. package/package.json +63 -0
package/LICENSE ADDED
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2025, Ireneo C. Cobar Jr
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,97 @@
1
+ # vite-plugin-envka
2
+
3
+ <!-- [![npm version](https://img.shields.io/npm/v/vite-plugin-envka.svg)](https://www.npmjs.com/package/vite-plugin-envka) -->
4
+
5
+ [![Vite](https://img.shields.io/badge/vite-compatible-blue.svg)](https://vitejs.dev/)
6
+
7
+ ## Overview
8
+
9
+ **Envka** is a vite plugin designed to enhance environment variable management in Vite projects.
10
+
11
+ ## Features
12
+
13
+ - Validate environment variables at Vite build and dev server startup
14
+ - TypeScript type generation (env.d.ts)
15
+ - Generate `.env.example` from schema
16
+ - Checking for unused and undeclared environment variables (planned)
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install vite-plugin-envka --save-dev
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ Add to your `vite.config.ts`:
27
+
28
+ ```ts
29
+ import envka from "vite-plugin-envka";
30
+
31
+ export default {
32
+ plugins: [envka(/* options */)],
33
+ };
34
+ ```
35
+
36
+ ## Configuration
37
+
38
+ ```ts
39
+ import envka from "vite-plugin-envka";
40
+
41
+ export default {
42
+ plugins: [
43
+ envka({
44
+ schema,
45
+ generateTypes: false /** Default */,
46
+ }),
47
+ ],
48
+ };
49
+ ```
50
+
51
+ ### env.d.ts generation
52
+
53
+ Generating env.d.ts is done after a successful validation. By default, its turned-off. You need to add `generateTypes: true` to turn it on.
54
+
55
+ ### .env.example generation
56
+
57
+ Generating .env.example is done via the CLI
58
+
59
+ ```bash
60
+ npx env example --schema /path/to/schema/file --output /optional/output
61
+ ```
62
+
63
+ ## Configuration example
64
+
65
+ ```ts
66
+ import envka, { envkaValidator } from "vite-plugin-envka";
67
+
68
+ /** Example using Envka Validator */
69
+ export const builtinSchema = envkaValidator({
70
+ FOO: { type: "string", default: "bar" },
71
+ BAR: {
72
+ type: "number",
73
+ description: "A comment on your .env.example",
74
+ },
75
+ TEST_MODE: { type: "enum", enum: ["dev", "prod"] },
76
+ });
77
+
78
+ export default {
79
+ plugins: [
80
+ envka({
81
+ schema: builtinSchema,
82
+ generateTypes: true,
83
+ }),
84
+ ],
85
+ };
86
+ ```
87
+
88
+ ## License
89
+
90
+ BSD-3 Clause
91
+
92
+ ## Links
93
+
94
+ <!-- - [npm](https://www.npmjs.com/package/vite-plugin-envka) -->
95
+
96
+ - [Vite](https://vitejs.dev/)
97
+ - [Issues](https://github.com/ireneo-cobarjr/vite-plugin-envka/issues)
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from "commander";
3
+ import * as path from "path";
4
+ import * as fs from "fs";
5
+ import { printEnvExample } from "../src/printEnvExample.js";
6
+ import { log } from "../src/utils/log.js";
7
+ const program = new Command();
8
+ program.name("env").description("Environment CLI for envka plugin");
9
+ program
10
+ .command("example")
11
+ .description("Generate a .env.example file from a validation schema.")
12
+ .requiredOption("--schema <schemaPath>", "Path to the validation schema file (e.g. ./path/schema.ts)")
13
+ .option("--output <outputPath>", "Optional path (including filename) to save the .env.example file")
14
+ .action(async (opts) => {
15
+ const schemaPath = opts.schema;
16
+ if (!schemaPath) {
17
+ log("--schema option is required.", "error");
18
+ process.exit(1);
19
+ }
20
+ const absSchemaPath = path.isAbsolute(schemaPath)
21
+ ? schemaPath
22
+ : path.resolve(process.cwd(), schemaPath);
23
+ if (!fs.existsSync(absSchemaPath)) {
24
+ log(`Schema file not found at ${absSchemaPath}`, "error");
25
+ process.exit(1);
26
+ }
27
+ // Import the schema module
28
+ let imported;
29
+ try {
30
+ imported = await import(absSchemaPath);
31
+ }
32
+ catch (e) {
33
+ log(`Failed to import schema from ${absSchemaPath}`, "error");
34
+ process.exit(1);
35
+ }
36
+ // Use imported schema for .env.example generation
37
+ const schema = imported.default || imported.schema || imported;
38
+ let exampleContent;
39
+ try {
40
+ exampleContent = printEnvExample(schema);
41
+ }
42
+ catch (e) {
43
+ log("Failed to generate .env.example", "error");
44
+ process.exit(1);
45
+ }
46
+ const outputPath = opts.output
47
+ ? path.isAbsolute(opts.output)
48
+ ? opts.output
49
+ : path.resolve(process.cwd(), opts.output)
50
+ : path.resolve(process.cwd(), ".env.example");
51
+ fs.writeFileSync(outputPath, exampleContent);
52
+ log(`.env.example generated at ${outputPath}`, "success");
53
+ });
54
+ program.parse(process.argv);
@@ -0,0 +1,28 @@
1
+ export type EnvkaStandardSchemaV1 = EnvkaSchema & {
2
+ "~standard": {
3
+ version: 1;
4
+ vendor: "envka";
5
+ validate: (env: Record<string, any>) => {
6
+ valid: boolean;
7
+ issues?: any[];
8
+ };
9
+ generateType: () => string;
10
+ generateExample: () => string;
11
+ rawSchema: EnvkaSchema;
12
+ };
13
+ };
14
+ export type EnvkaType = "string" | "number" | "boolean" | "enum" | "union" | "range";
15
+ export interface EnvkaField {
16
+ type: EnvkaType;
17
+ enum?: Array<string | number>;
18
+ union?: Array<EnvkaField>;
19
+ range?: [number, number];
20
+ description?: string;
21
+ }
22
+ export type EnvkaSchema = Record<string, EnvkaField>;
23
+ /**
24
+ * Generates a .env.example string from an EnvkaSchema.
25
+ */
26
+ export declare function generateExample(schema: EnvkaSchema): string;
27
+ declare const envkaValidator: (schema: EnvkaSchema) => EnvkaStandardSchemaV1;
28
+ export default envkaValidator;
@@ -0,0 +1,125 @@
1
+ import { renderEnvDts } from "./utils/renderEnvDts.js";
2
+ /**
3
+ * Generates a .env.example string from an EnvkaSchema.
4
+ */
5
+ export function generateExample(schema) {
6
+ const lines = Object.entries(schema).map(([key, field]) => {
7
+ let comment = "";
8
+ if (field.description) {
9
+ comment = `# ${field.description}`;
10
+ }
11
+ else if (field.type === "enum" && field.enum) {
12
+ comment = `# enum: ${field.enum.join(", ")}`;
13
+ }
14
+ else if (field.type) {
15
+ comment = `# ${field.type}`;
16
+ }
17
+ else {
18
+ comment = "#";
19
+ }
20
+ return `${comment}\n${key}=`;
21
+ });
22
+ return lines.join("\n\n") + "\n";
23
+ }
24
+ function validateField(field, value) {
25
+ switch (field.type) {
26
+ case "string":
27
+ return typeof value === "string";
28
+ case "number":
29
+ return typeof value === "number";
30
+ case "boolean":
31
+ return typeof value === "boolean";
32
+ case "enum":
33
+ return field.enum?.includes(value) ?? false;
34
+ case "union":
35
+ return field.union?.some((sub) => validateField(sub, value)) ?? false;
36
+ case "range":
37
+ if (!field.range)
38
+ return false;
39
+ return (typeof value === "number" &&
40
+ value >= field.range[0] &&
41
+ value <= field.range[1]);
42
+ default:
43
+ return false;
44
+ }
45
+ }
46
+ function validateEnvka(env, schema) {
47
+ const issues = [];
48
+ const result = {};
49
+ for (const key in schema) {
50
+ const field = schema[key];
51
+ const value = env[key];
52
+ if (!validateField(field, value)) {
53
+ let expectedStr = field.type;
54
+ if (field.type === "enum" && Array.isArray(field.enum)) {
55
+ expectedStr = field.enum.join(" | ");
56
+ }
57
+ issues.push(`Invalid value for ${key}: got ${value} but expected ${expectedStr}`);
58
+ }
59
+ else {
60
+ result[key] = value;
61
+ }
62
+ }
63
+ if (issues.length > 0) {
64
+ return { issues };
65
+ }
66
+ return { value: result };
67
+ }
68
+ function generateEnvkaTypes(schema) {
69
+ const lines = Object.entries(schema).map(([key, field]) => {
70
+ switch (field.type) {
71
+ case "string":
72
+ return ` readonly ${key}: string;`;
73
+ case "number":
74
+ return ` readonly ${key}: number;`;
75
+ case "boolean":
76
+ return ` readonly ${key}: boolean;`;
77
+ case "enum":
78
+ return ` readonly ${key}: ${field.enum
79
+ ?.map((v) => JSON.stringify(v))
80
+ .join(" | ")};`;
81
+ case "union":
82
+ return ` readonly ${key}: ${field.union
83
+ ?.map((sub) => {
84
+ if (sub.type === "enum")
85
+ return sub.enum?.map((v) => JSON.stringify(v)).join(" | ");
86
+ if (sub.type === "range")
87
+ return `${sub.range?.[0]} | ... | ${sub.range?.[1]}`;
88
+ return sub.type;
89
+ })
90
+ .join(" | ")};`;
91
+ case "range":
92
+ return ` readonly ${key}: number; // ${field.range?.[0]}-${field.range?.[1]}`;
93
+ default:
94
+ return ` readonly ${key}: unknown;`;
95
+ }
96
+ });
97
+ return renderEnvDts(lines);
98
+ }
99
+ const envkaValidator = (schema) => {
100
+ const { ["~standard"]: _, ...fields } = schema;
101
+ return Object.assign({}, fields, {
102
+ "~standard": {
103
+ version: 1,
104
+ vendor: "envka",
105
+ validate: (value) => {
106
+ const env = typeof value === "object" && value !== null
107
+ ? value
108
+ : {};
109
+ const result = validateEnvka(env, schema);
110
+ if (result.issues) {
111
+ return {
112
+ value: undefined,
113
+ issues: result.issues,
114
+ valid: false,
115
+ };
116
+ }
117
+ return { value: result.value, issues: undefined, valid: true };
118
+ },
119
+ generateType: () => generateEnvkaTypes(schema),
120
+ generateExample: () => generateExample(schema),
121
+ rawSchema: schema,
122
+ },
123
+ });
124
+ };
125
+ export default envkaValidator;
@@ -0,0 +1,2 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ export declare function generateEnvTypes(schema: StandardSchemaV1, validatedResult: Record<string, unknown>): string;
@@ -0,0 +1,11 @@
1
+ import { generate } from "./generateType.js";
2
+ export function generateEnvTypes(schema, validatedResult) {
3
+ let vendor = schema["~standard"].vendor.toLowerCase();
4
+ if (!vendor) {
5
+ throw new Error("Schema vendor is missing or invalid.");
6
+ }
7
+ if (vendor === "envka") {
8
+ return schema["~standard"].generateType();
9
+ }
10
+ return generate(validatedResult);
11
+ }
@@ -0,0 +1 @@
1
+ export declare function generateFromArkType(schema: any): string;
@@ -0,0 +1,35 @@
1
+ import { renderEnvDts } from "./utils/renderEnvDts.js";
2
+ // Use ArkType's toJsonSchema to extract types
3
+ export function generateFromArkType(schema) {
4
+ if (typeof schema.toJsonSchema !== "function") {
5
+ throw new Error("ArkType schema does not have toJsonSchema method.");
6
+ }
7
+ const jsonSchema = schema.toJsonSchema();
8
+ if (!jsonSchema || typeof jsonSchema !== "object" || !jsonSchema.properties) {
9
+ throw new Error("ArkType toJsonSchema did not return expected object shape.");
10
+ }
11
+ const lines = [];
12
+ for (const [key, prop] of Object.entries(jsonSchema.properties)) {
13
+ lines.push(` readonly ${key}: ${arkJsonSchemaTypeToTs(prop)};`);
14
+ }
15
+ return renderEnvDts(lines);
16
+ }
17
+ function arkJsonSchemaTypeToTs(prop) {
18
+ if (!prop || typeof prop !== "object")
19
+ return "unknown";
20
+ if (prop.enum) {
21
+ return prop.enum.map((v) => JSON.stringify(v)).join(" | ");
22
+ }
23
+ switch (prop.type) {
24
+ case "string":
25
+ return "string";
26
+ case "number":
27
+ return "number";
28
+ case "boolean":
29
+ return "boolean";
30
+ case "integer":
31
+ return "number";
32
+ default:
33
+ return "unknown";
34
+ }
35
+ }
@@ -0,0 +1 @@
1
+ export declare function generateFromGeneric(validated: Record<string, any>): string;
@@ -0,0 +1,19 @@
1
+ import { renderEnvDts } from "./utils/renderEnvDts.js";
2
+ function jsTypeToTs(type) {
3
+ if (type === "string")
4
+ return "string";
5
+ if (type === "number")
6
+ return "number";
7
+ if (type === "boolean")
8
+ return "boolean";
9
+ return "unknown";
10
+ }
11
+ export function generateFromGeneric(validated) {
12
+ const keys = Object.keys(validated);
13
+ const lines = keys.map((key) => {
14
+ const value = validated[key];
15
+ const tsType = jsTypeToTs(typeof value);
16
+ return ` readonly ${key}: ${tsType};`;
17
+ });
18
+ return renderEnvDts(lines);
19
+ }
@@ -0,0 +1,9 @@
1
+ export type ValibotObjectSchema = {
2
+ entries?: Record<string, {
3
+ type: string;
4
+ } & Record<string, unknown>>;
5
+ shape?: Record<string, {
6
+ type: string;
7
+ } & Record<string, unknown>>;
8
+ };
9
+ export declare function generateFromValibot(schema: ValibotObjectSchema): string;
@@ -0,0 +1,63 @@
1
+ import { renderEnvDts } from "./utils/renderEnvDts.js";
2
+ function valibotTypeToTs(valiType) {
3
+ if (valiType.type === "enum") {
4
+ // Valibot v1: enums are objects under the 'enum' property
5
+ if (valiType.enum && typeof valiType.enum === "object") {
6
+ return Object.values(valiType.enum)
7
+ .map((v) => JSON.stringify(v))
8
+ .join(" | ");
9
+ }
10
+ // fallback for older valibot: enums as array under 'values'
11
+ if ("values" in valiType &&
12
+ Array.isArray(valiType.values)) {
13
+ return valiType.values
14
+ .map((v) => JSON.stringify(v))
15
+ .join(" | ");
16
+ }
17
+ }
18
+ if (valiType.type === "union" &&
19
+ "options" in valiType &&
20
+ Array.isArray(valiType.options)) {
21
+ // Union: output as union of types
22
+ const options = valiType.options;
23
+ // Special case: all options are literals
24
+ if (options.every((opt) => typeof opt === "object" &&
25
+ opt !== null &&
26
+ "type" in opt &&
27
+ opt.type === "literal")) {
28
+ return options
29
+ .map((opt) => JSON.stringify(opt.value))
30
+ .join(" | ");
31
+ }
32
+ return options
33
+ .map((opt) => {
34
+ if (typeof opt === "object" && opt !== null && "type" in opt) {
35
+ return valibotTypeToTs(opt);
36
+ }
37
+ return "unknown";
38
+ })
39
+ .join(" | ");
40
+ }
41
+ if (valiType.type === "literal" && "value" in valiType) {
42
+ return JSON.stringify(valiType.value);
43
+ }
44
+ switch (valiType.type) {
45
+ case "string":
46
+ return "string";
47
+ case "number":
48
+ return "number";
49
+ case "boolean":
50
+ return "boolean";
51
+ default:
52
+ return "unknown";
53
+ }
54
+ }
55
+ export function generateFromValibot(schema) {
56
+ const shape = schema.entries ?? schema.shape ?? {};
57
+ const lines = Object.keys(shape).map((key) => {
58
+ const valiType = shape[key];
59
+ const tsType = valibotTypeToTs(valiType);
60
+ return ` readonly ${key}: ${tsType};`;
61
+ });
62
+ return renderEnvDts(lines);
63
+ }
@@ -0,0 +1,2 @@
1
+ import { ZodObject } from "zod";
2
+ export declare function generateFromZod(schema: ZodObject): string;
@@ -0,0 +1,59 @@
1
+ import { renderEnvDts } from "./utils/renderEnvDts.js";
2
+ import { ZodOptional, ZodNullable, ZodString, ZodNumber, ZodBoolean, ZodDate, ZodEnum, ZodLiteral, ZodUnion, ZodDefault, } from "zod";
3
+ function zodTypeToTs(zodType) {
4
+ if (typeof ZodDefault !== "undefined" && zodType instanceof ZodDefault) {
5
+ // Unwrap ZodDefault to get the inner type
6
+ const innerType = zodType._def.innerType;
7
+ return zodTypeToTs(innerType);
8
+ }
9
+ if (typeof ZodEnum !== "undefined" && zodType instanceof ZodEnum) {
10
+ // ZodEnum: output as union of string literals (use .options, not .values)
11
+ const options = zodType.options;
12
+ return options.map((v) => JSON.stringify(v)).join(" | ");
13
+ }
14
+ if (typeof ZodUnion !== "undefined" && zodType instanceof ZodUnion) {
15
+ // ZodUnion: output as union of types
16
+ const options = zodType.options;
17
+ // Special case: all options are ZodLiteral (e.g., union of string literals)
18
+ if (options.every((opt) => opt instanceof ZodLiteral)) {
19
+ return options
20
+ .map((opt) => JSON.stringify(opt.value))
21
+ .join(" | ");
22
+ }
23
+ // Otherwise, join the mapped types
24
+ return options.map(zodTypeToTs).join(" | ");
25
+ }
26
+ if (typeof ZodLiteral !== "undefined" && zodType instanceof ZodLiteral) {
27
+ // ZodLiteral: output as literal value
28
+ return JSON.stringify(zodType.value);
29
+ }
30
+ if (zodType instanceof ZodString)
31
+ return "string";
32
+ if (zodType instanceof ZodNumber)
33
+ return "number";
34
+ if (zodType instanceof ZodBoolean)
35
+ return "boolean";
36
+ if (zodType instanceof ZodDate)
37
+ return "Date";
38
+ if (zodType instanceof ZodOptional) {
39
+ const optionalInner = zodType.def
40
+ .innerType;
41
+ return zodTypeToTs(optionalInner) + " | undefined";
42
+ }
43
+ if (zodType instanceof ZodNullable) {
44
+ const nullableInner = zodType.def
45
+ .innerType;
46
+ return zodTypeToTs(nullableInner) + " | null";
47
+ }
48
+ return "unknown";
49
+ }
50
+ export function generateFromZod(schema) {
51
+ // Use .shape property (public Zod API)
52
+ const shape = schema.shape;
53
+ const lines = Object.keys(shape).map((key) => {
54
+ const zodType = shape[key];
55
+ const tsType = zodTypeToTs(zodType);
56
+ return ` readonly ${key}: ${tsType};`;
57
+ });
58
+ return renderEnvDts(lines);
59
+ }
@@ -0,0 +1 @@
1
+ export declare function generate(validated: Record<string, any>): string;
@@ -0,0 +1,19 @@
1
+ import { renderEnvDts } from "./utils/renderEnvDts.js";
2
+ function jsTypeToTs(type) {
3
+ if (type === "string")
4
+ return "string";
5
+ if (type === "number")
6
+ return "number";
7
+ if (type === "boolean")
8
+ return "boolean";
9
+ return "unknown";
10
+ }
11
+ export function generate(validated) {
12
+ const keys = Object.keys(validated);
13
+ const lines = keys.map((key) => {
14
+ const value = validated[key];
15
+ const tsType = jsTypeToTs(typeof value);
16
+ return ` readonly ${key}: ${tsType};`;
17
+ });
18
+ return renderEnvDts(lines);
19
+ }
@@ -0,0 +1,2 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ export declare function generateEnvTypes(schema: StandardSchemaV1, validatedResult: Record<string, unknown>): string;
@@ -0,0 +1,29 @@
1
+ import { generateFromZod } from "./generateFromZod.js";
2
+ import { generateFromValibot, } from "./generateFromValibot.js";
3
+ import { generateFromArkType } from "./generateFromArkType.js";
4
+ import { generateFromGeneric } from "./generateFromGeneric.js";
5
+ export function generateEnvTypes(schema, validatedResult) {
6
+ try {
7
+ let vendor = schema["~standard"].vendor.toLowerCase();
8
+ if (!vendor) {
9
+ throw new Error("Schema vendor is missing or invalid.");
10
+ }
11
+ if (vendor === "zod") {
12
+ return generateFromZod(schema);
13
+ }
14
+ if (vendor === "valibot") {
15
+ return generateFromValibot(schema);
16
+ }
17
+ if (vendor === "arktype") {
18
+ return generateFromArkType(schema);
19
+ }
20
+ if (vendor === "envka") {
21
+ return schema["~standard"].generateType();
22
+ }
23
+ return generateFromGeneric(validatedResult);
24
+ }
25
+ catch (e) {
26
+ throw new Error("Could not determine schema vendor: " +
27
+ (e instanceof Error ? e.message : String(e)));
28
+ }
29
+ }
@@ -0,0 +1,12 @@
1
+ import type { Plugin } from "vite";
2
+ import envkaValidator from "./envkaValidator.js";
3
+ import type { EnvkaStandardSchemaV1 } from "./envkaValidator.js";
4
+ export type { EnvkaStandardSchemaV1, EnvkaType, EnvkaField, EnvkaSchema, } from "./envkaValidator.js";
5
+ export interface EnvkaOptions {
6
+ /** Validation schema for environment variables */
7
+ schema: EnvkaStandardSchemaV1;
8
+ /** If true, generate env.d.ts after validation (default: false) */
9
+ generateTypes?: boolean;
10
+ }
11
+ export { envkaValidator };
12
+ export default function envka(options: EnvkaOptions): Plugin;
@@ -0,0 +1,69 @@
1
+ import { loadEnv } from "vite";
2
+ import { log } from "./utils/log.js";
3
+ import { parseEnv } from "./utils/parseEnv.js";
4
+ import * as fs from "fs";
5
+ import * as path from "path";
6
+ import envkaValidator from "./envkaValidator.js";
7
+ export { envkaValidator };
8
+ export default function envka(options) {
9
+ let envkaIssues = null;
10
+ const handleError = (msg, issues, command) => {
11
+ if (command !== "build") {
12
+ envkaIssues = issues;
13
+ log(msg, "error");
14
+ }
15
+ else {
16
+ throw new Error(msg);
17
+ }
18
+ };
19
+ return {
20
+ name: "vite-plugin-envka",
21
+ config(config, envCtx) {
22
+ if (!options || !options.schema) {
23
+ log("No schema provided for validation.", "info");
24
+ return;
25
+ }
26
+ if (!options.schema?.["~standard"] ||
27
+ typeof options.schema["~standard"].validate !== "function" ||
28
+ options.schema["~standard"].vendor !== "envka") {
29
+ const errorMsg = "Provided schema is not a valid envkaValidator schema.";
30
+ handleError(errorMsg, ["Provided schema is not a valid envkaValidator schema."], envCtx.command);
31
+ return;
32
+ }
33
+ const rootPath = config.root ?? process.cwd();
34
+ const envMap = loadEnv(envCtx.mode, rootPath, "");
35
+ const result = options.schema["~standard"].validate(parseEnv(envMap));
36
+ if (!result.valid) {
37
+ envkaIssues = result.issues ?? ["Unknown error"];
38
+ handleError(`Environment validation failed: ${envkaIssues.join("; ")}`, envkaIssues, envCtx.command);
39
+ }
40
+ else {
41
+ envkaIssues = null;
42
+ log("Environment validation passed.", "success");
43
+ if (options.generateTypes) {
44
+ if (envCtx.command !== "build") {
45
+ const types = options.schema["~standard"].generateType();
46
+ const outPath = path.resolve(rootPath, "env.d.ts");
47
+ fs.writeFileSync(outPath, types);
48
+ log(`Generated env.d.ts at ${outPath}`, "success");
49
+ }
50
+ }
51
+ }
52
+ },
53
+ configureServer(server) {
54
+ function sendOverlay() {
55
+ if (envkaIssues && envkaIssues.length > 0) {
56
+ server.ws.send({
57
+ type: "error",
58
+ err: {
59
+ message: `[envka] ${envkaIssues.join("\n")}`,
60
+ stack: "",
61
+ },
62
+ });
63
+ }
64
+ }
65
+ sendOverlay();
66
+ server.ws.on("connection", sendOverlay);
67
+ },
68
+ };
69
+ }
@@ -0,0 +1,2 @@
1
+ import { EnvkaStandardSchemaV1 } from "./envkaValidator.js";
2
+ export declare function printEnvExample(schema: EnvkaStandardSchemaV1): string;
@@ -0,0 +1,6 @@
1
+ export function printEnvExample(schema) {
2
+ if (schema && typeof schema["~standard"]?.generateExample === "function") {
3
+ return schema["~standard"].generateExample();
4
+ }
5
+ throw new TypeError("Provided schema is not a valid EnvkaStandardSchemaV1.");
6
+ }
@@ -0,0 +1,7 @@
1
+ import type { EnvkaStandardSchemaV1 } from "./envkaValidator.js";
2
+ export interface EnvkaOptions {
3
+ /** Validation schema for environment variables (Standard Schema spec) */
4
+ schema: EnvkaStandardSchemaV1;
5
+ /** If true, generate env.d.ts after validation (default: false) */
6
+ generateTypes?: boolean;
7
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ export declare function isStandardSchema(schema: unknown): schema is StandardSchemaV1<any, any>;
@@ -0,0 +1,14 @@
1
+ import { ZodType } from "zod";
2
+ export function isStandardSchema(schema) {
3
+ if ((typeof schema !== "object" && typeof schema !== "function") ||
4
+ schema === null)
5
+ return false;
6
+ if (schema instanceof ZodType)
7
+ return true;
8
+ const std = schema["~standard"];
9
+ return (typeof std === "object" &&
10
+ std !== null &&
11
+ std.version === 1 &&
12
+ typeof std.vendor === "string" &&
13
+ typeof std.validate === "function");
14
+ }
@@ -0,0 +1,3 @@
1
+ type LogType = "error" | "success" | "info";
2
+ export declare function log(message: string, type?: LogType): void;
3
+ export {};
@@ -0,0 +1,19 @@
1
+ // Utility for logging
2
+ import chalk from "chalk";
3
+ export function log(message, type = "info") {
4
+ const prefix = chalk.hex("#d898ca")("[envka]");
5
+ let colorFn;
6
+ switch (type) {
7
+ case "error":
8
+ colorFn = chalk.hex("#ff6666");
9
+ break;
10
+ case "success":
11
+ colorFn = chalk.hex("#66ff66");
12
+ break;
13
+ case "info":
14
+ default:
15
+ colorFn = chalk.hex("#88ffff");
16
+ break;
17
+ }
18
+ console.log(`${prefix} ${colorFn(message)}`);
19
+ }
@@ -0,0 +1 @@
1
+ export declare const parseEnv: (env: Record<string, string | undefined>) => Record<string, any>;
@@ -0,0 +1,22 @@
1
+ export const parseEnv = (env) => {
2
+ const parsedEnv = {};
3
+ for (const key in env) {
4
+ const value = env[key];
5
+ if (value === undefined) {
6
+ parsedEnv[key] = undefined;
7
+ }
8
+ else if (value.toLowerCase() === "true") {
9
+ parsedEnv[key] = true;
10
+ }
11
+ else if (value.toLowerCase() === "false") {
12
+ parsedEnv[key] = false;
13
+ }
14
+ else if (!isNaN(Number(value))) {
15
+ parsedEnv[key] = Number(value);
16
+ }
17
+ else {
18
+ parsedEnv[key] = value;
19
+ }
20
+ }
21
+ return parsedEnv;
22
+ };
@@ -0,0 +1 @@
1
+ export declare const parseEnv: (env: Record<string, string | undefined>) => Record<string, any>;
@@ -0,0 +1,22 @@
1
+ export const parseEnv = (env) => {
2
+ const parsedEnv = {};
3
+ for (const key in env) {
4
+ const value = env[key];
5
+ if (value === undefined) {
6
+ parsedEnv[key] = undefined;
7
+ }
8
+ else if (value.toLowerCase() === "true") {
9
+ parsedEnv[key] = true;
10
+ }
11
+ else if (value.toLowerCase() === "false") {
12
+ parsedEnv[key] = false;
13
+ }
14
+ else if (!isNaN(Number(value))) {
15
+ parsedEnv[key] = Number(value);
16
+ }
17
+ else {
18
+ parsedEnv[key] = value;
19
+ }
20
+ }
21
+ return parsedEnv;
22
+ };
@@ -0,0 +1 @@
1
+ export declare function renderEnvDts(lines: string[]): string;
@@ -0,0 +1,4 @@
1
+ // Utility to render env.d.ts output for Vite
2
+ export function renderEnvDts(lines) {
3
+ return `/// <reference types=\"vite/client\" />\ninterface ImportMetaEnv {\n${lines.join("\n")}\n}\n\ninterface ImportMeta {\n readonly env: ImportMetaEnv;\n}\n`;
4
+ }
@@ -0,0 +1,10 @@
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
+ export declare function validateEnv(schema: StandardSchemaV1, env: Record<string, any>): {
3
+ valid: boolean;
4
+ issues: readonly StandardSchemaV1.Issue[];
5
+ value?: undefined;
6
+ } | {
7
+ valid: boolean;
8
+ value: unknown;
9
+ issues?: undefined;
10
+ };
@@ -0,0 +1,10 @@
1
+ export function validateEnv(schema, env) {
2
+ const result = schema["~standard"].validate(env);
3
+ if (result instanceof Promise) {
4
+ throw new TypeError("Async validation is not supported.");
5
+ }
6
+ if ("issues" in result && result.issues) {
7
+ return { valid: false, issues: result.issues };
8
+ }
9
+ return { valid: true, value: result.value };
10
+ }
@@ -0,0 +1,5 @@
1
+ import type { EnvkaStandardSchemaV1 } from "./envkaValidator.js";
2
+ export declare function validateEnv(schema: EnvkaStandardSchemaV1, env: Record<string, any>): {
3
+ valid: boolean;
4
+ issues?: any[];
5
+ };
@@ -0,0 +1,3 @@
1
+ export function validateEnv(schema, env) {
2
+ return schema["~standard"].validate(env);
3
+ }
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "vite-plugin-envka",
3
+ "description": "Envka is a vite plugin designed to enhance environment variable management in Vite projects.",
4
+ "version": "1.0.0",
5
+ "author": {
6
+ "name": "Ireneo C. Cobar Jr"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ireneo-cobarjr/vite-plugin-envka.git"
11
+ },
12
+ "homepage": "https://github.com/ireneo-cobarjr/vite-plugin-envka",
13
+ "bugs": {
14
+ "url": "https://github.com/ireneo-cobarjr/vite-plugin-envka/issues"
15
+ },
16
+ "license": "BSD-3-Clause",
17
+ "keywords": [
18
+ "vite",
19
+ "vite-plugin",
20
+ "env",
21
+ "environment",
22
+ "environment-variables",
23
+ "dotenv",
24
+ ".env",
25
+ "config",
26
+ "configuration",
27
+ "schema",
28
+ "validation",
29
+ "typescript",
30
+ "plugin",
31
+ "nodejs",
32
+ "build",
33
+ "cli"
34
+ ],
35
+ "type": "module",
36
+ "main": "dist/src/index.js",
37
+ "files": [
38
+ "dist/",
39
+ "bin/env-cli.js",
40
+ "README.md",
41
+ "LICENSE",
42
+ "package.json"
43
+ ],
44
+ "bin": {
45
+ "env": "dist/bin/env-cli.js"
46
+ },
47
+ "types": "dist/src/index.d.ts",
48
+ "scripts": {
49
+ "build": "tsc",
50
+ "test": "vitest"
51
+ },
52
+ "devDependencies": {
53
+ "@types/node": "^24.8.0",
54
+ "typescript": "^5.9.3",
55
+ "vite": "^7.1.10",
56
+ "vitest": "^3.2.4"
57
+ },
58
+ "dependencies": {
59
+ "@standard-schema/spec": "^1.0.0",
60
+ "chalk": "^5.6.2",
61
+ "commander": "^14.0.1"
62
+ }
63
+ }