arkenv
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseArkEnv
ArkEnv
ArkEnv is a typesafe environment variable validator for modern JavaScript runtimes. It uses by default for schema definition but supports any validator (like or ).
ArkTypeStandard SchemaZodValibotArkEnv 是面向现代 JavaScript 运行时的类型安全环境变量验证工具。它默认使用 进行模式定义,但支持任何标准 Schema 验证器(如 或 )。
ArkTypeZodValibotCapabilities
功能特性
Core Usage
核心用法
- Define typesafe schemas using notation or any
ArkTypevalidator.Standard Schema - Implement complex types, arrays, and unions.
- Configure automatic coercion and default values.
- Follow best practices for schema organization.
- 使用 语法或任何标准 Schema 验证器定义类型安全的模式。
ArkType - 实现复杂类型、数组和联合类型。
- 配置自动类型转换和默认值。
- 遵循模式组织的最佳实践。
Framework Integration
框架集成
- Vite: Build-time validation and type augmentation via
import.meta.env.@arkenv/vite-plugin - Bun: Build-time/Runtime validation and type augmentation via
process.env.@arkenv/bun-plugin - Node.js: Standard validation and coercion.
process.env
- Vite:通过 实现构建时验证和
@arkenv/vite-plugin类型增强。import.meta.env - Bun:通过 实现构建时/运行时验证和
@arkenv/bun-plugin类型增强。process.env - Node.js:标准 验证与类型转换。
process.env
CLI (Setup & DevOps)
CLI(搭建与DevOps)
- Initialize ArkEnv in new or existing projects using .
pnpm dlx @arkenv/cli@latest init - Scaffold schema files and detect framework-specific configurations (,
Vite, etc.).Bun - Automatically configure and environment types for optimal typesafety.
tsconfig.json
- 使用 在新项目或现有项目中初始化ArkEnv。
pnpm dlx @arkenv/cli@latest init - 生成模式文件并检测框架特定配置(如 、
Vite等)。Bun - 自动配置 和环境类型以实现最佳类型安全。
tsconfig.json
Agent Setup (Machine-Readable)
Agent 配置(机器可读)
AI agents SHOULD always use the CLI for project initialization to ensure consistency and reliability. Use the flag for a fully automated, machine-readable experience.
--agent- Command:
pnpm dlx @arkenv/cli@latest init --agent - Behavior: The flag automatically enables the following behaviors:
--agent- : Bypasses all interactive prompts and uses recommended defaults.
--yes - : Suppresses spinners and ANSI formatting for cleaner terminal logs.
--quiet - : Emits a structured JSON summary to
--jsonupon completion (all other output is sent tostdout).stderr
- Success Verification: Parse the JSON output to verify and retrieve details like the scaffolded file path.
status: "success"
AI Agent 应始终使用CLI进行项目初始化,以确保一致性和可靠性。使用 标志获得完全自动化的机器可读体验。
--agent- 命令:
pnpm dlx @arkenv/cli@latest init --agent - 行为:标志会自动启用以下行为:
--agent- :跳过所有交互式提示,使用推荐的默认值。
--yes - :抑制加载动画和ANSI格式,生成更简洁的终端日志。
--quiet - :完成后向标准输出(stdout)发送结构化JSON摘要(所有其他输出发送到标准错误stderr)。
--json
- 成功验证:解析JSON输出以验证 ,并获取生成文件路径等详细信息。
status: "success"
Operational Logic
操作逻辑
- Detection:
- Look for or
env.tsimports to understand existing schema.arkenv - Check for framework config files (,
vite.config.ts,bunfig.tomlscripts) to recommend appropriate plugins.package.json
- Look for
- Setup:
- If ArkEnv is not present or a fresh setup is requested, trigger the Setup Workflow.
- Prefer using the CLI for initialization: .
pnpm dlx @arkenv/cli@latest init - If the CLI cannot be used or fails, fall back to manual configuration.
- 检测:
- 查找 或
env.ts导入以了解现有模式。arkenv - 检查框架配置文件(、
vite.config.ts、bunfig.toml脚本)以推荐合适的插件。package.json
- 查找
- 搭建:
- 如果项目中未安装ArkEnv或需要全新搭建,触发搭建流程。
- 优先使用CLI进行初始化:。
pnpm dlx @arkenv/cli@latest init - 如果CLI无法使用或执行失败,回退到手动配置。
Setup Workflow
搭建流程
When setting up ArkEnv, follow these steps:
- Initialize: Run . This will attempt to detect the environment, install dependencies, and scaffold a base
pnpm dlx @arkenv/cli@latest init --agent.env.ts - Review & Refine :
env.ts- Inspect the generated . Ensure it captures the required environment variables.
env.ts - Refine types (e.g., change to
stringor specific union types).number.port
- Inspect the generated
- Manual Plugin Configuration:
- The CLI installs plugins but might not update config files.
- Vite: Update to import and include the
vite.config.tsplugin.arkenv - Bun: Configure or add the plugin to the runtime if necessary.
bunfig.toml
- Typesafety & Augmentation:
- Vite: Add type augmentation to or a new
src/vite-env.d.ts.env.d.tstsinterface ImportMetaEnv extends import("@arkenv/vite-plugin").ImportMetaEnvAugmented<typeof import("./env").Env> {} - Bun: Create a file (or update an existing one) with the following pattern:
bun-env.d.tsts/// <reference types="bun-types" /> type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<typeof import("./src/env").default>; declare namespace NodeJS { interface ProcessEnv extends ProcessEnvAugmented {} } - Ensure has
tsconfig.json(the CLI tries to do this, but verify).strict: true
- Vite: Add type augmentation to
- Usage Update: Scan the codebase for existing environment variable usage (or
process.env) and ensure they are now typesafe via the augmentations.import.meta.env - Validation: Run (or equivalent) or a build to confirm everything is typesafe and valid.
pnpm check
搭建ArkEnv时,请遵循以下步骤:
- 初始化:运行 。该命令会尝试检测环境、安装依赖并生成基础的
pnpm dlx @arkenv/cli@latest init --agent文件。env.ts - 审核与优化 :
env.ts- 检查生成的 文件,确保它包含所需的环境变量。
env.ts - 优化类型(例如,将 改为
string或特定的联合类型)。number.port
- 检查生成的
- 手动配置插件:
- CLI会安装插件,但可能不会更新配置文件。
- Vite:更新 以导入并添加
vite.config.ts插件。arkenv - Bun:必要时配置 或在运行时添加插件。
bunfig.toml
- 类型安全与增强:
- Vite:在 或新的
src/vite-env.d.ts文件中添加类型增强。env.d.tstsinterface ImportMetaEnv extends import("@arkenv/vite-plugin").ImportMetaEnvAugmented<typeof import("./env").Env> {} - Bun:创建 文件(或更新现有文件),使用以下格式:
bun-env.d.tsts/// <reference types="bun-types" /> type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<typeof import("./src/env").default>; declare namespace NodeJS { interface ProcessEnv extends ProcessEnvAugmented {} } - 确保 中设置了
tsconfig.json(CLI会尝试配置,但请自行验证)。strict: true
- Vite:在
- 更新用法:扫描代码库中现有环境变量的使用(或
process.env),确保它们现在通过类型增强实现了类型安全。import.meta.env - 验证:运行 (或等效命令)或执行构建,确认所有内容都符合类型安全且验证通过。
pnpm check
Core Concepts
核心概念
Defining a Schema
定义模式
The best practice is to export a schema definition using .
typets
import { type } from 'arkenv';
export const Env = type({
NODE_ENV: "'development' | 'production' | 'test' = 'development'",
VITE_API_URL: "string",
PORT: "number.port = 3000"
});最佳实践是使用 导出模式定义。
typets
import { type } from 'arkenv';
export const Env = type({
NODE_ENV: "'development' | 'production' | 'test' = 'development'",
VITE_API_URL: "string",
PORT: "number.port = 3000"
});Usage: Node.js (Standard)
用法:Node.js(标准)
In Node.js, you validate the environment at runtime and export the result.
ts
import arkenv from 'arkenv';
import { Env } from './env';
export const env = arkenv(Env);
// Usage
const port = env.PORT; // typed as number在Node.js中,你需要在运行时验证环境并导出结果。
ts
import arkenv from 'arkenv';
import { Env } from './env';
export const env = arkenv(Env);
// 用法示例
const port = env.PORT; // 类型为numberUsage: Vite (Frontend)
用法:Vite(前端)
Vite requires build-time injection. Use the plugin in and augment .
vite.config.tsImportMetaEnvts
// vite.config.ts
import arkenv from '@arkenv/vite-plugin';
import { Env } from './env';
export default defineConfig({
plugins: [arkenv(Env)]
});ts
// src/vite-env.d.ts
import type { ImportMetaEnvAugmented } from "@arkenv/vite-plugin";
import type { Env } from "../env";
interface ImportMetaEnv extends ImportMetaEnvAugmented<typeof Env> {}Vite需要构建时注入。在 中使用插件并增强 。
vite.config.tsImportMetaEnvts
// vite.config.ts
import arkenv from '@arkenv/vite-plugin';
import { Env } from './env';
export default defineConfig({
plugins: [arkenv(Env)]
});ts
// src/vite-env.d.ts
import type { ImportMetaEnvAugmented } from "@arkenv/vite-plugin";
import type { Env } from "../env";
interface ImportMetaEnv extends ImportMetaEnvAugmented<typeof Env> {}Usage: Bun
用法:Bun
Bun can use either runtime validation or a plugin for type augmentation.
ts
// src/env.d.ts
import type { ProcessEnvAugmented } from "@arkenv/bun-plugin";
import type { Env } from "./env";
declare global {
namespace NodeJS {
interface ProcessEnv extends ProcessEnvAugmented<typeof Env> {}
}
}Bun可以使用运行时验证或插件实现类型增强。
ts
// src/env.d.ts
import type { ProcessEnvAugmented } from "@arkenv/bun-plugin";
import type { Env } from "./env";
declare global {
namespace NodeJS {
interface ProcessEnv extends ProcessEnvAugmented<typeof Env> {}
}
}CLI Commands
CLI 命令
init
initinit
initSet up ArkEnv in your project. It detects your framework and configures the appropriate plugin and type augmentations.
bash
pnpm dlx @arkenv/cli@latest init在你的项目中搭建ArkEnv。它会检测你的框架并配置相应的插件和类型增强。
bash
pnpm dlx @arkenv/cli@latest initBest Practices
最佳实践
- Prefer Native Primitives: To leverage the full power of ArkEnv plugins, you should access environment variables through the runtime's native primitives.
- Vite: Use .
import.meta.env - Bun: Use .
process.env - This ensures that build-time validation, static replacement (Vite), and runtime optimizations (Bun) work as intended while remaining fully typesafe via type augmentation.
- Vite: Use
- Avoid in Plugin-managed Projects: In projects using
import { env }or@arkenv/vite-plugin, you should generally avoid importing a runtime-validated@arkenv/bun-pluginobject. Using native primitives is the "cleanest" way to get typesafety and ensures consistency with framework-specific behavior.env - Use Type Augmentation: This is the recommended way to make or
import.meta.envtypesafe. It connects your schema definition to the native primitives without adding runtime overhead to your application logic.process.env - Re-use Schema: Define your schema once and use it for both the plugin (build-time/config) and runtime validation if needed.
- Coercion: ArkEnv automatically coerces strings from files (e.g.,
.envbecomes"3000").3000
- 优先使用原生原语:为了充分发挥ArkEnv插件的能力,你应该通过运行时的原生原语访问环境变量。
- Vite:使用 。
import.meta.env - Bun:使用 。
process.env - 这确保了构建时验证、静态替换(Vite)和运行时优化(Bun)按预期工作,同时通过类型增强保持完全的类型安全。
- Vite:使用
- 在插件管理的项目中避免 :在使用
import { env }或@arkenv/vite-plugin的项目中,通常应避免导入运行时验证的@arkenv/bun-plugin对象。使用原生原语是实现类型安全的“最简洁”方式,并确保与框架特定行为的一致性。env - 使用类型增强:这是让 或
import.meta.env实现类型安全的推荐方式。它将你的模式定义与原生原语关联,而不会为应用逻辑增加运行时开销。process.env - 复用模式:只需定义一次模式,即可同时用于插件(构建时/配置)和运行时验证(如果需要)。
- 类型转换:ArkEnv会自动转换 文件中的字符串(例如,
.env会转换为"3000")。3000