envapt 8.1.0 → 8.1.1
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/CHANGELOG.md +8 -0
- package/README.md +27 -10
- package/dist/node/_virtual/_rolldown/runtime.cjs +1 -1
- package/dist/node/converters/BuiltInConverters.cjs +1 -1
- package/dist/node/converters/BuiltInConverters.cjs.map +1 -1
- package/dist/node/converters/BuiltInConverters.mjs +1 -1
- package/dist/node/converters/BuiltInConverters.mjs.map +1 -1
- package/dist/node/core/engine.cjs.map +1 -1
- package/dist/node/core/engine.mjs.map +1 -1
- package/dist/node/decorators/legacy/createPropertyDecorator.cjs +1 -1
- package/dist/node/decorators/legacy/createPropertyDecorator.cjs.map +1 -1
- package/dist/node/decorators/legacy/createPropertyDecorator.mjs +1 -1
- package/dist/node/decorators/legacy/createPropertyDecorator.mjs.map +1 -1
- package/dist/node/decorators/modern/createAccessorDecorator.cjs +1 -1
- package/dist/node/decorators/modern/createAccessorDecorator.cjs.map +1 -1
- package/dist/node/decorators/modern/createAccessorDecorator.mjs +1 -1
- package/dist/node/decorators/modern/createAccessorDecorator.mjs.map +1 -1
- package/dist/node/decorators/resolveDecoratorValue.cjs +1 -1
- package/dist/node/decorators/resolveDecoratorValue.cjs.map +1 -1
- package/dist/node/decorators/resolveDecoratorValue.mjs +1 -1
- package/dist/node/decorators/resolveDecoratorValue.mjs.map +1 -1
- package/dist/node/engine/Envapter.cjs +1 -1
- package/dist/node/engine/Envapter.cjs.map +1 -1
- package/dist/node/engine/Envapter.mjs +1 -1
- package/dist/node/engine/Envapter.mjs.map +1 -1
- package/dist/node/engine/Validators.cjs +1 -1
- package/dist/node/engine/Validators.cjs.map +1 -1
- package/dist/node/engine/Validators.mjs +1 -1
- package/dist/node/engine/Validators.mjs.map +1 -1
- package/dist/node/infra/Dotenv.cjs +1 -1
- package/dist/node/infra/Dotenv.mjs +1 -1
- package/dist/node/sources/FileSource.cjs.map +1 -1
- package/dist/portable/converters/BuiltInConverters.mjs +1 -1
- package/dist/portable/converters/BuiltInConverters.mjs.map +1 -1
- package/dist/portable/core/engine.mjs.map +1 -1
- package/dist/portable/core/paths.mjs +1 -1
- package/dist/portable/decorators/legacy/createPropertyDecorator.mjs +1 -1
- package/dist/portable/decorators/legacy/createPropertyDecorator.mjs.map +1 -1
- package/dist/portable/decorators/modern/createAccessorDecorator.mjs +1 -1
- package/dist/portable/decorators/modern/createAccessorDecorator.mjs.map +1 -1
- package/dist/portable/decorators/resolveDecoratorValue.mjs +1 -1
- package/dist/portable/decorators/resolveDecoratorValue.mjs.map +1 -1
- package/dist/portable/engine/Envapter.mjs +1 -1
- package/dist/portable/engine/Envapter.mjs.map +1 -1
- package/dist/portable/engine/Validators.mjs +1 -1
- package/dist/portable/engine/Validators.mjs.map +1 -1
- package/dist/portable/infra/Dotenv.mjs +1 -1
- package/dist/types/config.d.mts +1 -1
- package/dist/types/converters/Converters.d.mts +1 -1
- package/dist/types/core/AdvancedMethods.d.mts +2 -3
- package/dist/types/core/EnvapterBase.d.mts +0 -1
- package/dist/types/core/EnvironmentMethods.d.mts +0 -1
- package/dist/types/core/PrimitiveMethods.d.mts +0 -1
- package/dist/types/decorators/legacy/Envapt.d.mts +0 -1
- package/dist/types/decorators/legacy/SugarDecorators.d.mts +0 -1
- package/dist/types/decorators/modern/Envapt.d.mts +0 -1
- package/dist/types/decorators/modern/SugarDecorators.d.mts +0 -1
- package/dist/types/engine/Envapter.d.mts +1 -2
- package/dist/types/engine/NodeEnvapter.d.mts +0 -1
- package/dist/types/engine/PortableEnvapter.d.mts +0 -1
- package/dist/types/infra/Error.d.mts +0 -1
- package/dist/types/sources/FileSource.d.mts +0 -1
- package/dist/types/sources/PortableSource.d.mts +0 -1
- package/dist/types/sources/merge.d.mts +0 -1
- package/dist/types/types/Conversion.d.mts +1 -2
- package/dist/types/types/Env.d.mts +0 -3
- package/dist/types/types/Options.d.mts +0 -1
- package/dist/types/types/Schema.d.mts +1 -2
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Envapter.mjs","names":[],"sources":["../../../src/engine/Envapter.ts"],"sourcesContent":["import { AdvancedMethods } from '../core';\nimport { resolveRequired } from '../core/AdvancedMethods';\nimport { resolveKeyInput, templateResolver } from '../core/engine';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { EnvKeyInput } from '../types';\n\nexport { Environment } from '../core';\n\n/**\n * Main configuration class for environment variable management.\n *\n * Provides both static and instance methods for retrieving typed environment variables\n * with support for template resolution, multiple .env files, and environment detection.\n *\n * Extend your own classes from this to define properties with \\@Envapt decorators and get access to environment-variable methods.\n *\n * @example\n * ```ts\n * // Static usage\n * const port = Envapter.getNumber('PORT', 3000);\n * const url = Envapter.get('API_URL', 'http://localhost');\n * const replica = Envapter.get(['READONLY_URL', 'DATABASE_URL'], 'sqlite://memory');\n *\n * // Instance usage\n * const env = new Envapter();\n * const dbUrl = env.get('DATABASE_URL', 'sqlite://memory');\n * const primaryHost = env.get(['PRIMARY_HOST', 'SECONDARY_HOST']);\n * ```\n *\n * @public\n */\nexport class Envapter extends AdvancedMethods {\n /**\n * Tagged template literal for resolving environment variables in template strings.\n *\n * @example\n * ```ts\n * // Given API_HOST=api.example.com and API_PORT=8080 in environment\n * const endpoint = Envapter.resolve`Connecting to ${'API_HOST'}:${'API_PORT'}`;\n * // Returns: \"Connecting to api.example.com:8080\"\n *\n * // Works with template variables in .env too:\n * // API_URL=https://${API_HOST}:${API_PORT}\n * const message = Envapter.resolve`Service endpoint: ${'API_URL'}`;\n * // Returns: \"Service endpoint: https://api.example.com:8080\"\n * ```\n * @see {@link https://envapt.materwelon.dev/docs/templates#the-resolve-tagged-template}\n */\n static resolve(strings: TemplateStringsArray, ...keys: string[]): string {\n const strict = Envapter.strict;\n return strings.reduce((result, string, i) => {\n const envKey = keys[i];\n if (!envKey) return result + string;\n const raw = super.get(envKey, '');\n if (strict && raw.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Cannot resolve template variable \"\\${${envKey}}\": value is missing or empty.`\n );\n }\n return result + string + raw;\n }, '');\n }\n\n /**\n * @see {@link Envapter.resolve}\n */\n resolve(strings: TemplateStringsArray, ...keys: string[]): string {\n return Envapter.resolve(strings, ...keys);\n }\n\n /**\n * Assert that one or more environment variables are present and non-empty after template\n * resolution. Throws `MissingEnvValue` listing every missing key. A whitespace-only value\n * counts as missing only under strict mode.\n *\n * For a typed required read in functional code, use `Envapter.getRequired(key, converter)`.\n *\n * @example\n * ```ts\n * Envapter.require('DATABASE_URL');\n * Envapter.require('DATABASE_URL', 'API_KEY', 'SENTRY_DSN');\n * ```\n */\n static require(...keys: [string, ...string[]]): void {\n const missing = keys.filter((k) => resolveRequired(resolveKeyInput(k), templateResolver).value === undefined);\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Missing required environment variables: ${missing.join(', ')}.`\n );\n }\n }\n\n /**\n * @see {@link Envapter.require}\n */\n require(...keys: [string, ...string[]]): void {\n Envapter.require(...keys);\n }\n\n /**\n * Check whether `key` has a value, with the same missing semantics as `getRequired`.\n * Under strict mode an unresolvable template in an ordered key list ends the scan early\n * and counts as absent. Returns `true` exactly when a required read of the same key\n * finds a value.\n *\n * @example\n * ```ts\n * if (!Envapter.has('DATABASE_URL')) throw new MyStartupError('DATABASE_URL');\n * ```\n * @see {@link https://envapt.materwelon.dev/docs/envapter#fail-fast-on-missing-values}\n */\n static has(key: EnvKeyInput): boolean {\n try {\n return resolveRequired(resolveKeyInput(key), templateResolver).value !== undefined;\n } catch (error) {\n // under strict an unresolvable template throws MissingEnvValue, and that read counts as absent\n if (error instanceof EnvaptError && error.code === EnvaptErrorCodes.MissingEnvValue) return false;\n throw error;\n }\n }\n\n /**\n * @see {@link Envapter.has}\n */\n has(key: EnvKeyInput): boolean {\n return Envapter.has(key);\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Envapter.mjs","names":[],"sources":["../../../src/engine/Envapter.ts"],"sourcesContent":["import { AdvancedMethods } from '../core';\nimport { resolveRequired } from '../core/AdvancedMethods';\nimport { resolveKeyInput, templateResolver } from '../core/engine';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { EnvKeyInput } from '../types';\n\nexport { Environment } from '../core';\n\n/**\n * Main configuration class for environment variable management.\n *\n * Provides both static and instance methods for retrieving typed environment variables\n * with support for template resolution, multiple .env files, and environment detection.\n *\n * Extend your own classes from this to define properties with \\@Envapt decorators and get access to environment-variable methods.\n *\n * @example\n * ```ts\n * // Static usage\n * const port = Envapter.getNumber('PORT', 3000);\n * const url = Envapter.get('API_URL', 'http://localhost');\n * const replica = Envapter.get(['READONLY_URL', 'DATABASE_URL'], 'sqlite://memory');\n *\n * // Instance usage\n * const env = new Envapter();\n * const dbUrl = env.get('DATABASE_URL', 'sqlite://memory');\n * const primaryHost = env.get(['PRIMARY_HOST', 'SECONDARY_HOST']);\n * ```\n *\n * @public\n */\nexport class Envapter extends AdvancedMethods {\n /**\n * Tagged template literal for resolving environment variables in template strings.\n *\n * @example\n * ```ts\n * // Given API_HOST=api.example.com and API_PORT=8080 in environment\n * const endpoint = Envapter.resolve`Connecting to ${'API_HOST'}:${'API_PORT'}`;\n * // Returns: \"Connecting to api.example.com:8080\"\n *\n * // Works with template variables in .env too:\n * // API_URL=https://${API_HOST}:${API_PORT}\n * const message = Envapter.resolve`Service endpoint: ${'API_URL'}`;\n * // Returns: \"Service endpoint: https://api.example.com:8080\"\n * ```\n * @see {@link https://envapt.materwelon.dev/docs/templates#the-resolve-tagged-template}\n */\n static resolve(strings: TemplateStringsArray, ...keys: string[]): string {\n const strict = Envapter.strict;\n return strings.reduce((result, string, i) => {\n const envKey = keys[i];\n if (!envKey) return result + string;\n const raw = super.get(envKey, '');\n if (strict && raw.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Cannot resolve template variable \"\\${${envKey}}\": value is missing or empty.`\n );\n }\n return result + string + raw;\n }, '');\n }\n\n /**\n * @see {@link Envapter.resolve}\n */\n resolve(strings: TemplateStringsArray, ...keys: string[]): string {\n return Envapter.resolve(strings, ...keys);\n }\n\n /**\n * Assert that one or more environment variables are present and non-empty after template\n * resolution. Throws `MissingEnvValue` listing every missing key. A whitespace-only value\n * counts as missing only under strict mode.\n *\n * For a typed required read in functional code, use `Envapter.getRequired(key, converter)`.\n *\n * @example\n * ```ts\n * Envapter.require('DATABASE_URL');\n * Envapter.require('DATABASE_URL', 'API_KEY', 'SENTRY_DSN');\n * ```\n */\n static require(...keys: [string, ...string[]]): void {\n const missing = keys.filter((k) => resolveRequired(resolveKeyInput(k), templateResolver).value === undefined);\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Missing required environment variables: ${missing.join(', ')}.`\n );\n }\n }\n\n /**\n * @see {@link Envapter.require}\n */\n require(...keys: [string, ...string[]]): void {\n Envapter.require(...keys);\n }\n\n /**\n * Check whether `key` has a value, with the same missing semantics as `getRequired`.\n * Under strict mode an unresolvable template in an ordered key list ends the scan early\n * and counts as absent. Returns `true` exactly when a required read of the same key\n * finds a value.\n *\n * @example\n * ```ts\n * if (!Envapter.has('DATABASE_URL')) throw new MyStartupError('DATABASE_URL');\n * ```\n * @see {@link https://envapt.materwelon.dev/docs/envapter#fail-fast-on-missing-values}\n */\n static has(key: EnvKeyInput): boolean {\n try {\n return resolveRequired(resolveKeyInput(key), templateResolver).value !== undefined;\n } catch (error) {\n // under strict an unresolvable template throws MissingEnvValue, and that read counts as absent\n if (error instanceof EnvaptError && error.code === EnvaptErrorCodes.MissingEnvValue) return false;\n throw error;\n }\n }\n\n /**\n * @see {@link Envapter.has}\n */\n has(key: EnvKeyInput): boolean {\n return Envapter.has(key);\n }\n}\n"],"mappings":"qQAgCA,IAAa,EAAb,MAAa,UAAiB,CAAgB,CAiB1C,OAAO,QAAQ,EAA+B,GAAG,EAAwB,CACrE,IAAM,EAAS,EAAS,OACxB,OAAO,EAAQ,QAAQ,EAAQ,EAAQ,IAAM,CACzC,IAAM,EAAS,EAAK,GACpB,GAAI,CAAC,EAAQ,OAAO,EAAS,EAC7B,IAAM,EAAM,MAAM,IAAI,EAAQ,EAAE,EAChC,GAAI,GAAU,EAAI,KAAK,IAAM,GACzB,MAAM,IAAI,EAAA,IAEN,wCAAwC,EAAO,+BACnD,EAEJ,OAAO,EAAS,EAAS,CAC7B,EAAG,EAAE,CACT,CAKA,QAAQ,EAA+B,GAAG,EAAwB,CAC9D,OAAO,EAAS,QAAQ,EAAS,GAAG,CAAI,CAC5C,CAeA,OAAO,QAAQ,GAAG,EAAmC,CACjD,IAAM,EAAU,EAAK,OAAQ,GAAM,EAAgB,EAAgB,CAAC,EAAG,CAAgB,CAAC,CAAC,QAAU,IAAA,EAAS,EAE5G,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,2CAA2C,EAAQ,KAAK,IAAI,EAAE,EAClE,CAER,CAKA,QAAQ,GAAG,EAAmC,CAC1C,EAAS,QAAQ,GAAG,CAAI,CAC5B,CAcA,OAAO,IAAI,EAA2B,CAClC,GAAI,CACA,OAAO,EAAgB,EAAgB,CAAG,EAAG,CAAgB,CAAC,CAAC,QAAU,IAAA,EAC7E,OAAS,EAAO,CAEZ,GAAI,aAAiB,GAAe,EAAM,OAAA,IAA2C,MAAO,GAC5F,MAAM,CACV,CACJ,CAKA,IAAI,EAA2B,CAC3B,OAAO,EAAS,IAAI,CAAG,CAC3B,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{isArrayOf as t}from"../converters/Converters.mjs";import{BuiltInConverterTypeCheckers as n,ListOfBuiltInConverters as r}from"../converters/ListOfBuiltInConverters.mjs";var i=class{static isBuiltInConverter(e){return typeof e==`string
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";import{isArrayOf as t}from"../converters/Converters.mjs";import{BuiltInConverterTypeCheckers as n,ListOfBuiltInConverters as r}from"../converters/ListOfBuiltInConverters.mjs";var i=class{static isBuiltInConverter(e){return typeof e==`string`&&r.includes(e)}static isArrayConverter(e){return t(e)}static isStandardSchema(e){if(typeof e!=`object`||!e||!(`~standard`in e))return!1;let t=e[`~standard`];if(typeof t!=`object`||!t)return!1;let n=t;return n.version===1&&typeof n.validate==`function`}static customConvertor(t){if(typeof t!=`function`)throw new e(203,`Custom converter must be a function, got ${typeof t}.`)}static arrayConverter(n){if(!t(n))throw new e(201,`Expected an ArrayOf<...> token produced by Converters.array(...)`);if(typeof n.delimiter!=`string`||n.delimiter.length===0)throw new e(301,`ArrayOf<...> requires a non-empty string delimiter, got ${typeof n.delimiter}`);let i=n.of;if(!(typeof i==`string`&&r.includes(i))&&typeof i!=`function`)throw new e(201,`ArrayOf<...> element ("of") must be a built-in scalar token or a function, got ${typeof i}`)}static builtInConverter(t){if(typeof t!=`string`)throw new e(204,`Expected string, got ${typeof t}`);if(!r.includes(t))throw new e(202,`"${t}" is not a valid converter type. Valid types are: ${r.join(`,`)}`)}static validateBuiltInConverterFallback(t,r){let i=n[t];if(!i(r))throw new e(104,`Fallback type does not match converter "${t}". Expected ${t} compatible type.`)}static validateArrayFallbackElementTypes(t){if(t.length===0)return;let n=typeof t[0];if(t.some((e,t)=>t!==0&&typeof e!==n))throw new e(103,`All elements in array fallback must have the same type. Found mixed types.`)}static validateArrayConverterElementTypeMatch(t,r){if(r.length===0||typeof t==`function`)return;let i=t;if(i===`time`){let t=r.every(e=>typeof e==`number`),n=r.every(e=>typeof e==`string`);if(!t&&!n)throw new e(103,`Time array fallback must be all numbers or all time-string entries.`);return}let a=n[i],o=r[0];if(!a(o))throw new e(103,`Array converter type "${i}" does not match fallback element type. Expected ${i} compatible elements.`)}static isPrimitiveConstructor(e){return e===String||e===Number||e===Boolean||e===BigInt||e===Symbol}static coercePrimitiveFallback(e,t){return this.isCorrectPrimitiveType(e,t)?t:this.performPrimitiveCoercion(e,t)}static isCorrectPrimitiveType(e,t){return e===String&&typeof t==`string`||e===Number&&typeof t==`number`||e===Boolean&&typeof t==`boolean`||e===BigInt&&typeof t==`bigint`||e===Symbol&&typeof t==`symbol`}static performPrimitiveCoercion(t,n){try{if(t===String)return String(n);if(t===Number)return Number(n);if(t===Boolean)return!!n;if(t===BigInt)return BigInt(n);if(t===Symbol)return Symbol.for(String(n))}catch(n){throw new e(205,`Failed to coerce fallback value using ${t.name}: ${n.message}`)}throw new e(205,`Unknown primitive converter: ${t.name}`)}static validateSyncProcessEnv(t){if(typeof t!=`boolean`)throw new e(302,`Envapter.syncProcessEnv must be a boolean, got ${typeof t}.`)}static validateFileApiMode(t){if(t!==`warn`&&t!==`throw`){let n=typeof t==`string`?`'${t}'`:typeof t;throw new e(302,`Envapter.fileApiMode must be 'warn' or 'throw', got ${n}.`)}}static validateEnvFileOptions(t){let n=new Set([`encoding`,`override`]),r=Object.keys(t).filter(e=>!n.has(e));if(r.length>0)throw new e(302,`Invalid envFileOptions: ${r.join(`, `)}. Allowed options: ${Array.from(n).join(`, `)}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`);return!0}static validateEnvFilesExist(t,n){let r=t.filter(e=>!n(e));if(r.length>0)throw new e(303,`Environment file not found at path: ${r.join(`, `)}`)}};export{i as Validator};
|
|
2
2
|
//# sourceMappingURL=Validators.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Validators.mjs","names":[],"sources":["../../../src/engine/Validators.ts"],"sourcesContent":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from '../converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from '../converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf, ConverterToken } from '../converters/Converters';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { StandardSchemaV1 } from '../infra/StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter, FileApiMode } from '../types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n static validateFileApiMode(value: unknown): asserts value is FileApiMode {\n if (value !== 'warn' && value !== 'throw') {\n const got = typeof value === 'string' ? `'${value}'` : typeof value;\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.fileApiMode must be 'warn' or 'throw', got ${got}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"gOAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,OAAO,GAAU,SAAiB,EAAwB,SAAS,CAAK,EACrE,EACX,CAKA,OAAO,iBAAiB,EAAkC,CACtD,OAAO,EAAU,CAAK,CAC1B,CAIA,OAAO,iBAAiB,EAA2C,CAE/D,GADI,OAAO,GAAU,WAAY,GAC7B,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAO,EAAM,aACnB,GAAI,OAAO,GAAS,WAAY,EAAe,MAAO,GACtD,IAAM,EAAQ,EACd,OAAO,EAAM,UAAY,GAAK,OAAO,EAAM,UAAa,UAC5D,CAEA,OAAO,gBACH,EACiD,CACjD,GAAI,OAAO,GAAc,WACrB,MAAM,IAAI,EAAA,IAEN,4CAA4C,OAAO,EAAU,EACjE,CAER,CAKA,OAAO,eAAe,EAA0C,CAC5D,GAAI,CAAC,EAAU,CAAK,EAChB,MAAM,IAAI,EAAA,IAEN,kEACJ,EAGJ,GAAI,OAAO,EAAM,WAAc,UAAY,EAAM,UAAU,SAAW,EAClE,MAAM,IAAI,EAAA,IAEN,2DAA2D,OAAO,EAAM,WAC5E,EAGJ,IAAM,EAAY,EAAM,GAGxB,GAAI,EAFa,OAAO,GAAc,UAAY,EAAwB,SAAS,CAAS,IACzE,OAAO,GAAc,WAEpC,MAAM,IAAI,EAAA,IAEN,kFAAkF,OAAO,GAC7F,CAER,CAKA,OAAO,iBAAiB,EAAmD,CACvE,GAAI,OAAO,GAAU,SACjB,MAAM,IAAI,EAAA,IAAmD,wBAAwB,OAAO,GAAO,EAGvG,GAAI,CAAC,EAAwB,SAAS,CAAuB,EACzD,MAAM,IAAI,EAAA,IAEN,I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EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CACJ"}
|
|
1
|
+
{"version":3,"file":"Validators.mjs","names":[],"sources":["../../../src/engine/Validators.ts"],"sourcesContent":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from '../converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from '../converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf, ConverterToken } from '../converters/Converters';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { StandardSchemaV1 } from '../infra/StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter, FileApiMode } from '../types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n static validateFileApiMode(value: unknown): asserts value is FileApiMode {\n if (value !== 'warn' && value !== 'throw') {\n const got = typeof value === 'string' ? `'${value}'` : typeof value;\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.fileApiMode must be 'warn' or 'throw', got ${got}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"gOAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,OAAO,GAAU,UAAiB,EAAwB,SAAS,CAAK,CAEhF,CAKA,OAAO,iBAAiB,EAAkC,CACtD,OAAO,EAAU,CAAK,CAC1B,CAIA,OAAO,iBAAiB,EAA2C,CAE/D,GADI,OAAO,GAAU,WAAY,GAC7B,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAO,EAAM,aACnB,GAAI,OAAO,GAAS,WAAY,EAAe,MAAO,GACtD,IAAM,EAAQ,EACd,OAAO,EAAM,UAAY,GAAK,OAAO,EAAM,UAAa,UAC5D,CAEA,OAAO,gBACH,EACiD,CACjD,GAAI,OAAO,GAAc,WACrB,MAAM,IAAI,EAAA,IAEN,4CAA4C,OAAO,EAAU,EACjE,CAER,CAKA,OAAO,eAAe,EAA0C,CAC5D,GAAI,CAAC,EAAU,CAAK,EAChB,MAAM,IAAI,EAAA,IAEN,kEACJ,EAGJ,GAAI,OAAO,EAAM,WAAc,UAAY,EAAM,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AI,CAAC,WAAY,UAAU,CAAC,EAC5C,EAAc,OAAO,KAAK,CAAM,CAAC,CAAC,OAAQ,GAAQ,CAAC,EAAU,IAAI,CAAG,CAAC,EAE3E,GAAI,EAAY,OAAS,EACrB,MAAM,IAAI,EAAA,IAEN,2BAA2B,EAAY,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,CAAS,CAAC,CAAC,KAAK,IAAI,EAAE,oEAC5G,EAGJ,MAAO,EACX,CAIA,OAAO,sBAAsB,EAAiB,EAA6C,CACvF,IAAM,EAAU,EAAM,OAAQ,GAAM,CAAC,EAAW,CAAC,CAAC,EAElD,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CACJ"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{debugVerbose as e,debugWarn as t}from"./Debug.mjs";const n=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/u;function r(e){let t=new Map,n=e.split(/\r?\n/u);for(let e=0;e<n.length;e++){let r=i(n,e);e=r.endLine,r.entry&&t.set(r.entry.key,r.entry.value)}return t}function i(e,t){let r=e[t]??``,i=r.trim();if(i===``||i.startsWith(`#`))return{entry:void 0,endLine:t};let s=r.match(n);if(!s)return{entry:void 0,endLine:t};let c=s[1],l=(s[2]??``).replace(/^\s+/u,``),u=l[0];if(u===`"`||u===`'`||u==="`"){let n=a(l,e,t,u);return{entry:{key:c,value:n.value},endLine:n.endLine}}return{entry:{key:c,value:o(l)},endLine:t}}function a(e,t,n,r){let i=e,a=n,o=c(i,r);for(;o<0&&a<t.length-1;)a++,i+=`\n${t[a]??``}`,o=c(i,r);let s=o>0?i.slice(1,o):i.slice(1);return{value:r===`"`?l(s):s,endLine:a}}function o(e){let t=s(e);return(t===-1?e:e.slice(0,t)).trimEnd()}function s(e){for(let t=0;t<e.length;t++)if(e[t]===`#`&&(t===0||/\s/u.test(e[t-1])))return t;return-1}function c(e,t){for(let n=e.length-1;n>0;n--)if(e[n]===t){if(t===`"`){let t=0,r=n-1;for(;r>=0&&e[r]===`\\`;)t++,r--;if(t%2==1)continue}return n}return-1}function l(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r!==`\\`||n===e.length-1){t+=r;continue}let i=e[n+1];switch(n++,i){case`n`:t+=`
|
|
2
|
-
`;break;case`r`:t+=`\r`;break;case`t`:t+=` `;break;case`\\`:t+=`\\`;break;case`"`:t+=`"`;break;default:t+=`\\${i??``}`}}return t}function u(n){let i=Array.isArray(n.path)?n.path:[n.path],a=n.encoding??`utf8`,o=n.override??!1,s=new Set;for(let c of i){let i=n.readFile(c,a);if(i===void 0){t(`could not read ${c}`);continue}let l=r(i);e(`loaded ${c}: ${l.size} ${l.size===1?`key`:`keys`}`);for(let[t,r]of l)(!Object.prototype.hasOwnProperty.call(n.processEnv,t)||o)&&(n.processEnv[t]=r,s.add(t),e(`${c} -> ${t}`))}return s}export{u as loadDotenv};
|
|
2
|
+
`;break;case`r`:t+=`\r`;break;case`t`:t+=` `;break;case`\\`:t+=`\\`;break;case`"`:t+=`"`;break;default:t+=`\\${i??``}`}}return t}function u(n){let i=Array.isArray(n.path)?n.path:[n.path],a=n.encoding??`utf8`,o=n.override??!1,s=new Set;for(let c of i){let i=n.readFile(c,a);if(i===void 0){t(`could not read ${c}`);continue}let l=r(i);e(`loaded ${c}: ${l.size} ${l.size===1?`key`:`keys`}`);for(let[t,r]of l)(!Object.prototype.hasOwnProperty.call(n.processEnv,t)||o)&&(n.processEnv[t]=r,s.add(t),e(`${c} -> ${t}`))}return s}export{u as loadDotenv,r as parseDotenv};
|
|
3
3
|
//# sourceMappingURL=Dotenv.mjs.map
|
package/dist/types/config.d.mts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export {}
|
|
@@ -75,5 +75,5 @@ declare const Converters: {
|
|
|
75
75
|
readonly Email: "email";
|
|
76
76
|
};
|
|
77
77
|
//#endregion
|
|
78
|
-
export { ArrayOf, ConverterToken, Converters, CustomElementConverter };
|
|
78
|
+
export { ArrayElement, ArrayOf, ConverterToken, Converters, CustomElementConverter };
|
|
79
79
|
//# sourceMappingURL=Converters.d.mts.map
|
|
@@ -5,7 +5,6 @@ import { InferSchemaOutput, StandardSchemaV1 } from "../infra/StandardSchema.mjs
|
|
|
5
5
|
import { SchemaConstraint } from "../types/Schema.mjs";
|
|
6
6
|
import { EnvKeyInput } from "../types/Env.mjs";
|
|
7
7
|
import { PrimitiveMethods } from "./PrimitiveMethods.mjs";
|
|
8
|
-
|
|
9
8
|
//#region src/core/AdvancedMethods.d.ts
|
|
10
9
|
/**
|
|
11
10
|
* Mixin for advanced methods for environment variable conversion using built-in and custom converters
|
|
@@ -65,11 +64,11 @@ declare class AdvancedMethods extends PrimitiveMethods {
|
|
|
65
64
|
* @see {@link https://envapt.materwelon.dev/docs/envapter#fail-fast-on-missing-values}
|
|
66
65
|
* @see {@link https://envapt.materwelon.dev/docs/converters#require-a-converted-value}
|
|
67
66
|
*/
|
|
68
|
-
static getRequiredAll<Spec extends RequiredSpec, Casing extends KeyCasing | undefined = undefined>(spec: Spec, casing?: Casing): { [K in keyof Spec as RecaseKey<K & string, Casing>]: InferSpecField<Spec[K]
|
|
67
|
+
static getRequiredAll<Spec extends RequiredSpec, Casing extends KeyCasing | undefined = undefined>(spec: Spec, casing?: Casing): { [K in keyof Spec as RecaseKey<K & string, Casing>]: InferSpecField<Spec[K]>; };
|
|
69
68
|
/**
|
|
70
69
|
* @see {@link AdvancedMethods.getRequiredAll}
|
|
71
70
|
*/
|
|
72
|
-
getRequiredAll<Spec extends RequiredSpec, Casing extends KeyCasing | undefined = undefined>(spec: Spec, casing?: Casing): { [K in keyof Spec as RecaseKey<K & string, Casing>]: InferSpecField<Spec[K]
|
|
71
|
+
getRequiredAll<Spec extends RequiredSpec, Casing extends KeyCasing | undefined = undefined>(spec: Spec, casing?: Casing): { [K in keyof Spec as RecaseKey<K & string, Casing>]: InferSpecField<Spec[K]>; };
|
|
73
72
|
/**
|
|
74
73
|
* Validate an environment variable through a {@link StandardSchemaV1}-conformant schema
|
|
75
74
|
* (zod, valibot, arktype, etc). Throws `MissingEnvValue` if the env value is absent and
|
|
@@ -2,7 +2,6 @@ import { DebugLevel } from "../infra/Debug.mjs";
|
|
|
2
2
|
import { FileApiMode } from "../types/Options.mjs";
|
|
3
3
|
import { EnvKeyInput } from "../types/Env.mjs";
|
|
4
4
|
import { Source } from "../types/Source.mjs";
|
|
5
|
-
|
|
6
5
|
//#region src/core/EnvapterBase.d.ts
|
|
7
6
|
/** @internal */
|
|
8
7
|
declare abstract class EnvapterBase {
|
|
@@ -4,7 +4,6 @@ import { InferSchemaOutput, StandardSchemaV1 } from "../../infra/StandardSchema.
|
|
|
4
4
|
import { SchemaConstraint } from "../../types/Schema.mjs";
|
|
5
5
|
import { EnvKeyInput } from "../../types/Env.mjs";
|
|
6
6
|
import { EnvaptFieldDecorator } from "../../types/Decorator.mjs";
|
|
7
|
-
|
|
8
7
|
//#region src/decorators/legacy/Envapt.d.ts
|
|
9
8
|
/**
|
|
10
9
|
* A custom converter function with a fallback (both required), or a fallback only.
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { TimeFallback } from "../../types/Conversion.mjs";
|
|
2
2
|
import { EnvKeyInput } from "../../types/Env.mjs";
|
|
3
3
|
import { EnvaptFieldDecorator } from "../../types/Decorator.mjs";
|
|
4
|
-
|
|
5
4
|
//#region src/decorators/legacy/SugarDecorators.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Shorthand for `@Envapt(key, { converter: Converters.Boolean, fallback })`.
|
|
@@ -4,7 +4,6 @@ import { InferSchemaOutput, StandardSchemaV1 } from "../../infra/StandardSchema.
|
|
|
4
4
|
import { SchemaConstraint } from "../../types/Schema.mjs";
|
|
5
5
|
import { EnvKeyInput } from "../../types/Env.mjs";
|
|
6
6
|
import { EnvaptAccessorDecorator } from "../../types/Decorator.mjs";
|
|
7
|
-
|
|
8
7
|
//#region src/decorators/modern/Envapt.d.ts
|
|
9
8
|
/**
|
|
10
9
|
* A custom converter function with a fallback (both required), or a fallback only.
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { TimeFallback } from "../../types/Conversion.mjs";
|
|
2
2
|
import { EnvKeyInput } from "../../types/Env.mjs";
|
|
3
3
|
import { EnvaptAccessorDecorator } from "../../types/Decorator.mjs";
|
|
4
|
-
|
|
5
4
|
//#region src/decorators/modern/SugarDecorators.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Shorthand for `@Envapt(key, { converter: Converters.Boolean, fallback })`.
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Environment } from "../core/Environment.mjs";
|
|
2
2
|
import { EnvKeyInput } from "../types/Env.mjs";
|
|
3
3
|
import { AdvancedMethods } from "../core/AdvancedMethods.mjs";
|
|
4
|
-
|
|
5
4
|
//#region src/engine/Envapter.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Main configuration class for environment variable management.
|
|
@@ -85,5 +84,5 @@ declare class Envapter extends AdvancedMethods {
|
|
|
85
84
|
has(key: EnvKeyInput): boolean;
|
|
86
85
|
}
|
|
87
86
|
//#endregion
|
|
88
|
-
export { Envapter };
|
|
87
|
+
export { Envapter, Environment };
|
|
89
88
|
//# sourceMappingURL=Envapter.d.mts.map
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { ProfilesConfig } from "../types/Options.mjs";
|
|
2
2
|
import { Envapter } from "./Envapter.mjs";
|
|
3
3
|
import { EnvFileOptions } from "../infra/Dotenv.mjs";
|
|
4
|
-
|
|
5
4
|
//#region src/engine/NodeEnvapter.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* The Node/Bun/Deno facade: {@link Envapter} plus the filesystem-only configuration APIs (`.env`
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { ProfilesConfig } from "../types/Options.mjs";
|
|
2
2
|
import { Envapter } from "./Envapter.mjs";
|
|
3
3
|
import { EnvFileOptions } from "../infra/Dotenv.mjs";
|
|
4
|
-
|
|
5
4
|
//#region src/engine/PortableEnvapter.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* The browser/Workers/edge facade. {@link Envapter} with the filesystem-only config APIs present in
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ArrayOf, ConverterToken, CustomElementConverter } from "../converters/Converters.mjs";
|
|
2
|
-
|
|
3
2
|
//#region src/types/Conversion.d.ts
|
|
4
3
|
type BuiltInConverter = ConverterToken;
|
|
5
4
|
type PrimitiveConstructor = typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol;
|
|
@@ -62,5 +61,5 @@ type InferConverterFallbackType<TConverter> = TConverter extends 'time' ? TimeFa
|
|
|
62
61
|
type AdvancedConverterReturn<TConverter, TFallback = undefined> = ConditionalReturn<InferConverterReturnType<TConverter>, TFallback>;
|
|
63
62
|
type InferPrimitiveReturnType<TConstructor extends PrimitiveConstructor> = TConstructor extends typeof String ? string : TConstructor extends typeof Number ? number : TConstructor extends typeof Boolean ? boolean : TConstructor extends typeof BigInt ? bigint : TConstructor extends typeof Symbol ? symbol : never;
|
|
64
63
|
//#endregion
|
|
65
|
-
export type { AdvancedConverterReturn, BuiltInConverter, ConditionalReturn, ConverterFunction, EnvaptConverter, InferConverterFallbackType, InferConverterReturnType, InferPrimitiveReturnType, InferSpecField, JsonValue, PrimitiveConstructor, RequiredSpec, TimeFallback };
|
|
64
|
+
export type { AdvancedConverterReturn, BuiltInConverter, ConditionalReturn, ConverterFunction, EnvaptConverter, InferConverterFallbackType, InferConverterReturnType, InferPrimitiveReturnType, InferSpecField, JsonValue, PrimitiveConstructor, RequiredSpec, TimeFallback, TimeUnit };
|
|
66
65
|
//# sourceMappingURL=Conversion.d.mts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { StandardSchemaV1 } from "../infra/StandardSchema.mjs";
|
|
2
|
-
|
|
3
2
|
//#region src/types/Schema.d.ts
|
|
4
3
|
declare const _envaptErrBrand: unique symbol;
|
|
5
4
|
type Err<Msg extends string> = Msg & {
|
|
@@ -8,5 +7,5 @@ type Err<Msg extends string> = Msg & {
|
|
|
8
7
|
type SchemaMustBeSync = Err<'Schema must be synchronous. envapt is boot-time config loading; async refinements (validate returning `Promise<Result>`) belong outside the env layer.'>;
|
|
9
8
|
type SchemaConstraint<Schema extends StandardSchemaV1> = ReturnType<Schema['~standard']['validate']> extends Promise<unknown> ? SchemaMustBeSync : Schema;
|
|
10
9
|
//#endregion
|
|
11
|
-
export type { SchemaConstraint };
|
|
10
|
+
export type { Err, SchemaConstraint, SchemaMustBeSync };
|
|
12
11
|
//# sourceMappingURL=Schema.d.mts.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "envapt",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "8.1.
|
|
4
|
+
"version": "8.1.1",
|
|
5
5
|
"description": "Type-safe config for TypeScript. Read typed values from any source, process.env, .env files, Cloudflare Workers bindings, browser bundles, or any object you supply. Zero runtime dependencies, one API across Node, Bun, Deno, Workers, and the browser. TC39 accessor decorators (legacy decorators at envapt/legacy), converters, and Standard Schema (zod/valibot/arktype) validation.",
|
|
6
6
|
"types": "./dist/types/index.d.mts",
|
|
7
7
|
"exports": {
|
|
@@ -187,7 +187,7 @@
|
|
|
187
187
|
},
|
|
188
188
|
"devDependencies": {
|
|
189
189
|
"@cloudflare/vitest-pool-workers": "0.18.0",
|
|
190
|
-
"@cloudflare/workers-types": "^5.
|
|
190
|
+
"@cloudflare/workers-types": "^5.20260730.1",
|
|
191
191
|
"@vitest/browser": "4.1.10",
|
|
192
192
|
"@vitest/browser-playwright": "4.1.10",
|
|
193
193
|
"arktype": "^2.2.2",
|
|
@@ -231,5 +231,5 @@
|
|
|
231
231
|
"bump": "pnpm tsx ../../scripts/release/bump-jsr.ts",
|
|
232
232
|
"release": "pnpm run cs:publish"
|
|
233
233
|
},
|
|
234
|
-
"readme": "<img src=\"https://raw.githubusercontent.com/materwelonDhruv/envapt/main/.github/assets/logo.png\" width=\"120\" align=\"left\" alt=\"envapt logo\" />\n\n<h3>envapt</h3>\n\n<p>\n <strong>The apt way to read typed config.</strong><br/>\n Read config from any source as real typed values, with zero runtime dependencies.\n</p>\n\n<p>\n <a href=\"https://www.npmjs.com/package/envapt\"><img alt=\"npm\" src=\"https://img.shields.io/npm/v/envapt?logo=npm&logoColor=cb3838&label=%20&labelColor=103544&color=cb3838\"></a>\n <a href=\"https://www.npmjs.com/package/envapt\"><img alt=\"downloads\" src=\"https://img.shields.io/npm/dm/envapt?style=flat&color=f7f6e8&labelColor=103544&label=downloads\"></a>\n <a href=\"https://jsr.io/@materwelon/envapt\"><img alt=\"jsr\" src=\"https://jsr.io/badges/@materwelon/envapt\"></a>\n <img alt=\"CI\" src=\"https://img.shields.io/github/actions/workflow/status/materwelonDhruv/envapt/checks.yml?branch=main&label=tests&style=flat&logo=github&color=3fb950&labelColor=103544\">\n <a href=\"LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/npm/l/envapt?style=flat&color=e97826&logo=apache&label=\"></a>\n</p>\n\n<br clear=\"left\"/>\n\nenvapt returns config as the type you asked for instead of the `string | undefined` you get raw, with\na fallback that removes `undefined` from the return type. It reads from whatever source you bind. On\nNode, Bun, and Deno that is `process.env` and your `.env` files, bound on import. On Cloudflare\nWorkers, in the browser, or for a secrets object you fetched at boot, you bind the source with\n`Envapter.useSource(...)`.\n\n```ts\nimport { Envapter } from 'envapt';\n\nconst port = Envapter.
|
|
234
|
+
"readme": "<img src=\"https://raw.githubusercontent.com/materwelonDhruv/envapt/main/.github/assets/logo.png\" width=\"120\" align=\"left\" alt=\"envapt logo\" />\n\n<h3>envapt</h3>\n\n<p>\n <strong>The apt way to read typed config.</strong><br/>\n Read config from any source as real typed values, with zero runtime dependencies.\n</p>\n\n<p>\n <a href=\"https://www.npmjs.com/package/envapt\"><img alt=\"npm\" src=\"https://img.shields.io/npm/v/envapt?logo=npm&logoColor=cb3838&label=%20&labelColor=103544&color=cb3838\"></a>\n <a href=\"https://www.npmjs.com/package/envapt\"><img alt=\"downloads\" src=\"https://img.shields.io/npm/dm/envapt?style=flat&color=f7f6e8&labelColor=103544&label=downloads\"></a>\n <a href=\"https://jsr.io/@materwelon/envapt\"><img alt=\"jsr\" src=\"https://jsr.io/badges/@materwelon/envapt\"></a>\n <img alt=\"CI\" src=\"https://img.shields.io/github/actions/workflow/status/materwelonDhruv/envapt/checks.yml?branch=main&label=tests&style=flat&logo=github&color=3fb950&labelColor=103544\">\n <a href=\"LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/npm/l/envapt?style=flat&color=e97826&logo=apache&label=\"></a>\n</p>\n\n<br clear=\"left\"/>\n\nenvapt returns config as the type you asked for instead of the `string | undefined` you get raw, with\na fallback that removes `undefined` from the return type. It reads from whatever source you bind. On\nNode, Bun, and Deno that is `process.env` and your `.env` files, bound on import. On Cloudflare\nWorkers, in the browser, or for a secrets object you fetched at boot, you bind the source with\n`Envapter.useSource(...)`.\n\n```ts\nimport { Converters, Envapter } from 'envapt';\n\nconst { port, databaseUrl, cacheTtl, allowedOrigins } = Envapter.getRequiredAll(\n {\n PORT: Converters.Port, // number, checked against 0-65535\n DATABASE_URL: Converters.Url, // URL\n CACHE_TTL: Converters.Time, // \"15m\" parsed to 900000\n ALLOWED_ORIGINS: Converters.array() // string[]\n // ... and many more built-in converters\n },\n 'camelCase'\n);\n```\n\nCall that at startup and a missing value fails the boot, with one error naming every key that was\nmissing. Reads with a fallback (`Envapter.getNumber('WORKERS', 4)`) never throw.\n\n**[Read the docs →](https://envapt.materwelon.dev)**\n\n## What you get\n\n- **Typed values.** A fallback removes `undefined` from the return type. Built-in converters cover\n numbers, integers, floats, booleans, bigint, symbols, JSON, URLs, regular expressions, dates,\n durations, ports, emails, and arrays, or pass your own function or a Standard Schema validator\n (zod, valibot, arktype).\n- **Any source.** A source is any object with a `readVars()` method, so you can bind `process.env`, a\n Cloudflare Workers binding, a browser bundle, or a secrets payload you fetched from a store at boot.\n On Node, Bun, and Deno one binds on import.\n- **Zero runtime dependencies.** The reader, converters, and built-in `.env` parser are self-contained,\n so nothing is added to your dependency tree.\n- **Runs on Node, Bun, Deno, Cloudflare Workers, and the browser.** Node `>=20`, Bun `>=1.3`, Deno\n `>=2.5` (ESM and CJS). The portable build resolves through the package `exports`\n conditions.\n- **`.env` loading built in on Node.** The default Node source adds a per-environment file cascade,\n `${VAR}` templates, and strict / required checks. Off Node there is no filesystem, so you bind\n another source with `Envapter.useSource(...)` and read with the same typed API.\n\n## Install\n\n```sh\nnpm install envapt\npnpm add envapt\nyarn add envapt\nbun add envapt\ndeno add jsr:@materwelon/envapt\n```\n\n## Quick start\n\nRead values functionally with `Envapter`, or bind them to class fields with the `@Envapt` decorator.\nBoth share the same parsing, converters, and cache.\n\n### Functional\n\nRead a value from any call site, in JavaScript or TypeScript. No build step. On Node the source is\nbound for you. On Workers and in the browser, call `Envapter.useSource(...)` first.\n\n```ts\nimport { Converters, Envapter } from 'envapt';\n\nconst requestTimeout = Envapter.getUsing('REQUEST_TIMEOUT', Converters.Time, '30s'); // 30000\nconst maxRetries = Envapter.getNumber('MAX_RETRIES', 3);\nconst debug = Envapter.getBoolean('DEBUG', false);\n```\n\nOn Cloudflare Workers, `env` is importable at module scope, so bind it once in a config module, and in\nthe browser seed a `PortableSource` from the object your bundler injects.\n\n```ts\nimport { env } from 'cloudflare:workers';\nimport { Envapter, PortableSource } from 'envapt';\n\nEnvapter.useSource(new PortableSource(env));\n\nexport const apiToken = Envapter.get('API_TOKEN');\n```\n\n### Decorator\n\nBind a value to a class field with a TC39 accessor decorator. No `experimentalDecorators` flag, and it runs on Bun and Deno from `.ts` directly.\n\n```ts\nimport { Converters, Envapt, EnvTime } from 'envapt';\n\nclass Config {\n @Envapt('PORT', { converter: Converters.Port, fallback: 3000 })\n static accessor port: number;\n\n @EnvTime('CACHE_TTL', '15m')\n static accessor cacheTtl: number;\n}\n```\n\nThe legacy (experimentalDecorators) decorators are exported from `envapt/legacy`.\n\n## Agent skill\n\nInstall the envapt agent skill so AI coding tools use the correct API:\n\n```sh\nnpx skills add materwelonDhruv/envapt\n```\n\n---\n\n<p align=\"center\"><sub>Built by <a href=\"https://github.com/materwelondhruv\">@materwelonDhruv</a> · Apache 2.0</sub></p>\n"
|
|
235
235
|
}
|