envapt 7.0.3 → 8.0.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -101
- package/README.md +5 -5
- package/dist/node/converters/BuiltInConverters.cjs +1 -1
- package/dist/node/converters/BuiltInConverters.cjs.map +1 -1
- package/dist/node/converters/BuiltInConverters.mjs +1 -1
- package/dist/node/converters/BuiltInConverters.mjs.map +1 -1
- package/dist/node/converters/Converters.cjs.map +1 -1
- package/dist/node/converters/Converters.mjs.map +1 -1
- package/dist/node/converters/ValueConverter.cjs +1 -1
- package/dist/node/converters/ValueConverter.cjs.map +1 -1
- package/dist/node/converters/ValueConverter.mjs +1 -1
- package/dist/node/converters/ValueConverter.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/Environment.cjs +2 -0
- package/dist/node/core/Environment.cjs.map +1 -0
- package/dist/node/core/Environment.mjs +2 -0
- package/dist/node/core/Environment.mjs.map +1 -0
- package/dist/node/core/EnvironmentMethods.cjs +1 -1
- package/dist/node/core/EnvironmentMethods.cjs.map +1 -1
- package/dist/node/core/EnvironmentMethods.mjs +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/core/engine.cjs +2 -0
- package/dist/node/core/engine.cjs.map +1 -0
- package/dist/node/core/engine.mjs +2 -0
- package/dist/node/core/engine.mjs.map +1 -0
- package/dist/node/core/paths.cjs +2 -0
- package/dist/node/core/paths.cjs.map +1 -0
- package/dist/node/core/paths.mjs +2 -0
- package/dist/node/core/paths.mjs.map +1 -0
- package/dist/node/core/state.cjs +2 -0
- package/dist/node/core/state.cjs.map +1 -0
- package/dist/node/core/state.mjs +2 -0
- package/dist/node/core/state.mjs.map +1 -0
- package/dist/node/decorators/resolveDecoratorValue.cjs +1 -1
- package/dist/node/decorators/resolveDecoratorValue.cjs.map +1 -1
- package/dist/node/decorators/resolveDecoratorValue.mjs +1 -1
- package/dist/node/decorators/resolveDecoratorValue.mjs.map +1 -1
- package/dist/node/engine/Envapter.cjs +1 -1
- package/dist/node/engine/Envapter.cjs.map +1 -1
- package/dist/node/engine/Envapter.mjs +1 -1
- package/dist/node/engine/Envapter.mjs.map +1 -1
- package/dist/node/engine/NodeEnvapter.cjs +1 -1
- package/dist/node/engine/NodeEnvapter.cjs.map +1 -1
- package/dist/node/engine/NodeEnvapter.mjs +1 -1
- package/dist/node/engine/NodeEnvapter.mjs.map +1 -1
- package/dist/node/engine/TemplateResolver.cjs +1 -1
- package/dist/node/engine/TemplateResolver.cjs.map +1 -1
- package/dist/node/engine/TemplateResolver.mjs +1 -1
- package/dist/node/engine/TemplateResolver.mjs.map +1 -1
- package/dist/node/engine/Validators.cjs +1 -1
- package/dist/node/engine/Validators.cjs.map +1 -1
- package/dist/node/engine/Validators.mjs +1 -1
- package/dist/node/engine/Validators.mjs.map +1 -1
- package/dist/node/index.cjs +1 -1
- package/dist/node/index.mjs +1 -1
- package/dist/node/infra/Error.cjs +1 -1
- package/dist/node/infra/Error.cjs.map +1 -1
- package/dist/node/infra/Error.mjs +1 -1
- package/dist/node/infra/Error.mjs.map +1 -1
- package/dist/node/infra/recase.cjs +2 -0
- package/dist/node/infra/recase.cjs.map +1 -0
- package/dist/node/infra/recase.mjs +2 -0
- package/dist/node/infra/recase.mjs.map +1 -0
- package/dist/node/infra/runtime.cjs.map +1 -1
- package/dist/node/infra/runtime.mjs.map +1 -1
- package/dist/node/sources/{NodeEnvSource.cjs → FileSource.cjs} +2 -2
- package/dist/node/sources/FileSource.cjs.map +1 -0
- package/dist/node/sources/{NodeEnvSource.mjs → FileSource.mjs} +2 -2
- package/dist/node/sources/FileSource.mjs.map +1 -0
- package/dist/node/sources/{ManualEnvSource.cjs → PortableSource.cjs} +2 -2
- package/dist/node/sources/PortableSource.cjs.map +1 -0
- package/dist/{browser/sources/ManualEnvSource.mjs → node/sources/PortableSource.mjs} +2 -2
- package/dist/node/sources/PortableSource.mjs.map +1 -0
- package/dist/node/sources/{UnboundEnvSource.cjs → UnboundSource.cjs} +2 -2
- package/dist/node/sources/UnboundSource.cjs.map +1 -0
- package/dist/{browser/sources/UnboundEnvSource.mjs → node/sources/UnboundSource.mjs} +2 -2
- package/dist/node/sources/UnboundSource.mjs.map +1 -0
- package/dist/node/sources/coerce.cjs.map +1 -1
- package/dist/node/sources/coerce.mjs.map +1 -1
- package/dist/node/sources/merge.cjs +2 -0
- package/dist/node/sources/merge.cjs.map +1 -0
- package/dist/node/sources/merge.mjs +2 -0
- package/dist/node/sources/merge.mjs.map +1 -0
- package/dist/portable/converters/BuiltInConverters.mjs +2 -0
- package/dist/portable/converters/BuiltInConverters.mjs.map +1 -0
- package/dist/portable/converters/Converters.mjs.map +1 -0
- package/dist/portable/converters/ValueConverter.mjs +2 -0
- package/dist/portable/converters/ValueConverter.mjs.map +1 -0
- package/dist/portable/core/AdvancedMethods.mjs +2 -0
- package/dist/portable/core/AdvancedMethods.mjs.map +1 -0
- package/dist/portable/core/EnvapterBase.mjs +2 -0
- package/dist/portable/core/EnvapterBase.mjs.map +1 -0
- package/dist/portable/core/Environment.mjs +2 -0
- package/dist/portable/core/Environment.mjs.map +1 -0
- package/dist/portable/core/EnvironmentMethods.mjs +2 -0
- package/dist/portable/core/EnvironmentMethods.mjs.map +1 -0
- package/dist/portable/core/PrimitiveMethods.mjs +2 -0
- package/dist/portable/core/PrimitiveMethods.mjs.map +1 -0
- package/dist/portable/core/engine.mjs +2 -0
- package/dist/portable/core/engine.mjs.map +1 -0
- package/dist/portable/core/paths.mjs +2 -0
- package/dist/portable/core/paths.mjs.map +1 -0
- package/dist/portable/core/state.mjs +2 -0
- package/dist/portable/core/state.mjs.map +1 -0
- package/dist/portable/decorators/resolveDecoratorValue.mjs +2 -0
- package/dist/portable/decorators/resolveDecoratorValue.mjs.map +1 -0
- package/dist/portable/engine/Envapter.mjs +2 -0
- package/dist/portable/engine/Envapter.mjs.map +1 -0
- package/dist/portable/engine/PortableEnvapter.mjs +2 -0
- package/dist/portable/engine/PortableEnvapter.mjs.map +1 -0
- package/dist/portable/engine/TemplateResolver.mjs +2 -0
- package/dist/portable/engine/TemplateResolver.mjs.map +1 -0
- package/dist/portable/engine/Validators.mjs +2 -0
- package/dist/portable/engine/Validators.mjs.map +1 -0
- package/dist/portable/engine/fileApiStub.mjs +2 -0
- package/dist/portable/engine/fileApiStub.mjs.map +1 -0
- package/dist/portable/index.mjs +1 -0
- package/dist/{browser → portable}/infra/Error.mjs +1 -1
- package/dist/{browser → portable}/infra/Error.mjs.map +1 -1
- package/dist/portable/infra/recase.mjs +2 -0
- package/dist/portable/infra/recase.mjs.map +1 -0
- package/dist/portable/infra/runtime.mjs.map +1 -0
- package/dist/{browser/sources/WorkerEnvSource.mjs → portable/sources/PortableSource.mjs} +2 -2
- package/dist/portable/sources/PortableSource.mjs.map +1 -0
- package/dist/{node/sources/UnboundEnvSource.mjs → portable/sources/UnboundSource.mjs} +2 -2
- package/dist/portable/sources/UnboundSource.mjs.map +1 -0
- package/dist/portable/sources/coerce.mjs.map +1 -0
- package/dist/portable/sources/merge.mjs +2 -0
- package/dist/portable/sources/merge.mjs.map +1 -0
- package/dist/types/converters/Converters.d.mts +1 -15
- package/dist/types/core/AdvancedMethods.d.mts +31 -19
- package/dist/types/core/EnvapterBase.d.mts +16 -30
- package/dist/types/core/Environment.d.mts +25 -0
- package/dist/types/core/EnvironmentMethods.d.mts +2 -67
- package/dist/types/core/PrimitiveMethods.d.mts +2 -10
- package/dist/types/engine/Envapter.d.mts +2 -3
- package/dist/types/engine/NodeEnvapter.d.mts +4 -7
- package/dist/types/engine/PortableEnvapter.d.mts +17 -5
- package/dist/types/index.d.mts +10 -13
- package/dist/types/index.portable.d.mts +9 -12
- package/dist/types/infra/Error.d.mts +3 -1
- package/dist/types/infra/StandardSchema.d.mts +1 -12
- package/dist/types/sources/{NodeEnvSource.d.mts → FileSource.d.mts} +5 -5
- package/dist/types/sources/PortableSource.d.mts +24 -0
- package/dist/types/sources/merge.d.mts +13 -0
- package/dist/types/types/Casing.d.mts +8 -0
- package/dist/types/types/Conversion.d.mts +9 -66
- package/dist/types/types/Decorator.d.mts +0 -14
- package/dist/types/types/Env.d.mts +1 -10
- package/dist/types/types/Options.d.mts +9 -2
- package/dist/types/types/Schema.d.mts +1 -13
- package/dist/types/types/Source.d.mts +8 -28
- package/package.json +62 -19
- package/aliases/browser.d.mts +0 -7
- package/aliases/browser.mjs +0 -4
- package/aliases/workerd.d.mts +0 -7
- package/aliases/workerd.mjs +0 -4
- package/dist/browser/converters/BuiltInConverters.mjs +0 -2
- package/dist/browser/converters/BuiltInConverters.mjs.map +0 -1
- package/dist/browser/converters/Converters.mjs.map +0 -1
- package/dist/browser/converters/ValueConverter.mjs +0 -2
- package/dist/browser/converters/ValueConverter.mjs.map +0 -1
- package/dist/browser/core/AdvancedMethods.mjs +0 -2
- package/dist/browser/core/AdvancedMethods.mjs.map +0 -1
- package/dist/browser/core/EnvapterBase.mjs +0 -2
- package/dist/browser/core/EnvapterBase.mjs.map +0 -1
- package/dist/browser/core/EnvironmentMethods.mjs +0 -2
- package/dist/browser/core/EnvironmentMethods.mjs.map +0 -1
- package/dist/browser/core/PrimitiveMethods.mjs +0 -2
- package/dist/browser/core/PrimitiveMethods.mjs.map +0 -1
- package/dist/browser/decorators/resolveDecoratorValue.mjs +0 -2
- package/dist/browser/decorators/resolveDecoratorValue.mjs.map +0 -1
- package/dist/browser/engine/Envapter.mjs +0 -2
- package/dist/browser/engine/Envapter.mjs.map +0 -1
- package/dist/browser/engine/PortableEnvapter.mjs +0 -2
- package/dist/browser/engine/PortableEnvapter.mjs.map +0 -1
- package/dist/browser/engine/TemplateResolver.mjs +0 -2
- package/dist/browser/engine/TemplateResolver.mjs.map +0 -1
- package/dist/browser/engine/Validators.mjs +0 -2
- package/dist/browser/engine/Validators.mjs.map +0 -1
- package/dist/browser/engine/installFileApiStubs.mjs +0 -2
- package/dist/browser/engine/installFileApiStubs.mjs.map +0 -1
- package/dist/browser/index.mjs +0 -1
- package/dist/browser/infra/runtime.mjs.map +0 -1
- package/dist/browser/sources/ManualEnvSource.mjs.map +0 -1
- package/dist/browser/sources/UnboundEnvSource.mjs.map +0 -1
- package/dist/browser/sources/WorkerEnvSource.mjs.map +0 -1
- package/dist/browser/sources/coerce.mjs.map +0 -1
- package/dist/node/sources/ManualEnvSource.cjs.map +0 -1
- package/dist/node/sources/ManualEnvSource.mjs +0 -2
- package/dist/node/sources/ManualEnvSource.mjs.map +0 -1
- package/dist/node/sources/NodeEnvSource.cjs.map +0 -1
- package/dist/node/sources/NodeEnvSource.mjs.map +0 -1
- package/dist/node/sources/UnboundEnvSource.cjs.map +0 -1
- package/dist/node/sources/UnboundEnvSource.mjs.map +0 -1
- package/dist/node/sources/WorkerEnvSource.cjs +0 -2
- package/dist/node/sources/WorkerEnvSource.cjs.map +0 -1
- package/dist/node/sources/WorkerEnvSource.mjs +0 -2
- package/dist/node/sources/WorkerEnvSource.mjs.map +0 -1
- package/dist/types/converters/ValueConverter.d.mts +0 -25
- package/dist/types/engine/TemplateResolver.d.mts +0 -17
- package/dist/types/sources/ManualEnvSource.d.mts +0 -22
- package/dist/types/sources/WorkerEnvSource.d.mts +0 -22
- package/dist/workerd/converters/BuiltInConverters.mjs +0 -2
- package/dist/workerd/converters/BuiltInConverters.mjs.map +0 -1
- package/dist/workerd/converters/Converters.mjs +0 -2
- package/dist/workerd/converters/Converters.mjs.map +0 -1
- package/dist/workerd/converters/ListOfBuiltInConverters.mjs +0 -2
- package/dist/workerd/converters/ListOfBuiltInConverters.mjs.map +0 -1
- package/dist/workerd/converters/ValueConverter.mjs +0 -2
- package/dist/workerd/converters/ValueConverter.mjs.map +0 -1
- package/dist/workerd/core/AdvancedMethods.mjs +0 -2
- package/dist/workerd/core/AdvancedMethods.mjs.map +0 -1
- package/dist/workerd/core/EnvapterBase.mjs +0 -2
- package/dist/workerd/core/EnvapterBase.mjs.map +0 -1
- package/dist/workerd/core/EnvironmentMethods.mjs +0 -2
- package/dist/workerd/core/EnvironmentMethods.mjs.map +0 -1
- package/dist/workerd/core/PrimitiveMethods.mjs +0 -2
- package/dist/workerd/core/PrimitiveMethods.mjs.map +0 -1
- package/dist/workerd/decorators/legacy/Envapt.mjs +0 -2
- package/dist/workerd/decorators/legacy/Envapt.mjs.map +0 -1
- package/dist/workerd/decorators/legacy/SugarDecorators.mjs +0 -2
- package/dist/workerd/decorators/legacy/SugarDecorators.mjs.map +0 -1
- package/dist/workerd/decorators/legacy/createPropertyDecorator.mjs +0 -2
- package/dist/workerd/decorators/legacy/createPropertyDecorator.mjs.map +0 -1
- package/dist/workerd/decorators/modern/Envapt.mjs +0 -2
- package/dist/workerd/decorators/modern/Envapt.mjs.map +0 -1
- package/dist/workerd/decorators/modern/SugarDecorators.mjs +0 -2
- package/dist/workerd/decorators/modern/SugarDecorators.mjs.map +0 -1
- package/dist/workerd/decorators/modern/createAccessorDecorator.mjs +0 -2
- package/dist/workerd/decorators/modern/createAccessorDecorator.mjs.map +0 -1
- package/dist/workerd/decorators/parseEnvaptOptions.mjs +0 -2
- package/dist/workerd/decorators/parseEnvaptOptions.mjs.map +0 -1
- package/dist/workerd/decorators/resolveDecoratorValue.mjs +0 -2
- package/dist/workerd/decorators/resolveDecoratorValue.mjs.map +0 -1
- package/dist/workerd/engine/Envapter.mjs +0 -2
- package/dist/workerd/engine/Envapter.mjs.map +0 -1
- package/dist/workerd/engine/PortableEnvapter.mjs +0 -2
- package/dist/workerd/engine/PortableEnvapter.mjs.map +0 -1
- package/dist/workerd/engine/TemplateResolver.mjs +0 -2
- package/dist/workerd/engine/TemplateResolver.mjs.map +0 -1
- package/dist/workerd/engine/Validators.mjs +0 -2
- package/dist/workerd/engine/Validators.mjs.map +0 -1
- package/dist/workerd/engine/installFileApiStubs.mjs +0 -2
- package/dist/workerd/engine/installFileApiStubs.mjs.map +0 -1
- package/dist/workerd/index.mjs +0 -1
- package/dist/workerd/infra/Debug.mjs +0 -2
- package/dist/workerd/infra/Debug.mjs.map +0 -1
- package/dist/workerd/infra/Dotenv.mjs +0 -3
- package/dist/workerd/infra/Dotenv.mjs.map +0 -1
- package/dist/workerd/infra/Error.mjs +0 -2
- package/dist/workerd/infra/Error.mjs.map +0 -1
- package/dist/workerd/infra/runtime.mjs +0 -2
- package/dist/workerd/infra/runtime.mjs.map +0 -1
- package/dist/workerd/legacy.mjs +0 -1
- package/dist/workerd/sources/ManualEnvSource.mjs +0 -2
- package/dist/workerd/sources/ManualEnvSource.mjs.map +0 -1
- package/dist/workerd/sources/UnboundEnvSource.mjs +0 -2
- package/dist/workerd/sources/UnboundEnvSource.mjs.map +0 -1
- package/dist/workerd/sources/WorkerEnvSource.mjs +0 -2
- package/dist/workerd/sources/WorkerEnvSource.mjs.map +0 -1
- package/dist/workerd/sources/coerce.mjs +0 -2
- package/dist/workerd/sources/coerce.mjs.map +0 -1
- /package/dist/{browser → portable}/converters/Converters.mjs +0 -0
- /package/dist/{browser → portable}/converters/ListOfBuiltInConverters.mjs +0 -0
- /package/dist/{browser → portable}/converters/ListOfBuiltInConverters.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/legacy/Envapt.mjs +0 -0
- /package/dist/{browser → portable}/decorators/legacy/Envapt.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/legacy/SugarDecorators.mjs +0 -0
- /package/dist/{browser → portable}/decorators/legacy/SugarDecorators.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/legacy/createPropertyDecorator.mjs +0 -0
- /package/dist/{browser → portable}/decorators/legacy/createPropertyDecorator.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/modern/Envapt.mjs +0 -0
- /package/dist/{browser → portable}/decorators/modern/Envapt.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/modern/SugarDecorators.mjs +0 -0
- /package/dist/{browser → portable}/decorators/modern/SugarDecorators.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/modern/createAccessorDecorator.mjs +0 -0
- /package/dist/{browser → portable}/decorators/modern/createAccessorDecorator.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/parseEnvaptOptions.mjs +0 -0
- /package/dist/{browser → portable}/decorators/parseEnvaptOptions.mjs.map +0 -0
- /package/dist/{browser → portable}/infra/Debug.mjs +0 -0
- /package/dist/{browser → portable}/infra/Debug.mjs.map +0 -0
- /package/dist/{browser → portable}/infra/Dotenv.mjs +0 -0
- /package/dist/{browser → portable}/infra/Dotenv.mjs.map +0 -0
- /package/dist/{browser → portable}/infra/runtime.mjs +0 -0
- /package/dist/{browser → portable}/legacy.mjs +0 -0
- /package/dist/{browser → portable}/sources/coerce.mjs +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Validators.cjs","names":["ListOfBuiltInConverters","isArrayOf","EnvaptError","BuiltInConverterTypeCheckers"],"sources":["../../../src/engine/Validators.ts"],"sourcesContent":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from '../converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from '../converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf, ConverterToken } from '../converters/Converters';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { StandardSchemaV1 } from '../infra/StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter } from '../types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"uIAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/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Content":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from '../converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from '../converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf, ConverterToken } from '../converters/Converters';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { StandardSchemaV1 } from '../infra/StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter, FileApiMode } from '../types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n static validateFileApiMode(value: unknown): asserts value is FileApiMode {\n if (value !== 'warn' && value !== 'throw') {\n const got = typeof value === 'string' ? `'${value}'` : typeof value;\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.fileApiMode must be 'warn' or 'throw', got ${got}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"uIAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,OAAO,GAAU,SAAiBA,EAAAA,wBAAwB,SAAS,CAAK,EACrE,EACX,CAKA,OAAO,iBAAiB,EAAkC,CACtD,OAAOC,EAAAA,UAAU,CAAK,CAC1B,CAIA,OAAO,iBAAiB,EAA2C,CAE/D,GADI,OAAO,GAAU,WAAY,GAC7B,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAO,EAAM,aACnB,GAAI,OAAO,GAAS,WAAY,EAAe,MAAO,GACtD,IAAM,EAAQ,EACd,OAAO,EAAM,UAAY,GAAK,OAAO,EAAM,UAAa,UAC5D,CAEA,OAAO,gBACH,EACiD,CACjD,GAAI,OAAO,GAAc,WACrB,MAAM,IAAIC,EAAAA,YAAAA,IAEN,4CAA4C,OAAO,EAAU,EACjE,CAER,CAKA,OAAO,eAAe,EAA0C,CAC5D,GAAI,CAACD,EAAAA,UAAU,CAAK,EAChB,MAAM,IAAIC,EAAAA,YAAAA,IAEN,kEACJ,EAGJ,GAAI,OAAO,EAAM,WAAc,UAAY,EAAM,UAAU,SAAW,EAClE,MAAM,IAAIA,EAAAA,YAAAA,IAEN,2DAA2D,OAAO,EAAM,WAC5E,EA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AAuD,EAAI,EAC/D,CACJ,CACJ,CAKA,OAAO,uBAAuB,EAA0C,CACpE,IAAM,EAAY,IAAI,IAAI,CAAC,WAAY,UAAU,CAAC,EAC5C,EAAc,OAAO,KAAK,CAAM,CAAC,CAAC,OAAQ,GAAQ,CAAC,EAAU,IAAI,CAAG,CAAC,EAE3E,GAAI,EAAY,OAAS,EACrB,MAAM,IAAIA,EAAAA,YAAAA,IAEN,2BAA2B,EAAY,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,CAAS,CAAC,CAAC,KAAK,IAAI,EAAE,oEAC5G,EAGJ,MAAO,EACX,CAIA,OAAO,sBAAsB,EAAiB,EAA6C,CACvF,IAAM,EAAU,EAAM,OAAQ,GAAM,CAAC,EAAW,CAAC,CAAC,EAElD,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAIA,EAAAA,YAAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isArrayOf as e}from"../converters/Converters.mjs";import{
|
|
1
|
+
import{isArrayOf as e}from"../converters/Converters.mjs";import{EnvaptError as t}from"../infra/Error.mjs";import{BuiltInConverterTypeCheckers as n,ListOfBuiltInConverters as r}from"../converters/ListOfBuiltInConverters.mjs";var i=class{static isBuiltInConverter(e){return typeof e==`string`?r.includes(e):!1}static isArrayConverter(t){return e(t)}static isStandardSchema(e){if(typeof e!=`object`||!e||!(`~standard`in e))return!1;let t=e[`~standard`];if(typeof t!=`object`||!t)return!1;let n=t;return n.version===1&&typeof n.validate==`function`}static customConvertor(e){if(typeof e!=`function`)throw new t(203,`Custom converter must be a function, got ${typeof e}.`)}static arrayConverter(n){if(!e(n))throw new t(201,`Expected an ArrayOf<...> token produced by Converters.array(...)`);if(typeof n.delimiter!=`string`||n.delimiter.length===0)throw new t(301,`ArrayOf<...> requires a non-empty string delimiter, got ${typeof n.delimiter}`);let i=n.of;if(!(typeof i==`string`&&r.includes(i))&&typeof i!=`function`)throw new t(201,`ArrayOf<...> element ("of") must be a built-in scalar token or a function, got ${typeof i}`)}static builtInConverter(e){if(typeof e!=`string`)throw new t(204,`Expected string, got ${typeof e}`);if(!r.includes(e))throw new t(202,`"${e}" is not a valid converter type. Valid types are: ${r.join(`,`)}`)}static validateBuiltInConverterFallback(e,r){let i=n[e];if(!i(r))throw new t(104,`Fallback type does not match converter "${e}". Expected ${e} compatible type.`)}static validateArrayFallbackElementTypes(e){if(e.length===0)return;let n=typeof e[0];if(e.some((e,t)=>t===0?!1:typeof e!==n))throw new t(103,`All elements in array fallback must have the same type. Found mixed types.`)}static validateArrayConverterElementTypeMatch(e,r){if(r.length===0||typeof e==`function`)return;let i=e;if(i===`time`){let e=r.every(e=>typeof e==`number`),n=r.every(e=>typeof e==`string`);if(!e&&!n)throw new t(103,`Time array fallback must be all numbers or all time-string entries.`);return}let a=n[i],o=r[0];if(!a(o))throw new t(103,`Array converter type "${i}" does not match fallback element type. Expected ${i} compatible elements.`)}static isPrimitiveConstructor(e){return e===String||e===Number||e===Boolean||e===BigInt||e===Symbol}static coercePrimitiveFallback(e,t){return this.isCorrectPrimitiveType(e,t)?t:this.performPrimitiveCoercion(e,t)}static isCorrectPrimitiveType(e,t){return e===String&&typeof t==`string`||e===Number&&typeof t==`number`||e===Boolean&&typeof t==`boolean`||e===BigInt&&typeof t==`bigint`||e===Symbol&&typeof t==`symbol`}static performPrimitiveCoercion(e,n){try{if(e===String)return String(n);if(e===Number)return Number(n);if(e===Boolean)return!!n;if(e===BigInt)return BigInt(n);if(e===Symbol)return Symbol.for(String(n))}catch(n){throw new t(205,`Failed to coerce fallback value using ${e.name}: ${n.message}`)}throw new t(205,`Unknown primitive converter: ${e.name}`)}static validateSyncProcessEnv(e){if(typeof e!=`boolean`)throw new t(302,`Envapter.syncProcessEnv must be a boolean, got ${typeof e}.`)}static validateFileApiMode(e){if(e!==`warn`&&e!==`throw`)throw new t(302,`Envapter.fileApiMode must be 'warn' or 'throw', got ${typeof e==`string`?`'${e}'`:typeof e}.`)}static validateEnvFileOptions(e){let n=new Set([`encoding`,`override`]),r=Object.keys(e).filter(e=>!n.has(e));if(r.length>0)throw new t(302,`Invalid envFileOptions: ${r.join(`, `)}. Allowed options: ${Array.from(n).join(`, `)}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`);return!0}static validateEnvFilesExist(e,n){let r=e.filter(e=>!n(e));if(r.length>0)throw new t(303,`Environment file not found at path: ${r.join(`, `)}`)}};export{i as Validator};
|
|
2
2
|
//# sourceMappingURL=Validators.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Validators.mjs","names":[],"sources":["../../../src/engine/Validators.ts"],"sourcesContent":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from '../converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from '../converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf, ConverterToken } from '../converters/Converters';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { StandardSchemaV1 } from '../infra/StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter } from '../types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"gOAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,OAAO,GAAU,SAAiB,EAAwB,SAAS,CAAK,EACrE,EACX,CAKA,OAAO,iBAAiB,EAAkC,CACtD,OAAO,EAAU,CAAK,CAC1B,CAIA,OAAO,iBAAiB,EAA2C,CAE/D,GADI,OAAO,GAAU,WAAY,GAC7B,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAO,EAAM,aACnB,GAAI,OAAO,GAAS,WAAY,EAAe,MAAO,GACtD,IAAM,EAAQ,EACd,OAAO,EAAM,UAAY,GAAK,OAAO,EAAM,UAAa,UAC5D,CAEA,OAAO,gBACH,EACiD,CACjD,GAAI,OAAO,GAAc,WACrB,MAAM,IAAI,EAAA,IAEN,4CAA4C,OAAO,EAAU,EACjE,CAER,CAKA,OAAO,eAAe,EAA0C,CA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AAQ,GAAQ,CAAC,EAAU,IAAI,CAAG,CAAC,EAE3E,GAAI,EAAY,OAAS,EACrB,MAAM,IAAI,EAAA,IAEN,2BAA2B,EAAY,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,CAAS,CAAC,CAAC,KAAK,IAAI,EAAE,oEAC5G,EAGJ,MAAO,EACX,CAIA,OAAO,sBAAsB,EAAiB,EAA6C,CACvF,IAAM,EAAU,EAAM,OAAQ,GAAM,CAAC,EAAW,CAAC,CAAC,EAElD,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CACJ"}
|
|
1
|
+
{"version":3,"file":"Validators.mjs","names":[],"sources":["../../../src/engine/Validators.ts"],"sourcesContent":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from '../converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from '../converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf, ConverterToken } from '../converters/Converters';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { StandardSchemaV1 } from '../infra/StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter, FileApiMode } from '../types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n static validateFileApiMode(value: unknown): asserts value is FileApiMode {\n if (value !== 'warn' && value !== 'throw') {\n const got = typeof value === 'string' ? `'${value}'` : typeof value;\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.fileApiMode must be 'warn' or 'throw', got ${got}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"gOAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,OAAO,GAAU,SAAiB,EAAwB,SAAS,CAAK,EACrE,EACX,CAKA,OAAO,iBAAiB,EAAkC,CACtD,OAAO,EAAU,CAAK,CAC1B,CAIA,OAAO,iBAAiB,EAA2C,CAE/D,GADI,OAAO,GAAU,WAAY,GAC7B,EAAE,cAAe,GAAQ,MAAO,GACpC,IAAM,EAAO,EAAM,aACnB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C,CACJ,CAMA,OAAO,uBAAuB,EAA0C,CACpE,GAAI,OAAO,GAAU,UACjB,MAAM,IAAI,EAAA,IAEN,kDAAkD,OAAO,EAAM,EACnE,CAER,CAEA,OAAO,oBAAoB,EAA8C,CACrE,GAAI,IAAU,QAAU,IAAU,QAE9B,MAAM,IAAI,EAAA,IAEN,uDAHQ,OAAO,GAAU,SAAW,IAAI,EAAM,GAAK,OAAO,EAGC,EAC/D,CAER,CAKA,OAAO,uBAAuB,EAA0C,CACpE,IAAM,EAAY,IAAI,IAAI,CAAC,WAAY,UAAU,CAAC,EAC5C,EAAc,OAAO,KAAK,CAAM,CAAC,CAAC,OAAQ,GAAQ,CAAC,EAAU,IAAI,CAAG,CAAC,EAE3E,GAAI,EAAY,OAAS,EACrB,MAAM,IAAI,EAAA,IAEN,2BAA2B,EAAY,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,CAAS,CAAC,CAAC,KAAK,IAAI,EAAE,oEAC5G,EAGJ,MAAO,EACX,CAIA,OAAO,sBAAsB,EAAiB,EAA6C,CACvF,IAAM,EAAU,EAAM,OAAQ,GAAM,CAAC,EAAW,CAAC,CAAC,EAElD,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CACJ"}
|
package/dist/node/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./core/Environment.cjs"),t=require("./converters/Converters.cjs"),n=require("./infra/Error.cjs"),r=require("./sources/PortableSource.cjs"),i=require("./sources/merge.cjs"),a=require("./decorators/modern/Envapt.cjs"),o=require("./decorators/modern/SugarDecorators.cjs"),s=require("./sources/FileSource.cjs"),c=require("./engine/NodeEnvapter.cjs");exports.Converters=t.Converters,exports.EnvBool=o.EnvBool,exports.EnvNum=o.EnvNum,exports.EnvStr=o.EnvStr,exports.EnvTime=o.EnvTime,exports.EnvUrl=o.EnvUrl,exports.Envapt=a.Envapt,exports.EnvaptError=n.EnvaptError,exports.EnvaptErrorCodes=n.EnvaptErrorCodes,exports.Envapter=c.NodeEnvapter,exports.Environment=e.Environment,exports.FileSource=s.FileSource,exports.PortableSource=r.PortableSource,exports.isArrayOf=t.isArrayOf,exports.merge=i.merge;
|
package/dist/node/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Environment as e}from"./core/Environment.mjs";import{Converters as t,isArrayOf as n}from"./converters/Converters.mjs";import{EnvaptError as r,EnvaptErrorCodes as i}from"./infra/Error.mjs";import{PortableSource as a}from"./sources/PortableSource.mjs";import{merge as o}from"./sources/merge.mjs";import{Envapt as s}from"./decorators/modern/Envapt.mjs";import{EnvBool as c,EnvNum as l,EnvStr as u,EnvTime as d,EnvUrl as f}from"./decorators/modern/SugarDecorators.mjs";import{FileSource as p}from"./sources/FileSource.mjs";import{NodeEnvapter as m}from"./engine/NodeEnvapter.mjs";export{t as Converters,c as EnvBool,l as EnvNum,u as EnvStr,d as EnvTime,f as EnvUrl,s as Envapt,r as EnvaptError,i as EnvaptErrorCodes,m as Envapter,e as Environment,p as FileSource,a as PortableSource,n as isArrayOf,o as merge};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let e=function(e){return e[e.InvalidFallback=101]=`InvalidFallback`,e[e.InvalidFallbackType=102]=`InvalidFallbackType`,e[e.ArrayFallbackElementTypeMismatch=103]=`ArrayFallbackElementTypeMismatch`,e[e.FallbackConverterTypeMismatch=104]=`FallbackConverterTypeMismatch`,e[e.MalformedTimeFallback=105]=`MalformedTimeFallback`,e[e.InvalidArrayConverterType=201]=`InvalidArrayConverterType`,e[e.InvalidBuiltInConverter=202]=`InvalidBuiltInConverter`,e[e.InvalidCustomConverter=203]=`InvalidCustomConverter`,e[e.InvalidConverterType=204]=`InvalidConverterType`,e[e.PrimitiveCoercionFailed=205]=`PrimitiveCoercionFailed`,e[e.ArrayElementConversionFailed=206]=`ArrayElementConversionFailed`,e[e.EmptyArrayElement=207]=`EmptyArrayElement`,e[e.SchemaValidationFailed=208]=`SchemaValidationFailed`,e[e.SchemaThrew=209]=`SchemaThrew`,e[e.MissingDelimiter=301]=`MissingDelimiter`,e[e.InvalidUserDefinedConfig=302]=`InvalidUserDefinedConfig`,e[e.EnvFilesNotFound=303]=`EnvFilesNotFound`,e[e.InvalidKeyInput=304]=`InvalidKeyInput`,e[e.MissingEnvValue=305]=`MissingEnvValue`,e[e.FileApiUnsupported=306]=`FileApiUnsupported`,e[e.NoSourceBound=307]=`NoSourceBound`,e}({});var t=class extends Error{code;issues;constructor(e,t,n){super(t,n?.cause===void 0?void 0:{cause:n.cause}),this.name=`EnvaptError [${e}]`,this.code=e,this.issues=n?.issues}};exports.EnvaptError=t,exports.EnvaptErrorCodes=e;
|
|
1
|
+
let e=function(e){return e[e.InvalidFallback=101]=`InvalidFallback`,e[e.InvalidFallbackType=102]=`InvalidFallbackType`,e[e.ArrayFallbackElementTypeMismatch=103]=`ArrayFallbackElementTypeMismatch`,e[e.FallbackConverterTypeMismatch=104]=`FallbackConverterTypeMismatch`,e[e.MalformedTimeFallback=105]=`MalformedTimeFallback`,e[e.InvalidArrayConverterType=201]=`InvalidArrayConverterType`,e[e.InvalidBuiltInConverter=202]=`InvalidBuiltInConverter`,e[e.InvalidCustomConverter=203]=`InvalidCustomConverter`,e[e.InvalidConverterType=204]=`InvalidConverterType`,e[e.PrimitiveCoercionFailed=205]=`PrimitiveCoercionFailed`,e[e.ArrayElementConversionFailed=206]=`ArrayElementConversionFailed`,e[e.EmptyArrayElement=207]=`EmptyArrayElement`,e[e.SchemaValidationFailed=208]=`SchemaValidationFailed`,e[e.SchemaThrew=209]=`SchemaThrew`,e[e.MissingDelimiter=301]=`MissingDelimiter`,e[e.InvalidUserDefinedConfig=302]=`InvalidUserDefinedConfig`,e[e.EnvFilesNotFound=303]=`EnvFilesNotFound`,e[e.InvalidKeyInput=304]=`InvalidKeyInput`,e[e.MissingEnvValue=305]=`MissingEnvValue`,e[e.FileApiUnsupported=306]=`FileApiUnsupported`,e[e.NoSourceBound=307]=`NoSourceBound`,e[e.InvalidMergedSource=308]=`InvalidMergedSource`,e}({});var t=class extends Error{code;issues;constructor(e,t,n){super(t,n?.cause===void 0?void 0:{cause:n.cause}),this.name=`EnvaptError [${e}]`,this.code=e,this.issues=n?.issues}};exports.EnvaptError=t,exports.EnvaptErrorCodes=e;
|
|
2
2
|
//# sourceMappingURL=Error.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Error.cjs","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,
|
|
1
|
+
{"version":3,"file":"Error.cjs","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 /** Thrown when `merge` is called with no members, or with more than one filesystem-backed source */\n InvalidMergedSource = 308\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,gBAEA,EAAA,EAAA,oBAAA,KAAA,uBACJ,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,2 +1,2 @@
|
|
|
1
|
-
let e=function(e){return e[e.InvalidFallback=101]=`InvalidFallback`,e[e.InvalidFallbackType=102]=`InvalidFallbackType`,e[e.ArrayFallbackElementTypeMismatch=103]=`ArrayFallbackElementTypeMismatch`,e[e.FallbackConverterTypeMismatch=104]=`FallbackConverterTypeMismatch`,e[e.MalformedTimeFallback=105]=`MalformedTimeFallback`,e[e.InvalidArrayConverterType=201]=`InvalidArrayConverterType`,e[e.InvalidBuiltInConverter=202]=`InvalidBuiltInConverter`,e[e.InvalidCustomConverter=203]=`InvalidCustomConverter`,e[e.InvalidConverterType=204]=`InvalidConverterType`,e[e.PrimitiveCoercionFailed=205]=`PrimitiveCoercionFailed`,e[e.ArrayElementConversionFailed=206]=`ArrayElementConversionFailed`,e[e.EmptyArrayElement=207]=`EmptyArrayElement`,e[e.SchemaValidationFailed=208]=`SchemaValidationFailed`,e[e.SchemaThrew=209]=`SchemaThrew`,e[e.MissingDelimiter=301]=`MissingDelimiter`,e[e.InvalidUserDefinedConfig=302]=`InvalidUserDefinedConfig`,e[e.EnvFilesNotFound=303]=`EnvFilesNotFound`,e[e.InvalidKeyInput=304]=`InvalidKeyInput`,e[e.MissingEnvValue=305]=`MissingEnvValue`,e[e.FileApiUnsupported=306]=`FileApiUnsupported`,e[e.NoSourceBound=307]=`NoSourceBound`,e}({});var t=class extends Error{code;issues;constructor(e,t,n){super(t,n?.cause===void 0?void 0:{cause:n.cause}),this.name=`EnvaptError [${e}]`,this.code=e,this.issues=n?.issues}};export{t as EnvaptError,e as EnvaptErrorCodes};
|
|
1
|
+
let e=function(e){return e[e.InvalidFallback=101]=`InvalidFallback`,e[e.InvalidFallbackType=102]=`InvalidFallbackType`,e[e.ArrayFallbackElementTypeMismatch=103]=`ArrayFallbackElementTypeMismatch`,e[e.FallbackConverterTypeMismatch=104]=`FallbackConverterTypeMismatch`,e[e.MalformedTimeFallback=105]=`MalformedTimeFallback`,e[e.InvalidArrayConverterType=201]=`InvalidArrayConverterType`,e[e.InvalidBuiltInConverter=202]=`InvalidBuiltInConverter`,e[e.InvalidCustomConverter=203]=`InvalidCustomConverter`,e[e.InvalidConverterType=204]=`InvalidConverterType`,e[e.PrimitiveCoercionFailed=205]=`PrimitiveCoercionFailed`,e[e.ArrayElementConversionFailed=206]=`ArrayElementConversionFailed`,e[e.EmptyArrayElement=207]=`EmptyArrayElement`,e[e.SchemaValidationFailed=208]=`SchemaValidationFailed`,e[e.SchemaThrew=209]=`SchemaThrew`,e[e.MissingDelimiter=301]=`MissingDelimiter`,e[e.InvalidUserDefinedConfig=302]=`InvalidUserDefinedConfig`,e[e.EnvFilesNotFound=303]=`EnvFilesNotFound`,e[e.InvalidKeyInput=304]=`InvalidKeyInput`,e[e.MissingEnvValue=305]=`MissingEnvValue`,e[e.FileApiUnsupported=306]=`FileApiUnsupported`,e[e.NoSourceBound=307]=`NoSourceBound`,e[e.InvalidMergedSource=308]=`InvalidMergedSource`,e}({});var t=class extends Error{code;issues;constructor(e,t,n){super(t,n?.cause===void 0?void 0:{cause:n.cause}),this.name=`EnvaptError [${e}]`,this.code=e,this.issues=n?.issues}};export{t as EnvaptError,e as EnvaptErrorCodes};
|
|
2
2
|
//# sourceMappingURL=Error.mjs.map
|
|
@@ -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\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,
|
|
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 /** Thrown when `merge` is called with no members, or with more than one filesystem-backed source */\n InvalidMergedSource = 308\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,gBAEA,EAAA,EAAA,oBAAA,KAAA,uBACJ,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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e,t){if(t===void 0)return e;let n=e.split(`_`).filter(e=>e.length>0);if(t===`kebab-case`)return n.map(e=>e.toLowerCase()).join(`-`);let r=n.map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``);return t===`PascalCase`?r:r.charAt(0).toLowerCase()+r.slice(1)}exports.recase=e;
|
|
2
|
+
//# sourceMappingURL=recase.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recase.cjs","names":[],"sources":["../../../src/infra/recase.ts"],"sourcesContent":["import type { KeyCasing } from '../types';\n\n// underscore-delimited words, kept in step with the RecaseKey type transforms in types/Casing.ts.\nexport function recase(name: string, casing?: KeyCasing): string {\n if (casing === undefined) return name;\n const words = name.split('_').filter((word) => word.length > 0);\n if (casing === 'kebab-case') return words.map((word) => word.toLowerCase()).join('-');\n const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join('');\n return casing === 'PascalCase' ? pascal : pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n"],"mappings":"AAGA,SAAgB,EAAO,EAAc,EAA4B,CAC7D,GAAI,IAAW,IAAA,GAAW,OAAO,EACjC,IAAM,EAAQ,EAAK,MAAM,GAAG,CAAC,CAAC,OAAQ,GAAS,EAAK,OAAS,CAAC,EAC9D,GAAI,IAAW,aAAc,OAAO,EAAM,IAAK,GAAS,EAAK,YAAY,CAAC,CAAC,CAAC,KAAK,GAAG,EACpF,IAAM,EAAS,EAAM,IAAK,GAAS,EAAK,OAAO,CAAC,CAAC,CAAC,YAAY,EAAI,EAAK,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,EAAE,EACtG,OAAO,IAAW,aAAe,EAAS,EAAO,OAAO,CAAC,CAAC,CAAC,YAAY,EAAI,EAAO,MAAM,CAAC,CAC7F"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e,t){if(t===void 0)return e;let n=e.split(`_`).filter(e=>e.length>0);if(t===`kebab-case`)return n.map(e=>e.toLowerCase()).join(`-`);let r=n.map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(``);return t===`PascalCase`?r:r.charAt(0).toLowerCase()+r.slice(1)}export{e as recase};
|
|
2
|
+
//# sourceMappingURL=recase.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recase.mjs","names":[],"sources":["../../../src/infra/recase.ts"],"sourcesContent":["import type { KeyCasing } from '../types';\n\n// underscore-delimited words, kept in step with the RecaseKey type transforms in types/Casing.ts.\nexport function recase(name: string, casing?: KeyCasing): string {\n if (casing === undefined) return name;\n const words = name.split('_').filter((word) => word.length > 0);\n if (casing === 'kebab-case') return words.map((word) => word.toLowerCase()).join('-');\n const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join('');\n return casing === 'PascalCase' ? pascal : pascal.charAt(0).toLowerCase() + pascal.slice(1);\n}\n"],"mappings":"AAGA,SAAgB,EAAO,EAAc,EAA4B,CAC7D,GAAI,IAAW,IAAA,GAAW,OAAO,EACjC,IAAM,EAAQ,EAAK,MAAM,GAAG,CAAC,CAAC,OAAQ,GAAS,EAAK,OAAS,CAAC,EAC9D,GAAI,IAAW,aAAc,OAAO,EAAM,IAAK,GAAS,EAAK,YAAY,CAAC,CAAC,CAAC,KAAK,GAAG,EACpF,IAAM,EAAS,EAAM,IAAK,GAAS,EAAK,OAAO,CAAC,CAAC,CAAC,YAAY,EAAI,EAAK,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,EAAE,EACtG,OAAO,IAAW,aAAe,EAAS,EAAO,OAAO,CAAC,CAAC,CAAC,YAAY,EAAI,EAAO,MAAM,CAAC,CAC7F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.cjs","names":[],"sources":["../../../src/infra/runtime.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"runtime.cjs","names":[],"sources":["../../../src/infra/runtime.ts"],"sourcesContent":["import type { Source } from '../types';\n\n// importing Debug back into EnvapterBase would cycle, so the source and sink are injected via the setters below.\n/* v8 ignore start -- @preserve replaced at load on Node, so the Node suite never runs these defaults */\nlet sink: (line: string) => void = (line) => {\n // eslint-disable-next-line no-console -- the off-Node fallback log sink\n console.error(line);\n};\nlet envReader: () => Record<string, string> = () => ({});\n/* v8 ignore stop */\n\nexport function setRuntimeSink(fn: (line: string) => void): void {\n sink = fn;\n}\n\nexport function writeRuntimeLine(line: string): void {\n sink(line);\n}\n\nexport function readRuntimeEnv(): Record<string, string> {\n return envReader();\n}\n\nexport function bindRuntimeFromSource(source: Source): void {\n envReader = (): Record<string, string> => source.readVars();\n}\n"],"mappings":"AAIA,IAAI,EAAgC,GAAS,CAEzC,QAAQ,MAAM,CAAI,CACtB,EACI,OAAiD,CAAC,GAGtD,SAAgB,EAAe,EAAkC,CAC7D,EAAO,CACX,CAEA,SAAgB,EAAiB,EAAoB,CACjD,EAAK,CAAI,CACb,CAEA,SAAgB,GAAyC,CACrD,OAAO,EAAU,CACrB,CAEA,SAAgB,EAAsB,EAAsB,CACxD,MAA0C,EAAO,SAAS,CAC9D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","names":[],"sources":["../../../src/infra/runtime.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"runtime.mjs","names":[],"sources":["../../../src/infra/runtime.ts"],"sourcesContent":["import type { Source } from '../types';\n\n// importing Debug back into EnvapterBase would cycle, so the source and sink are injected via the setters below.\n/* v8 ignore start -- @preserve replaced at load on Node, so the Node suite never runs these defaults */\nlet sink: (line: string) => void = (line) => {\n // eslint-disable-next-line no-console -- the off-Node fallback log sink\n console.error(line);\n};\nlet envReader: () => Record<string, string> = () => ({});\n/* v8 ignore stop */\n\nexport function setRuntimeSink(fn: (line: string) => void): void {\n sink = fn;\n}\n\nexport function writeRuntimeLine(line: string): void {\n sink(line);\n}\n\nexport function readRuntimeEnv(): Record<string, string> {\n return envReader();\n}\n\nexport function bindRuntimeFromSource(source: Source): void {\n envReader = (): Record<string, string> => source.readVars();\n}\n"],"mappings":"AAIA,IAAI,EAAgC,GAAS,CAEzC,QAAQ,MAAM,CAAI,CACtB,EACI,OAAiD,CAAC,GAGtD,SAAgB,EAAe,EAAkC,CAC7D,EAAO,CACX,CAEA,SAAgB,EAAiB,EAAoB,CACjD,EAAK,CAAI,CACb,CAEA,SAAgB,GAAyC,CACrD,OAAO,EAAU,CACrB,CAEA,SAAgB,EAAsB,EAAsB,CACxD,MAA0C,EAAO,SAAS,CAC9D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("node:process");t=e.__toESM(t,1);let n=require("node:fs");n=e.__toESM(n,1);let r=require("node:path"),i=require("node:url");var a=class{supportsFiles=!0;readVars(){return{...t.default.env}}readFile(e,t){try{return n.default.readFileSync(e,t)}catch{return}}normalizeBaseDir(e){return e instanceof URL||e.startsWith(`file:`)?(0,r.dirname)((0,i.fileURLToPath)(e)):(0,r.resolve)(e)}resolvePath(e,t){return(0,r.isAbsolute)(t)?t:(0,r.join)(e,t)}writeVars(e){for(let[n,r]of Object.entries(e))t.default.env[n]=r}};exports.
|
|
2
|
-
//# sourceMappingURL=
|
|
1
|
+
const e=require("../_virtual/_rolldown/runtime.cjs");let t=require("node:process");t=e.__toESM(t,1);let n=require("node:fs");n=e.__toESM(n,1);let r=require("node:path"),i=require("node:url");var a=class{supportsFiles=!0;readVars(){return{...t.default.env}}readFile(e,t){try{return n.default.readFileSync(e,t)}catch{return}}normalizeBaseDir(e){return e instanceof URL||e.startsWith(`file:`)?(0,r.dirname)((0,i.fileURLToPath)(e)):(0,r.resolve)(e)}resolvePath(e,t){return(0,r.isAbsolute)(t)?t:(0,r.join)(e,t)}writeVars(e){for(let[n,r]of Object.entries(e))t.default.env[n]=r}};exports.FileSource=a;
|
|
2
|
+
//# sourceMappingURL=FileSource.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FileSource.cjs","names":["process","fs"],"sources":["../../../src/sources/FileSource.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport process from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\nimport type { FileCapableSource } from '../types';\n\n/**\n * Default environment source on Node, Bun, and Deno: a snapshot of `process.env`. Its\n * `supportsFiles` is `true`, so the engine also layers the `.env` cascade on top, resolves\n * `baseDir`, and can mirror loaded keys back to `process.env`.\n * @public\n */\nexport class FileSource implements FileCapableSource {\n /** Always `true`. The engine layers the `.env` cascade and `baseDir` on top of `process.env`. */\n readonly supportsFiles = true;\n\n /** Returns a snapshot clone of `process.env` as plain strings. */\n readVars(): Record<string, string> {\n // Clone so the loader and downstream reads never mutate process.env.\n return { ...(process.env as Record<string, string>) };\n }\n\n /** Reads a file with `fs.readFileSync`, or `undefined` when it is missing or unreadable. */\n readFile(path: string, encoding: string): string | undefined {\n try {\n // justified: our public encoding type is `string`; fs needs the BufferEncoding subset.\n return fs.readFileSync(path, encoding as BufferEncoding);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Resolves a directory path or a module / `file:` URL to an absolute directory. A `file:` URL\n * resolves to its containing directory, and a plain path (`import.meta.dirname`, `__dirname`) is\n * taken as the directory itself.\n */\n normalizeBaseDir(value: string | URL): string {\n if (value instanceof URL) return dirname(fileURLToPath(value));\n if (value.startsWith('file:')) return dirname(fileURLToPath(value));\n return resolve(value);\n }\n\n /** Joins a relative `.env` path onto `baseDir`. Absolute paths pass through unchanged. */\n resolvePath(baseDir: string, candidate: string): string {\n if (isAbsolute(candidate)) return candidate;\n return join(baseDir, candidate);\n }\n\n /** Writes each key to `process.env`, backing `Envapter.syncProcessEnv`. */\n writeVars(vars: Record<string, string>): void {\n for (const [key, value] of Object.entries(vars)) {\n process.env[key] = value;\n }\n }\n}\n"],"mappings":"+LAaA,IAAa,EAAb,KAAqD,CAEjD,cAAyB,GAGzB,UAAmC,CAE/B,MAAO,CAAE,GAAIA,EAAAA,QAAQ,GAA+B,CACxD,CAGA,SAAS,EAAc,EAAsC,CACzD,GAAI,CAEA,OAAOC,EAAAA,QAAG,aAAa,EAAM,CAA0B,CAC3D,MAAQ,CACJ,MACJ,CACJ,CAOA,iBAAiB,EAA6B,CAG1C,OAFI,aAAiB,KACjB,EAAM,WAAW,OAAO,GAAG,EAAA,EAAA,QAAA,EAAA,EAAA,EAAA,cAAA,CAA6B,CAAK,CAAC,GAClE,EAAA,EAAA,QAAA,CAAe,CAAK,CACxB,CAGA,YAAY,EAAiB,EAA2B,CAEpD,OADA,EAAA,EAAA,WAAA,CAAe,CAAS,EAAU,GAClC,EAAA,EAAA,KAAA,CAAY,EAAS,CAAS,CAClC,CAGA,UAAU,EAAoC,CAC1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAI,EAC1C,EAAA,QAAQ,IAAI,GAAO,CAE3B,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"node:process";import t from"node:fs";import{dirname as n,isAbsolute as r,join as i,resolve as a}from"node:path";import{fileURLToPath as o}from"node:url";var s=class{supportsFiles=!0;readVars(){return{...e.env}}readFile(e,n){try{return t.readFileSync(e,n)}catch{return}}normalizeBaseDir(e){return e instanceof URL||e.startsWith(`file:`)?n(o(e)):a(e)}resolvePath(e,t){return r(t)?t:i(e,t)}writeVars(t){for(let[n,r]of Object.entries(t))e.env[n]=r}};export{s as
|
|
2
|
-
//# sourceMappingURL=
|
|
1
|
+
import e from"node:process";import t from"node:fs";import{dirname as n,isAbsolute as r,join as i,resolve as a}from"node:path";import{fileURLToPath as o}from"node:url";var s=class{supportsFiles=!0;readVars(){return{...e.env}}readFile(e,n){try{return t.readFileSync(e,n)}catch{return}}normalizeBaseDir(e){return e instanceof URL||e.startsWith(`file:`)?n(o(e)):a(e)}resolvePath(e,t){return r(t)?t:i(e,t)}writeVars(t){for(let[n,r]of Object.entries(t))e.env[n]=r}};export{s as FileSource};
|
|
2
|
+
//# sourceMappingURL=FileSource.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FileSource.mjs","names":[],"sources":["../../../src/sources/FileSource.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport process from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\nimport type { FileCapableSource } from '../types';\n\n/**\n * Default environment source on Node, Bun, and Deno: a snapshot of `process.env`. Its\n * `supportsFiles` is `true`, so the engine also layers the `.env` cascade on top, resolves\n * `baseDir`, and can mirror loaded keys back to `process.env`.\n * @public\n */\nexport class FileSource implements FileCapableSource {\n /** Always `true`. The engine layers the `.env` cascade and `baseDir` on top of `process.env`. */\n readonly supportsFiles = true;\n\n /** Returns a snapshot clone of `process.env` as plain strings. */\n readVars(): Record<string, string> {\n // Clone so the loader and downstream reads never mutate process.env.\n return { ...(process.env as Record<string, string>) };\n }\n\n /** Reads a file with `fs.readFileSync`, or `undefined` when it is missing or unreadable. */\n readFile(path: string, encoding: string): string | undefined {\n try {\n // justified: our public encoding type is `string`; fs needs the BufferEncoding subset.\n return fs.readFileSync(path, encoding as BufferEncoding);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Resolves a directory path or a module / `file:` URL to an absolute directory. A `file:` URL\n * resolves to its containing directory, and a plain path (`import.meta.dirname`, `__dirname`) is\n * taken as the directory itself.\n */\n normalizeBaseDir(value: string | URL): string {\n if (value instanceof URL) return dirname(fileURLToPath(value));\n if (value.startsWith('file:')) return dirname(fileURLToPath(value));\n return resolve(value);\n }\n\n /** Joins a relative `.env` path onto `baseDir`. Absolute paths pass through unchanged. */\n resolvePath(baseDir: string, candidate: string): string {\n if (isAbsolute(candidate)) return candidate;\n return join(baseDir, candidate);\n }\n\n /** Writes each key to `process.env`, backing `Envapter.syncProcessEnv`. */\n writeVars(vars: Record<string, string>): void {\n for (const [key, value] of Object.entries(vars)) {\n process.env[key] = value;\n }\n }\n}\n"],"mappings":"uKAaA,IAAa,EAAb,KAAqD,CAEjD,cAAyB,GAGzB,UAAmC,CAE/B,MAAO,CAAE,GAAI,EAAQ,GAA+B,CACxD,CAGA,SAAS,EAAc,EAAsC,CACzD,GAAI,CAEA,OAAO,EAAG,aAAa,EAAM,CAA0B,CAC3D,MAAQ,CACJ,MACJ,CACJ,CAOA,iBAAiB,EAA6B,CAG1C,OAFI,aAAiB,KACjB,EAAM,WAAW,OAAO,EAAU,EAAQ,EAAc,CAAK,CAAC,EAC3D,EAAQ,CAAK,CACxB,CAGA,YAAY,EAAiB,EAA2B,CAEpD,OADI,EAAW,CAAS,EAAU,EAC3B,EAAK,EAAS,CAAS,CAClC,CAGA,UAAU,EAAoC,CAC1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAI,EAC1C,EAAQ,IAAI,GAAO,CAE3B,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./coerce.cjs");var t=class{supportsFiles=!1;vars;constructor(t){this.vars=e.coerceToStringRecord(t)}readVars(){return{...this.vars}}};exports.
|
|
2
|
-
//# sourceMappingURL=
|
|
1
|
+
const e=require("./coerce.cjs");var t=class{supportsFiles=!1;vars;constructor(t){this.vars=e.coerceToStringRecord(t)}readVars(){return{...this.vars}}};exports.PortableSource=t;
|
|
2
|
+
//# sourceMappingURL=PortableSource.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PortableSource.cjs","names":["coerceToStringRecord"],"sources":["../../../src/sources/PortableSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareSource } from '../types';\n\n/**\n * Environment source seeded from an object you provide, for every runtime without a filesystem. The\n * config your bundler injects into a browser build (Vite's `import.meta.env`, a webpack `DefinePlugin`\n * global), the Cloudflare `env` binding, a Vercel Edge or Fastly config object, a test fixture, or any\n * plain object. Pass it straight through. Non-string values are JSON-stringified so the converters\n * still apply, which means they must be JSON-serializable. Without a filesystem the `.env` cascade and\n * file APIs do not apply.\n * @public\n */\nexport class PortableSource implements BareSource {\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: object) {\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":"gCAaA,IAAa,EAAb,KAAkD,CAE9C,cAAyB,GACzB,KAGA,YAAY,EAAc,CACtB,KAAK,KAAOA,EAAAA,qBAAqB,CAAI,CACzC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{coerceToStringRecord as e}from"./coerce.mjs";var t=class{supportsFiles=!1;vars;constructor(t){this.vars=e(t)}readVars(){return{...this.vars}}};export{t as
|
|
2
|
-
//# sourceMappingURL=
|
|
1
|
+
import{coerceToStringRecord as e}from"./coerce.mjs";var t=class{supportsFiles=!1;vars;constructor(t){this.vars=e(t)}readVars(){return{...this.vars}}};export{t as PortableSource};
|
|
2
|
+
//# sourceMappingURL=PortableSource.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PortableSource.mjs","names":[],"sources":["../../../src/sources/PortableSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareSource } from '../types';\n\n/**\n * Environment source seeded from an object you provide, for every runtime without a filesystem. The\n * config your bundler injects into a browser build (Vite's `import.meta.env`, a webpack `DefinePlugin`\n * global), the Cloudflare `env` binding, a Vercel Edge or Fastly config object, a test fixture, or any\n * plain object. Pass it straight through. Non-string values are JSON-stringified so the converters\n * still apply, which means they must be JSON-serializable. Without a filesystem the `.env` cascade and\n * file APIs do not apply.\n * @public\n */\nexport class PortableSource implements BareSource {\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: object) {\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":"oDAaA,IAAa,EAAb,KAAkD,CAE9C,cAAyB,GACzB,KAGA,YAAY,EAAc,CACtB,KAAK,KAAO,EAAqB,CAAI,CACzC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../infra/Error.cjs");var t=class{supportsFiles=!1;readVars(){throw new e.EnvaptError(307,`No environment source is bound. Call Envapter.useSource(...) with a source such as new
|
|
2
|
-
//# sourceMappingURL=
|
|
1
|
+
const e=require("../infra/Error.cjs");var t=class{supportsFiles=!1;readVars(){throw new e.EnvaptError(307,`No environment source is bound. Call Envapter.useSource(...) with a source such as new PortableSource({...}) before reading.`)}};exports.UnboundSource=t;
|
|
2
|
+
//# sourceMappingURL=UnboundSource.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"UnboundSource.cjs","names":["EnvaptError"],"sources":["../../../src/sources/UnboundSource.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { BareSource } from '../types';\n\n/**\n * The default source until one is bound. Every read throws NoSourceBound so a forgotten `useSource`\n * surfaces at read time instead of silently yielding nothing. The Node entry binds {@link FileSource}\n * at load, browser and Workers bundles must call `Envapter.useSource(...)` before reading.\n * @internal\n */\nexport class UnboundSource implements BareSource {\n readonly supportsFiles = false;\n\n readVars(): Record<string, string> {\n throw new EnvaptError(\n EnvaptErrorCodes.NoSourceBound,\n 'No environment source is bound. Call Envapter.useSource(...) with a source such as new PortableSource({...}) before reading.'\n );\n }\n}\n"],"mappings":"sCAUA,IAAa,EAAb,KAAiD,CAC7C,cAAyB,GAEzB,UAAmC,CAC/B,MAAM,IAAIA,EAAAA,YAAAA,IAEN,8HACJ,CACJ,CACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";var t=class{supportsFiles=!1;readVars(){throw new e(307,`No environment source is bound. Call Envapter.useSource(...) with a source such as new
|
|
2
|
-
//# sourceMappingURL=
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";var t=class{supportsFiles=!1;readVars(){throw new e(307,`No environment source is bound. Call Envapter.useSource(...) with a source such as new PortableSource({...}) before reading.`)}};export{t as UnboundSource};
|
|
2
|
+
//# sourceMappingURL=UnboundSource.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"UnboundSource.mjs","names":[],"sources":["../../../src/sources/UnboundSource.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { BareSource } from '../types';\n\n/**\n * The default source until one is bound. Every read throws NoSourceBound so a forgotten `useSource`\n * surfaces at read time instead of silently yielding nothing. The Node entry binds {@link FileSource}\n * at load, browser and Workers bundles must call `Envapter.useSource(...)` before reading.\n * @internal\n */\nexport class UnboundSource implements BareSource {\n readonly supportsFiles = false;\n\n readVars(): Record<string, string> {\n throw new EnvaptError(\n EnvaptErrorCodes.NoSourceBound,\n 'No environment source is bound. Call Envapter.useSource(...) with a source such as new PortableSource({...}) before reading.'\n );\n }\n}\n"],"mappings":"iDAUA,IAAa,EAAb,KAAiD,CAC7C,cAAyB,GAEzB,UAAmC,CAC/B,MAAM,IAAI,EAAA,IAEN,8HACJ,CACJ,CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coerce.cjs","names":[],"sources":["../../../src/sources/coerce.ts"],"sourcesContent":["//
|
|
1
|
+
{"version":3,"file":"coerce.cjs","names":[],"sources":["../../../src/sources/coerce.ts"],"sourcesContent":["// The returned record is fresh, so a caller mutating its object\n// later cannot leak into the source, and non-string values are JSON-stringified.\nexport function coerceToStringRecord(env: object): Record<string, string> {\n const snapshot: Record<string, string> = {};\n // `object` so a Cloudflare `Env` (an interface with no index signature) is accepted. cast to a record\n // to read entries as `unknown` rather than `any`.\n for (const [key, value] of Object.entries(env as Record<string, unknown>)) {\n if (typeof value === 'string') {\n snapshot[key] = value;\n continue;\n }\n const encoded = JSON.stringify(value);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- TS lib mistypes JSON.stringify's return as always-string when it is string | undefined at runtime\n if (encoded !== undefined) snapshot[key] = encoded;\n }\n return snapshot;\n}\n"],"mappings":"AAEA,SAAgB,EAAqB,EAAqC,CACtE,IAAM,EAAmC,CAAC,EAG1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAA8B,EAAG,CACvE,GAAI,OAAO,GAAU,SAAU,CAC3B,EAAS,GAAO,EAChB,QACJ,CACA,IAAM,EAAU,KAAK,UAAU,CAAK,EAEhC,IAAY,IAAA,KAAW,EAAS,GAAO,EAC/C,CACA,OAAO,CACX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coerce.mjs","names":[],"sources":["../../../src/sources/coerce.ts"],"sourcesContent":["//
|
|
1
|
+
{"version":3,"file":"coerce.mjs","names":[],"sources":["../../../src/sources/coerce.ts"],"sourcesContent":["// The returned record is fresh, so a caller mutating its object\n// later cannot leak into the source, and non-string values are JSON-stringified.\nexport function coerceToStringRecord(env: object): Record<string, string> {\n const snapshot: Record<string, string> = {};\n // `object` so a Cloudflare `Env` (an interface with no index signature) is accepted. cast to a record\n // to read entries as `unknown` rather than `any`.\n for (const [key, value] of Object.entries(env as Record<string, unknown>)) {\n if (typeof value === 'string') {\n snapshot[key] = value;\n continue;\n }\n const encoded = JSON.stringify(value);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- TS lib mistypes JSON.stringify's return as always-string when it is string | undefined at runtime\n if (encoded !== undefined) snapshot[key] = encoded;\n }\n return snapshot;\n}\n"],"mappings":"AAEA,SAAgB,EAAqB,EAAqC,CACtE,IAAM,EAAmC,CAAC,EAG1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAA8B,EAAG,CACvE,GAAI,OAAO,GAAU,SAAU,CAC3B,EAAS,GAAO,EAChB,QACJ,CACA,IAAM,EAAU,KAAK,UAAU,CAAK,EAEhC,IAAY,IAAA,KAAW,EAAS,GAAO,EAC/C,CACA,OAAO,CACX"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../infra/Error.cjs");function t(...t){if(t.length===0)throw new e.EnvaptError(308,`merge requires at least one source.`);let n=t.filter(e=>e.supportsFiles===!0);if(n.length>1)throw new e.EnvaptError(308,`merge accepts at most one filesystem-backed source, so the .env cascade and file APIs route to a single member.`);let r=()=>{let e={};for(let n of t)Object.assign(e,n.readVars());return e},i=n[0];return i?{readVars:r,supportsFiles:!0,readFile:(e,t)=>i.readFile(e,t),resolvePath:(e,t)=>i.resolvePath(e,t),normalizeBaseDir:e=>i.normalizeBaseDir(e),writeVars:e=>i.writeVars(e)}:{readVars:r}}exports.merge=t;
|
|
2
|
+
//# sourceMappingURL=merge.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"merge.cjs","names":["EnvaptError"],"sources":["../../../src/sources/merge.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { FileCapableSource, Source } from '../types';\n\n/**\n * Compose several sources into one, read last-wins. A later member's value overrides an earlier\n * member's value for the same key. Bind the result with `Envapter.useSource`. Throws\n * {@link EnvaptErrorCodes.InvalidMergedSource} with no members or with more than one file-backed member.\n * @public\n */\nexport function merge(...members: Source[]): Source {\n if (members.length === 0) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidMergedSource, 'merge requires at least one source.');\n }\n\n const fileMembers = members.filter((m): m is FileCapableSource => m.supportsFiles === true);\n if (fileMembers.length > 1) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidMergedSource,\n 'merge accepts at most one filesystem-backed source, so the .env cascade and file APIs route to a single member.'\n );\n }\n\n const readVars = (): Record<string, string> => {\n const merged: Record<string, string> = {};\n for (const m of members) Object.assign(merged, m.readVars());\n return merged;\n };\n\n const fileMember = fileMembers[0];\n if (!fileMember) return { readVars };\n\n const fileCapable: FileCapableSource = {\n readVars,\n supportsFiles: true,\n readFile: (path, encoding) => fileMember.readFile(path, encoding),\n resolvePath: (baseDir, candidate) => fileMember.resolvePath(baseDir, candidate),\n normalizeBaseDir: (value) => fileMember.normalizeBaseDir(value),\n writeVars: (vars) => fileMember.writeVars(vars)\n };\n return fileCapable;\n}\n"],"mappings":"sCAUA,SAAgB,EAAM,GAAG,EAA2B,CAChD,GAAI,EAAQ,SAAW,EACnB,MAAM,IAAIA,EAAAA,YAAAA,IAAkD,qCAAqC,EAGrG,IAAM,EAAc,EAAQ,OAAQ,GAA8B,EAAE,gBAAkB,EAAI,EAC1F,GAAI,EAAY,OAAS,EACrB,MAAM,IAAIA,EAAAA,YAAAA,IAEN,iHACJ,EAGJ,IAAM,MAAyC,CAC3C,IAAM,EAAiC,CAAC,EACxC,IAAK,IAAM,KAAK,EAAS,OAAO,OAAO,EAAQ,EAAE,SAAS,CAAC,EAC3D,OAAO,CACX,EAEM,EAAa,EAAY,GAW/B,OAVK,EAUE,CAPH,WACA,cAAe,GACf,UAAW,EAAM,IAAa,EAAW,SAAS,EAAM,CAAQ,EAChE,aAAc,EAAS,IAAc,EAAW,YAAY,EAAS,CAAS,EAC9E,iBAAmB,GAAU,EAAW,iBAAiB,CAAK,EAC9D,UAAY,GAAS,EAAW,UAAU,CAAI,CAEjC,EAVO,CAAE,UAAS,CAWvC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";function t(...t){if(t.length===0)throw new e(308,`merge requires at least one source.`);let n=t.filter(e=>e.supportsFiles===!0);if(n.length>1)throw new e(308,`merge accepts at most one filesystem-backed source, so the .env cascade and file APIs route to a single member.`);let r=()=>{let e={};for(let n of t)Object.assign(e,n.readVars());return e},i=n[0];return i?{readVars:r,supportsFiles:!0,readFile:(e,t)=>i.readFile(e,t),resolvePath:(e,t)=>i.resolvePath(e,t),normalizeBaseDir:e=>i.normalizeBaseDir(e),writeVars:e=>i.writeVars(e)}:{readVars:r}}export{t as merge};
|
|
2
|
+
//# sourceMappingURL=merge.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"merge.mjs","names":[],"sources":["../../../src/sources/merge.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { FileCapableSource, Source } from '../types';\n\n/**\n * Compose several sources into one, read last-wins. A later member's value overrides an earlier\n * member's value for the same key. Bind the result with `Envapter.useSource`. Throws\n * {@link EnvaptErrorCodes.InvalidMergedSource} with no members or with more than one file-backed member.\n * @public\n */\nexport function merge(...members: Source[]): Source {\n if (members.length === 0) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidMergedSource, 'merge requires at least one source.');\n }\n\n const fileMembers = members.filter((m): m is FileCapableSource => m.supportsFiles === true);\n if (fileMembers.length > 1) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidMergedSource,\n 'merge accepts at most one filesystem-backed source, so the .env cascade and file APIs route to a single member.'\n );\n }\n\n const readVars = (): Record<string, string> => {\n const merged: Record<string, string> = {};\n for (const m of members) Object.assign(merged, m.readVars());\n return merged;\n };\n\n const fileMember = fileMembers[0];\n if (!fileMember) return { readVars };\n\n const fileCapable: FileCapableSource = {\n readVars,\n supportsFiles: true,\n readFile: (path, encoding) => fileMember.readFile(path, encoding),\n resolvePath: (baseDir, candidate) => fileMember.resolvePath(baseDir, candidate),\n normalizeBaseDir: (value) => fileMember.normalizeBaseDir(value),\n writeVars: (vars) => fileMember.writeVars(vars)\n };\n return fileCapable;\n}\n"],"mappings":"iDAUA,SAAgB,EAAM,GAAG,EAA2B,CAChD,GAAI,EAAQ,SAAW,EACnB,MAAM,IAAI,EAAA,IAAkD,qCAAqC,EAGrG,IAAM,EAAc,EAAQ,OAAQ,GAA8B,EAAE,gBAAkB,EAAI,EAC1F,GAAI,EAAY,OAAS,EACrB,MAAM,IAAI,EAAA,IAEN,iHACJ,EAGJ,IAAM,MAAyC,CAC3C,IAAM,EAAiC,CAAC,EACxC,IAAK,IAAM,KAAK,EAAS,OAAO,OAAO,EAAQ,EAAE,SAAS,CAAC,EAC3D,OAAO,CACX,EAEM,EAAa,EAAY,GAW/B,OAVK,EAUE,CAPH,WACA,cAAe,GACf,UAAW,EAAM,IAAa,EAAW,SAAS,EAAM,CAAQ,EAChE,aAAc,EAAS,IAAc,EAAW,YAAY,EAAS,CAAS,EAC9E,iBAAmB,GAAU,EAAW,iBAAiB,CAAK,EAC9D,UAAY,GAAS,EAAW,UAAU,CAAI,CAEjC,EAVO,CAAE,UAAS,CAWvC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";const t=1e3,n=60*t,r=60*n,i=24*r,a={ms:1,s:t,m:n,h:r,d:i,w:7*i},o=new RegExp(String.raw`^(\d+(?:\.\d+)?)(ms|s|m|h|d|w)?$`,`u`),s=new RegExp(String.raw`^(\d+(?:\.\d+)?)(ms|s|m|h|d|w)$`,`u`);function c(e,t=!1){let n=e.match(t?s:o);if(!n)return;let[,r,i]=n;if(!r)return;let c=Number.parseFloat(r);if(!Number.isNaN(c))return c*a[i??`ms`]}var l=class t{static string(e,t){return String(e)}static number(e,t){let n=Number(e);return Number.isNaN(n)?t:n}static boolean(e,t){let n=e.toLowerCase().trim();return[`1`,`yes`,`true`,`on`].includes(n)?!0:[`0`,`no`,`false`,`off`].includes(n)?!1:t}static bigint(e,t){try{return BigInt(e)}catch{return t}}static symbol(e,t){try{return e?Symbol.for(e):t}catch{return t}}static integer(e,t){let n=e.trim();if(n===``)return t;let r=Number(n);return Number.isSafeInteger(r)?r:t}static float(e,t){let n=e.trim();if(n===``)return t;let r=Number(n);return Number.isNaN(r)?t:r}static json(e,t){try{return JSON.parse(e)}catch{return t}}static url(e,t){try{return new URL(e)}catch{return t}}static regexp(e,t){try{let t=e.match(new RegExp(String.raw`^\/(.+)\/([gimsuvy]*)$`));return t?new RegExp(t[1],t[2]):new RegExp(e)}catch{return t}}static date(e,t){if(new RegExp(String.raw`^\d+$`).test(e)){let n=new Date(parseInt(e,10));return Number.isNaN(n.getTime())?t:n}if(!new RegExp(String.raw`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$`,`u`).test(e))return t;let n=new Date(e);return Number.isNaN(n.getTime())?t:n}static time(t,n){let r=c(t);if(r!==void 0)return r;if(typeof n==`number`)return n;if(typeof n==`string`){let t=c(n,!0);if(t===void 0)throw new e(105,`Time-string fallback "${n}" is not a valid format. Expected <number><unit> where unit is one of: ms, s, m, h, d, w.`);return t}}static processArrayConverter(n,r,i=!1){if(n.trim()===``)return[];let a=n.split(r.delimiter).map(e=>String(e).trim());if(i){let t=a.findIndex(e=>e===``);if(t!==-1)throw new e(207,`Array element at index ${t} is empty or whitespace only (strict mode).`)}let o=a.filter(Boolean);if(!o.length)return[];let s=r.of;if(typeof s==`function`)return o.map((t,n)=>{let r=s(t);if(r===void 0)throw new e(206,`Custom element converter returned undefined for item "${t}" at index ${n}.`);return r});let c=t.getConverter(s);return o.map((t,n)=>{let r=c(t,void 0);if(r===void 0)throw new e(206,`Element "${t}" at index ${n} could not be converted to ${s}.`);return r})}static getConverter(e){return{string:t.string,number:t.number,boolean:t.boolean,integer:t.integer,bigint:t.bigint,symbol:t.symbol,float:t.float,json:t.json,url:t.url,regexp:t.regexp,date:t.date,time:t.time}[e]}};export{l as BuiltInConverters};
|
|
2
|
+
//# sourceMappingURL=BuiltInConverters.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BuiltInConverters.mjs","names":["converter"],"sources":["../../../src/converters/BuiltInConverters.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\n\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf, CustomElementConverter } from './Converters';\nimport type {\n BuiltInConverter,\n BuiltInConverterFunction,\n JsonValue,\n MapOfConverterFunctions,\n TimeFallback,\n TimeUnit\n} from '../types';\n\nconst MS_PER_SECOND = 1000;\nconst SECONDS_PER_MINUTE = 60;\nconst MINUTES_PER_HOUR = 60;\nconst HOURS_PER_DAY = 24;\nconst DAYS_PER_WEEK = 7;\nconst MS_PER_MINUTE = SECONDS_PER_MINUTE * MS_PER_SECOND;\nconst MS_PER_HOUR = MINUTES_PER_HOUR * MS_PER_MINUTE;\nconst MS_PER_DAY = HOURS_PER_DAY * MS_PER_HOUR;\nconst MS_PER_WEEK = DAYS_PER_WEEK * MS_PER_DAY;\n\nconst TIME_UNIT_MS: Record<TimeUnit, number> = {\n ms: 1,\n s: MS_PER_SECOND,\n m: MS_PER_MINUTE,\n h: MS_PER_HOUR,\n d: MS_PER_DAY,\n w: MS_PER_WEEK\n};\n\nconst TIME_LOOSE_RE = new RegExp(String.raw`^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)?$`, 'u');\nconst TIME_STRICT_RE = new RegExp(String.raw`^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)$`, 'u');\n\n/**\n * Parse a time string (e.g. `\"30s\"`, `\"1.5h\"`) into milliseconds.\n *\n * @param input - The string to parse.\n * @param strict - When `true`, require an explicit unit (used for fallback strings).\n * When `false` (default), treat a missing unit as `ms` (used for raw env values). Both allow decimals.\n * @returns The duration in milliseconds, or `undefined` if the input does not match the expected format.\n * @internal\n */\nfunction parseTimeString(input: string, strict = false): number | undefined {\n const match = input.match(strict ? TIME_STRICT_RE : TIME_LOOSE_RE);\n if (!match) return undefined;\n\n const [, numStr, capturedUnit] = match;\n if (!numStr) return undefined;\n\n const value = Number.parseFloat(numStr);\n if (Number.isNaN(value)) return undefined;\n\n const unit = (capturedUnit ?? 'ms') as TimeUnit;\n return value * TIME_UNIT_MS[unit];\n}\n\n/**\n * Built-in converter implementations\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- dispatch-table helper, the documented exception to the no-static-class rule\nexport class BuiltInConverters {\n static string(raw: string, _fallback?: string): string | undefined {\n return String(raw);\n }\n\n static number(raw: string, fallback?: number): number | undefined {\n const parsed = Number(raw);\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static boolean(raw: string, fallback?: boolean): boolean | undefined {\n const lower = raw.toLowerCase().trim();\n\n const truthyValues = ['1', 'yes', 'true', 'on'];\n const falsyValues = ['0', 'no', 'false', 'off'];\n\n if (truthyValues.includes(lower)) return true;\n if (falsyValues.includes(lower)) return false;\n return fallback;\n }\n\n static bigint(raw: string, fallback?: bigint): bigint | undefined {\n try {\n return BigInt(raw);\n } catch {\n return fallback;\n }\n }\n\n static symbol(raw: string, fallback?: symbol): symbol | undefined {\n try {\n return raw ? Symbol.for(raw) : fallback;\n } catch {\n return fallback;\n }\n }\n\n static integer(raw: string, fallback?: number): number | undefined {\n const trimmed = raw.trim();\n if (trimmed === '') return fallback;\n const parsed = Number(trimmed);\n // isSafeInteger also guards the 2^53 boundary, past which an integer value silently loses precision.\n return Number.isSafeInteger(parsed) ? parsed : fallback;\n }\n\n static float(raw: string, fallback?: number): number | undefined {\n const trimmed = raw.trim();\n if (trimmed === '') return fallback;\n const parsed = Number(trimmed);\n // isNaN keeps Infinity valid, matching the number converter.\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static json(raw: string, fallback?: JsonValue): JsonValue | undefined {\n try {\n return JSON.parse(raw) as JsonValue;\n } catch {\n return fallback;\n }\n }\n\n static url(raw: string, fallback?: URL): URL | undefined {\n try {\n return new URL(raw);\n } catch {\n return fallback;\n }\n }\n\n static regexp(raw: string, fallback?: RegExp): RegExp | undefined {\n try {\n // Handle flags if provided in format: /pattern/flags\n const match = raw.match(new RegExp(String.raw`^\\/(.+)\\/([gimsuvy]*)$`));\n if (match) return new RegExp(match[1] as string, match[2]);\n\n return new RegExp(raw);\n } catch {\n return fallback;\n }\n }\n\n static date(raw: string, fallback?: Date): Date | undefined {\n // Try parsing as timestamp first (if it's all digits)\n if (new RegExp(String.raw`^\\d+$`).test(raw)) {\n const timestamp = parseInt(raw, 10);\n const parsed = new Date(timestamp);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n\n // Only accept ISO 8601 date strings (strict format)\n const isoRegex = new RegExp(String.raw`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z$`, 'u');\n if (!isoRegex.test(raw)) return fallback;\n\n const parsed = new Date(raw);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n\n static time(raw: string, fallback?: TimeFallback): number | undefined {\n const parsedRaw = parseTimeString(raw);\n if (parsedRaw !== undefined) return parsedRaw;\n\n // Raw didn't parse so apply fallback\n if (typeof fallback === 'number') return fallback;\n if (typeof fallback === 'string') {\n // A string fallback must name a unit; a unitless number is expressed as a number fallback, not a string.\n const parsedFallback = parseTimeString(fallback, true);\n if (parsedFallback === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.MalformedTimeFallback,\n `Time-string fallback \"${fallback}\" is not a valid format. Expected <number><unit> where unit is one of: ms, s, m, h, d, w.`\n );\n }\n return parsedFallback;\n }\n return undefined;\n }\n\n /**\n * Process the raw env value for an {@link ArrayOf} configuration.\n *\n * Behaviour:\n * - Splits on `config.delimiter`, trims each item, and filters out empty entries.\n * - With a scalar element token: runs each item through the matching built-in converter.\n * If any element returns `undefined`, throws `ArrayElementConversionFailed` with positional info.\n * - With a custom function element: runs each item through the function. Propagates user\n * exceptions; treats `undefined` returns as conversion failures (same throw as scalar path).\n * - Returns `[]` when the raw value is empty/whitespace.\n * - When `strict` is true, throws `EmptyArrayElement` on any empty/whitespace item instead\n * of silently filtering it out.\n */\n static processArrayConverter(raw: string, config: ArrayOf, strict = false): unknown[] {\n if (raw.trim() === '') return [];\n\n const trimmedItems = raw.split(config.delimiter).map((item) => String(item).trim());\n\n if (strict) {\n const emptyIdx = trimmedItems.findIndex((item) => item === '');\n if (emptyIdx !== -1) {\n throw new EnvaptError(\n EnvaptErrorCodes.EmptyArrayElement,\n `Array element at index ${emptyIdx} is empty or whitespace only (strict mode).`\n );\n }\n }\n\n const items = trimmedItems.filter(Boolean);\n\n if (!items.length) return [];\n\n const elementOf = config.of;\n\n if (typeof elementOf === 'function') {\n return items.map((item, index) => {\n const converter = elementOf as CustomElementConverter;\n const result = converter(item);\n if (result === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayElementConversionFailed,\n `Custom element converter returned undefined for item \"${item}\" at index ${index}.`\n );\n }\n return result;\n });\n }\n\n const converter = BuiltInConverters.getConverter(elementOf);\n return items.map((item, index) => {\n const converted = converter(item, undefined);\n if (converted === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayElementConversionFailed,\n `Element \"${item}\" at index ${index} could not be converted to ${elementOf}.`\n );\n }\n return converted;\n });\n }\n\n /**\n * Get the converter function for a built-in converter type\n */\n static getConverter<TFallback extends BuiltInConverter>(type: TFallback): BuiltInConverterFunction {\n const converters: MapOfConverterFunctions = {\n string: BuiltInConverters.string,\n number: BuiltInConverters.number,\n boolean: BuiltInConverters.boolean,\n integer: BuiltInConverters.integer,\n bigint: BuiltInConverters.bigint,\n symbol: BuiltInConverters.symbol,\n float: BuiltInConverters.float,\n json: BuiltInConverters.json,\n url: BuiltInConverters.url,\n regexp: BuiltInConverters.regexp,\n date: BuiltInConverters.date,\n time: BuiltInConverters.time\n } as const;\n\n return converters[type];\n }\n}\n"],"mappings":"iDAcA,MAAM,EAAgB,IAKhB,EAAgB,GAAqB,EACrC,EAAc,GAAmB,EACjC,EAAa,GAAgB,EAG7B,EAAyC,CAC3C,GAAI,EACJ,EAAG,EACH,EAAG,EACH,EAAG,EACH,EAAG,EACH,EARgB,EAAgB,CASpC,EAEM,EAAgB,IAAI,OAAO,OAAO,GAAG,mCAAoC,GAAG,EAC5E,EAAiB,IAAI,OAAO,OAAO,GAAG,kCAAmC,GAAG,EAWlF,SAAS,EAAgB,EAAe,EAAS,GAA2B,CACxE,IAAM,EAAQ,EAAM,MAAM,EAAS,EAAiB,CAAa,EACjE,GAAI,CAAC,EAAO,OAEZ,GAAM,EAAG,EAAQ,GAAgB,EACjC,GAAI,CAAC,EAAQ,OAEb,IAAM,EAAQ,OAAO,WAAW,CAAM,EAClC,WAAO,MAAM,CAAK,EAGtB,OAAO,EAAQ,EADD,GAAgB,KAElC,CAOA,IAAa,EAAb,MAAa,CAAkB,CAC3B,OAAO,OAAO,EAAa,EAAwC,CAC/D,OAAO,OAAO,CAAG,CACrB,CAEA,OAAO,OAAO,EAAa,EAAuC,CAC9D,IAAM,EAAS,OAAO,CAAG,EACzB,OAAO,OAAO,MAAM,CAAM,EAAI,EAAW,CAC7C,CAEA,OAAO,QAAQ,EAAa,EAAyC,CACjE,IAAM,EAAQ,EAAI,YAAY,CAAC,CAAC,KAAK,EAOr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M,IAAI,EAAA,IAEN,yDAAyD,EAAK,aAAa,EAAM,EACrF,EAEJ,OAAO,CACX,CAAC,EAGL,IAAM,EAAY,EAAkB,aAAa,CAAS,EAC1D,OAAO,EAAM,KAAK,EAAM,IAAU,CAC9B,IAAM,EAAY,EAAU,EAAM,IAAA,EAAS,EAC3C,GAAI,IAAc,IAAA,GACd,MAAM,IAAI,EAAA,IAEN,YAAY,EAAK,aAAa,EAAM,6BAA6B,EAAU,EAC/E,EAEJ,OAAO,CACX,CAAC,CACL,CAKA,OAAO,aAAiD,EAA2C,CAgB/F,MAAO,CAdH,OAAQ,EAAkB,OAC1B,OAAQ,EAAkB,OAC1B,QAAS,EAAkB,QAC3B,QAAS,EAAkB,QAC3B,OAAQ,EAAkB,OAC1B,OAAQ,EAAkB,OAC1B,MAAO,EAAkB,MACzB,KAAM,EAAkB,KACxB,IAAK,EAAkB,IACvB,OAAQ,EAAkB,OAC1B,KAAM,EAAkB,KACxB,KAAM,EAAkB,IAGZ,EAAE,EACtB,CACJ"}
|
|
@@ -0,0 +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// array element converters, any scalar token except json/regexp (those don't compose) or a custom function\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n// phantom-branded token from Converters.array. TElement carries the element converter through variable\n// indirection so inference survives. __envaptKind is the runtime dispatch discriminant.\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,EA8BA,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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";import{BuiltInConverters as t}from"./BuiltInConverters.mjs";import{state as n}from"../core/state.mjs";import{Validator as r}from"../engine/Validators.mjs";function i(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}var a=class{envService;constructor(e){this.envService=e}convertValue(e,t,n,i){let a=this.resolveConverter(n,t),o=this.processFallbackForConverter(a,t);if(r.isArrayConverter(a))return this.processArrayConverter(e,o,a,i);if(r.isPrimitiveConstructor(a)){let t=this.convertPrimitiveToString(a);return this.processBuiltInConverter(e,o,t,i,!0)}return r.isBuiltInConverter(a)?this.processBuiltInConverter(e,o,a,i,!1):this.processCustomConverter(e,o,a,i)}processFallbackForConverter(e,t){return r.isPrimitiveConstructor(e)&&t!==void 0?r.coercePrimitiveFallback(e,t):t}convertPrimitiveToString(t){if(t===String)return`string`;if(t===Number)return`number`;if(t===Boolean)return`boolean`;if(t===BigInt)return`bigint`;if(t===Symbol)return`symbol`;throw new e(204,`Unknown primitive constructor`)}processBuiltInConverter(e,n,i,a,o){r.builtInConverter(i),a&&n!==void 0&&!o&&r.validateBuiltInConverterFallback(i,n);let s=this.envService.get(e,void 0);if(s===void 0)return a?i===`time`&&typeof n==`string`?t.getConverter(i)(``,n):n:null;let c=t.getConverter(i)(s,n);return c===void 0&&!a?null:c}processArrayConverter(i,a,o,s){if(r.arrayConverter(o),s&&a!==void 0&&!Array.isArray(a))throw new e(101,`ArrayOf<...> requires that the fallback be an array, got ${typeof a}`);s&&Array.isArray(a)&&(r.validateArrayFallbackElementTypes(a),r.validateArrayConverterElementTypeMatch(o.of,a));let c=this.envService.get(i,void 0);if(c===void 0){if(!s)return null;if(o.of===`time`&&Array.isArray(a)&&a.every(e=>typeof e==`string`)){let e=t.getConverter(`time`);return a.map(t=>e(``,t))}return a}return t.processArrayConverter(c,o,n.strict)}processCustomConverter(e,t,n,i){return r.customConvertor(n),n(this.envService.get(e,void 0),t)}resolveConverter(e,t){if(e)return e;let n=typeof t;return n===`number`?`number`:n===`boolean`?`boolean`:n===`bigint`?`bigint`:n===`symbol`?`symbol`:`string`}convertWithSchema(t,n,r,a){let o=this.envService.get(t,void 0);if(o===void 0){if(a)return r;throw new e(305,`Required environment variable "${i(t)}" is missing or empty.`)}let s;try{s=n[`~standard`].validate(o)}catch(n){throw new e(209,`Schema for "${i(t)}" threw during validation: ${n.message}`,{cause:n})}if(s instanceof Promise)throw new e(302,`Schema for "${i(t)}" returned a Promise. envapt requires synchronous schemas; use a sync validator or perform async checks outside the env layer.`);if(s.issues!==void 0){let n=s.issues[0]?.message??`no issue message`;throw new e(208,`Schema validation failed for "${i(t)}": ${n}`,{issues:s.issues})}return s.value}};export{a as ValueConverter};
|
|
2
|
+
//# sourceMappingURL=ValueConverter.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ValueConverter.mjs","names":[],"sources":["../../../src/converters/ValueConverter.ts"],"sourcesContent":["import { BuiltInConverters } from './BuiltInConverters';\nimport { state } from '../core/state';\nimport { Validator } from '../engine/Validators';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf } from './Converters';\nimport type { StandardSchemaV1 } from '../infra/StandardSchema';\nimport type { BuiltInConverter, EnvKeyInput, EnvaptConverter, PrimitiveConstructor } from '../types';\nimport type { EnvapterService } from '../types/Env';\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Convert a resolved environment value to its declared type via built-in, primitive, array,\n * custom, or Standard Schema converters.\n * @internal\n */\nexport class ValueConverter {\n constructor(private readonly envService: EnvapterService) {}\n\n convertValue<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n converter: EnvaptConverter<TFallback> | undefined,\n hasFallback: boolean\n ): TFallback | null | undefined {\n const resolvedConverter = this.resolveConverter(converter, fallback);\n const processedFallback = this.processFallbackForConverter(resolvedConverter, fallback);\n\n if (Validator.isArrayConverter(resolvedConverter)) {\n return this.processArrayConverter(key, processedFallback, resolvedConverter, hasFallback);\n }\n\n if (Validator.isPrimitiveConstructor(resolvedConverter)) {\n const stringConverter = this.convertPrimitiveToString(resolvedConverter);\n return this.processBuiltInConverter(key, processedFallback, stringConverter, hasFallback, true);\n }\n\n if (Validator.isBuiltInConverter(resolvedConverter)) {\n return this.processBuiltInConverter(key, processedFallback, resolvedConverter, hasFallback, false);\n }\n\n return this.processCustomConverter(key, processedFallback, resolvedConverter, hasFallback);\n }\n\n private processFallbackForConverter<TFallback>(\n converter: EnvaptConverter<TFallback>,\n fallback: TFallback | undefined\n ): TFallback | undefined {\n if (Validator.isPrimitiveConstructor(converter) && fallback !== undefined) {\n return Validator.coercePrimitiveFallback<TFallback>(converter, fallback);\n }\n return fallback;\n }\n\n private convertPrimitiveToString(primitiveConstructor: PrimitiveConstructor): BuiltInConverter {\n if (primitiveConstructor === String) return 'string';\n if (primitiveConstructor === Number) return 'number';\n if (primitiveConstructor === Boolean) return 'boolean';\n if (primitiveConstructor === BigInt) return 'bigint';\n /* v8 ignore next -- @preserve */\n if (primitiveConstructor === Symbol) return 'symbol';\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Unknown primitive constructor`);\n }\n\n private processBuiltInConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: BuiltInConverter,\n hasFallback: boolean,\n wasOriginallyConstructor: boolean\n ): TFallback | null | undefined {\n Validator.builtInConverter(resolvedConverter);\n\n if (hasFallback && fallback !== undefined && !wasOriginallyConstructor) {\n Validator.validateBuiltInConverterFallback(resolvedConverter, fallback);\n }\n\n const parsed = this.envService.get(key, undefined);\n\n if (parsed === undefined) {\n if (!hasFallback) return null;\n // For converters with asymmetric fallback / return types — currently only `time`,\n // whose fallback may be a string while the return type is `number` — route the\n // fallback through the converter so it gets coerced to the return type.\n if (resolvedConverter === 'time' && typeof fallback === 'string') {\n const timeFn = BuiltInConverters.getConverter(resolvedConverter);\n return timeFn('', fallback) as TFallback;\n }\n return fallback;\n }\n\n const converterFn = BuiltInConverters.getConverter(resolvedConverter);\n const result = converterFn(parsed, fallback);\n\n if (result === undefined && !hasFallback) return null;\n\n return result as TFallback;\n }\n\n private processArrayConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: ArrayOf,\n hasFallback: boolean\n ): TFallback | null | undefined {\n Validator.arrayConverter(resolvedConverter);\n\n if (hasFallback && fallback !== undefined && !Array.isArray(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidFallback,\n `ArrayOf<...> requires that the fallback be an array, got ${typeof fallback}`\n );\n }\n\n if (hasFallback && Array.isArray(fallback)) {\n Validator.validateArrayFallbackElementTypes(fallback);\n Validator.validateArrayConverterElementTypeMatch(resolvedConverter.of, fallback);\n }\n\n const parsed = this.envService.get(key, undefined);\n\n if (parsed === undefined) {\n if (!hasFallback) return null;\n // When the array element is `time` and the fallback is a list of time-strings,\n // coerce each entry through the time converter so the returned array is\n // `number[]` matching the declared return type.\n if (\n resolvedConverter.of === 'time' &&\n Array.isArray(fallback) &&\n fallback.every((v) => typeof v === 'string')\n ) {\n const timeFn = BuiltInConverters.getConverter('time');\n return fallback.map((v) => timeFn('', v as string)) as TFallback;\n }\n return fallback;\n }\n\n const result = BuiltInConverters.processArrayConverter(parsed, resolvedConverter, state.strict);\n return result as TFallback;\n }\n\n private processCustomConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: EnvaptConverter<TFallback>,\n _hasFallback: boolean // hasFallback is not needed because customConverter is called even if the raw value is undefined\n ): TFallback | null | undefined {\n Validator.customConvertor(resolvedConverter);\n\n const raw = this.envService.get(key, undefined);\n\n return resolvedConverter(raw, fallback);\n }\n\n private resolveConverter<TFallback>(\n converter: EnvaptConverter<TFallback> | undefined,\n fallback: TFallback | undefined\n ): EnvaptConverter<TFallback> {\n if (converter) return converter;\n\n const fallbackType = typeof fallback;\n if (fallbackType === 'number') return 'number';\n if (fallbackType === 'boolean') return 'boolean';\n if (fallbackType === 'bigint') return 'bigint';\n if (fallbackType === 'symbol') return 'symbol';\n return 'string';\n }\n\n // Single dispatch site for decorator + `Envapter.parse()` so error codes (208 / 209 / 305)\n // stay consistent. Missing+no-fallback throws here so callers don't duplicate the check.\n convertWithSchema(key: EnvKeyInput, schema: StandardSchemaV1, fallback: unknown, hasFallback: boolean): unknown {\n const raw = this.envService.get(key, undefined);\n\n if (raw === undefined) {\n if (hasFallback) return fallback;\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n let outcome: StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>;\n try {\n outcome = schema['~standard'].validate(raw);\n } catch (cause) {\n throw new EnvaptError(\n EnvaptErrorCodes.SchemaThrew,\n `Schema for \"${formatKeyForError(key)}\" threw during validation: ${(cause as Error).message}`,\n { cause }\n );\n }\n\n if (outcome instanceof Promise) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Schema for \"${formatKeyForError(key)}\" returned a Promise. envapt requires synchronous schemas; use a sync validator or perform async checks outside the env layer.`\n );\n }\n\n if (outcome.issues !== undefined) {\n const first = outcome.issues[0];\n const firstMessage = first?.message ?? 'no issue message';\n throw new EnvaptError(\n EnvaptErrorCodes.SchemaValidationFailed,\n `Schema validation failed for \"${formatKeyForError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JI,IAAiB,SAAiB,SAClC,IAAiB,UAAkB,UACnC,IAAiB,SAAiB,SAClC,IAAiB,SAAiB,SAC/B,QACX,CAIA,kBAAkB,EAAkB,EAA0B,EAAmB,EAA+B,CAC5G,IAAM,EAAM,KAAK,WAAW,IAAI,EAAK,IAAA,EAAS,EAE9C,GAAI,IAAQ,IAAA,GAAW,CACnB,GAAI,EAAa,OAAO,EACxB,MAAM,IAAI,EAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,CACJ,CAEA,IAAI,EACJ,GAAI,CACA,EAAU,EAAO,YAAY,CAAC,SAAS,CAAG,CAC9C,OAAS,EAAO,CACZ,MAAM,IAAI,EAAA,IAEN,eAAe,EAAkB,CAAG,EAAE,6BAA8B,EAAgB,UACpF,CAAE,OAAM,CACZ,CACJ,CAEA,GAAI,aAAmB,QACnB,MAAM,IAAI,EAAA,IAEN,eAAe,EAAkB,CAAG,EAAE,+HAC1C,EAGJ,GAAI,EAAQ,SAAW,IAAA,GAAW,CAE9B,IAAM,EADQ,EAAQ,OAAO,EACH,EAAE,SAAW,mBACvC,MAAM,IAAI,EAAA,IAEN,iCAAiC,EAAkB,CAAG,EAAE,KAAK,IAC7D,CAAE,OAAQ,EAAQ,MAAO,CAC7B,CACJ,CAEA,OAAO,EAAQ,KACnB,CACJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{EnvaptError as e}from"../infra/Error.mjs";import{debugWarn as t}from"../infra/Debug.mjs";import{resolveKeyInput as n,templateResolver as r,treatAsMissing as i,valueConverter as a}from"./engine.mjs";import{PrimitiveMethods as o}from"./PrimitiveMethods.mjs";import{recase as s}from"../infra/recase.mjs";function c(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}function l(e,t){if(e.value===void 0)return e;let n=t.resolveTemplate(e.key,e.value);return{key:e.key,value:n.trim()===``?void 0:n}}var u=class u extends o{static getUsing(e,r,o){let{key:s,value:c}=n(e);if(i(c)&&o===void 0){t(`${s} is missing or empty`);return}let l=o!==void 0;return a.convertValue(s,o,r,l)}getUsing(e,t,n){return u.getUsing(e,t,n)}static getWith(e,r,o){let{key:s,value:c}=n(e);if(i(c))return t(`${s} is missing or empty`),o;let l=o!==void 0;return a.convertValue(s,o,r,l)}getWith(e,t,n){return u.getWith(e,t,n)}static getRequired(t,i){let o=typeof t==`string`?[t]:t,s=``,u;for(let e of o){let t=l(n(e),r);if(s=t.key,t.value!==void 0){u=t.value;break}}if(u===void 0)throw new e(305,`Required environment variable "${c(t)}" is missing or empty.`);let d=a.convertValue(s,void 0,i,!1);if(d==null)throw new e(305,`Required environment variable "${c(t)}" is present but could not be converted.`);return d}getRequired(e,t){return u.getRequired(e,t)}static getRequiredAll(t,i){let o=Object.keys(t),c=o.filter(e=>l(n(e),r).value===void 0);if(c.length>0)throw new e(305,`Missing required environment variables: ${c.join(`, `)}.`);let u={};for(let n of o){let r=a.convertValue(n,void 0,t[n],!1);if(r==null)throw new e(305,`Required environment variable "${n}" is present but could not be converted.`);u[s(n,i)]=r}return u}getRequiredAll(e,t){return u.getRequiredAll(e,t)}static parse(e,t,n){let r=arguments.length>2;return a.convertWithSchema(e,t,n,r)}parse(e,t,n){let r=arguments.length>2;return a.convertWithSchema(e,t,n,r)}};export{u as AdvancedMethods,l as resolveRequired};
|
|
2
|
+
//# sourceMappingURL=AdvancedMethods.mjs.map
|