envapt 7.0.0 → 7.0.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 +20 -0
- package/dist/browser/converters/Converters.mjs.map +1 -1
- package/dist/browser/core/AdvancedMethods.mjs +1 -1
- package/dist/browser/core/AdvancedMethods.mjs.map +1 -1
- package/dist/browser/core/EnvapterBase.mjs +1 -1
- package/dist/browser/core/EnvapterBase.mjs.map +1 -1
- package/dist/browser/core/EnvironmentMethods.mjs.map +1 -1
- package/dist/browser/core/PrimitiveMethods.mjs +1 -1
- package/dist/browser/core/PrimitiveMethods.mjs.map +1 -1
- package/dist/browser/infra/Debug.mjs.map +1 -1
- package/dist/browser/infra/Error.mjs.map +1 -1
- package/dist/browser/sources/ManualEnvSource.mjs.map +1 -1
- package/dist/browser/sources/WorkerEnvSource.mjs.map +1 -1
- package/dist/node/config.cjs.map +1 -1
- package/dist/node/config.mjs.map +1 -1
- package/dist/node/converters/Converters.cjs.map +1 -1
- package/dist/node/converters/Converters.mjs.map +1 -1
- package/dist/node/core/AdvancedMethods.cjs +1 -1
- package/dist/node/core/AdvancedMethods.cjs.map +1 -1
- package/dist/node/core/AdvancedMethods.mjs +1 -1
- package/dist/node/core/AdvancedMethods.mjs.map +1 -1
- package/dist/node/core/EnvapterBase.cjs +1 -1
- package/dist/node/core/EnvapterBase.cjs.map +1 -1
- package/dist/node/core/EnvapterBase.mjs +1 -1
- package/dist/node/core/EnvapterBase.mjs.map +1 -1
- package/dist/node/core/EnvironmentMethods.cjs.map +1 -1
- package/dist/node/core/EnvironmentMethods.mjs.map +1 -1
- package/dist/node/core/PrimitiveMethods.cjs +1 -1
- package/dist/node/core/PrimitiveMethods.cjs.map +1 -1
- package/dist/node/core/PrimitiveMethods.mjs +1 -1
- package/dist/node/core/PrimitiveMethods.mjs.map +1 -1
- package/dist/node/engine/NodeEnvapter.cjs.map +1 -1
- package/dist/node/engine/NodeEnvapter.mjs.map +1 -1
- package/dist/node/infra/Debug.cjs.map +1 -1
- package/dist/node/infra/Debug.mjs.map +1 -1
- package/dist/node/infra/Error.cjs.map +1 -1
- package/dist/node/infra/Error.mjs.map +1 -1
- package/dist/node/sources/ManualEnvSource.cjs.map +1 -1
- package/dist/node/sources/ManualEnvSource.mjs.map +1 -1
- package/dist/node/sources/NodeEnvSource.cjs.map +1 -1
- package/dist/node/sources/NodeEnvSource.mjs.map +1 -1
- package/dist/node/sources/WorkerEnvSource.cjs.map +1 -1
- package/dist/node/sources/WorkerEnvSource.mjs.map +1 -1
- package/dist/types/converters/Converters.d.mts +3 -0
- package/dist/types/core/EnvapterBase.d.mts +1 -0
- package/dist/types/core/EnvironmentMethods.d.mts +11 -0
- package/dist/types/core/PrimitiveMethods.d.mts +1 -0
- package/dist/types/engine/NodeEnvapter.d.mts +3 -1
- package/dist/types/infra/Debug.d.mts +4 -4
- package/dist/types/infra/Error.d.mts +6 -0
- package/dist/types/infra/StandardSchema.d.mts +1 -0
- package/dist/types/sources/ManualEnvSource.d.mts +3 -0
- package/dist/types/sources/NodeEnvSource.d.mts +10 -0
- package/dist/types/sources/WorkerEnvSource.d.mts +3 -0
- package/dist/types/types/Options.d.mts +3 -0
- package/dist/types/types/Schema.d.mts +12 -0
- package/dist/workerd/converters/Converters.mjs.map +1 -1
- package/dist/workerd/core/AdvancedMethods.mjs +1 -1
- package/dist/workerd/core/AdvancedMethods.mjs.map +1 -1
- package/dist/workerd/core/EnvapterBase.mjs +1 -1
- package/dist/workerd/core/EnvapterBase.mjs.map +1 -1
- package/dist/workerd/core/EnvironmentMethods.mjs.map +1 -1
- package/dist/workerd/core/PrimitiveMethods.mjs +1 -1
- package/dist/workerd/core/PrimitiveMethods.mjs.map +1 -1
- package/dist/workerd/infra/Debug.mjs.map +1 -1
- package/dist/workerd/infra/Error.mjs.map +1 -1
- package/dist/workerd/sources/ManualEnvSource.mjs.map +1 -1
- package/dist/workerd/sources/WorkerEnvSource.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
1
|
# envapt
|
|
2
2
|
|
|
3
|
+
## 7.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 8f4cac8: Fixed: `syncProcessEnv` and `import 'envapt/config'` now mirror template-resolved values to `process.env`, matching `Envapter.get`.
|
|
8
|
+
|
|
9
|
+
Also, verbose debug logging reports the base directory in use now.
|
|
10
|
+
|
|
11
|
+
- 8f4cac8: `Envapter.debug = 'warn'` now logs whenever a read hits a missing or empty variable, including reads with no fallback and reads through `getUsing`, `getWith`, and `parse`. Previously only a read that fell back to a provided default logged, so a bare `Envapter.get('MISSING')` was silent.
|
|
12
|
+
|
|
13
|
+
## 7.0.1-next.0
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- 8f4cac8: Fixed: `syncProcessEnv` and `import 'envapt/config'` now mirror template-resolved values to `process.env`, matching `Envapter.get`.
|
|
18
|
+
|
|
19
|
+
Also, verbose debug logging reports the base directory in use now.
|
|
20
|
+
|
|
21
|
+
- 8f4cac8: `Envapter.debug = 'warn'` now logs whenever a read hits a missing or empty variable, including reads with no fallback and reads through `getUsing`, `getWith`, and `parse`. Previously only a read that fell back to a provided default logged, so a bare `Envapter.get('MISSING')` was silent.
|
|
22
|
+
|
|
3
23
|
## 7.0.0
|
|
4
24
|
|
|
5
25
|
### Major Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Converters.mjs","names":[],"sources":["../../../src/converters/Converters.ts"],"sourcesContent":["const SCALAR = {\n String: 'string',\n Number: 'number',\n Boolean: 'boolean',\n Bigint: 'bigint',\n Symbol: 'symbol',\n Integer: 'integer',\n Float: 'float',\n Json: 'json',\n Url: 'url',\n Regexp: 'regexp',\n Date: 'date',\n Time: 'time'\n} as const;\n\n/**\n * String tokens for every built-in scalar converter.\n * @public\n */\nexport type ConverterToken = (typeof SCALAR)[keyof typeof SCALAR];\n\n/**\n * Custom element converter for use inside {@link Converters.array}. Receives the trimmed,\n * non-empty raw string for one array slot and returns the parsed value.\n * @public\n */\nexport type CustomElementConverter<TReturn = unknown> = (raw: string) => TReturn;\n\n/**\n * Valid element converters for {@link Converters.array}: any scalar token except\n * `json` and `regexp` (those don't compose as array elements), or a custom function.\n * @public\n */\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n/**\n * Phantom-branded token produced by {@link Converters.array}. The `T` type parameter carries\n * the element converter through any variable indirection so inference survives. The\n * `__envaptKind` discriminant is present at runtime for dispatch.\n * @public\n */\nexport interface ArrayOf<TElement extends ArrayElement = ArrayElement> {\n readonly __envaptKind: 'array';\n readonly of: TElement;\n readonly delimiter: string;\n}\n\n/**\n * Runtime type guard for tokens produced by {@link Converters.array}.\n * @internal\n */\nexport function isArrayOf(value: unknown): value is ArrayOf {\n return typeof value === 'object' && value !== null && '__envaptKind' in value && value.__envaptKind === 'array';\n}\n\ntype ArrayScalarElement = Exclude<ConverterToken, 'json' | 'regexp'>;\n\n// Overloads. The function-element overload must come first so it wins inference when `of`\n// is a function, otherwise TS picks the scalar branch and `raw` defaults to `any`.\nfunction buildArrayConverter<TReturn>(opts: {\n of: CustomElementConverter<TReturn>;\n delimiter?: string;\n}): ArrayOf<CustomElementConverter<TReturn>>;\nfunction buildArrayConverter<TToken extends ArrayScalarElement>(opts: {\n of: TToken;\n delimiter?: string;\n}): ArrayOf<TToken>;\nfunction buildArrayConverter(opts?: { delimiter?: string }): ArrayOf<'string'>;\nfunction buildArrayConverter(opts?: { of?: ArrayElement; delimiter?: string }): ArrayOf<ArrayElement> {\n return {\n __envaptKind: 'array',\n of: opts?.of ?? SCALAR.String,\n delimiter: opts?.delimiter ?? ','\n };\n}\n\n/**\n * Built-in converters for environment variables. Use the scalar tokens (e.g. `Converters.Number`)\n * for primitive types and the {@link Converters.array} builder for delimited lists.\n *\n * @example\n * ```ts\n * \\@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * \\@Envapt('TAGS', { converter: Converters.array({ of: Converters.String, delimiter: ' ' }) })\n * static readonly tags: string[];\n * ```\n *\n * @public\n */\nexport const Converters = {\n ...SCALAR,\n array: buildArrayConverter\n} as const;\n"],"mappings":"AAAA,MAAM,EAAS,CACX,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,KAAM,OACN,KAAM,MACV,
|
|
1
|
+
{"version":3,"file":"Converters.mjs","names":[],"sources":["../../../src/converters/Converters.ts"],"sourcesContent":["const SCALAR = {\n String: 'string',\n Number: 'number',\n Boolean: 'boolean',\n Bigint: 'bigint',\n Symbol: 'symbol',\n Integer: 'integer',\n Float: 'float',\n Json: 'json',\n Url: 'url',\n Regexp: 'regexp',\n Date: 'date',\n Time: 'time'\n} as const;\n\n/**\n * String tokens for every built-in scalar converter.\n * @public\n */\nexport type ConverterToken = (typeof SCALAR)[keyof typeof SCALAR];\n\n/**\n * Custom element converter for use inside {@link Converters.array}. Receives the trimmed,\n * non-empty raw string for one array slot and returns the parsed value.\n * @public\n */\nexport type CustomElementConverter<TReturn = unknown> = (raw: string) => TReturn;\n\n/**\n * Valid element converters for {@link Converters.array}: any scalar token except\n * `json` and `regexp` (those don't compose as array elements), or a custom function.\n * @public\n */\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n/**\n * Phantom-branded token produced by {@link Converters.array}. The `T` type parameter carries\n * the element converter through any variable indirection so inference survives. The\n * `__envaptKind` discriminant is present at runtime for dispatch.\n * @public\n */\nexport interface ArrayOf<TElement extends ArrayElement = ArrayElement> {\n /** Runtime discriminant marking this token as an array converter. Don't use directly. */\n readonly __envaptKind: 'array';\n /** The element converter applied to each split slot. */\n readonly of: TElement;\n /** The string the raw value is split on. */\n readonly delimiter: string;\n}\n\n/**\n * Runtime type guard for tokens produced by {@link Converters.array}.\n * @internal\n */\nexport function isArrayOf(value: unknown): value is ArrayOf {\n return typeof value === 'object' && value !== null && '__envaptKind' in value && value.__envaptKind === 'array';\n}\n\ntype ArrayScalarElement = Exclude<ConverterToken, 'json' | 'regexp'>;\n\n// Overloads. The function-element overload must come first so it wins inference when `of`\n// is a function, otherwise TS picks the scalar branch and `raw` defaults to `any`.\nfunction buildArrayConverter<TReturn>(opts: {\n of: CustomElementConverter<TReturn>;\n delimiter?: string;\n}): ArrayOf<CustomElementConverter<TReturn>>;\nfunction buildArrayConverter<TToken extends ArrayScalarElement>(opts: {\n of: TToken;\n delimiter?: string;\n}): ArrayOf<TToken>;\nfunction buildArrayConverter(opts?: { delimiter?: string }): ArrayOf<'string'>;\nfunction buildArrayConverter(opts?: { of?: ArrayElement; delimiter?: string }): ArrayOf<ArrayElement> {\n return {\n __envaptKind: 'array',\n of: opts?.of ?? SCALAR.String,\n delimiter: opts?.delimiter ?? ','\n };\n}\n\n/**\n * Built-in converters for environment variables. Use the scalar tokens (e.g. `Converters.Number`)\n * for primitive types and the {@link Converters.array} builder for delimited lists.\n *\n * @example\n * ```ts\n * \\@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * \\@Envapt('TAGS', { converter: Converters.array({ of: Converters.String, delimiter: ' ' }) })\n * static readonly tags: string[];\n * ```\n *\n * @public\n */\nexport const Converters = {\n ...SCALAR,\n array: buildArrayConverter\n} as const;\n"],"mappings":"AAAA,MAAM,EAAS,CACX,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,KAAM,OACN,KAAM,MACV,EAyCA,SAAgB,EAAU,EAAkC,CACxD,OAAO,OAAO,GAAU,YAAY,GAAkB,iBAAkB,GAAS,EAAM,eAAiB,OAC5G,CAeA,SAAS,EAAoB,EAAyE,CAClG,MAAO,CACH,aAAc,QACd,GAAI,GAAM,IAAM,EAAO,OACvB,UAAW,GAAM,WAAa,GAClC,CACJ,CAiBA,MAAa,EAAa,CACtB,GAAG,EACH,MAAO,CACX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";import{debugWarn as t}from"../infra/Debug.mjs";import{PrimitiveMethods as n}from"./PrimitiveMethods.mjs";function r(e){return typeof e==`object`&&!!e&&`converter`in e}function i(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}var a=class a extends n{static getUsing(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let s=a,{key:c,value:l}=this.resolveKeyInput(n);if(this.treatAsMissing(l)&&o===void 0){t(`${c} is missing or empty`);return}let u=o!==void 0;return this.valueConverter.convertValue(c,o,s,u)}getUsing(e,t,n){return a.getUsing(e,t,n)}static getWith(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let{key:s,value:c}=this.resolveKeyInput(n);if(this.treatAsMissing(c))return t(`${s} is missing or empty`),o;let l=o!==void 0;return this.valueConverter.convertValue(s,o,a,l)}getWith(e,t,n){return a.getWith(e,t,n)}static parse(e,t,n){let r=arguments.length>2;return this.valueConverter.convertWithSchema(e,t,n,r)}parse(e,t,n){let r=arguments.length>2;return a.valueConverter.convertWithSchema(e,t,n,r)}};export{a as AdvancedMethods};
|
|
2
2
|
//# sourceMappingURL=AdvancedMethods.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdvancedMethods.mjs","names":[],"sources":["../../../src/core/AdvancedMethods.ts"],"sourcesContent":["import { PrimitiveMethods } from './PrimitiveMethods';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../infra/StandardSchema';\nimport type {\n AdvancedConverterReturn,\n BuiltInConverter,\n ConditionalReturn,\n ConverterFunction,\n EnvKeyInput,\n InferConverterReturnType,\n SchemaConstraint,\n TimeFallback\n} from '../types';\n\ninterface GetUsingRequiredOptions<TConverter> {\n converter: TConverter;\n required: true;\n}\n\ninterface GetWithRequiredOptions<TReturnType> {\n converter: ConverterFunction<TReturnType>;\n required: true;\n}\n\nfunction isOptionsBag(value: unknown): value is { converter: unknown; required?: boolean; fallback?: unknown } {\n // `ArrayOf` tokens have `of`/`delimiter` but no `converter` key, so the presence of\n // `converter` discriminates the options-bag form from a positional converter token.\n return typeof value === 'object' && value !== null && 'converter' in value;\n}\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Mixin for advanced methods for environment variable conversion using built-in and custom converters\n * @internal\n */\nexport class AdvancedMethods extends PrimitiveMethods {\n /**\n * Get an environment variable using a built-in converter.\n *\n * Supports both scalar tokens (e.g. `Converters.Number`) and `ArrayOf<...>` tokens\n * produced by `Converters.array(...)`. The key can be a single name or an ordered list;\n * the first defined value wins.\n */\n // Time-specific overload must precede the generic BuiltInConverter overload so it wins\n // overload resolution (TimeFallback accepts time-strings like `'10s'`).\n static getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n static getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n static getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as TConverter,\n false\n );\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const converter = converterOrOptions as TConverter;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n // No env value AND no fallback: return undefined to match primitive-method semantics.\n // Otherwise route through the parser so asymmetric fallback types (TimeFallback,\n // TimeFallback[] for `of: time` arrays) get coerced to the declared return type.\n if (this.treatAsMissing(value) && fallback === undefined) {\n return undefined as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n const result = this.valueConverter.convertValue(resolvedKey, fallback, converter, hasFallback);\n\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getUsing}\n */\n getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n return AdvancedMethods.getUsing(key, converterOrOptions as TConverter, fallback);\n }\n\n /**\n * Get an environment variable using a custom converter function.\n * Accepts a single key or an ordered list for automatic fallback.\n */\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n static getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as ConverterFunction<undefined>,\n false\n );\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n // Check if variable exists first, for consistency with primitive methods\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) return fallback as ConditionalReturn<TReturnType, TFallback>;\n\n const hasFallback = fallback !== undefined;\n // Convert the converter to match the expected signature via unknown\n const result = this.valueConverter.convertValue(\n resolvedKey,\n fallback,\n converterOrOptions as unknown as ConverterFunction<TFallback>,\n hasFallback\n );\n\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getWith}\n */\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n return AdvancedMethods.getWith(key, converterOrOptions as ConverterFunction<TReturnType>, fallback);\n }\n\n /**\n * Validate an environment variable through a {@link StandardSchemaV1}-conformant schema\n * (zod, valibot, arktype, etc). Throws `MissingEnvValue` if the env value is absent and\n * no fallback is provided. The fallback, when provided, is returned as-is on missing;\n * it does NOT pass through the schema (mirrors custom-converter behavior).\n *\n * Synchronous schemas only. A Promise-returning `validate` triggers an\n * `InvalidUserDefinedConfig` throw at the call site.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * const port = Envapter.parse('PORT', z.coerce.number().min(1024).max(65535), 3000);\n * ```\n */\n static parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n // SchemaConstraint resolves to the unsatisfiable SchemaMustBeSync brand for async\n // schemas, so reaching this body means the input is structurally a sync Schema.\n const result = this.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n\n /**\n * @see {@link AdvancedMethods.parse}\n */\n parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n const result = AdvancedMethods.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n}\n"],"mappings":"2GA0BA,SAAS,EAAa,EAAyF,CAG3G,OAAO,OAAO,GAAU,YAAY,GAAkB,cAAe,CACzE,CAEA,SAAS,EAAkB,EAA0B,CACjD,OAAO,MAAM,QAAQ,CAAG,EAAI,IAAI,EAAI,KAAK,IAAI,EAAE,GAAK,OAAO,CAAG,CAClE,CAMA,IAAa,EAAb,MAAa,UAAwB,CAAiB,CA0BlD,OAAO,SACH,EACA,EACA,EAC8C,CAC9C,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAI,EAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAEA,IAAM,EAAY,EACZ,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAK5D,GAAI,KAAK,eAAe,CAAK,GAAK,IAAa,IAAA,GAC3C,OAGJ,IAAM,EAAc,IAAa,IAAA,GAGjC,OAFe,KAAK,eAAe,aAAa,EAAa,EAAU,EAAW,CAEtE,CAChB,CAqBA,SACI,EACA,EACA,EAC8C,CAC9C,OAAO,EAAgB,SAAS,EAAK,EAAkC,CAAQ,CACnF,CAYA,OAAO,QACH,EACA,EACA,EACyC,CACzC,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAI,EAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAGA,GAAM,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAC5D,GAAI,KAAK,eAAe,CAAK,EAAG,OAAO,EAEvC,IAAM,EAAc,IAAa,IAAA,GASjC,OAPe,KAAK,eAAe,aAC/B,EACA,EACA,EACA,CAGQ,CAChB,CAWA,QACI,EACA,EACA,EACyC,CACzC,OAAO,EAAgB,QAAQ,EAAK,EAAsD,CAAQ,CACtG,CAiBA,OAAO,MACH,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EASvC,OANe,KAAK,eAAe,kBAC/B,EACA,EACA,EACA,CAEQ,CAChB,CAKA,MACI,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EAOvC,OANe,EAAgB,eAAe,kBAC1C,EACA,EACA,EACA,CAEQ,CAChB,CACJ"}
|
|
1
|
+
{"version":3,"file":"AdvancedMethods.mjs","names":[],"sources":["../../../src/core/AdvancedMethods.ts"],"sourcesContent":["import { PrimitiveMethods } from './PrimitiveMethods';\nimport { debugWarn } from '../infra/Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../infra/StandardSchema';\nimport type {\n AdvancedConverterReturn,\n BuiltInConverter,\n ConditionalReturn,\n ConverterFunction,\n EnvKeyInput,\n InferConverterReturnType,\n SchemaConstraint,\n TimeFallback\n} from '../types';\n\ninterface GetUsingRequiredOptions<TConverter> {\n converter: TConverter;\n required: true;\n}\n\ninterface GetWithRequiredOptions<TReturnType> {\n converter: ConverterFunction<TReturnType>;\n required: true;\n}\n\nfunction isOptionsBag(value: unknown): value is { converter: unknown; required?: boolean; fallback?: unknown } {\n // `ArrayOf` tokens have `of`/`delimiter` but no `converter` key, so the presence of\n // `converter` discriminates the options-bag form from a positional converter token.\n return typeof value === 'object' && value !== null && 'converter' in value;\n}\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Mixin for advanced methods for environment variable conversion using built-in and custom converters\n * @internal\n */\nexport class AdvancedMethods extends PrimitiveMethods {\n /**\n * Get an environment variable using a built-in converter.\n *\n * Supports both scalar tokens (e.g. `Converters.Number`) and `ArrayOf<...>` tokens\n * produced by `Converters.array(...)`. The key can be a single name or an ordered list;\n * the first defined value wins.\n */\n // Time-specific overload must precede the generic BuiltInConverter overload so it wins\n // overload resolution (TimeFallback accepts time-strings like `'10s'`).\n static getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n static getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n static getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as TConverter,\n false\n );\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const converter = converterOrOptions as TConverter;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n // No env value AND no fallback: return undefined to match primitive-method semantics.\n // Otherwise route through the parser so asymmetric fallback types (TimeFallback,\n // TimeFallback[] for `of: time` arrays) get coerced to the declared return type.\n if (this.treatAsMissing(value) && fallback === undefined) {\n debugWarn(`${resolvedKey} is missing or empty`);\n return undefined as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n const result = this.valueConverter.convertValue(resolvedKey, fallback, converter, hasFallback);\n\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getUsing}\n */\n getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n return AdvancedMethods.getUsing(key, converterOrOptions as TConverter, fallback);\n }\n\n /**\n * Get an environment variable using a custom converter function.\n * Accepts a single key or an ordered list for automatic fallback.\n */\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n static getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as ConverterFunction<undefined>,\n false\n );\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n // Check if variable exists first, for consistency with primitive methods\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) {\n debugWarn(`${resolvedKey} is missing or empty`);\n return fallback as ConditionalReturn<TReturnType, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n // Convert the converter to match the expected signature via unknown\n const result = this.valueConverter.convertValue(\n resolvedKey,\n fallback,\n converterOrOptions as unknown as ConverterFunction<TFallback>,\n hasFallback\n );\n\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getWith}\n */\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n return AdvancedMethods.getWith(key, converterOrOptions as ConverterFunction<TReturnType>, fallback);\n }\n\n /**\n * Validate an environment variable through a {@link StandardSchemaV1}-conformant schema\n * (zod, valibot, arktype, etc). Throws `MissingEnvValue` if the env value is absent and\n * no fallback is provided. The fallback, when provided, is returned as-is on missing;\n * it does NOT pass through the schema (mirrors custom-converter behavior).\n *\n * Synchronous schemas only. A Promise-returning `validate` triggers an\n * `InvalidUserDefinedConfig` throw at the call site.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * const port = Envapter.parse('PORT', z.coerce.number().min(1024).max(65535), 3000);\n * ```\n */\n static parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n // SchemaConstraint resolves to the unsatisfiable SchemaMustBeSync brand for async\n // schemas, so reaching this body means the input is structurally a sync Schema.\n const result = this.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n\n /**\n * @see {@link AdvancedMethods.parse}\n */\n parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n const result = AdvancedMethods.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n}\n"],"mappings":"0JA2BA,SAAS,EAAa,EAAyF,CAG3G,OAAO,OAAO,GAAU,YAAY,GAAkB,cAAe,CACzE,CAEA,SAAS,EAAkB,EAA0B,CACjD,OAAO,MAAM,QAAQ,CAAG,EAAI,IAAI,EAAI,KAAK,IAAI,EAAE,GAAK,OAAO,CAAG,CAClE,CAMA,IAAa,EAAb,MAAa,UAAwB,CAAiB,CA0BlD,OAAO,SACH,EACA,EACA,EAC8C,CAC9C,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAI,EAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAEA,IAAM,EAAY,EACZ,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAK5D,GAAI,KAAK,eAAe,CAAK,GAAK,IAAa,IAAA,GAAW,CACtD,EAAU,GAAG,EAAY,qBAAqB,EAC9C,MACJ,CAEA,IAAM,EAAc,IAAa,IAAA,GAGjC,OAFe,KAAK,eAAe,aAAa,EAAa,EAAU,EAAW,CAEtE,CAChB,CAqBA,SACI,EACA,EACA,EAC8C,CAC9C,OAAO,EAAgB,SAAS,EAAK,EAAkC,CAAQ,CACnF,CAYA,OAAO,QACH,EACA,EACA,EACyC,CACzC,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAI,EAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAGA,GAAM,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAC5D,GAAI,KAAK,eAAe,CAAK,EAEzB,OADA,EAAU,GAAG,EAAY,qBAAqB,EACvC,EAGX,IAAM,EAAc,IAAa,IAAA,GASjC,OAPe,KAAK,eAAe,aAC/B,EACA,EACA,EACA,CAGQ,CAChB,CAWA,QACI,EACA,EACA,EACyC,CACzC,OAAO,EAAgB,QAAQ,EAAK,EAAsD,CAAQ,CACtG,CAiBA,OAAO,MACH,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EASvC,OANe,KAAK,eAAe,kBAC/B,EACA,EACA,EACA,CAEQ,CAChB,CAKA,MACI,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EAOvC,OANe,EAAgB,eAAe,kBAC1C,EACA,EACA,EACA,CAEQ,CAChB,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{Validator as t}from"../engine/Validators.mjs";import{bindRuntimeFromSource as n}from"../infra/runtime.mjs";import{debugVerbose as r,getDebugLevel as i,setDebugLevel as a}from"../infra/Debug.mjs";import{loadDotenv as o}from"../infra/Dotenv.mjs";import{UnboundEnvSource as s}from"../sources/UnboundEnvSource.mjs";const c=new Map;var l=class l{static _envPaths=[`.env`];static _envPathsExplicitlySet=!1;static _baseDir=void 0;static _userDefinedEnvFileOptions={};static _strict=!1;static _syncProcessEnv=!1;static _dotenvAddedKeys=new Set;static _source=new s;static set strict(e){l._strict=e,this.refreshCache()}static get strict(){return l._strict}static set debug(e){a(e)}static get debug(){return i()}static set syncProcessEnv(e){t.validateSyncProcessEnv(e);let n=l._syncProcessEnv;l._syncProcessEnv=e,!n&&e&&c.size>0&&this.mirrorToProcessEnv()}static get syncProcessEnv(){return l._syncProcessEnv}static treatAsMissing(e){return!!(e===void 0||e===``||l._strict&&e.trim()===``)}static resolveAgainstBase(e){let t=l._baseDir;if(t===void 0)return e;let n=l._source;return n.supportsFiles?n.resolvePath(t,e):e}static assertFileApiSupported(t,n){if(!n.supportsFiles)throw new e(306,`${t} requires a filesystem-backed source; the bound source does not support .env files.`)}static sourceFileExists(e){let t=l._source;return t.supportsFiles?t.readFile(e,`utf8`)!==void 0:!1}static refreshCache(){c.clear(),l._dotenvAddedKeys=new Set,r(`cache cleared, reloading config`),this.config}static mirrorToProcessEnv(){if(l._dotenvAddedKeys.size===0)return;let e=l._source;if(!e.supportsFiles)return;let t={};for(let e of l._dotenvAddedKeys){let n=c.get(e);typeof n==`string`&&(t[e]=n,r(`mirrored ${e} to the ambient environment`))}e.writeVars(t),r(`mirrored ${l._dotenvAddedKeys.size} keys to the ambient environment`)}static resolveEffectivePaths(){return this._envPaths.map(e=>this.resolveAgainstBase(e))}static resolveKeyInput(t){let n=Array.isArray(t)?t:[t];if(n.length===0)throw new e(304,`At least one environment key must be provided.`);if(n.some(e=>typeof e!=`string`))throw new e(304,`Environment keys must be strings.`);if(n.some(e=>e.trim()===``))throw new e(304,`Environment keys cannot be empty strings.`);for(let e of n){let t=this.config.get(e);if(t!==void 0)return{key:e,value:t}}return{key:n[0],value:void 0}}static get config(){if(c.size===0){let e=l._source,t={...e.readVars()},n=new Set;if(e.supportsFiles){let i=this.resolveEffectivePaths();r(`effective .env paths: ${i.length===0?`(none)`:i.join(`, `)}`);try{n=o({...this._userDefinedEnvFileOptions,path:i,processEnv:t,readFile:e.readFile.bind(e)})}catch{}}l._dotenvAddedKeys=n;for(let[e,n]of Object.entries(t))c.set(e,n);r(`cache populated: ${c.size} keys total`),l._syncProcessEnv&&this.mirrorToProcessEnv()}return c}static load(){this.config}static useSource(e){l._source=e,n(e),this.refreshCache()}getRaw(e){return l.resolveKeyInput(e).value}};export{c as EnvaptCache,l as EnvapterBase};
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";import{Validator as t}from"../engine/Validators.mjs";import{bindRuntimeFromSource as n}from"../infra/runtime.mjs";import{debugVerbose as r,getDebugLevel as i,setDebugLevel as a}from"../infra/Debug.mjs";import{loadDotenv as o}from"../infra/Dotenv.mjs";import{UnboundEnvSource as s}from"../sources/UnboundEnvSource.mjs";const c=new Map;var l=class l{static _envPaths=[`.env`];static _envPathsExplicitlySet=!1;static _baseDir=void 0;static _userDefinedEnvFileOptions={};static _strict=!1;static _syncProcessEnv=!1;static _dotenvAddedKeys=new Set;static _source=new s;static set strict(e){l._strict=e,this.refreshCache()}static get strict(){return l._strict}static set debug(e){a(e)}static get debug(){return i()}static set syncProcessEnv(e){t.validateSyncProcessEnv(e);let n=l._syncProcessEnv;l._syncProcessEnv=e,!n&&e&&c.size>0&&this.mirrorToProcessEnv()}static get syncProcessEnv(){return l._syncProcessEnv}static treatAsMissing(e){return!!(e===void 0||e===``||l._strict&&e.trim()===``)}static resolveAgainstBase(e){let t=l._baseDir;if(t===void 0)return e;let n=l._source;return n.supportsFiles?n.resolvePath(t,e):e}static assertFileApiSupported(t,n){if(!n.supportsFiles)throw new e(306,`${t} requires a filesystem-backed source; the bound source does not support .env files.`)}static sourceFileExists(e){let t=l._source;return t.supportsFiles?t.readFile(e,`utf8`)!==void 0:!1}static refreshCache(){c.clear(),l._dotenvAddedKeys=new Set,r(`cache cleared, reloading config`),this.config}static mirrorToProcessEnv(){if(l._dotenvAddedKeys.size===0)return;let e=l._source;if(!e.supportsFiles)return;let t={};for(let e of l._dotenvAddedKeys){let n=c.get(e);typeof n==`string`&&(t[e]=this.resolveForMirror(e,n),r(`mirrored ${e} to the ambient environment`))}e.writeVars(t),r(`mirrored ${l._dotenvAddedKeys.size} keys to the ambient environment`)}static resolveForMirror(e,t){return t}static resolveEffectivePaths(){return this._envPaths.map(e=>this.resolveAgainstBase(e))}static resolveKeyInput(t){let n=Array.isArray(t)?t:[t];if(n.length===0)throw new e(304,`At least one environment key must be provided.`);if(n.some(e=>typeof e!=`string`))throw new e(304,`Environment keys must be strings.`);if(n.some(e=>e.trim()===``))throw new e(304,`Environment keys cannot be empty strings.`);for(let e of n){let t=this.config.get(e);if(t!==void 0)return{key:e,value:t}}return{key:n[0],value:void 0}}static get config(){if(c.size===0){let e=l._source,t={...e.readVars()},n=new Set;if(e.supportsFiles){r(`base dir: ${l._baseDir??`working directory`}`);let i=this.resolveEffectivePaths();r(`effective .env paths: ${i.length===0?`(none)`:i.join(`, `)}`);try{n=o({...this._userDefinedEnvFileOptions,path:i,processEnv:t,readFile:e.readFile.bind(e)})}catch{}}l._dotenvAddedKeys=n;for(let[e,n]of Object.entries(t))c.set(e,n);r(`cache populated: ${c.size} keys total`),l._syncProcessEnv&&this.mirrorToProcessEnv()}return c}static load(){this.config}static useSource(e){l._source=e,n(e),this.refreshCache()}getRaw(e){return l.resolveKeyInput(e).value}};export{c as EnvaptCache,l as EnvapterBase};
|
|
2
2
|
//# sourceMappingURL=EnvapterBase.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EnvapterBase.mjs","names":[],"sources":["../../../src/core/EnvapterBase.ts"],"sourcesContent":["import { Validator } from '../engine/Validators';\nimport { debugVerbose, getDebugLevel, setDebugLevel } from '../infra/Debug';\nimport { loadDotenv } from '../infra/Dotenv';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\nimport { bindRuntimeFromSource } from '../infra/runtime';\nimport { UnboundEnvSource } from '../sources/UnboundEnvSource';\n\nimport type { DebugLevel } from '../infra/Debug';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { EnvKeyInput, EnvSource, FileEnvSource } from '../types';\n\n/** @internal */\nexport const EnvaptCache = new Map<string, unknown>();\n\n/** @internal */\nexport abstract class EnvapterBase {\n protected static _envPaths: string[] = ['.env'];\n protected static _envPathsExplicitlySet = false;\n protected static _baseDir: string | undefined = undefined;\n protected static _userDefinedEnvFileOptions: EnvFileOptions = {};\n protected static _strict = false;\n protected static _syncProcessEnv = false;\n // Loader-written keys only (collisions skipped). Refilled on every cache rebuild.\n protected static _dotenvAddedKeys: Set<string> = new Set<string>();\n // Unbound by default so non-Node builds throw NoSourceBound on read until useSource() is called.\n // NodeEnvapter's static block binds NodeEnvSource when referenced, so `import 'envapt'` needs no setup.\n protected static _source: EnvSource = new UnboundEnvSource();\n\n /**\n * Enable or disable strict mode. Default `false`. Setting refreshes the cache so\n * previously-cached converted values get re-evaluated under the new rule.\n */\n static set strict(value: boolean) {\n // Anchored to EnvapterBase: `this._strict` would write an own-property on the subclass that base readers miss.\n EnvapterBase._strict = value;\n // `this`, not EnvapterBase: rebuild via the subclass so its `resolveEffectivePaths` override is honored.\n this.refreshCache();\n }\n\n static get strict(): boolean {\n return EnvapterBase._strict;\n }\n\n /**\n * Set the debug log level. Defaults to `silent`. When unset, reads `ENVAPT_DEBUG` from the\n * bound source on first access; the setter overrides any env-var value. Output goes to stderr\n * on Node (the console elsewhere), prefixed with `[envapt]`.\n */\n static set debug(level: DebugLevel) {\n setDebugLevel(level);\n }\n\n static get debug(): DebugLevel {\n return getDebugLevel();\n }\n\n /**\n * Opt-in mirror of dotenv-loaded keys back to `process.env`. Default `false`.\n *\n * Only keys the loader actually wrote are mirrored, so collision behavior follows\n * `envFileOptions.override`: with the default `false`, pre-existing `process.env` values\n * are preserved; with `true`, the file value wins in both the cache and the mirror.\n *\n * Flipping `false → true` mirrors the existing tracked delta immediately (no cache\n * refresh). Flipping `true → false` is one-way: previously mirrored keys remain in\n * `process.env` until the process exits.\n */\n static set syncProcessEnv(value: boolean) {\n Validator.validateSyncProcessEnv(value);\n const previous = EnvapterBase._syncProcessEnv;\n // Anchored to EnvapterBase: `this._syncProcessEnv` would write an own-property on the subclass that base readers miss.\n EnvapterBase._syncProcessEnv = value;\n if (!previous && value && EnvaptCache.size > 0) this.mirrorToProcessEnv();\n }\n\n static get syncProcessEnv(): boolean {\n return EnvapterBase._syncProcessEnv;\n }\n\n protected static treatAsMissing(value: string | undefined): boolean {\n if (value === undefined || value === '') return true;\n if (EnvapterBase._strict && value.trim() === '') return true;\n return false;\n }\n\n // No baseDir: candidate returned unchanged so the source resolves it against its own default\n // (process.cwd() on Node). Resolution goes through the source to keep this class node-free.\n protected static resolveAgainstBase(candidate: string): string {\n const baseDir = EnvapterBase._baseDir;\n if (baseDir === undefined) return candidate;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve callers are all file-gated, so the source is never bare here */\n if (!source.supportsFiles) return candidate;\n return source.resolvePath(baseDir, candidate);\n }\n\n // File-based config (envPaths/baseDir/configureProfiles) is meaningless without a filesystem;\n // throw instead of silently ignoring it on the browser or Workers. Narrows the source so callers\n // can reach the file capabilities (resolvePath/normalizeBaseDir) after the check.\n protected static assertFileApiSupported(api: string, source: EnvSource): asserts source is FileEnvSource {\n if (!source.supportsFiles) {\n throw new EnvaptError(\n EnvaptErrorCodes.FileApiUnsupported,\n `${api} requires a filesystem-backed source; the bound source does not support .env files.`\n );\n }\n }\n\n // Existence via the bound source instead of fs.existsSync/accessSync: a file \"exists\" when the\n // source can read it.\n protected static sourceFileExists(path: string): boolean {\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve every caller is file-gated, so this never sees a bare source */\n if (!source.supportsFiles) return false;\n return source.readFile(path, 'utf8') !== undefined;\n }\n\n protected static refreshCache(): void {\n EnvaptCache.clear();\n EnvapterBase._dotenvAddedKeys = new Set();\n debugVerbose('cache cleared, reloading config');\n void this.config; // getter rebuilds the cache as a side effect\n }\n\n protected static mirrorToProcessEnv(): void {\n if (EnvapterBase._dotenvAddedKeys.size === 0) return;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve dotenv keys only accumulate under a file source, so the delta implies supportsFiles here */\n if (!source.supportsFiles) return;\n const mirrored: Record<string, string> = {};\n for (const key of EnvapterBase._dotenvAddedKeys) {\n const value = EnvaptCache.get(key);\n /* v8 ignore next -- @preserve loader only writes strings; defensive against future cache contents */\n if (typeof value !== 'string') continue;\n mirrored[key] = value;\n debugVerbose(`mirrored ${key} to the ambient environment`);\n }\n source.writeVars(mirrored);\n debugVerbose(`mirrored ${EnvapterBase._dotenvAddedKeys.size} keys to the ambient environment`);\n }\n\n // Default returns the explicit `_envPaths`; EnvironmentMethods overrides to layer the dotenv-flow\n // cascade + configureProfiles when envPaths was never explicitly set.\n protected static resolveEffectivePaths(): string[] {\n /* v8 ignore next -- @preserve */\n return this._envPaths.map((p) => this.resolveAgainstBase(p));\n }\n\n protected static resolveKeyInput(keyInput: EnvKeyInput): { key: string; value: string | undefined } {\n const keys = Array.isArray(keyInput) ? keyInput : [keyInput];\n const normalizedKeys = keys as readonly string[];\n\n if (normalizedKeys.length === 0) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'At least one environment key must be provided.');\n }\n\n if (normalizedKeys.some((k) => typeof k !== 'string')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys must be strings.');\n }\n\n if (normalizedKeys.some((k) => k.trim() === '')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys cannot be empty strings.');\n }\n\n for (const candidate of normalizedKeys) {\n const value = this.config.get(candidate) as string | undefined;\n if (value !== undefined) {\n return { key: candidate, value };\n }\n }\n\n return { key: normalizedKeys[0] as string, value: undefined };\n }\n\n protected static get config(): Map<string, unknown> {\n if (EnvaptCache.size === 0) {\n const source = EnvapterBase._source;\n // Clone so the loader and downstream reads never mutate the source's backing object.\n const isolatedEnv: Record<string, string> = { ...source.readVars() };\n\n let added = new Set<string>();\n // Sources without a filesystem (injected objects on the browser or Workers) skip the\n // .env cascade, profiles, and envPaths; only the readVars() snapshot populates the cache.\n if (source.supportsFiles) {\n // Outside the try below so a missing configured profile path surfaces its EnvaptError; only dotenv parse errors stay caught.\n const effectivePaths = this.resolveEffectivePaths();\n debugVerbose(\n `effective .env paths: ${effectivePaths.length === 0 ? '(none)' : effectivePaths.join(', ')}`\n );\n try {\n added = loadDotenv({\n ...this._userDefinedEnvFileOptions,\n path: effectivePaths,\n processEnv: isolatedEnv,\n readFile: source.readFile.bind(source)\n });\n } catch {}\n }\n EnvapterBase._dotenvAddedKeys = added;\n for (const [key, value] of Object.entries(isolatedEnv)) EnvaptCache.set(key, value);\n debugVerbose(`cache populated: ${EnvaptCache.size} keys total`);\n if (EnvapterBase._syncProcessEnv) this.mirrorToProcessEnv();\n }\n\n return EnvaptCache;\n }\n\n /**\n * Eagerly load the `.env` cascade now instead of lazily on the first read. Idempotent: a no-op\n * once the cache is built. Useful before mirroring to `process.env` (see {@link syncProcessEnv}),\n * which is what the `envapt/config` side-effect entry does.\n */\n static load(): void {\n void this.config;\n }\n\n /**\n * Bind the environment {@link EnvSource}. On Node the entry binds {@link NodeEnvSource} for you\n * (a `process.env` snapshot plus the `.env` cascade); on the browser or Workers, pass a\n * `ManualEnvSource` / `WorkerEnvSource` (or any `EnvSource`) before reading. Clears and rebuilds\n * the cache.\n */\n static useSource(source: EnvSource): void {\n EnvapterBase._source = source;\n bindRuntimeFromSource(source);\n this.refreshCache();\n }\n\n /**\n * Read an environment variable as its raw string, skipping parsing and conversion.\n */\n getRaw(key: EnvKeyInput): string | undefined {\n return EnvapterBase.resolveKeyInput(key).value;\n }\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"EnvapterBase.mjs","names":[],"sources":["../../../src/core/EnvapterBase.ts"],"sourcesContent":["import { Validator } from '../engine/Validators';\nimport { debugVerbose, getDebugLevel, setDebugLevel } from '../infra/Debug';\nimport { loadDotenv } from '../infra/Dotenv';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\nimport { bindRuntimeFromSource } from '../infra/runtime';\nimport { UnboundEnvSource } from '../sources/UnboundEnvSource';\n\nimport type { DebugLevel } from '../infra/Debug';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { EnvKeyInput, EnvSource, FileEnvSource } from '../types';\n\n/** @internal */\nexport const EnvaptCache = new Map<string, unknown>();\n\n/** @internal */\nexport abstract class EnvapterBase {\n protected static _envPaths: string[] = ['.env'];\n protected static _envPathsExplicitlySet = false;\n protected static _baseDir: string | undefined = undefined;\n protected static _userDefinedEnvFileOptions: EnvFileOptions = {};\n protected static _strict = false;\n protected static _syncProcessEnv = false;\n // Loader-written keys only (collisions skipped). Refilled on every cache rebuild.\n protected static _dotenvAddedKeys: Set<string> = new Set<string>();\n // Unbound by default so non-Node builds throw NoSourceBound on read until useSource() is called.\n // NodeEnvapter's static block binds NodeEnvSource when referenced, so `import 'envapt'` needs no setup.\n protected static _source: EnvSource = new UnboundEnvSource();\n\n /**\n * Enable or disable strict mode. Default `false`. Setting refreshes the cache so\n * previously-cached converted values get re-evaluated under the new rule.\n */\n static set strict(value: boolean) {\n // Anchored to EnvapterBase: `this._strict` would write an own-property on the subclass that base readers miss.\n EnvapterBase._strict = value;\n // `this`, not EnvapterBase: rebuild via the subclass so its `resolveEffectivePaths` override is honored.\n this.refreshCache();\n }\n\n static get strict(): boolean {\n return EnvapterBase._strict;\n }\n\n /**\n * Set the debug log level. Defaults to `silent`. When unset, reads `ENVAPT_DEBUG` from the\n * bound source on first access; the setter overrides any env-var value. Output goes to stderr\n * on Node (the console elsewhere), prefixed with `[envapt]`.\n */\n static set debug(level: DebugLevel) {\n setDebugLevel(level);\n }\n\n static get debug(): DebugLevel {\n return getDebugLevel();\n }\n\n /**\n * Opt-in mirror of dotenv-loaded keys back to `process.env`. Default `false`.\n *\n * Only keys the loader actually wrote are mirrored, so collision behavior follows\n * `envFileOptions.override`: with the default `false`, pre-existing `process.env` values\n * are preserved; with `true`, the file value wins in both the cache and the mirror.\n *\n * Flipping `false → true` mirrors the existing tracked delta immediately (no cache\n * refresh). Flipping `true → false` is one-way: previously mirrored keys remain in\n * `process.env` until the process exits.\n */\n static set syncProcessEnv(value: boolean) {\n Validator.validateSyncProcessEnv(value);\n const previous = EnvapterBase._syncProcessEnv;\n // Anchored to EnvapterBase: `this._syncProcessEnv` would write an own-property on the subclass that base readers miss.\n EnvapterBase._syncProcessEnv = value;\n if (!previous && value && EnvaptCache.size > 0) this.mirrorToProcessEnv();\n }\n\n static get syncProcessEnv(): boolean {\n return EnvapterBase._syncProcessEnv;\n }\n\n protected static treatAsMissing(value: string | undefined): boolean {\n if (value === undefined || value === '') return true;\n if (EnvapterBase._strict && value.trim() === '') return true;\n return false;\n }\n\n // No baseDir: candidate returned unchanged so the source resolves it against its own default\n // (process.cwd() on Node). Resolution goes through the source to keep this class node-free.\n protected static resolveAgainstBase(candidate: string): string {\n const baseDir = EnvapterBase._baseDir;\n if (baseDir === undefined) return candidate;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve callers are all file-gated, so the source is never bare here */\n if (!source.supportsFiles) return candidate;\n return source.resolvePath(baseDir, candidate);\n }\n\n // File-based config (envPaths/baseDir/configureProfiles) is meaningless without a filesystem;\n // throw instead of silently ignoring it on the browser or Workers. Narrows the source so callers\n // can reach the file capabilities (resolvePath/normalizeBaseDir) after the check.\n protected static assertFileApiSupported(api: string, source: EnvSource): asserts source is FileEnvSource {\n if (!source.supportsFiles) {\n throw new EnvaptError(\n EnvaptErrorCodes.FileApiUnsupported,\n `${api} requires a filesystem-backed source; the bound source does not support .env files.`\n );\n }\n }\n\n // Existence via the bound source instead of fs.existsSync/accessSync: a file \"exists\" when the\n // source can read it.\n protected static sourceFileExists(path: string): boolean {\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve every caller is file-gated, so this never sees a bare source */\n if (!source.supportsFiles) return false;\n return source.readFile(path, 'utf8') !== undefined;\n }\n\n protected static refreshCache(): void {\n EnvaptCache.clear();\n EnvapterBase._dotenvAddedKeys = new Set();\n debugVerbose('cache cleared, reloading config');\n void this.config; // getter rebuilds the cache as a side effect\n }\n\n protected static mirrorToProcessEnv(): void {\n if (EnvapterBase._dotenvAddedKeys.size === 0) return;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve dotenv keys only accumulate under a file source, so the delta implies supportsFiles here */\n if (!source.supportsFiles) return;\n const mirrored: Record<string, string> = {};\n for (const key of EnvapterBase._dotenvAddedKeys) {\n const value = EnvaptCache.get(key);\n /* v8 ignore next -- @preserve loader only writes strings; defensive against future cache contents */\n if (typeof value !== 'string') continue;\n mirrored[key] = this.resolveForMirror(key, value);\n debugVerbose(`mirrored ${key} to the ambient environment`);\n }\n source.writeVars(mirrored);\n debugVerbose(`mirrored ${EnvapterBase._dotenvAddedKeys.size} keys to the ambient environment`);\n }\n\n // The template resolver is defined in PrimitiveMethods, and EnvapterBase can't call it without an\n // import cycle, so the mirror expands ${VAR} through this override.\n protected static resolveForMirror(_key: string, value: string): string {\n /* v8 ignore next -- @preserve overridden by PrimitiveMethods on every concrete class */\n return value;\n }\n\n // Default returns the explicit `_envPaths`; EnvironmentMethods overrides to layer the dotenv-flow\n // cascade + configureProfiles when envPaths was never explicitly set.\n protected static resolveEffectivePaths(): string[] {\n /* v8 ignore next -- @preserve */\n return this._envPaths.map((p) => this.resolveAgainstBase(p));\n }\n\n protected static resolveKeyInput(keyInput: EnvKeyInput): { key: string; value: string | undefined } {\n const keys = Array.isArray(keyInput) ? keyInput : [keyInput];\n const normalizedKeys = keys as readonly string[];\n\n if (normalizedKeys.length === 0) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'At least one environment key must be provided.');\n }\n\n if (normalizedKeys.some((k) => typeof k !== 'string')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys must be strings.');\n }\n\n if (normalizedKeys.some((k) => k.trim() === '')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys cannot be empty strings.');\n }\n\n for (const candidate of normalizedKeys) {\n const value = this.config.get(candidate) as string | undefined;\n if (value !== undefined) {\n return { key: candidate, value };\n }\n }\n\n return { key: normalizedKeys[0] as string, value: undefined };\n }\n\n protected static get config(): Map<string, unknown> {\n if (EnvaptCache.size === 0) {\n const source = EnvapterBase._source;\n // Clone so the loader and downstream reads never mutate the source's backing object.\n const isolatedEnv: Record<string, string> = { ...source.readVars() };\n\n let added = new Set<string>();\n // Sources without a filesystem (injected objects on the browser or Workers) skip the\n // .env cascade, profiles, and envPaths; only the readVars() snapshot populates the cache.\n if (source.supportsFiles) {\n debugVerbose(`base dir: ${EnvapterBase._baseDir ?? 'working directory'}`);\n // Outside the try below so a missing configured profile path surfaces its EnvaptError; only dotenv parse errors stay caught.\n const effectivePaths = this.resolveEffectivePaths();\n debugVerbose(\n `effective .env paths: ${effectivePaths.length === 0 ? '(none)' : effectivePaths.join(', ')}`\n );\n try {\n added = loadDotenv({\n ...this._userDefinedEnvFileOptions,\n path: effectivePaths,\n processEnv: isolatedEnv,\n readFile: source.readFile.bind(source)\n });\n } catch {}\n }\n EnvapterBase._dotenvAddedKeys = added;\n for (const [key, value] of Object.entries(isolatedEnv)) EnvaptCache.set(key, value);\n debugVerbose(`cache populated: ${EnvaptCache.size} keys total`);\n if (EnvapterBase._syncProcessEnv) this.mirrorToProcessEnv();\n }\n\n return EnvaptCache;\n }\n\n /**\n * Eagerly load the `.env` cascade now instead of lazily on the first read. Idempotent: a no-op\n * once the cache is built. Useful before mirroring to `process.env` (see {@link syncProcessEnv}),\n * which is what the `envapt/config` side-effect entry does.\n */\n static load(): void {\n void this.config;\n }\n\n /**\n * Bind the environment {@link EnvSource}. On Node the entry binds {@link NodeEnvSource} for you\n * (a `process.env` snapshot plus the `.env` cascade); on the browser or Workers, pass a\n * `ManualEnvSource` / `WorkerEnvSource` (or any `EnvSource`) before reading. Clears and rebuilds\n * the cache.\n */\n static useSource(source: EnvSource): void {\n EnvapterBase._source = source;\n bindRuntimeFromSource(source);\n this.refreshCache();\n }\n\n /**\n * Read an environment variable as its raw string, skipping parsing and conversion.\n */\n getRaw(key: EnvKeyInput): string | undefined {\n return EnvapterBase.resolveKeyInput(key).value;\n }\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EnvironmentMethods.mjs","names":[],"sources":["../../../src/core/EnvironmentMethods.ts"],"sourcesContent":["import { EnvapterBase } from './EnvapterBase';\nimport { debugWarn } from '../infra/Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { EnvProfile, ProfilesConfig } from '../types';\n\n/**\n * Environment types supported by Envapter\n * @public\n */\nexport enum Environment {\n Development,\n Staging,\n Production,\n Test\n}\n\n// Keys carrying the environment name, highest precedence first. Checked in order until the first with a non-empty value is found, or defaulting to development if none are set.\nconst ENV_KEYS = ['ENVIRONMENT', 'ENV', 'NODE_ENV', 'MODE'] as const;\n\nfunction parseEnvironment(raw: string): Environment | undefined {\n switch (raw.toLowerCase()) {\n case 'production':\n return Environment.Production;\n case 'staging':\n return Environment.Staging;\n case 'test':\n return Environment.Test;\n case 'development':\n return Environment.Development;\n default:\n return undefined;\n }\n}\n\n/**\n * Mixin for environment detection and checking methods\n * @internal\n */\nexport class EnvironmentMethods extends EnvapterBase {\n protected static _environment: Environment | undefined;\n protected static _environmentExplicitlySet = false;\n protected static _profiles: ProfilesConfig | undefined;\n\n protected static determineEnvironment(env?: string | Environment): void {\n if (typeof env === 'number') {\n this._environment = env;\n this._environmentExplicitlySet = true;\n return;\n }\n if (typeof env === 'string') {\n this._environment = parseEnvironment(env) ?? Environment.Development;\n this._environmentExplicitlySet = true;\n return;\n }\n\n const raw = this.firstEnvKeyValue((key) => {\n const value = this.config.get(key);\n return typeof value === 'string' ? value : undefined;\n });\n if (raw === undefined) {\n debugWarn(`no environment set (looked for ${ENV_KEYS.join(', ')}); defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n const parsed = parseEnvironment(raw);\n if (parsed === undefined) {\n debugWarn(`unrecognized environment \"${raw}\"; defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n this._environment = parsed;\n }\n\n private static firstEnvKeyValue(read: (key: string) => string | undefined): string | undefined {\n for (const key of ENV_KEYS) {\n const value = read(key);\n if (value !== undefined && value.length > 0) return value;\n }\n return undefined;\n }\n\n /**\n * Get the current application environment\n */\n static get environment(): Environment {\n if (this._environment === undefined) {\n this.determineEnvironment();\n }\n return this._environment as Environment;\n }\n\n /**\n * Set the application environment. Accepts either Environment enum or string value.\n */\n static set environment(env: string | Environment) {\n this.determineEnvironment(env);\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n get environment(): Environment {\n return EnvironmentMethods.environment;\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n set environment(env: string | Environment) {\n EnvironmentMethods.determineEnvironment(env);\n }\n\n /**\n * Check if the current environment is production\n */\n static get isProduction(): boolean {\n return this.environment === Environment.Production;\n }\n\n /**\n * @see {@link EnvironmentMethods.isProduction}\n */\n get isProduction(): boolean {\n return EnvironmentMethods.environment === Environment.Production;\n }\n\n /**\n * Check if the current environment is staging\n */\n static get isStaging(): boolean {\n return this.environment === Environment.Staging;\n }\n\n /**\n * @see {@link EnvironmentMethods.isStaging}\n */\n get isStaging(): boolean {\n return EnvironmentMethods.environment === Environment.Staging;\n }\n\n /**\n * Check if the current environment is development\n */\n static get isDevelopment(): boolean {\n return this.environment === Environment.Development;\n }\n\n /**\n * @see {@link EnvironmentMethods.isDevelopment}\n */\n get isDevelopment(): boolean {\n return EnvironmentMethods.environment === Environment.Development;\n }\n\n /**\n * Check if the current environment is test\n */\n static get isTest(): boolean {\n return this.environment === Environment.Test;\n }\n\n /**\n * @see {@link EnvironmentMethods.isTest}\n */\n get isTest(): boolean {\n return EnvironmentMethods.environment === Environment.Test;\n }\n\n protected static override refreshCache(): void {\n // If the env was inferred (not user-set), reset it so re-hydration re-determines\n // from current state. If the user explicitly set Envapter.environment = X, preserve\n // that value through the refresh. The immediate re-hydration inside super.refreshCache()\n // will use it for cascade selection.\n if (!this._environmentExplicitlySet) this._environment = undefined;\n super.refreshCache();\n }\n\n /**\n * Reads the source's raw vars (not `this.config`, which would recurse: cascade selection runs\n * before the `.env` load). `Envapter.environment` may differ post-load if a file sets `ENVIRONMENT`.\n * @internal\n */\n protected static getCascadeEnvironment(): Environment {\n if (this._environment !== undefined) return this._environment;\n\n const vars = EnvapterBase._source.readVars();\n const raw = this.firstEnvKeyValue((key) => vars[key]);\n return raw === undefined ? Environment.Development : (parseEnvironment(raw) ?? Environment.Development);\n }\n\n /**\n * Build the dotenv-flow cascade for a given environment, in dotenv first-wins precedence\n * order (highest precedence first). Missing files are silently filtered.\n *\n * Precedence is **most-specific-wins** (matches Vite / Astro / Vocs):\n * `.env.${env}.local` \\> `.env.${env}` \\> `.env.local` \\> `.env`\n *\n * This differs from dotenv-flow / Next.js convention which puts `.env.local` above\n * `.env.${env}`. We chose the most-specific-wins order so committed env-specific files\n * (`.env.production`) are authoritative for that environment regardless of whether a\n * stray `.env.local` is present.\n * @internal\n */\n protected static buildCascadePaths(env: Environment): string[] {\n const envName = Environment[env].toLowerCase();\n return [`.env.${envName}.local`, `.env.${envName}`, '.env.local', '.env']\n .map((name) => this.resolveAgainstBase(name))\n .filter((p) => this.sourceFileExists(p));\n }\n\n private static normalizeProfilePaths(profile: EnvProfile | undefined): string[] {\n if (!profile) return [];\n return Array.isArray(profile.paths) ? profile.paths : [profile.paths];\n }\n\n /**\n * Override the base implementation to layer the dotenv-flow cascade + any\n * `Envapter.configureProfiles` overrides on top of `_envPaths` when the user has NOT\n * explicitly set `envPaths`.\n *\n * Precedence (passed to dotenv with first-wins semantics):\n * 1. profile-configured paths for the current env (if any)\n * 2. `.env.${env}.local`\n * 3. `.env.${env}`\n * 4. `.env.local`\n * 5. `.env`\n *\n * If `useDefaults: false` is set on the profiles config, only (1) is loaded, no cascade.\n * If `envPaths` was explicitly set, only `envPaths` is loaded (everything else ignored).\n * @internal\n */\n protected static override resolveEffectivePaths(): string[] {\n if (this._envPathsExplicitlySet) return this._envPaths.map((p) => this.resolveAgainstBase(p));\n\n const env = this.getCascadeEnvironment();\n const profileEntry = this._profiles?.[env];\n const profilePaths = this.normalizeProfilePaths(profileEntry);\n\n // Validate that explicitly configured profile paths exist for the active env.\n if (profilePaths.length > 0) {\n const missing = profilePaths.filter((p) => !this.sourceFileExists(this.resolveAgainstBase(p)));\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 const cascade = this._profiles?.useDefaults === false ? [] : this.buildCascadePaths(env);\n return [...profilePaths.map((p) => this.resolveAgainstBase(p)), ...cascade];\n }\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"EnvironmentMethods.mjs","names":[],"sources":["../../../src/core/EnvironmentMethods.ts"],"sourcesContent":["import { EnvapterBase } from './EnvapterBase';\nimport { debugWarn } from '../infra/Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { EnvProfile, ProfilesConfig } from '../types';\n\n/**\n * Environment types supported by Envapter\n *\n * The following keys are checked in order until the first with a non-empty value is found, or defaulting to development if none are set:\n * - `ENVIRONMENT`\n * - `ENV`\n * - `NODE_ENV`\n * - `MODE`\n *\n * @public\n */\nexport enum Environment {\n /** The default when no environment variable names a known environment. */\n Development,\n /** Selected when an environment variable reads `staging`. */\n Staging,\n /** Selected when an environment variable reads `production`. */\n Production,\n /** Selected when an environment variable reads `test`. */\n Test\n}\n\n// Keys carrying the environment name, highest precedence first. Checked in order until the first with a non-empty value is found, or defaulting to development if none are set.\nconst ENV_KEYS = ['ENVIRONMENT', 'ENV', 'NODE_ENV', 'MODE'] as const;\n\nfunction parseEnvironment(raw: string): Environment | undefined {\n switch (raw.toLowerCase()) {\n case 'production':\n return Environment.Production;\n case 'staging':\n return Environment.Staging;\n case 'test':\n return Environment.Test;\n case 'development':\n return Environment.Development;\n default:\n return undefined;\n }\n}\n\n/**\n * Mixin for environment detection and checking methods\n * @internal\n */\nexport class EnvironmentMethods extends EnvapterBase {\n protected static _environment: Environment | undefined;\n protected static _environmentExplicitlySet = false;\n protected static _profiles: ProfilesConfig | undefined;\n\n protected static determineEnvironment(env?: string | Environment): void {\n if (typeof env === 'number') {\n this._environment = env;\n this._environmentExplicitlySet = true;\n return;\n }\n if (typeof env === 'string') {\n this._environment = parseEnvironment(env) ?? Environment.Development;\n this._environmentExplicitlySet = true;\n return;\n }\n\n const raw = this.firstEnvKeyValue((key) => {\n const value = this.config.get(key);\n return typeof value === 'string' ? value : undefined;\n });\n if (raw === undefined) {\n debugWarn(`no environment set (looked for ${ENV_KEYS.join(', ')}); defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n const parsed = parseEnvironment(raw);\n if (parsed === undefined) {\n debugWarn(`unrecognized environment \"${raw}\"; defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n this._environment = parsed;\n }\n\n private static firstEnvKeyValue(read: (key: string) => string | undefined): string | undefined {\n for (const key of ENV_KEYS) {\n const value = read(key);\n if (value !== undefined && value.length > 0) return value;\n }\n return undefined;\n }\n\n /**\n * Get the current application environment\n */\n static get environment(): Environment {\n if (this._environment === undefined) {\n this.determineEnvironment();\n }\n return this._environment as Environment;\n }\n\n /**\n * Set the application environment. Accepts either Environment enum or string value.\n */\n static set environment(env: string | Environment) {\n this.determineEnvironment(env);\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n get environment(): Environment {\n return EnvironmentMethods.environment;\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n set environment(env: string | Environment) {\n EnvironmentMethods.determineEnvironment(env);\n }\n\n /**\n * Check if the current environment is production\n */\n static get isProduction(): boolean {\n return this.environment === Environment.Production;\n }\n\n /**\n * @see {@link EnvironmentMethods.isProduction}\n */\n get isProduction(): boolean {\n return EnvironmentMethods.environment === Environment.Production;\n }\n\n /**\n * Check if the current environment is staging\n */\n static get isStaging(): boolean {\n return this.environment === Environment.Staging;\n }\n\n /**\n * @see {@link EnvironmentMethods.isStaging}\n */\n get isStaging(): boolean {\n return EnvironmentMethods.environment === Environment.Staging;\n }\n\n /**\n * Check if the current environment is development\n */\n static get isDevelopment(): boolean {\n return this.environment === Environment.Development;\n }\n\n /**\n * @see {@link EnvironmentMethods.isDevelopment}\n */\n get isDevelopment(): boolean {\n return EnvironmentMethods.environment === Environment.Development;\n }\n\n /**\n * Check if the current environment is test\n */\n static get isTest(): boolean {\n return this.environment === Environment.Test;\n }\n\n /**\n * @see {@link EnvironmentMethods.isTest}\n */\n get isTest(): boolean {\n return EnvironmentMethods.environment === Environment.Test;\n }\n\n protected static override refreshCache(): void {\n // If the env was inferred (not user-set), reset it so re-hydration re-determines\n // from current state. If the user explicitly set Envapter.environment = X, preserve\n // that value through the refresh. The immediate re-hydration inside super.refreshCache()\n // will use it for cascade selection.\n if (!this._environmentExplicitlySet) this._environment = undefined;\n super.refreshCache();\n }\n\n /**\n * Reads the source's raw vars (not `this.config`, which would recurse: cascade selection runs\n * before the `.env` load). `Envapter.environment` may differ post-load if a file sets `ENVIRONMENT`.\n * @internal\n */\n protected static getCascadeEnvironment(): Environment {\n if (this._environment !== undefined) return this._environment;\n\n const vars = EnvapterBase._source.readVars();\n const raw = this.firstEnvKeyValue((key) => vars[key]);\n return raw === undefined ? Environment.Development : (parseEnvironment(raw) ?? Environment.Development);\n }\n\n /**\n * Build the dotenv-flow cascade for a given environment, in dotenv first-wins precedence\n * order (highest precedence first). Missing files are silently filtered.\n *\n * Precedence is **most-specific-wins** (matches Vite / Astro / Vocs):\n * `.env.${env}.local` \\> `.env.${env}` \\> `.env.local` \\> `.env`\n *\n * This differs from dotenv-flow / Next.js convention which puts `.env.local` above\n * `.env.${env}`. We chose the most-specific-wins order so committed env-specific files\n * (`.env.production`) are authoritative for that environment regardless of whether a\n * stray `.env.local` is present.\n * @internal\n */\n protected static buildCascadePaths(env: Environment): string[] {\n const envName = Environment[env].toLowerCase();\n return [`.env.${envName}.local`, `.env.${envName}`, '.env.local', '.env']\n .map((name) => this.resolveAgainstBase(name))\n .filter((p) => this.sourceFileExists(p));\n }\n\n private static normalizeProfilePaths(profile: EnvProfile | undefined): string[] {\n if (!profile) return [];\n return Array.isArray(profile.paths) ? profile.paths : [profile.paths];\n }\n\n /**\n * Override the base implementation to layer the dotenv-flow cascade + any\n * `Envapter.configureProfiles` overrides on top of `_envPaths` when the user has NOT\n * explicitly set `envPaths`.\n *\n * Precedence (passed to dotenv with first-wins semantics):\n * 1. profile-configured paths for the current env (if any)\n * 2. `.env.${env}.local`\n * 3. `.env.${env}`\n * 4. `.env.local`\n * 5. `.env`\n *\n * If `useDefaults: false` is set on the profiles config, only (1) is loaded, no cascade.\n * If `envPaths` was explicitly set, only `envPaths` is loaded (everything else ignored).\n * @internal\n */\n protected static override resolveEffectivePaths(): string[] {\n if (this._envPathsExplicitlySet) return this._envPaths.map((p) => this.resolveAgainstBase(p));\n\n const env = this.getCascadeEnvironment();\n const profileEntry = this._profiles?.[env];\n const profilePaths = this.normalizeProfilePaths(profileEntry);\n\n // Validate that explicitly configured profile paths exist for the active env.\n if (profilePaths.length > 0) {\n const missing = profilePaths.filter((p) => !this.sourceFileExists(this.resolveAgainstBase(p)));\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 const cascade = this._profiles?.useDefaults === false ? [] : this.buildCascadePaths(env);\n return [...profilePaths.map((p) => this.resolveAgainstBase(p)), ...cascade];\n }\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{debugWarn as e}from"../infra/Debug.mjs";import{EnvapterBase as t}from"./EnvapterBase.mjs";import{EnvironmentMethods as n}from"./EnvironmentMethods.mjs";import{BuiltInConverters as r}from"../converters/BuiltInConverters.mjs";import{ValueConverter as i}from"../converters/ValueConverter.mjs";import{TemplateResolver as a}from"../engine/TemplateResolver.mjs";var o=class o extends n{static service=new o;static templateResolver=new a(o.service);static valueConverter=new i(o.service);isStrict(){return t.strict}static _get(t,n,i){let{key:a,value:o}=this.resolveKeyInput(t);if(this.treatAsMissing(o))return i
|
|
1
|
+
import{debugWarn as e}from"../infra/Debug.mjs";import{EnvapterBase as t}from"./EnvapterBase.mjs";import{EnvironmentMethods as n}from"./EnvironmentMethods.mjs";import{BuiltInConverters as r}from"../converters/BuiltInConverters.mjs";import{ValueConverter as i}from"../converters/ValueConverter.mjs";import{TemplateResolver as a}from"../engine/TemplateResolver.mjs";var o=class o extends n{static service=new o;static templateResolver=new a(o.service);static valueConverter=new i(o.service);isStrict(){return t.strict}static resolveForMirror(e,t){return this.templateResolver.resolveTemplate(e,t)}static _get(t,n,i){let{key:a,value:o}=this.resolveKeyInput(t);if(this.treatAsMissing(o))return e(i===void 0?`${a} is missing or empty`:`${a} is missing or empty, using fallback ${String(i)}`),i;let s=o,c=this.templateResolver.resolveTemplate(a,String(s)),l;return l=n===1?r.number(c,i):n===2?r.boolean(c,i):n===3?r.bigint(c,i):n===4?r.symbol(c,i):r.string(c,i),l}static get(e,t){return this._get(e,0,t)}get(e,t){return o._get(e,0,t)}static getNumber(e,t){return this._get(e,1,t)}getNumber(e,t){return o._get(e,1,t)}static getBoolean(e,t){return this._get(e,2,t)}getBoolean(e,t){return o._get(e,2,t)}static getBigInt(e,t){return this._get(e,3,t)}getBigInt(e,t){return o._get(e,3,t)}static getSymbol(e,t){return this._get(e,4,t)}getSymbol(e,t){return o._get(e,4,t)}};export{o as PrimitiveMethods};
|
|
2
2
|
//# sourceMappingURL=PrimitiveMethods.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrimitiveMethods.mjs","names":[],"sources":["../../../src/core/PrimitiveMethods.ts"],"sourcesContent":["import { BuiltInConverters, ValueConverter } from '../converters';\nimport { EnvapterBase } from './EnvapterBase';\nimport { EnvironmentMethods } from './EnvironmentMethods';\nimport { TemplateResolver } from '../engine/TemplateResolver';\nimport { debugWarn } from '../infra/Debug';\n\nimport type { ConditionalReturn, EnvKeyInput } from '../types';\nimport type { EnvapterService } from '../types/Env';\n\n/**\n * @internal\n */\nenum Primitive {\n String,\n Number,\n Boolean,\n BigInt,\n Symbol\n}\n\n/**\n * @internal\n */\nexport class PrimitiveMethods extends EnvironmentMethods implements EnvapterService {\n private static readonly service = new PrimitiveMethods();\n protected static readonly templateResolver: TemplateResolver = new TemplateResolver(PrimitiveMethods.service);\n protected static readonly valueConverter: ValueConverter = new ValueConverter(PrimitiveMethods.service);\n\n // Read `EnvapterBase.strict` directly: `PrimitiveMethods._strict` would resolve to the\n // BaseClass default because a `Envapter.strict = true` write lands as an own-property\n // on `Envapter`, which is a descendant of `PrimitiveMethods`, not an ancestor.\n isStrict(): boolean {\n return EnvapterBase.strict;\n }\n\n private static _get<EnvVarReturnType, DefaultType extends EnvVarReturnType | undefined = undefined>(\n key: EnvKeyInput,\n type: Primitive,\n def?: DefaultType\n ): ConditionalReturn<EnvVarReturnType, DefaultType> {\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) {\n if (def !== undefined) debugWarn(`${resolvedKey}
|
|
1
|
+
{"version":3,"file":"PrimitiveMethods.mjs","names":[],"sources":["../../../src/core/PrimitiveMethods.ts"],"sourcesContent":["import { BuiltInConverters, ValueConverter } from '../converters';\nimport { EnvapterBase } from './EnvapterBase';\nimport { EnvironmentMethods } from './EnvironmentMethods';\nimport { TemplateResolver } from '../engine/TemplateResolver';\nimport { debugWarn } from '../infra/Debug';\n\nimport type { ConditionalReturn, EnvKeyInput } from '../types';\nimport type { EnvapterService } from '../types/Env';\n\n/**\n * @internal\n */\nenum Primitive {\n String,\n Number,\n Boolean,\n BigInt,\n Symbol\n}\n\n/**\n * @internal\n */\nexport class PrimitiveMethods extends EnvironmentMethods implements EnvapterService {\n private static readonly service = new PrimitiveMethods();\n protected static readonly templateResolver: TemplateResolver = new TemplateResolver(PrimitiveMethods.service);\n protected static readonly valueConverter: ValueConverter = new ValueConverter(PrimitiveMethods.service);\n\n // Read `EnvapterBase.strict` directly: `PrimitiveMethods._strict` would resolve to the\n // BaseClass default because a `Envapter.strict = true` write lands as an own-property\n // on `Envapter`, which is a descendant of `PrimitiveMethods`, not an ancestor.\n isStrict(): boolean {\n return EnvapterBase.strict;\n }\n\n protected static override resolveForMirror(key: string, value: string): string {\n return this.templateResolver.resolveTemplate(key, value);\n }\n\n private static _get<EnvVarReturnType, DefaultType extends EnvVarReturnType | undefined = undefined>(\n key: EnvKeyInput,\n type: Primitive,\n def?: DefaultType\n ): ConditionalReturn<EnvVarReturnType, DefaultType> {\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) {\n if (def !== undefined) debugWarn(`${resolvedKey} is missing or empty, using fallback ${String(def)}`);\n else debugWarn(`${resolvedKey} is missing or empty`);\n return def as ConditionalReturn<EnvVarReturnType, DefaultType>;\n }\n const rawVal = value as string | number | boolean | undefined;\n\n const parsed = this.templateResolver.resolveTemplate(resolvedKey, String(rawVal));\n\n let result: EnvVarReturnType;\n if (type === Primitive.Number) result = BuiltInConverters.number(parsed, def as number) as EnvVarReturnType;\n else if (type === Primitive.Boolean)\n result = BuiltInConverters.boolean(parsed, def as boolean) as EnvVarReturnType;\n else if (type === Primitive.BigInt)\n result = BuiltInConverters.bigint(parsed, def as bigint) as EnvVarReturnType;\n else if (type === Primitive.Symbol)\n result = BuiltInConverters.symbol(parsed, def as symbol) as EnvVarReturnType;\n else result = BuiltInConverters.string(parsed, def as string) as EnvVarReturnType;\n\n return result;\n }\n\n /**\n * Get a string environment variable with optional fallback.\n * Supports template variable resolution using `${VAR}` syntax.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static get<Default extends string | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<string, Default> {\n return this._get(key, Primitive.String, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.get}\n */\n get<Default extends string | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<string, Default> {\n return PrimitiveMethods._get(key, Primitive.String, def);\n }\n\n /**\n * Get a number environment variable with optional fallback.\n * Automatically converts string values to numbers.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getNumber<Default extends number | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<number, Default> {\n return this._get(key, Primitive.Number, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getNumber}\n */\n getNumber<Default extends number | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<number, Default> {\n return PrimitiveMethods._get(key, Primitive.Number, def);\n }\n\n /**\n * Get a boolean environment variable with optional fallback.\n * Recognizes: `1`, `yes`, `true`, `on` as **true**; `0`, `no`, `false`, `off` as **false** (case-insensitive).\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getBoolean<Default extends boolean | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<boolean, Default> {\n return this._get(key, Primitive.Boolean, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getBoolean}\n */\n getBoolean<Default extends boolean | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<boolean, Default> {\n return PrimitiveMethods._get(key, Primitive.Boolean, def);\n }\n\n /**\n * Get a bigint environment variable with optional fallback.\n * Automatically converts string values to bigint.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getBigInt<Default extends bigint | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<bigint, Default> {\n return this._get(key, Primitive.BigInt, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getBigInt}\n */\n getBigInt<Default extends bigint | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<bigint, Default> {\n return PrimitiveMethods._get(key, Primitive.BigInt, def);\n }\n\n /**\n * Get a symbol environment variable with optional fallback.\n * Creates a symbol from the string value.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getSymbol<Default extends symbol | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<symbol, Default> {\n return this._get(key, Primitive.Symbol, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getSymbol}\n */\n getSymbol<Default extends symbol | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<symbol, Default> {\n return PrimitiveMethods._get(key, Primitive.Symbol, def);\n }\n}\n"],"mappings":"2WAuBA,IAAa,EAAb,MAAa,UAAyB,CAA8C,CAChF,OAAwB,QAAU,IAAI,EACtC,OAA0B,iBAAqC,IAAI,EAAiB,EAAiB,OAAO,EAC5G,OAA0B,eAAiC,IAAI,EAAe,EAAiB,OAAO,EAKtG,UAAoB,CAChB,OAAO,EAAa,MACxB,CAEA,OAA0B,iBAAiB,EAAa,EAAuB,CAC3E,OAAO,KAAK,iBAAiB,gBAAgB,EAAK,CAAK,CAC3D,CAEA,OAAe,KACX,EACA,EACA,EACgD,CAChD,GAAM,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAC5D,GAAI,KAAK,eAAe,CAAK,EAGzB,OADK,EADD,IAAQ,IAAA,GACG,GAAG,EAAY,sBADG,GAAG,EAAY,uCAAuC,OAAO,CAAG,GAC9C,EAC5C,EAEX,IAAM,EAAS,EAET,EAAS,KAAK,iBAAiB,gBAAgB,EAAa,OAAO,CAAM,CAAC,EAE5E,EAUJ,MATA,CAOK,EAPD,IAAA,EAAoC,EAAkB,OAAO,EAAQ,CAAa,EAC7E,IAAA,EACI,EAAkB,QAAQ,EAAQ,CAAc,EACpD,IAAA,EACI,EAAkB,OAAO,EAAQ,CAAa,EAClD,IAAA,EACI,EAAkB,OAAO,EAAQ,CAAa,EAC7C,EAAkB,OAAO,EAAQ,CAAa,EAErD,CACX,CAOA,OAAO,IACH,EACA,EACkC,CAClC,OAAO,KAAK,KAAK,EAAA,EAAuB,CAAG,CAC/C,CAKA,IACI,EACA,EACkC,CAClC,OAAO,EAAiB,KAAK,EAAA,EAAuB,CAAG,CAC3D,CAOA,OAAO,UACH,EACA,EACkC,CAClC,OAAO,KAAK,KAAK,EAAA,EAAuB,CAAG,CAC/C,CAKA,UACI,EACA,EACkC,CAClC,OAAO,EAAiB,KAAK,EAAA,EAAuB,CAAG,CAC3D,CAOA,OAAO,WACH,EACA,EACmC,CACnC,OAAO,KAAK,KAAK,EAAA,EAAwB,CAAG,CAChD,CAKA,WACI,EACA,EACmC,CACnC,OAAO,EAAiB,KAAK,EAAA,EAAwB,CAAG,CAC5D,CAOA,OAAO,UACH,EACA,EACkC,CAClC,OAAO,KAAK,KAAK,EAAA,EAAuB,CAAG,CAC/C,CAKA,UACI,EACA,EACkC,CAClC,OAAO,EAAiB,KAAK,EAAA,EAAuB,CAAG,CAC3D,CAOA,OAAO,UACH,EACA,EACkC,CAClC,OAAO,KAAK,KAAK,EAAA,EAAuB,CAAG,CAC/C,CAKA,UACI,EACA,EACkC,CAClC,OAAO,EAAiB,KAAK,EAAA,EAAuB,CAAG,CAC3D,CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Debug.mjs","names":[],"sources":["../../../src/infra/Debug.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from './Error';\nimport { readRuntimeEnv, writeRuntimeLine } from './runtime';\n\n/**\n * Debug log levels for {@link Envapter.debug}. `silent` (default) emits nothing.\n * `warn` covers signals that might indicate misconfiguration
|
|
1
|
+
{"version":3,"file":"Debug.mjs","names":[],"sources":["../../../src/infra/Debug.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from './Error';\nimport { readRuntimeEnv, writeRuntimeLine } from './runtime';\n\n/**\n * Debug log levels for {@link Envapter.debug}. `silent` (default) emits nothing.\n * `warn` covers signals that might indicate misconfiguration, failed file reads,\n * unresolved templates (when not strict), and any read of a missing or empty variable\n * (whether it returns a fallback or `undefined`). `verbose` adds every loaded file,\n * per-file key count, per-key load lines, and effective-paths / cache-rebuild notices.\n * @public\n */\nexport type DebugLevel = 'silent' | 'warn' | 'verbose';\n\nconst VALID_LEVELS: ReadonlySet<string> = new Set<DebugLevel>(['silent', 'warn', 'verbose']);\n\nlet currentLevel: DebugLevel = 'silent';\nlet initialized = false;\n\nfunction isDebugLevel(value: string | undefined): value is DebugLevel {\n return value !== undefined && VALID_LEVELS.has(value);\n}\n\n// Reads `ENVAPT_DEBUG` lazily on first access. Setter wins after that.\nfunction resolveLevel(): DebugLevel {\n if (!initialized) {\n const fromEnv = readRuntimeEnv().ENVAPT_DEBUG;\n currentLevel = isDebugLevel(fromEnv) ? fromEnv : 'silent';\n initialized = true;\n }\n return currentLevel;\n}\n\n/** @internal */\nexport function setDebugLevel(level: DebugLevel): void {\n if (!isDebugLevel(level)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid debug level \"${String(level)}\". Expected 'silent' | 'warn' | 'verbose'.`\n );\n }\n currentLevel = level;\n initialized = true;\n}\n\n/** @internal */\nexport function getDebugLevel(): DebugLevel {\n return resolveLevel();\n}\n\n/** @internal */\nexport function resetDebugForTesting(): void {\n currentLevel = 'silent';\n initialized = false;\n}\n\n/** @internal */\nexport function debugWarn(message: string): void {\n const level = resolveLevel();\n if (level === 'warn' || level === 'verbose') {\n writeRuntimeLine(`[envapt] ${message}`);\n }\n}\n\n/** @internal */\nexport function debugVerbose(message: string): void {\n if (resolveLevel() === 'verbose') {\n writeRuntimeLine(`[envapt] ${message}`);\n }\n}\n"],"mappings":"+GAaA,MAAM,EAAoC,IAAI,IAAgB,CAAC,SAAU,OAAQ,SAAS,CAAC,EAE3F,IAAI,EAA2B,SAC3B,EAAc,GAElB,SAAS,EAAa,EAAgD,CAClE,OAAO,IAAU,IAAA,IAAa,EAAa,IAAI,CAAK,CACxD,CAGA,SAAS,GAA2B,CAChC,GAAI,CAAC,EAAa,CACd,IAAM,EAAU,EAAe,CAAC,CAAC,aACjC,EAAe,EAAa,CAAO,EAAI,EAAU,SACjD,EAAc,EAClB,CACA,OAAO,CACX,CAGA,SAAgB,EAAc,EAAyB,CACnD,GAAI,CAAC,EAAa,CAAK,EACnB,MAAM,IAAI,EAAA,IAEN,wBAAwB,OAAO,CAAK,EAAE,2CAC1C,EAEJ,EAAe,EACf,EAAc,EAClB,CAGA,SAAgB,GAA4B,CACxC,OAAO,EAAa,CACxB,CASA,SAAgB,EAAU,EAAuB,CAC7C,IAAM,EAAQ,EAAa,GACvB,IAAU,QAAU,IAAU,YAC9B,EAAiB,YAAY,GAAS,CAE9C,CAGA,SAAgB,EAAa,EAAuB,CAC5C,EAAa,IAAM,WACnB,EAAiB,YAAY,GAAS,CAE9C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Error.mjs","names":[],"sources":["../../../src/infra/Error.ts"],"sourcesContent":["/* eslint-disable no-magic-numbers */\nimport type { StandardSchemaV1 } from './StandardSchema';\n\nexport enum EnvaptErrorCodes {\n // Fallback related errors\n /** Thrown when an invalid fallback value is provided */\n InvalidFallback = 101,\n /** Thrown when fallback value type doesn't match expected converter type */\n InvalidFallbackType = 102,\n /** Thrown when array fallback contains elements of wrong type */\n ArrayFallbackElementTypeMismatch = 103,\n /** Thrown when fallback type doesn't match the specified converter */\n FallbackConverterTypeMismatch = 104,\n /** Thrown when a time-string fallback is malformed (does not match the required `<number><unit>` format) */\n MalformedTimeFallback = 105,\n\n // Converter related errors\n /** Thrown when invalid array converter configuration is provided */\n InvalidArrayConverterType = 201,\n /** Thrown when an invalid built-in converter is specified */\n InvalidBuiltInConverter = 202,\n /** Thrown when a custom converter is not a function */\n InvalidCustomConverter = 203,\n /** Thrown when converter type is not recognized */\n InvalidConverterType = 204,\n /** Thrown when primitive type coercion on fallback value fails */\n PrimitiveCoercionFailed = 205,\n /** Thrown when an array element fails to convert to the configured element type */\n ArrayElementConversionFailed = 206,\n /** Thrown under strict mode when an array element is empty or whitespace only */\n EmptyArrayElement = 207,\n /** Thrown when a Standard Schema returns issues for a non-empty env value */\n SchemaValidationFailed = 208,\n /** Thrown when a Standard Schema's `validate` itself throws (e.g. a refinement that crashes) */\n SchemaThrew = 209,\n\n // Other errors\n /** Thrown when delimiter is missing in array converter configuration */\n // This doesn't happen because 203 is thrown when object without delimiter is passed\n MissingDelimiter = 301,\n /** Thrown when invalid user-defined configuration is provided */\n InvalidUserDefinedConfig = 302,\n /** Thrown when specified environment files don't exist */\n EnvFilesNotFound = 303,\n /** Thrown when no valid environment key is provided */\n InvalidKeyInput = 304,\n /** Thrown when a required environment value is missing or empty (post-trim) */\n MissingEnvValue = 305,\n /** Thrown when a file-based API (envPaths, baseDir, configureProfiles) is used on a source without filesystem support */\n FileApiUnsupported = 306,\n /** Thrown when an environment value is read before a source is bound via Envapter.useSource */\n NoSourceBound = 307\n}\n\ninterface EnvaptErrorOptions {\n issues?: readonly StandardSchemaV1.Issue[];\n cause?: unknown;\n}\n\n/**\n * Custom error for better DX and debugging when using Envapt.\n *\n * @example\n * ```ts\n * throw new EnvaptError(EnvaptErrorCodes.InvalidFallback, \"Invalid fallback value provided for environment variable.\");\n * ```\n */\nexport class EnvaptError extends Error {\n public readonly code: EnvaptErrorCodes;\n /**\n * Populated only for {@link EnvaptErrorCodes.SchemaValidationFailed} (208). For every other\n * code this is `undefined`. Lets callers do `if (err.code === 208) err.issues?.forEach(...)`\n * without a type cast.\n */\n public readonly issues: readonly StandardSchemaV1.Issue[] | undefined;\n\n constructor(code: EnvaptErrorCodes, message: string, options?: EnvaptErrorOptions) {\n super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = `EnvaptError [${code}]`;\n this.code = code;\n this.issues = options?.issues;\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"Error.mjs","names":[],"sources":["../../../src/infra/Error.ts"],"sourcesContent":["/* eslint-disable no-magic-numbers */\nimport type { StandardSchemaV1 } from './StandardSchema';\n\n/**\n * Numeric codes carried by {@link EnvaptError.code}, grouped by fallback (1xx), converter (2xx),\n * and configuration (3xx) failures.\n */\nexport enum EnvaptErrorCodes {\n // Fallback related errors\n /** Thrown when an invalid fallback value is provided */\n InvalidFallback = 101,\n /** Thrown when fallback value type doesn't match expected converter type */\n InvalidFallbackType = 102,\n /** Thrown when array fallback contains elements of wrong type */\n ArrayFallbackElementTypeMismatch = 103,\n /** Thrown when fallback type doesn't match the specified converter */\n FallbackConverterTypeMismatch = 104,\n /** Thrown when a time-string fallback is malformed (does not match the required `<number><unit>` format) */\n MalformedTimeFallback = 105,\n\n // Converter related errors\n /** Thrown when invalid array converter configuration is provided */\n InvalidArrayConverterType = 201,\n /** Thrown when an invalid built-in converter is specified */\n InvalidBuiltInConverter = 202,\n /** Thrown when a custom converter is not a function */\n InvalidCustomConverter = 203,\n /** Thrown when converter type is not recognized */\n InvalidConverterType = 204,\n /** Thrown when primitive type coercion on fallback value fails */\n PrimitiveCoercionFailed = 205,\n /** Thrown when an array element fails to convert to the configured element type */\n ArrayElementConversionFailed = 206,\n /** Thrown under strict mode when an array element is empty or whitespace only */\n EmptyArrayElement = 207,\n /** Thrown when a Standard Schema returns issues for a non-empty env value */\n SchemaValidationFailed = 208,\n /** Thrown when a Standard Schema's `validate` itself throws (e.g. a refinement that crashes) */\n SchemaThrew = 209,\n\n // Other errors\n /** Thrown when delimiter is missing in array converter configuration */\n // This doesn't happen because 203 is thrown when object without delimiter is passed\n MissingDelimiter = 301,\n /** Thrown when invalid user-defined configuration is provided */\n InvalidUserDefinedConfig = 302,\n /** Thrown when specified environment files don't exist */\n EnvFilesNotFound = 303,\n /** Thrown when no valid environment key is provided */\n InvalidKeyInput = 304,\n /** Thrown when a required environment value is missing or empty (post-trim) */\n MissingEnvValue = 305,\n /** Thrown when a file-based API (envPaths, baseDir, configureProfiles) is used on a source without filesystem support */\n FileApiUnsupported = 306,\n /** Thrown when an environment value is read before a source is bound via Envapter.useSource */\n NoSourceBound = 307\n}\n\ninterface EnvaptErrorOptions {\n issues?: readonly StandardSchemaV1.Issue[];\n cause?: unknown;\n}\n\n/**\n * Custom error for better DX and debugging when using Envapt.\n *\n * @example\n * ```ts\n * throw new EnvaptError(EnvaptErrorCodes.InvalidFallback, \"Invalid fallback value provided for environment variable.\");\n * ```\n */\nexport class EnvaptError extends Error {\n /** The {@link EnvaptErrorCodes} value identifying what failed. */\n public readonly code: EnvaptErrorCodes;\n /**\n * Populated only for {@link EnvaptErrorCodes.SchemaValidationFailed} (208). For every other\n * code this is `undefined`. Lets callers do `if (err.code === 208) err.issues?.forEach(...)`\n * without a type cast.\n */\n public readonly issues: readonly StandardSchemaV1.Issue[] | undefined;\n\n /** Create an error carrying an {@link EnvaptErrorCodes} code, a message, and optional `cause` / `issues`. */\n constructor(code: EnvaptErrorCodes, message: string, options?: EnvaptErrorOptions) {\n super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = `EnvaptError [${code}]`;\n this.code = code;\n this.issues = options?.issues;\n }\n}\n"],"mappings":"AAOA,IAAY,EAAL,SAAA,EAAA,OAGH,GAAA,EAAA,gBAAA,KAAA,kBAEA,EAAA,EAAA,oBAAA,KAAA,sBAEA,EAAA,EAAA,iCAAA,KAAA,mCAEA,EAAA,EAAA,8BAAA,KAAA,gCAEA,EAAA,EAAA,sBAAA,KAAA,wBAIA,EAAA,EAAA,0BAAA,KAAA,4BAEA,EAAA,EAAA,wBAAA,KAAA,0BAEA,EAAA,EAAA,uBAAA,KAAA,yBAEA,EAAA,EAAA,qBAAA,KAAA,uBAEA,EAAA,EAAA,wBAAA,KAAA,0BAEA,EAAA,EAAA,6BAAA,KAAA,+BAEA,EAAA,EAAA,kBAAA,KAAA,oBAEA,EAAA,EAAA,uBAAA,KAAA,yBAEA,EAAA,EAAA,YAAA,KAAA,cAKA,EAAA,EAAA,iBAAA,KAAA,mBAEA,EAAA,EAAA,yBAAA,KAAA,2BAEA,EAAA,EAAA,iBAAA,KAAA,mBAEA,EAAA,EAAA,gBAAA,KAAA,kBAEA,EAAA,EAAA,gBAAA,KAAA,kBAEA,EAAA,EAAA,mBAAA,KAAA,qBAEA,EAAA,EAAA,cAAA,KAAA,iBACJ,EAAA,CAAA,CAAA,EAeA,IAAa,EAAb,cAAiC,KAAM,CAEnC,KAMA,OAGA,YAAY,EAAwB,EAAiB,EAA8B,CAC/E,MAAM,EAAS,GAAS,QAAU,IAAA,GAAuC,IAAA,GAA3B,CAAE,MAAO,EAAQ,KAAM,CAAa,EAClF,KAAK,KAAO,gBAAgB,EAAK,GACjC,KAAK,KAAO,EACZ,KAAK,OAAS,GAAS,MAC3B,CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ManualEnvSource.mjs","names":[],"sources":["../../../src/sources/ManualEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source seeded from an object you provide: the config your bundler injects into a browser\n * build (Vite's `import.meta.env`, a webpack `DefinePlugin` global), a test fixture, or any other plain\n * object. Pass it straight through; non-string values are JSON-stringified so the converters still apply.\n * It has no filesystem, so the `.env` cascade and file-based APIs do not apply.\n * @public\n */\nexport class ManualEnvSource implements BareEnvSource {\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n constructor(vars: Record<string, unknown>) {\n this.vars = coerceToStringRecord(vars);\n }\n\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,
|
|
1
|
+
{"version":3,"file":"ManualEnvSource.mjs","names":[],"sources":["../../../src/sources/ManualEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source seeded from an object you provide: the config your bundler injects into a browser\n * build (Vite's `import.meta.env`, a webpack `DefinePlugin` global), a test fixture, or any other plain\n * object. Pass it straight through; non-string values are JSON-stringified so the converters still apply.\n * It has no filesystem, so the `.env` cascade and file-based APIs do not apply.\n * @public\n */\nexport class ManualEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from `vars`. Non-string values are JSON-stringified so the converters still apply. */\n constructor(vars: Record<string, unknown>) {\n this.vars = coerceToStringRecord(vars);\n }\n\n /** Returns a snapshot clone of the provided object as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA+B,CACvC,KAAK,KAAO,EAAqB,CAAI,CACzC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerEnvSource.mjs","names":[],"sources":["../../../src/sources/WorkerEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source for Cloudflare Workers, seeded from the `env` binding. String bindings pass\n * through; non-string bindings are JSON-stringified so the converters still apply, and so must be\n * JSON-serializable (a `bigint` or circular value throws). No filesystem, so the `.env` cascade and\n * file-based APIs do not apply.\n * @public\n */\nexport class WorkerEnvSource implements BareEnvSource {\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n constructor(env: Record<string, unknown>) {\n this.vars = coerceToStringRecord(env);\n }\n\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,
|
|
1
|
+
{"version":3,"file":"WorkerEnvSource.mjs","names":[],"sources":["../../../src/sources/WorkerEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source for Cloudflare Workers, seeded from the `env` binding. String bindings pass\n * through; non-string bindings are JSON-stringified so the converters still apply, and so must be\n * JSON-serializable (a `bigint` or circular value throws). No filesystem, so the `.env` cascade and\n * file-based APIs do not apply.\n * @public\n */\nexport class WorkerEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from the Workers `env` binding. Non-string values are JSON-stringified, so they must be JSON-serializable. */\n constructor(env: Record<string, unknown>) {\n this.vars = coerceToStringRecord(env);\n }\n\n /** Returns a snapshot clone of the `env` binding as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA8B,CACtC,KAAK,KAAO,EAAqB,CAAG,CACxC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
package/dist/node/config.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.cjs","names":["Envapter"],"sources":["../../src/config.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"config.cjs","names":["Envapter"],"sources":["../../src/config.ts"],"sourcesContent":["/**\n * Side-effect entry (`import 'envapt/config'`, `node --import envapt/config`, `-r envapt/config` for\n * CJS). A drop-in for `dotenv/config` that loads the `.env` cascade and mirrors it into `process.env`.\n *\n * Set `ENVAPT_DEBUG=verbose` before the import to log the load. Setting `Envapter.debug` in code after\n * the import is too late, the load has already run.\n *\n * @module\n */\n\nimport { Envapter } from '.';\n\n// Importing Envapter evaluates NodeEnvapter, whose static block binds the default source before load() runs.\nEnvapter.syncProcessEnv = true;\nEnvapter.load();\n"],"mappings":"gGAaA,EAAA,aAAS,eAAiB,GAC1BA,EAAAA,aAAS,KAAK"}
|
package/dist/node/config.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.mjs","names":["Envapter"],"sources":["../../src/config.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"config.mjs","names":["Envapter"],"sources":["../../src/config.ts"],"sourcesContent":["/**\n * Side-effect entry (`import 'envapt/config'`, `node --import envapt/config`, `-r envapt/config` for\n * CJS). A drop-in for `dotenv/config` that loads the `.env` cascade and mirrors it into `process.env`.\n *\n * Set `ENVAPT_DEBUG=verbose` before the import to log the load. Setting `Envapter.debug` in code after\n * the import is too late, the load has already run.\n *\n * @module\n */\n\nimport { Envapter } from '.';\n\n// Importing Envapter evaluates NodeEnvapter, whose static block binds the default source before load() runs.\nEnvapter.syncProcessEnv = true;\nEnvapter.load();\n"],"mappings":"4GAaA,EAAS,eAAiB,GAC1BA,EAAS,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Converters.cjs","names":[],"sources":["../../../src/converters/Converters.ts"],"sourcesContent":["const SCALAR = {\n String: 'string',\n Number: 'number',\n Boolean: 'boolean',\n Bigint: 'bigint',\n Symbol: 'symbol',\n Integer: 'integer',\n Float: 'float',\n Json: 'json',\n Url: 'url',\n Regexp: 'regexp',\n Date: 'date',\n Time: 'time'\n} as const;\n\n/**\n * String tokens for every built-in scalar converter.\n * @public\n */\nexport type ConverterToken = (typeof SCALAR)[keyof typeof SCALAR];\n\n/**\n * Custom element converter for use inside {@link Converters.array}. Receives the trimmed,\n * non-empty raw string for one array slot and returns the parsed value.\n * @public\n */\nexport type CustomElementConverter<TReturn = unknown> = (raw: string) => TReturn;\n\n/**\n * Valid element converters for {@link Converters.array}: any scalar token except\n * `json` and `regexp` (those don't compose as array elements), or a custom function.\n * @public\n */\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n/**\n * Phantom-branded token produced by {@link Converters.array}. The `T` type parameter carries\n * the element converter through any variable indirection so inference survives. The\n * `__envaptKind` discriminant is present at runtime for dispatch.\n * @public\n */\nexport interface ArrayOf<TElement extends ArrayElement = ArrayElement> {\n readonly __envaptKind: 'array';\n readonly of: TElement;\n readonly delimiter: string;\n}\n\n/**\n * Runtime type guard for tokens produced by {@link Converters.array}.\n * @internal\n */\nexport function isArrayOf(value: unknown): value is ArrayOf {\n return typeof value === 'object' && value !== null && '__envaptKind' in value && value.__envaptKind === 'array';\n}\n\ntype ArrayScalarElement = Exclude<ConverterToken, 'json' | 'regexp'>;\n\n// Overloads. The function-element overload must come first so it wins inference when `of`\n// is a function, otherwise TS picks the scalar branch and `raw` defaults to `any`.\nfunction buildArrayConverter<TReturn>(opts: {\n of: CustomElementConverter<TReturn>;\n delimiter?: string;\n}): ArrayOf<CustomElementConverter<TReturn>>;\nfunction buildArrayConverter<TToken extends ArrayScalarElement>(opts: {\n of: TToken;\n delimiter?: string;\n}): ArrayOf<TToken>;\nfunction buildArrayConverter(opts?: { delimiter?: string }): ArrayOf<'string'>;\nfunction buildArrayConverter(opts?: { of?: ArrayElement; delimiter?: string }): ArrayOf<ArrayElement> {\n return {\n __envaptKind: 'array',\n of: opts?.of ?? SCALAR.String,\n delimiter: opts?.delimiter ?? ','\n };\n}\n\n/**\n * Built-in converters for environment variables. Use the scalar tokens (e.g. `Converters.Number`)\n * for primitive types and the {@link Converters.array} builder for delimited lists.\n *\n * @example\n * ```ts\n * \\@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * \\@Envapt('TAGS', { converter: Converters.array({ of: Converters.String, delimiter: ' ' }) })\n * static readonly tags: string[];\n * ```\n *\n * @public\n */\nexport const Converters = {\n ...SCALAR,\n array: buildArrayConverter\n} as const;\n"],"mappings":"yDAAM,EAAS,CACX,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,KAAM,OACN,KAAM,MACV,
|
|
1
|
+
{"version":3,"file":"Converters.cjs","names":[],"sources":["../../../src/converters/Converters.ts"],"sourcesContent":["const SCALAR = {\n String: 'string',\n Number: 'number',\n Boolean: 'boolean',\n Bigint: 'bigint',\n Symbol: 'symbol',\n Integer: 'integer',\n Float: 'float',\n Json: 'json',\n Url: 'url',\n Regexp: 'regexp',\n Date: 'date',\n Time: 'time'\n} as const;\n\n/**\n * String tokens for every built-in scalar converter.\n * @public\n */\nexport type ConverterToken = (typeof SCALAR)[keyof typeof SCALAR];\n\n/**\n * Custom element converter for use inside {@link Converters.array}. Receives the trimmed,\n * non-empty raw string for one array slot and returns the parsed value.\n * @public\n */\nexport type CustomElementConverter<TReturn = unknown> = (raw: string) => TReturn;\n\n/**\n * Valid element converters for {@link Converters.array}: any scalar token except\n * `json` and `regexp` (those don't compose as array elements), or a custom function.\n * @public\n */\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n/**\n * Phantom-branded token produced by {@link Converters.array}. The `T` type parameter carries\n * the element converter through any variable indirection so inference survives. The\n * `__envaptKind` discriminant is present at runtime for dispatch.\n * @public\n */\nexport interface ArrayOf<TElement extends ArrayElement = ArrayElement> {\n /** Runtime discriminant marking this token as an array converter. Don't use directly. */\n readonly __envaptKind: 'array';\n /** The element converter applied to each split slot. */\n readonly of: TElement;\n /** The string the raw value is split on. */\n readonly delimiter: string;\n}\n\n/**\n * Runtime type guard for tokens produced by {@link Converters.array}.\n * @internal\n */\nexport function isArrayOf(value: unknown): value is ArrayOf {\n return typeof value === 'object' && value !== null && '__envaptKind' in value && value.__envaptKind === 'array';\n}\n\ntype ArrayScalarElement = Exclude<ConverterToken, 'json' | 'regexp'>;\n\n// Overloads. The function-element overload must come first so it wins inference when `of`\n// is a function, otherwise TS picks the scalar branch and `raw` defaults to `any`.\nfunction buildArrayConverter<TReturn>(opts: {\n of: CustomElementConverter<TReturn>;\n delimiter?: string;\n}): ArrayOf<CustomElementConverter<TReturn>>;\nfunction buildArrayConverter<TToken extends ArrayScalarElement>(opts: {\n of: TToken;\n delimiter?: string;\n}): ArrayOf<TToken>;\nfunction buildArrayConverter(opts?: { delimiter?: string }): ArrayOf<'string'>;\nfunction buildArrayConverter(opts?: { of?: ArrayElement; delimiter?: string }): ArrayOf<ArrayElement> {\n return {\n __envaptKind: 'array',\n of: opts?.of ?? SCALAR.String,\n delimiter: opts?.delimiter ?? ','\n };\n}\n\n/**\n * Built-in converters for environment variables. Use the scalar tokens (e.g. `Converters.Number`)\n * for primitive types and the {@link Converters.array} builder for delimited lists.\n *\n * @example\n * ```ts\n * \\@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * \\@Envapt('TAGS', { converter: Converters.array({ of: Converters.String, delimiter: ' ' }) })\n * static readonly tags: string[];\n * ```\n *\n * @public\n */\nexport const Converters = {\n ...SCALAR,\n array: buildArrayConverter\n} as const;\n"],"mappings":"yDAAM,EAAS,CACX,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,KAAM,OACN,KAAM,MACV,EAyCA,SAAgB,EAAU,EAAkC,CACxD,OAAO,OAAO,GAAU,YAAY,GAAkB,iBAAkB,GAAS,EAAM,eAAiB,OAC5G,CAeA,SAAS,EAAoB,EAAyE,CAClG,MAAO,CACH,aAAc,QACd,GAAI,GAAM,IAAM,EAAO,OACvB,UAAW,GAAM,WAAa,GAClC,CACJ,CAiBA,MAAa,EAAa,CACtB,GAAG,EACH,MAAO,CACX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Converters.mjs","names":[],"sources":["../../../src/converters/Converters.ts"],"sourcesContent":["const SCALAR = {\n String: 'string',\n Number: 'number',\n Boolean: 'boolean',\n Bigint: 'bigint',\n Symbol: 'symbol',\n Integer: 'integer',\n Float: 'float',\n Json: 'json',\n Url: 'url',\n Regexp: 'regexp',\n Date: 'date',\n Time: 'time'\n} as const;\n\n/**\n * String tokens for every built-in scalar converter.\n * @public\n */\nexport type ConverterToken = (typeof SCALAR)[keyof typeof SCALAR];\n\n/**\n * Custom element converter for use inside {@link Converters.array}. Receives the trimmed,\n * non-empty raw string for one array slot and returns the parsed value.\n * @public\n */\nexport type CustomElementConverter<TReturn = unknown> = (raw: string) => TReturn;\n\n/**\n * Valid element converters for {@link Converters.array}: any scalar token except\n * `json` and `regexp` (those don't compose as array elements), or a custom function.\n * @public\n */\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n/**\n * Phantom-branded token produced by {@link Converters.array}. The `T` type parameter carries\n * the element converter through any variable indirection so inference survives. The\n * `__envaptKind` discriminant is present at runtime for dispatch.\n * @public\n */\nexport interface ArrayOf<TElement extends ArrayElement = ArrayElement> {\n readonly __envaptKind: 'array';\n readonly of: TElement;\n readonly delimiter: string;\n}\n\n/**\n * Runtime type guard for tokens produced by {@link Converters.array}.\n * @internal\n */\nexport function isArrayOf(value: unknown): value is ArrayOf {\n return typeof value === 'object' && value !== null && '__envaptKind' in value && value.__envaptKind === 'array';\n}\n\ntype ArrayScalarElement = Exclude<ConverterToken, 'json' | 'regexp'>;\n\n// Overloads. The function-element overload must come first so it wins inference when `of`\n// is a function, otherwise TS picks the scalar branch and `raw` defaults to `any`.\nfunction buildArrayConverter<TReturn>(opts: {\n of: CustomElementConverter<TReturn>;\n delimiter?: string;\n}): ArrayOf<CustomElementConverter<TReturn>>;\nfunction buildArrayConverter<TToken extends ArrayScalarElement>(opts: {\n of: TToken;\n delimiter?: string;\n}): ArrayOf<TToken>;\nfunction buildArrayConverter(opts?: { delimiter?: string }): ArrayOf<'string'>;\nfunction buildArrayConverter(opts?: { of?: ArrayElement; delimiter?: string }): ArrayOf<ArrayElement> {\n return {\n __envaptKind: 'array',\n of: opts?.of ?? SCALAR.String,\n delimiter: opts?.delimiter ?? ','\n };\n}\n\n/**\n * Built-in converters for environment variables. Use the scalar tokens (e.g. `Converters.Number`)\n * for primitive types and the {@link Converters.array} builder for delimited lists.\n *\n * @example\n * ```ts\n * \\@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * \\@Envapt('TAGS', { converter: Converters.array({ of: Converters.String, delimiter: ' ' }) })\n * static readonly tags: string[];\n * ```\n *\n * @public\n */\nexport const Converters = {\n ...SCALAR,\n array: buildArrayConverter\n} as const;\n"],"mappings":"yDAAM,EAAS,CACX,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,KAAM,OACN,KAAM,MACV,
|
|
1
|
+
{"version":3,"file":"Converters.mjs","names":[],"sources":["../../../src/converters/Converters.ts"],"sourcesContent":["const SCALAR = {\n String: 'string',\n Number: 'number',\n Boolean: 'boolean',\n Bigint: 'bigint',\n Symbol: 'symbol',\n Integer: 'integer',\n Float: 'float',\n Json: 'json',\n Url: 'url',\n Regexp: 'regexp',\n Date: 'date',\n Time: 'time'\n} as const;\n\n/**\n * String tokens for every built-in scalar converter.\n * @public\n */\nexport type ConverterToken = (typeof SCALAR)[keyof typeof SCALAR];\n\n/**\n * Custom element converter for use inside {@link Converters.array}. Receives the trimmed,\n * non-empty raw string for one array slot and returns the parsed value.\n * @public\n */\nexport type CustomElementConverter<TReturn = unknown> = (raw: string) => TReturn;\n\n/**\n * Valid element converters for {@link Converters.array}: any scalar token except\n * `json` and `regexp` (those don't compose as array elements), or a custom function.\n * @public\n */\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n/**\n * Phantom-branded token produced by {@link Converters.array}. The `T` type parameter carries\n * the element converter through any variable indirection so inference survives. The\n * `__envaptKind` discriminant is present at runtime for dispatch.\n * @public\n */\nexport interface ArrayOf<TElement extends ArrayElement = ArrayElement> {\n /** Runtime discriminant marking this token as an array converter. Don't use directly. */\n readonly __envaptKind: 'array';\n /** The element converter applied to each split slot. */\n readonly of: TElement;\n /** The string the raw value is split on. */\n readonly delimiter: string;\n}\n\n/**\n * Runtime type guard for tokens produced by {@link Converters.array}.\n * @internal\n */\nexport function isArrayOf(value: unknown): value is ArrayOf {\n return typeof value === 'object' && value !== null && '__envaptKind' in value && value.__envaptKind === 'array';\n}\n\ntype ArrayScalarElement = Exclude<ConverterToken, 'json' | 'regexp'>;\n\n// Overloads. The function-element overload must come first so it wins inference when `of`\n// is a function, otherwise TS picks the scalar branch and `raw` defaults to `any`.\nfunction buildArrayConverter<TReturn>(opts: {\n of: CustomElementConverter<TReturn>;\n delimiter?: string;\n}): ArrayOf<CustomElementConverter<TReturn>>;\nfunction buildArrayConverter<TToken extends ArrayScalarElement>(opts: {\n of: TToken;\n delimiter?: string;\n}): ArrayOf<TToken>;\nfunction buildArrayConverter(opts?: { delimiter?: string }): ArrayOf<'string'>;\nfunction buildArrayConverter(opts?: { of?: ArrayElement; delimiter?: string }): ArrayOf<ArrayElement> {\n return {\n __envaptKind: 'array',\n of: opts?.of ?? SCALAR.String,\n delimiter: opts?.delimiter ?? ','\n };\n}\n\n/**\n * Built-in converters for environment variables. Use the scalar tokens (e.g. `Converters.Number`)\n * for primitive types and the {@link Converters.array} builder for delimited lists.\n *\n * @example\n * ```ts\n * \\@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * \\@Envapt('TAGS', { converter: Converters.array({ of: Converters.String, delimiter: ' ' }) })\n * static readonly tags: string[];\n * ```\n *\n * @public\n */\nexport const Converters = {\n ...SCALAR,\n array: buildArrayConverter\n} as const;\n"],"mappings":"yDAAM,EAAS,CACX,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,KAAM,OACN,KAAM,MACV,EAyCA,SAAgB,EAAU,EAAkC,CACxD,OAAO,OAAO,GAAU,YAAY,GAAkB,iBAAkB,GAAS,EAAM,eAAiB,OAC5G,CAeA,SAAS,EAAoB,EAAyE,CAClG,MAAO,CACH,aAAc,QACd,GAAI,GAAM,IAAM,EAAO,OACvB,UAAW,GAAM,WAAa,GAClC,CACJ,CAiBA,MAAa,EAAa,CACtB,GAAG,EACH,MAAO,CACX"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"node:path";import"node:url";import.meta.url;const e=require("../infra/Error.cjs"),t=require("./PrimitiveMethods.cjs");function
|
|
1
|
+
import"node:path";import"node:url";import.meta.url;const e=require("../infra/Error.cjs"),t=require("../infra/Debug.cjs"),n=require("./PrimitiveMethods.cjs");function r(e){return typeof e==`object`&&!!e&&`converter`in e}function i(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}var a=class a extends n.PrimitiveMethods{static getUsing(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e.EnvaptError(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let s=a,{key:c,value:l}=this.resolveKeyInput(n);if(this.treatAsMissing(l)&&o===void 0){t.debugWarn(`${c} is missing or empty`);return}let u=o!==void 0;return this.valueConverter.convertValue(c,o,s,u)}getUsing(e,t,n){return a.getUsing(e,t,n)}static getWith(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e.EnvaptError(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let{key:s,value:c}=this.resolveKeyInput(n);if(this.treatAsMissing(c))return t.debugWarn(`${s} is missing or empty`),o;let l=o!==void 0;return this.valueConverter.convertValue(s,o,a,l)}getWith(e,t,n){return a.getWith(e,t,n)}static parse(e,t,n){let r=arguments.length>2;return this.valueConverter.convertWithSchema(e,t,n,r)}parse(e,t,n){let r=arguments.length>2;return a.valueConverter.convertWithSchema(e,t,n,r)}};exports.AdvancedMethods=a;
|
|
2
2
|
//# sourceMappingURL=AdvancedMethods.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AdvancedMethods.cjs","names":["PrimitiveMethods","EnvaptError"],"sources":["../../../src/core/AdvancedMethods.ts"],"sourcesContent":["import { PrimitiveMethods } from './PrimitiveMethods';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../infra/StandardSchema';\nimport type {\n AdvancedConverterReturn,\n BuiltInConverter,\n ConditionalReturn,\n ConverterFunction,\n EnvKeyInput,\n InferConverterReturnType,\n SchemaConstraint,\n TimeFallback\n} from '../types';\n\ninterface GetUsingRequiredOptions<TConverter> {\n converter: TConverter;\n required: true;\n}\n\ninterface GetWithRequiredOptions<TReturnType> {\n converter: ConverterFunction<TReturnType>;\n required: true;\n}\n\nfunction isOptionsBag(value: unknown): value is { converter: unknown; required?: boolean; fallback?: unknown } {\n // `ArrayOf` tokens have `of`/`delimiter` but no `converter` key, so the presence of\n // `converter` discriminates the options-bag form from a positional converter token.\n return typeof value === 'object' && value !== null && 'converter' in value;\n}\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Mixin for advanced methods for environment variable conversion using built-in and custom converters\n * @internal\n */\nexport class AdvancedMethods extends PrimitiveMethods {\n /**\n * Get an environment variable using a built-in converter.\n *\n * Supports both scalar tokens (e.g. `Converters.Number`) and `ArrayOf<...>` tokens\n * produced by `Converters.array(...)`. The key can be a single name or an ordered list;\n * the first defined value wins.\n */\n // Time-specific overload must precede the generic BuiltInConverter overload so it wins\n // overload resolution (TimeFallback accepts time-strings like `'10s'`).\n static getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n static getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n static getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as TConverter,\n false\n );\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const converter = converterOrOptions as TConverter;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n // No env value AND no fallback: return undefined to match primitive-method semantics.\n // Otherwise route through the parser so asymmetric fallback types (TimeFallback,\n // TimeFallback[] for `of: time` arrays) get coerced to the declared return type.\n if (this.treatAsMissing(value) && fallback === undefined) {\n return undefined as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n const result = this.valueConverter.convertValue(resolvedKey, fallback, converter, hasFallback);\n\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getUsing}\n */\n getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n return AdvancedMethods.getUsing(key, converterOrOptions as TConverter, fallback);\n }\n\n /**\n * Get an environment variable using a custom converter function.\n * Accepts a single key or an ordered list for automatic fallback.\n */\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n static getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as ConverterFunction<undefined>,\n false\n );\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n // Check if variable exists first, for consistency with primitive methods\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) return fallback as ConditionalReturn<TReturnType, TFallback>;\n\n const hasFallback = fallback !== undefined;\n // Convert the converter to match the expected signature via unknown\n const result = this.valueConverter.convertValue(\n resolvedKey,\n fallback,\n converterOrOptions as unknown as ConverterFunction<TFallback>,\n hasFallback\n );\n\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getWith}\n */\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n return AdvancedMethods.getWith(key, converterOrOptions as ConverterFunction<TReturnType>, fallback);\n }\n\n /**\n * Validate an environment variable through a {@link StandardSchemaV1}-conformant schema\n * (zod, valibot, arktype, etc). Throws `MissingEnvValue` if the env value is absent and\n * no fallback is provided. The fallback, when provided, is returned as-is on missing;\n * it does NOT pass through the schema (mirrors custom-converter behavior).\n *\n * Synchronous schemas only. A Promise-returning `validate` triggers an\n * `InvalidUserDefinedConfig` throw at the call site.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * const port = Envapter.parse('PORT', z.coerce.number().min(1024).max(65535), 3000);\n * ```\n */\n static parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n // SchemaConstraint resolves to the unsatisfiable SchemaMustBeSync brand for async\n // schemas, so reaching this body means the input is structurally a sync Schema.\n const result = this.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n\n /**\n * @see {@link AdvancedMethods.parse}\n */\n parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n const result = AdvancedMethods.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n}\n"],"mappings":"6HA0BA,SAAS,EAAa,EAAyF,CAG3G,OAAO,OAAO,GAAU,YAAY,GAAkB,cAAe,CACzE,CAEA,SAAS,EAAkB,EAA0B,CACjD,OAAO,MAAM,QAAQ,CAAG,EAAI,IAAI,EAAI,KAAK,IAAI,EAAE,GAAK,OAAO,CAAG,CAClE,CAMA,IAAa,EAAb,MAAa,UAAwBA,EAAAA,gBAAiB,CA0BlD,OAAO,SACH,EACA,EACA,EAC8C,CAC9C,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAIC,EAAAA,YAAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAEA,IAAM,EAAY,EACZ,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAK5D,GAAI,KAAK,eAAe,CAAK,GAAK,IAAa,IAAA,GAC3C,OAGJ,IAAM,EAAc,IAAa,IAAA,GAGjC,OAFe,KAAK,eAAe,aAAa,EAAa,EAAU,EAAW,CAEtE,CAChB,CAqBA,SACI,EACA,EACA,EAC8C,CAC9C,OAAO,EAAgB,SAAS,EAAK,EAAkC,CAAQ,CACnF,CAYA,OAAO,QACH,EACA,EACA,EACyC,CACzC,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAIA,EAAAA,YAAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAGA,GAAM,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAC5D,GAAI,KAAK,eAAe,CAAK,EAAG,OAAO,EAEvC,IAAM,EAAc,IAAa,IAAA,GASjC,OAPe,KAAK,eAAe,aAC/B,EACA,EACA,EACA,CAGQ,CAChB,CAWA,QACI,EACA,EACA,EACyC,CACzC,OAAO,EAAgB,QAAQ,EAAK,EAAsD,CAAQ,CACtG,CAiBA,OAAO,MACH,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EASvC,OANe,KAAK,eAAe,kBAC/B,EACA,EACA,EACA,CAEQ,CAChB,CAKA,MACI,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EAOvC,OANe,EAAgB,eAAe,kBAC1C,EACA,EACA,EACA,CAEQ,CAChB,CACJ"}
|
|
1
|
+
{"version":3,"file":"AdvancedMethods.cjs","names":["PrimitiveMethods","EnvaptError"],"sources":["../../../src/core/AdvancedMethods.ts"],"sourcesContent":["import { PrimitiveMethods } from './PrimitiveMethods';\nimport { debugWarn } from '../infra/Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../infra/StandardSchema';\nimport type {\n AdvancedConverterReturn,\n BuiltInConverter,\n ConditionalReturn,\n ConverterFunction,\n EnvKeyInput,\n InferConverterReturnType,\n SchemaConstraint,\n TimeFallback\n} from '../types';\n\ninterface GetUsingRequiredOptions<TConverter> {\n converter: TConverter;\n required: true;\n}\n\ninterface GetWithRequiredOptions<TReturnType> {\n converter: ConverterFunction<TReturnType>;\n required: true;\n}\n\nfunction isOptionsBag(value: unknown): value is { converter: unknown; required?: boolean; fallback?: unknown } {\n // `ArrayOf` tokens have `of`/`delimiter` but no `converter` key, so the presence of\n // `converter` discriminates the options-bag form from a positional converter token.\n return typeof value === 'object' && value !== null && 'converter' in value;\n}\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Mixin for advanced methods for environment variable conversion using built-in and custom converters\n * @internal\n */\nexport class AdvancedMethods extends PrimitiveMethods {\n /**\n * Get an environment variable using a built-in converter.\n *\n * Supports both scalar tokens (e.g. `Converters.Number`) and `ArrayOf<...>` tokens\n * produced by `Converters.array(...)`. The key can be a single name or an ordered list;\n * the first defined value wins.\n */\n // Time-specific overload must precede the generic BuiltInConverter overload so it wins\n // overload resolution (TimeFallback accepts time-strings like `'10s'`).\n static getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n static getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n static getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as TConverter,\n false\n );\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const converter = converterOrOptions as TConverter;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n // No env value AND no fallback: return undefined to match primitive-method semantics.\n // Otherwise route through the parser so asymmetric fallback types (TimeFallback,\n // TimeFallback[] for `of: time` arrays) get coerced to the declared return type.\n if (this.treatAsMissing(value) && fallback === undefined) {\n debugWarn(`${resolvedKey} is missing or empty`);\n return undefined as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n const result = this.valueConverter.convertValue(resolvedKey, fallback, converter, hasFallback);\n\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getUsing}\n */\n getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n return AdvancedMethods.getUsing(key, converterOrOptions as TConverter, fallback);\n }\n\n /**\n * Get an environment variable using a custom converter function.\n * Accepts a single key or an ordered list for automatic fallback.\n */\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n static getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as ConverterFunction<undefined>,\n false\n );\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n // Check if variable exists first, for consistency with primitive methods\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) {\n debugWarn(`${resolvedKey} is missing or empty`);\n return fallback as ConditionalReturn<TReturnType, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n // Convert the converter to match the expected signature via unknown\n const result = this.valueConverter.convertValue(\n resolvedKey,\n fallback,\n converterOrOptions as unknown as ConverterFunction<TFallback>,\n hasFallback\n );\n\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getWith}\n */\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n return AdvancedMethods.getWith(key, converterOrOptions as ConverterFunction<TReturnType>, fallback);\n }\n\n /**\n * Validate an environment variable through a {@link StandardSchemaV1}-conformant schema\n * (zod, valibot, arktype, etc). Throws `MissingEnvValue` if the env value is absent and\n * no fallback is provided. The fallback, when provided, is returned as-is on missing;\n * it does NOT pass through the schema (mirrors custom-converter behavior).\n *\n * Synchronous schemas only. A Promise-returning `validate` triggers an\n * `InvalidUserDefinedConfig` throw at the call site.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * const port = Envapter.parse('PORT', z.coerce.number().min(1024).max(65535), 3000);\n * ```\n */\n static parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n // SchemaConstraint resolves to the unsatisfiable SchemaMustBeSync brand for async\n // schemas, so reaching this body means the input is structurally a sync Schema.\n const result = this.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n\n /**\n * @see {@link AdvancedMethods.parse}\n */\n parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n const result = AdvancedMethods.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n}\n"],"mappings":"6JA2BA,SAAS,EAAa,EAAyF,CAG3G,OAAO,OAAO,GAAU,YAAY,GAAkB,cAAe,CACzE,CAEA,SAAS,EAAkB,EAA0B,CACjD,OAAO,MAAM,QAAQ,CAAG,EAAI,IAAI,EAAI,KAAK,IAAI,EAAE,GAAK,OAAO,CAAG,CAClE,CAMA,IAAa,EAAb,MAAa,UAAwBA,EAAAA,gBAAiB,CA0BlD,OAAO,SACH,EACA,EACA,EAC8C,CAC9C,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAIC,EAAAA,YAAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAEA,IAAM,EAAY,EACZ,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAK5D,GAAI,KAAK,eAAe,CAAK,GAAK,IAAa,IAAA,GAAW,CACtD,EAAA,UAAU,GAAG,EAAY,qBAAqB,EAC9C,MACJ,CAEA,IAAM,EAAc,IAAa,IAAA,GAGjC,OAFe,KAAK,eAAe,aAAa,EAAa,EAAU,EAAW,CAEtE,CAChB,CAqBA,SACI,EACA,EACA,EAC8C,CAC9C,OAAO,EAAgB,SAAS,EAAK,EAAkC,CAAQ,CACnF,CAYA,OAAO,QACH,EACA,EACA,EACyC,CACzC,GAAI,EAAa,CAAkB,EAAG,CAClC,IAAM,EAAU,EACV,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAE5D,GAAI,IAAU,IAAA,IAAa,EAAM,KAAK,IAAM,GACxC,MAAM,IAAIA,EAAAA,YAAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,EASJ,OANe,KAAK,eAAe,aAC/B,EACA,IAAA,GACA,EAAQ,UACR,EAEQ,CAChB,CAGA,GAAM,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAC5D,GAAI,KAAK,eAAe,CAAK,EAEzB,OADA,EAAA,UAAU,GAAG,EAAY,qBAAqB,EACvC,EAGX,IAAM,EAAc,IAAa,IAAA,GASjC,OAPe,KAAK,eAAe,aAC/B,EACA,EACA,EACA,CAGQ,CAChB,CAWA,QACI,EACA,EACA,EACyC,CACzC,OAAO,EAAgB,QAAQ,EAAK,EAAsD,CAAQ,CACtG,CAiBA,OAAO,MACH,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EASvC,OANe,KAAK,eAAe,kBAC/B,EACA,EACA,EACA,CAEQ,CAChB,CAKA,MACI,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EAOvC,OANe,EAAgB,eAAe,kBAC1C,EACA,EACA,EACA,CAEQ,CAChB,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"node:path";import"node:url";import.meta.url;import{EnvaptError as e}from"../infra/Error.mjs";import{
|
|
1
|
+
import"node:path";import"node:url";import.meta.url;import{EnvaptError as e}from"../infra/Error.mjs";import{debugWarn as t}from"../infra/Debug.mjs";import{PrimitiveMethods as n}from"./PrimitiveMethods.mjs";function r(e){return typeof e==`object`&&!!e&&`converter`in e}function i(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}var a=class a extends n{static getUsing(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let s=a,{key:c,value:l}=this.resolveKeyInput(n);if(this.treatAsMissing(l)&&o===void 0){t(`${c} is missing or empty`);return}let u=o!==void 0;return this.valueConverter.convertValue(c,o,s,u)}getUsing(e,t,n){return a.getUsing(e,t,n)}static getWith(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let{key:s,value:c}=this.resolveKeyInput(n);if(this.treatAsMissing(c))return t(`${s} is missing or empty`),o;let l=o!==void 0;return this.valueConverter.convertValue(s,o,a,l)}getWith(e,t,n){return a.getWith(e,t,n)}static parse(e,t,n){let r=arguments.length>2;return this.valueConverter.convertWithSchema(e,t,n,r)}parse(e,t,n){let r=arguments.length>2;return a.valueConverter.convertWithSchema(e,t,n,r)}};export{a as AdvancedMethods};
|
|
2
2
|
//# sourceMappingURL=AdvancedMethods.mjs.map
|