@reharik/smart-enum 0.5.1 → 0.5.2
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/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +2 -2
- package/dist/core.d.ts +2 -2
- package/dist/core.js.map +1 -1
- package/dist/database.cjs.map +1 -1
- package/dist/database.d.cts +2 -2
- package/dist/database.d.ts +2 -2
- package/dist/database.js.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/{transformation-Crhi2Xwm.d.cts → transformation-CrXfK1cB.d.cts} +15 -9
- package/dist/{transformation-Crhi2Xwm.d.ts → transformation-CrXfK1cB.d.ts} +15 -9
- package/dist/transport.cjs.map +1 -1
- package/dist/transport.d.cts +2 -2
- package/dist/transport.d.ts +2 -2
- package/dist/transport.js.map +1 -1
- package/package.json +1 -1
package/dist/transport.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transport.ts","../src/enumerations.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/enumItemsEqual.ts","../src/extensionMethods.ts","../src/utilities/serializationMode.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts","../src/utilities/transport/transportRegistry.ts","../src/utilities/transport/reviveAfterTransport.ts","../src/utilities/transport/serializeForTransport.ts"],"sourcesContent":["/**\n * Smart Enums with Transport Utilities\n *\n * This entry point includes the core enumeration functionality plus utilities\n * for serializing/reviving enums for API transport (JSON over the wire).\n *\n * @example\n * ```typescript\n * import { enumeration, serializeForTransport, reviveAfterTransport } from '@reharik/smart-enum/transport';\n * ```\n */\n\n// Re-export core functionality\nexport { enumeration } from './enumerations.js';\nexport { isSmartEnumItem, isSmartEnum } from './utilities/typeGuards.js';\nexport {\n serializeSmartEnums,\n reviveSmartEnums,\n reviveEnumField,\n} from './utilities/transformation.js';\nexport {\n reviveAfterTransport,\n serializeForTransport,\n initializeSmartEnumMappings,\n getGlobalEnumRegistry,\n} from './utilities/transport/index.js';\n\n// Re-export core types plus transport-specific types\nexport type {\n Enumeration,\n AnyEnumLike,\n SerializedSmartEnums,\n RevivedSmartEnums,\n SmartEnumItemSerialized,\n LogLevel,\n SmartEnumMappingsConfig,\n StandardEnumItemBase,\n StandardEnumItem,\n} from './types.js';\n","import { capitalCase, constantCase } from 'case-anything';\n\nimport { addExtensionMethods } from './extensionMethods.js';\nimport {\n SMART_ENUM,\n SMART_ENUM_ID,\n SMART_ENUM_ITEM,\n SerializationMode,\n type EnumFromNormalizedObject,\n type EnumItemFromNormalizedObject,\n type EnumMemberUnionFromNormalizedObject,\n type EnumerationProps,\n type FinalizableEnumItem,\n type FinalizedEnumFields,\n type NormalizedInputType,\n type ObjectEnumInput,\n type PropertyAutoFormatter,\n type StandardEnumItem,\n} from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nimport { resolveSerializationMode } from './utilities/serializationMode.js';\n\nexport type EnumItem<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends { __smart_enum_brand: true }\n ? TEnum[K]\n : never;\n}[keyof TEnum];\n\nfunction normalizeInput<TInput extends readonly string[] | ObjectEnumInput>(\n input: TInput,\n): NormalizedInputType<TInput> {\n if (Array.isArray(input)) {\n return Object.fromEntries(\n input.map(k => [k, {}]),\n ) as NormalizedInputType<TInput>;\n }\n\n return input as NormalizedInputType<TInput>;\n}\n\nconst finalizeEnumItem = <T extends { value: string; key: string }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\n serializeAs: SerializationMode | undefined,\n): T & FinalizedEnumFields => {\n Object.defineProperty(item, SMART_ENUM_ITEM, {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, SMART_ENUM_ID, {\n value: enumInstanceId,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_brand', {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_type', {\n value: enumType,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toJSON', {\n value: () => {\n const mode = resolveSerializationMode(serializeAs);\n if (mode === 'value') {\n return item.value;\n }\n return { __smart_enum_type: enumType, value: item.value };\n },\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'equals', {\n value: (other: StandardEnumItem) => enumItemsEqual(item, other),\n enumerable: false,\n });\n\n Object.defineProperty(item, 'match', {\n value: (handlers: Record<string, (i: unknown) => unknown>) => {\n const handler = handlers[item.key];\n if (!handler) {\n throw new Error(\n `match: no handler for '${item.key}' on enum '${enumType}'`,\n );\n }\n return handler(item);\n },\n enumerable: false,\n });\n return item as T & FinalizedEnumFields;\n};\n\nconst formatProperties = (\n k: string,\n formatters: PropertyAutoFormatter[],\n): { value: string; display: string } & Record<string, string> =>\n formatters.reduce(\n (acc, formatter) => {\n acc[formatter.key] = formatter.format(k);\n return acc;\n },\n {\n value: constantCase(k),\n display: capitalCase(k),\n } as { value: string; display: string } & Record<string, string>,\n );\n\nfunction buildEnumFromObject<TObj extends ObjectEnumInput>(\n enumType: string,\n input: TObj,\n propertyAutoFormatters?: PropertyAutoFormatter[],\n serializeAs?: SerializationMode,\n): EnumFromNormalizedObject<TObj> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumMemberUnionFromNormalizedObject<TObj>;\n\n const rawEnumItems: Partial<{\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }> = {};\n\n const enumInstanceId = Symbol('smart-enum-instance');\n let index = 0;\n\n for (const key in input) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n const typedKey = key;\n const value = input[typedKey];\n\n const enumItemBase = {\n index,\n key: typedKey,\n ...formatProperties(typedKey, formattersWithDefaults),\n ...value,\n } as FinalizableEnumItem & TObj[typeof typedKey];\n\n const enumItem = finalizeEnumItem(\n enumItemBase,\n enumType,\n enumInstanceId,\n serializeAs,\n ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey as keyof TObj] = enumItem;\n index++;\n }\n }\n\n const extensionMethods = addExtensionMethods<TItem>(\n Object.values(rawEnumItems) as TItem[],\n );\n\n const enumObject = {\n ...rawEnumItems,\n ...extensionMethods,\n } as EnumFromNormalizedObject<TObj>;\n\n Object.defineProperty(enumObject, SMART_ENUM, {\n value: true,\n enumerable: false,\n });\n\n Object.freeze(enumObject);\n\n return enumObject;\n}\n\nexport function enumeration<const TArr extends readonly string[]>(\n enumType: string,\n props: EnumerationProps<TArr>,\n): EnumFromNormalizedObject<NormalizedInputType<TArr>>;\n\nexport function enumeration<const TObj extends ObjectEnumInput>(\n enumType: string,\n props: EnumerationProps<TObj>,\n): EnumFromNormalizedObject<NormalizedInputType<TObj>>;\n\nexport function enumeration(\n enumType: string,\n props: EnumerationProps<readonly string[] | ObjectEnumInput>,\n): EnumFromNormalizedObject<\n NormalizedInputType<readonly string[] | ObjectEnumInput>\n> {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n props.serializeAs,\n );\n}\n","/**\n * Type guard to check if a value is not null or undefined\n * @param value - The value to check\n * @returns True if the value is defined and not null\n */\nexport const notEmpty = <X>(\n value: X | null | undefined,\n): value is NonNullable<X> => {\n // eslint-disable-next-line unicorn/no-null\n return value != null;\n};\n\n// Public symbols used at runtime for detection/identity (not used in type keys)\nexport const SMART_ENUM_ITEM = Symbol('smart-enum-item');\nexport const SMART_ENUM_ID = Symbol('smart-enum-id');\nexport const SMART_ENUM = Symbol('smart-enum');\n\n/**\n * Options for filtering enum items in various methods\n */\nexport type EnumFilterOptions = {\n /** Include items with null/undefined values (default: false) */\n showEmpty?: boolean;\n /** Include deprecated items (default: false) */\n showDeprecated?: boolean;\n};\n\n// export type EnumInput = readonly string[] | ObjectEnumInput;\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Structural detection checks for\n * presence of `key` and `value`.\n */\nexport type SerializedSmartEnums<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<SerializedSmartEnums<U>>\n : T extends Array<infer U>\n ? SerializedSmartEnums<U>[]\n : T extends object\n ? { [K in keyof T]: SerializedSmartEnums<T[K]> }\n : T;\n\n/**\n * Revived shape: for keys present in mapping M, the string becomes the\n * corresponding enum item type (derived from the provided enum object);\n * other fields recurse.\n */\nexport type EnumItemFromEnum<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\n/**\n * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).\n * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).\n */\nexport type AnyEnumLike<T = unknown> = {\n tryFromValue: (value?: string | null) => T | undefined;\n tryFromKey: (key?: string | null) => T | undefined;\n} & Record<string, unknown>;\n\nexport type RevivedSmartEnums<T, M extends Record<string, AnyEnumLike>> =\n T extends ReadonlyArray<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends Array<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends object\n ? {\n [K in keyof T]: K extends Extract<keyof M, string>\n ? Enumeration<M[K]>\n : RevivedSmartEnums<T[K], M>;\n }\n : T;\n\nexport type SmartEnumItemSerialized = {\n __smart_enum_type: string;\n value: string;\n};\n\n/** Example shape for transport tests (`reviveAfterTransport` registry). */\nexport type SmartApiHelperConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n};\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Used for database storage.\n */\nexport type DatabaseFormat<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DatabaseFormat<U>>\n : T extends Array<infer U>\n ? DatabaseFormat<U>[]\n : T extends object\n ? { [K in keyof T]: DatabaseFormat<T[K]> }\n : T;\n\n/**\n * Log levels for smart enum mappings\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Configuration for smart enum mappings initialization\n */\nexport type SmartEnumMappingsConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n logLevel?: LogLevel;\n logger?: import('./utilities/logger.js').Logger;\n};\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\n/**\n * Structural fields shared by every enum member (key, value, display, index, optional deprecated).\n * Does not include smart-enum branding or database helpers; see {@link StandardEnumItem}.\n */\nexport type StandardEnumItemBase = {\n readonly key: string;\n readonly value: string;\n readonly display: string;\n readonly index: number;\n readonly deprecated?: boolean;\n};\n\n/**\n * Branded item produced by `enumeration()`: {@link StandardEnumItemBase} plus runtime identity\n * (`__smart_enum_brand`, `__smart_enum_type`) and `toPostgres()`.\n */\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\n readonly toJSON: () => string | { __smart_enum_type: string; value: string };\n readonly equals: <T extends StandardEnumItem>(other: T) => this is T;\n};\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n Record<string, unknown>;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\nexport type EmptyEnumInputItem = Record<never, never>;\n\ntype Separator = '-' | '_' | ' ' | '.';\n\ntype IsUpperChar<C extends string> =\n C extends Uppercase<C> ? (C extends Lowercase<C> ? false : true) : false;\n\ntype IsLowerChar<C extends string> =\n C extends Lowercase<C> ? (C extends Uppercase<C> ? false : true) : false;\n\ntype PushUnderscore<S extends string> = S extends '' | `${string}_`\n ? S\n : `${S}_`;\n\ntype TrimUnderscore<S extends string> = S extends `_${infer R}`\n ? TrimUnderscore<R>\n : S extends `${infer R}_`\n ? TrimUnderscore<R>\n : S;\n\ntype CollapseUnderscores<S extends string> = S extends `${infer A}__${infer B}`\n ? CollapseUnderscores<`${A}_${B}`>\n : S;\n\ntype ConstantCaseInternal<\n S extends string,\n Prev extends string = '',\n Out extends string = '',\n> = S extends `${infer C}${infer Rest}`\n ? C extends Separator\n ? ConstantCaseInternal<Rest, C, PushUnderscore<Out>>\n : IsUpperChar<C> extends true\n ? IsLowerChar<Prev> extends true\n ? ConstantCaseInternal<Rest, C, `${PushUnderscore<Out>}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : CollapseUnderscores<TrimUnderscore<Out>>;\n\ntype ConstantCase<S extends string> = string extends S\n ? string\n : ConstantCaseInternal<S>;\n\n/** Segments of a `ConstantCase` string (underscore-separated ALL CAPS words). */\ntype SplitConstantCaseSegments<S extends string> =\n S extends `${infer A}_${infer B}`\n ? [A, ...SplitConstantCaseSegments<B>]\n : [S];\n\n/** First character upper, remainder lower (for ALL-CAPS words from `ConstantCase`). */\ntype TitleCaseAllCapsWord<W extends string> = W extends ''\n ? ''\n : W extends `${infer F}${infer R}`\n ? `${Uppercase<F>}${Lowercase<R>}`\n : W;\n\ntype JoinDisplaySegments<T extends readonly string[]> = T extends readonly [\n infer A extends string,\n ...infer Rest extends readonly string[],\n]\n ? Rest extends readonly []\n ? TitleCaseAllCapsWord<A>\n : `${TitleCaseAllCapsWord<A>} ${JoinDisplaySegments<Rest>}`\n : '';\n\n/**\n * Display string derived from the enum member key: `ConstantCase` → split → title-case words → join with spaces.\n * Matches default runtime `capitalCase(key)` for typical PascalCase / camelCase keys. Member keys that already\n * contain separators may differ from `capitalCase` at runtime; custom `propertyAutoFormatters` for `display`\n * are not reflected in this type.\n */\ntype DisplayCaseFromEnumKey<K extends string> = string extends K\n ? string\n : JoinDisplaySegments<SplitConstantCaseSegments<ConstantCase<K>>>;\n\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\n/** Input-derived fields for one member key (excludes built-ins filled by `enumeration()`). */\nexport type EnumMemberExtra<\n TObj extends ObjectEnumInput,\n K extends keyof TObj,\n> = Omit<TObj[K], BuiltInOverrideKeys>;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n> = Omit<StandardEnumItem, 'key' | 'value' | 'display'> &\n SmartEnumMatch &\n EnumMemberExtra<TObj, K> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? [Extract<V, string>] extends [never]\n ? ConstantCase<Extract<K, string>>\n : Extract<V, string>\n : ConstantCase<Extract<K, string>>;\n readonly display: TObj[K] extends { display?: infer D }\n ? [Extract<D, string>] extends [never]\n ? DisplayCaseFromEnumKey<Extract<K, string>>\n : Extract<D, string>\n : DisplayCaseFromEnumKey<Extract<K, string>>;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<TObj extends ObjectEnumInput> =\n {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }[keyof TObj];\n\nexport type EnumFromNormalizedObject<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj>>;\n\nexport type UnionKeys<T> = T extends T ? keyof T : never;\n\n/*\nTo widen the type of the OptionalObject from literals to their actual types,\ne.g.\nshape?: \"round\" | \"square\" | \"long\";\nslices?: true;\nlayers?: 2;\n--turns into:--\nshape: string | undefined;\nslices: boolean| undefined;\nlayers: number| undefined;\n\nwe can use the following code:\ntype Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T;\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? Widen<V> : undefined;\n};\n*/\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? V : undefined;\n};\n\ntype ExtraShapeUnion<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: Omit<TObj[K], BuiltInOverrideKeys>;\n}[keyof TObj];\n\nexport type InferredExtraFields<TObj extends ObjectEnumInput> =\n MergeUnionToObject<ExtraShapeUnion<TObj>>;\n\nexport type PropertyAutoFormatter = {\n /** The property name to generate */\n key: string;\n /** Function to transform the key into the property value */\n format: (k: string) => string;\n};\n\nexport type CoreEnumMethods<TItem extends StandardEnumItem> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n /** Matches runtime: `items.map(i => i.value)` (see {@link EnumLikeBase}). */\n values(): readonly TItem['value'][];\n /** Matches runtime: `items.map(i => i.key)` (see {@link EnumLikeBase}). */\n keys(): readonly TItem['key'][];\n};\n\n/**\n * Structural shape of a smart-style enum object: lookup by value/key, list items/values/keys,\n * plus an index signature so registry and mapping types can treat instances as records.\n * Use {@link SmartEnumLike} when items are full {@link StandardEnumItem}s (the usual case).\n */\nexport type EnumLikeBase<\n TItem extends StandardEnumItemBase = StandardEnumItemBase,\n> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n values(): readonly TItem['value'][];\n keys(): readonly TItem['key'][];\n} & Record<string, unknown>;\n\n/**\n * A {@link EnumLikeBase} whose items are branded {@link StandardEnumItem}s (typical `enumeration()` result).\n */\nexport type SmartEnumLike<TItem extends StandardEnumItem = StandardEnumItem> =\n EnumLikeBase<TItem>;\n\n/** Union of branded enum member values on an enum object `T`. */\nexport type SmartEnumMemberUnion<T extends Record<string, unknown>> = {\n [K in keyof T]: T[K] extends StandardEnumItem ? T[K] : never;\n}[keyof T];\n\n/** Keys on `TEnum` whose member matches `Record<P, V>` within `ItemUnion`. */\nexport type SmartEnumSubsetKeys<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = {\n [K in keyof TEnum]: TEnum[K] extends Extract<ItemUnion, Record<P, V>>\n ? K\n : never;\n}[keyof TEnum];\n\nexport type SmartEnumSubsetItemUnion<\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Extract<ItemUnion, Record<P, V>>;\n\nexport type SmartEnumSubsetView<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Pick<TEnum, SmartEnumSubsetKeys<TEnum, ItemUnion, P, V>> &\n CoreEnumMethods<SmartEnumSubsetItemUnion<ItemUnion, P, V>>;\n\n/** Return type of {@link getSubsetByProp} / {@link subsetByProp} for explicit consumer annotations. */\nexport type SubsetByPropResult<\n TEnum extends Record<string, unknown> &\n SmartEnumLike<SmartEnumMemberUnion<TEnum>>,\n P extends keyof SmartEnumMemberUnion<TEnum> & string,\n V extends SmartEnumMemberUnion<TEnum>[P],\n> = SmartEnumSubsetView<TEnum, SmartEnumMemberUnion<TEnum>, P, V>;\n\nexport type FieldEnumMapping = Record<string, SmartEnumLike>;\n\nexport type ReviveRowOptions = {\n fieldEnumMapping: FieldEnumMapping;\n strict?: boolean;\n};\n\nexport type PathEnumMapping = Record<string, SmartEnumLike>;\n\nexport type RevivePayloadOptions = {\n pathEnumMapping: PathEnumMapping;\n strict?: boolean;\n};\n\n/**\n * Serialization mode controls how smart-enum items are serialized to JSON.\n *\n * - 'wrapped' (default): toJSON returns { __smart_enum_type, value }.\n * Use this when payloads need to be self-describing for revival on the\n * receiving end (e.g. REST APIs with explicit revive middleware).\n *\n * - 'value': toJSON returns just the wire value string.\n * Use this when the receiving end already knows the enum types from\n * schema context (e.g. GraphQL boundaries).\n *\n * Resolution order at toJSON call time:\n * 1. Per-enum `serializeAs` option (if set on enumeration())\n * 2. Global default (set via setDefaultSerializationMode)\n * 3. 'wrapped' (built-in default, preserves backward compatibility)\n */\nexport type SerializationMode = 'wrapped' | 'value';\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n serializeAs?: SerializationMode;\n};\n\nexport type Enumeration<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\nexport type FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type' | 'toJSON'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n\n/**\n * Exhaustive branch-on-member. One arm required per member of the *statically\n * known* receiver — miss one and it won't compile. Over a pickEnum view the\n * arms are exhaustive over just the picked members.\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SmartEnumMatch {\n readonly key: string;\n match<R>(handlers: {\n [P in this['key']]: (item: Extract<this, { key: P }>) => R;\n }): R;\n}\n\n/** Member keys of an enum object (excludes the method keys). */\nexport type EnumMemberKeys<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends StandardEnumItem ? K : never;\n}[keyof TEnum];\n\n/**\n * Enum-like view over an explicit list of member keys. Reuses the parent's item\n * references; methods scope to the picked subset. See {@link pickEnum}.\n */\nexport type PickEnumView<\n TEnum extends Record<string, unknown>,\n K extends EnumMemberKeys<TEnum>,\n> = Pick<TEnum, K> & CoreEnumMethods<Extract<TEnum[K], StandardEnumItem>>;\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\n SmartEnumLike,\n} from '../types.js';\n\n/**\n * Runtime type guard to detect Smart Enum items created by this library.\n * Returns true if the value has the SMART_ENUM_ITEM symbol.\n *\n * @example\n * ```typescript\n * import { Status } from './status';\n * const item = Status.active;\n * isSmartEnumItem(item); // true\n * isSmartEnumItem({ key: 'active', value: 'ACTIVE' }); // false (plain object)\n * if (isSmartEnumItem(x)) {\n * console.log(x.value, x.__smart_enum_type); // narrowed to enum item\n * }\n * ```\n */\nexport const isSmartEnumItem = (\n x: unknown,\n): x is {\n key: string;\n value: string;\n index?: number;\n __smart_enum_type?: string;\n} => {\n return (\n !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM_ITEM) === true\n );\n};\n\n/**\n * Runtime type guard to detect a full Smart Enum object created by this library.\n * Returns true if the object has the SMART_ENUM property.\n *\n * @example\n * ```typescript\n * import { MyEnum } from './blah';\n * isSmartEnum(MyEnum) === true; // true\n * isSmartEnum(MyEnum.one) === false; // false (this is an item, not the enum)\n * ```\n */\nexport const isSmartEnum = (x: unknown): x is SmartEnumLike => {\n return !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM) === true;\n};\n\n/**\n * Runtime type guard to detect a serialized Smart Enum item created by this library.\n * Returns true if the value has `__smart_enum_type` and `value` (wire/database shape).\n *\n * @example\n * ```typescript\n * const wire = { __smart_enum_type: 'Status', value: 'ACTIVE' };\n * isSerializedSmartEnumItem(wire); // true\n * isSerializedSmartEnumItem(Status.active); // false (live enum item)\n * if (isSerializedSmartEnumItem(x)) {\n * reviveItem(x.__smart_enum_type, x.value); // narrowed to SmartEnumItemSerialized\n * }\n * ```\n */\nexport const isSerializedSmartEnumItem = (\n x: unknown,\n): x is SmartEnumItemSerialized => {\n return (\n !!x &&\n typeof x === 'object' &&\n Reflect.has(x, '__smart_enum_type') &&\n Reflect.has(x, 'value')\n );\n};\n","import { SMART_ENUM_ID } from '../types.js';\n\nimport { isSmartEnumItem } from './typeGuards.js';\n\n/** Value-based equality for smart enum items from the same enumeration instance. */\nexport const enumItemsEqual = (a: unknown, b: unknown): boolean => {\n if (!isSmartEnumItem(a) || !isSmartEnumItem(b)) {\n return false;\n }\n\n return (\n Reflect.get(a, SMART_ENUM_ID) === Reflect.get(b, SMART_ENUM_ID) &&\n a.value === b.value\n );\n};\n","import type { CoreEnumMethods, StandardEnumItem } from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nexport const addExtensionMethods = <TItem extends StandardEnumItem>(\n enumItems: readonly TItem[],\n): CoreEnumMethods<TItem> => {\n const findBy = <K extends keyof TItem>(field: K, target: TItem[K]) =>\n enumItems.find(item => item[field] === target);\n\n const requireBy = <K extends keyof TItem>(\n field: K,\n target: TItem[K],\n label: string,\n ) => {\n const item = findBy(field, target);\n if (!item) {\n throw new Error(`No enum ${label} found for '${String(target)}'`);\n }\n return item;\n };\n\n return {\n fromValue: value => requireBy('value', value as TItem['value'], 'value'),\n tryFromValue: value =>\n value ? findBy('value', value as TItem['value']) : undefined,\n\n fromKey: key => requireBy('key', key as TItem['key'], 'key'),\n tryFromKey: key => (key ? findBy('key', key as TItem['key']) : undefined),\n\n equals: enumItemsEqual,\n\n items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\n };\n};\n","import { SerializationMode } from '../types.js';\n\nlet globalDefault: SerializationMode | undefined;\n\n/**\n * Set the global default serialization mode for all smart-enum items\n * that don't have a per-enum serializeAs option.\n *\n * Call once at app startup, before any JSON.stringify happens on enum items.\n *\n * @example\n * setDefaultSerializationMode('value');\n */\nexport const setDefaultSerializationMode = (mode: SerializationMode): void => {\n globalDefault = mode;\n};\n\n/**\n * Reset the global default to its initial unset state.\n * Primarily useful for tests.\n */\nexport const resetDefaultSerializationMode = (): void => {\n globalDefault = undefined;\n};\n\n/**\n * Resolve the effective serialization mode for an enum item.\n * Per-enum option wins, then global, then 'wrapped'.\n */\nexport const resolveSerializationMode = (\n perEnum: SerializationMode | undefined,\n): SerializationMode => perEnum ?? globalDefault ?? 'wrapped';\n","/**\n * Logger interface for @reharik/smart-enum library\n *\n * This interface allows users to inject their own logging implementation\n * or use the default console logger.\n */\n\nexport type Logger = {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n};\n\n/**\n * Default console logger implementation\n */\nconst consoleLogger: Logger = {\n debug(message: string, ...args: unknown[]): void {\n console.debug(`[@reharik/smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[@reharik/smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[@reharik/smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[@reharik/smart-enum:error] ${message}`, ...args);\n },\n};\n\n/**\n * Global logger instance\n * Defaults to console logger\n */\nlet globalLogger: Logger = consoleLogger;\n\n/**\n * Sets the global logger instance\n *\n * @param logger - The logger implementation to use\n *\n * @example\n * ```typescript\n * import { setLogger } from '@reharik/smart-enum';\n *\n * // Use custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, args),\n * info: (msg, ...args) => myLogger.info(msg, args),\n * warn: (msg, ...args) => myLogger.warn(msg, args),\n * error: (msg, ...args) => myLogger.error(msg, args),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n globalLogger = logger;\n}\n\n/**\n * Gets the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n return globalLogger;\n}\n\n// Internal convenience functions for library use\nexport function debug(message: string, ...args: unknown[]): void {\n globalLogger.debug(message, ...args);\n}\n\nexport function info(message: string, ...args: unknown[]): void {\n globalLogger.info(message, ...args);\n}\n\nexport function warn(message: string, ...args: unknown[]): void {\n globalLogger.warn(message, ...args);\n}\n\nexport function error(message: string, ...args: unknown[]): void {\n globalLogger.error(message, ...args);\n}\n","// serializeSmartEnums.ts\nexport { isSmartEnumItem, isSmartEnum } from './typeGuards.js';\nimport type { SerializedSmartEnums, AnyEnumLike } from '../types.js';\n\nimport { debug } from './logger.js';\nimport { isSerializedSmartEnumItem, isSmartEnumItem } from './typeGuards.js';\n\ntype PlainObject = Record<string, unknown>;\n\nconst isPlainObject = (x: unknown): x is PlainObject =>\n typeof x === 'object' &&\n x !== null &&\n Object.getPrototypeOf(x) === Object.prototype;\n\n/**\n * Recursively replaces Smart Enum items with self-describing objects\n * `{ __smart_enum_type, value }` for JSON transport or storage.\n *\n * @param input - Object or array that may contain enum items\n * @returns Same structure with enum items replaced by serialized shape\n *\n * @example\n * ```typescript\n * const dto = { id: '1', status: Status.active, color: Color.red };\n * const wire = serializeSmartEnums(dto);\n * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }\n * ```\n */\n// Overloads:\n// 1) Inferred\nexport function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;\n// 2) Return-type only (constrained to objects/arrays)\nexport function serializeSmartEnums<\n S extends Readonly<PlainObject> | readonly unknown[],\n>(input: unknown): S;\n// Implementation\nexport function serializeSmartEnums(input: unknown): unknown {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n if (isSmartEnumItem(v)) {\n return {\n __smart_enum_type: v.__smart_enum_type,\n value: v.value,\n };\n }\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) {\n arr.push(walk(item));\n }\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n\n return walk(input);\n}\n\n/**\n * Recursively revives serialized enum objects back to Smart Enum items\n * using a registry of enum types. Expects payload to contain\n * `{ __smart_enum_type, value }` where the type exists in the registry.\n *\n * @param input - Serialized payload (e.g. from JSON)\n * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)\n * @returns Payload with serialized enums revived to enum items\n *\n * @example\n * ```typescript\n * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };\n * const revived = reviveSmartEnums(wire, { Status, Color });\n * // revived.status === Status.active\n * ```\n */\nexport function reviveSmartEnums<R>(\n input: unknown,\n registry: Record<string, AnyEnumLike>,\n): R {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n // Handle self-describing enum objects with __smart_enum_type and value\n if (isSerializedSmartEnumItem(v)) {\n debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);\n const enumInstance = registry[v.__smart_enum_type];\n if (enumInstance) {\n debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);\n // Try to find the enum item by value first\n const enumItem = enumInstance.tryFromValue(v.value);\n if (enumItem) {\n debug(`Revived enumItem using value: ${v.value}`);\n return enumItem;\n }\n // If that fails, try to find by key (convert value to key format)\n const key = v.value.toLowerCase();\n const enumItemFromKey = enumInstance.tryFromKey(key);\n if (enumItemFromKey) {\n debug(`Revived enumItem using key: ${key}`);\n return enumItemFromKey;\n }\n }\n // If no matching enum type in registry, return the original serialized object\n return v;\n }\n\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) arr.push(walk(item));\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n return walk(input) as R;\n}\n\n/**\n * Maps a plain string (for example a column value from a database query) to the\n * corresponding Smart Enum item by calling `tryFromValue` on the given enum.\n *\n * Use this when you already know which enum type a field uses and the stored\n * value is the enum’s wire `value` string (same shape `tryFromValue` expects).\n *\n * @param value - Raw value; only strings are resolved—anything else returns `undefined`\n * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)\n * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`\n * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)\n *\n * @example\n * ```typescript\n * const item = reviveEnumField(row.status, UserStatus);\n * const mustMatch = reviveEnumField(row.code, OrderStatus, true);\n * ```\n */\nexport const reviveEnumField = <TItem>(\n value: unknown,\n smartEnum: AnyEnumLike<TItem>,\n strict = false,\n): TItem | undefined => {\n if (typeof value !== 'string') return undefined;\n\n const revived = smartEnum.tryFromValue(value);\n if (revived !== undefined) return revived;\n\n if (strict) {\n throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);\n }\n\n return undefined;\n};\n","import type {\n AnyEnumLike,\n LogLevel,\n SmartEnumMappingsConfig,\n} from '../../types.js';\nimport { info, setLogger, getLogger, type Logger } from '../logger.js';\n\nconst createLevelFilteredLogger = (logger: Logger, level: LogLevel): Logger => {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n const currentLevel = levels[level];\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.debug) {\n logger.debug(message, ...args);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.info) {\n logger.info(message, ...args);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.warn) {\n logger.warn(message, ...args);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.error) {\n logger.error(message, ...args);\n }\n },\n };\n};\n\nlet globalEnumRegistry: Record<string, AnyEnumLike> | undefined;\n\n/**\n * Wire-format registry for `reviveAfterTransport` / `reviveSmartEnums`.\n * Not used for database string revival.\n */\nexport const initializeSmartEnumMappings = (\n config: SmartEnumMappingsConfig,\n): void => {\n globalEnumRegistry = config.enumRegistry;\n\n const logLevel = config.logLevel ?? 'error';\n const logger = config.logger ?? getLogger();\n setLogger(createLevelFilteredLogger(logger, logLevel));\n\n info('Initialized smart enum mappings', {\n enumCount: Object.keys(config.enumRegistry).length,\n enumTypes: Object.keys(config.enumRegistry),\n logLevel,\n });\n};\n\nexport const getGlobalEnumRegistry = ():\n | Record<string, AnyEnumLike>\n | undefined => globalEnumRegistry;\n","import { reviveSmartEnums } from '../transformation.js';\n\nimport { getGlobalEnumRegistry } from './transportRegistry.js';\n\n/**\n * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.\n */\nexport const reviveAfterTransport = <T>(payload: unknown): T => {\n const registry = getGlobalEnumRegistry();\n if (!registry) {\n return payload as T;\n }\n return reviveSmartEnums(payload, registry);\n};\n","import { serializeSmartEnums } from '../transformation.js';\nimport type { SerializedSmartEnums } from '../../types.js';\n\n/**\n * Serializes smart enums for transport (to client or API).\n * Wire payloads include `__smart_enum_type` for `reviveAfterTransport`.\n */\nexport const serializeForTransport = <T>(payload: T): SerializedSmartEnums<T> =>\n serializeSmartEnums(payload);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,2BAA0C;;;ACanC,IAAM,kBAAkB,OAAO,iBAAiB;AAChD,IAAM,gBAAgB,OAAO,eAAe;AAC5C,IAAM,aAAa,OAAO,YAAY;;;ACOtC,IAAM,kBAAkB,CAC7B,MAMG;AACH,SACE,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,QAAQ,IAAI,GAAG,eAAe,MAAM;AAExE;AAaO,IAAM,cAAc,CAAC,MAAmC;AAC7D,SAAO,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,QAAQ,IAAI,GAAG,UAAU,MAAM;AACxE;AAgBO,IAAM,4BAA4B,CACvC,MACiC;AACjC,SACE,CAAC,CAAC,KACF,OAAO,MAAM,YACb,QAAQ,IAAI,GAAG,mBAAmB,KAClC,QAAQ,IAAI,GAAG,OAAO;AAE1B;;;ACpEO,IAAM,iBAAiB,CAAC,GAAY,MAAwB;AACjE,MAAI,CAAC,gBAAgB,CAAC,KAAK,C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OAAK,mCAAmC;AAAA,IACtC,WAAW,OAAO,KAAK,OAAO,YAAY,EAAE;AAAA,IAC5C,WAAW,OAAO,KAAK,OAAO,YAAY;AAAA,IAC1C;AAAA,EACF,CAAC;AACH;AAEO,IAAM,wBAAwB,MAEpB;;;AC1DV,IAAM,uBAAuB,CAAI,YAAwB;AAC9D,QAAM,WAAW,sBAAsB;AACvC,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AACA,SAAO,iBAAiB,SAAS,QAAQ;AAC3C;;;ACNO,IAAM,wBAAwB,CAAI,YACvC,oBAAoB,OAAO;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/transport.ts","../src/enumerations.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/enumItemsEqual.ts","../src/extensionMethods.ts","../src/utilities/serializationMode.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts","../src/utilities/transport/transportRegistry.ts","../src/utilities/transport/reviveAfterTransport.ts","../src/utilities/transport/serializeForTransport.ts"],"sourcesContent":["/**\n * Smart Enums with Transport Utilities\n *\n * This entry point includes the core enumeration functionality plus utilities\n * for serializing/reviving enums for API transport (JSON over the wire).\n *\n * @example\n * ```typescript\n * import { enumeration, serializeForTransport, reviveAfterTransport } from '@reharik/smart-enum/transport';\n * ```\n */\n\n// Re-export core functionality\nexport { enumeration } from './enumerations.js';\nexport { isSmartEnumItem, isSmartEnum } from './utilities/typeGuards.js';\nexport {\n serializeSmartEnums,\n reviveSmartEnums,\n reviveEnumField,\n} from './utilities/transformation.js';\nexport {\n reviveAfterTransport,\n serializeForTransport,\n initializeSmartEnumMappings,\n getGlobalEnumRegistry,\n} from './utilities/transport/index.js';\n\n// Re-export core types plus transport-specific types\nexport type {\n Enumeration,\n AnyEnumLike,\n SerializedSmartEnums,\n RevivedSmartEnums,\n SmartEnumItemSerialized,\n LogLevel,\n SmartEnumMappingsConfig,\n StandardEnumItemBase,\n StandardEnumItem,\n} from './types.js';\n","import { capitalCase, constantCase } from 'case-anything';\n\nimport { addExtensionMethods } from './extensionMethods.js';\nimport {\n SMART_ENUM,\n SMART_ENUM_ID,\n SMART_ENUM_ITEM,\n SerializationMode,\n type EnumFromNormalizedObject,\n type EnumItemFromNormalizedObject,\n type EnumMemberUnionFromNormalizedObject,\n type EnumerationProps,\n type FinalizableEnumItem,\n type FinalizedEnumFields,\n type NormalizedInputType,\n type ObjectEnumInput,\n type PropertyAutoFormatter,\n type StandardEnumItem,\n} from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nimport { resolveSerializationMode } from './utilities/serializationMode.js';\n\nexport type EnumItem<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends { __smart_enum_brand: true }\n ? TEnum[K]\n : never;\n}[keyof TEnum];\n\nfunction normalizeInput<TInput extends readonly string[] | ObjectEnumInput>(\n input: TInput,\n): NormalizedInputType<TInput> {\n if (Array.isArray(input)) {\n return Object.fromEntries(\n input.map(k => [k, {}]),\n ) as NormalizedInputType<TInput>;\n }\n\n return input as NormalizedInputType<TInput>;\n}\n\nconst finalizeEnumItem = <T extends { value: string; key: string }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\n serializeAs: SerializationMode | undefined,\n): T & FinalizedEnumFields => {\n Object.defineProperty(item, SMART_ENUM_ITEM, {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, SMART_ENUM_ID, {\n value: enumInstanceId,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_brand', {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_type', {\n value: enumType,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toJSON', {\n value: () => {\n const mode = resolveSerializationMode(serializeAs);\n if (mode === 'value') {\n return item.value;\n }\n return { __smart_enum_type: enumType, value: item.value };\n },\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'equals', {\n value: (other: StandardEnumItem) => enumItemsEqual(item, other),\n enumerable: false,\n });\n\n Object.defineProperty(item, 'match', {\n value: (handlers: Record<string, (i: unknown) => unknown>) => {\n const handler = handlers[item.key];\n if (!handler) {\n throw new Error(\n `match: no handler for '${item.key}' on enum '${enumType}'`,\n );\n }\n return handler(item);\n },\n enumerable: false,\n });\n return item as T & FinalizedEnumFields;\n};\n\nconst formatProperties = (\n k: string,\n formatters: PropertyAutoFormatter[],\n): { value: string; display: string } & Record<string, string> =>\n formatters.reduce(\n (acc, formatter) => {\n acc[formatter.key] = formatter.format(k);\n return acc;\n },\n {\n value: constantCase(k),\n display: capitalCase(k),\n } as { value: string; display: string } & Record<string, string>,\n );\n\nfunction buildEnumFromObject<\n TName extends string,\n TObj extends ObjectEnumInput,\n>(\n enumType: TName,\n input: TObj,\n propertyAutoFormatters?: PropertyAutoFormatter[],\n serializeAs?: SerializationMode,\n): EnumFromNormalizedObject<TObj, TName> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumMemberUnionFromNormalizedObject<TObj, TName>;\n\n const rawEnumItems: Partial<{\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K, TName>;\n }> = {};\n\n const enumInstanceId = Symbol('smart-enum-instance');\n let index = 0;\n\n for (const key in input) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n const typedKey = key;\n const value = input[typedKey];\n\n const enumItemBase = {\n index,\n key: typedKey,\n ...formatProperties(typedKey, formattersWithDefaults),\n ...value,\n } as FinalizableEnumItem & TObj[typeof typedKey];\n\n const enumItem = finalizeEnumItem(\n enumItemBase,\n enumType,\n enumInstanceId,\n serializeAs,\n ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey as keyof TObj] = enumItem;\n index++;\n }\n }\n\n const extensionMethods = addExtensionMethods<TItem>(\n Object.values(rawEnumItems) as TItem[],\n );\n\n const enumObject = {\n ...rawEnumItems,\n ...extensionMethods,\n } as EnumFromNormalizedObject<TObj, TName>;\n\n Object.defineProperty(enumObject, SMART_ENUM, {\n value: true,\n enumerable: false,\n });\n\n Object.freeze(enumObject);\n\n return enumObject;\n}\n\nexport function enumeration<\n const TArr extends readonly string[],\n const TName extends string = string,\n>(\n enumType: TName,\n props: EnumerationProps<TArr>,\n): EnumFromNormalizedObject<NormalizedInputType<TArr>, TName>;\n\nexport function enumeration<\n const TObj extends ObjectEnumInput,\n const TName extends string = string,\n>(\n enumType: TName,\n props: EnumerationProps<TObj>,\n): EnumFromNormalizedObject<NormalizedInputType<TObj>, TName>;\n\nexport function enumeration<const TName extends string = string>(\n enumType: TName,\n props: EnumerationProps<readonly string[] | ObjectEnumInput>,\n): EnumFromNormalizedObject<\n NormalizedInputType<readonly string[] | ObjectEnumInput>,\n TName\n> {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n props.serializeAs,\n );\n}\n","/**\n * Type guard to check if a value is not null or undefined\n * @param value - The value to check\n * @returns True if the value is defined and not null\n */\nexport const notEmpty = <X>(\n value: X | null | undefined,\n): value is NonNullable<X> => {\n // eslint-disable-next-line unicorn/no-null\n return value != null;\n};\n\n// Public symbols used at runtime for detection/identity (not used in type keys)\nexport const SMART_ENUM_ITEM = Symbol('smart-enum-item');\nexport const SMART_ENUM_ID = Symbol('smart-enum-id');\nexport const SMART_ENUM = Symbol('smart-enum');\n\n/**\n * Options for filtering enum items in various methods\n */\nexport type EnumFilterOptions = {\n /** Include items with null/undefined values (default: false) */\n showEmpty?: boolean;\n /** Include deprecated items (default: false) */\n showDeprecated?: boolean;\n};\n\n// export type EnumInput = readonly string[] | ObjectEnumInput;\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Structural detection checks for\n * presence of `key` and `value`.\n */\nexport type SerializedSmartEnums<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<SerializedSmartEnums<U>>\n : T extends Array<infer U>\n ? SerializedSmartEnums<U>[]\n : T extends object\n ? { [K in keyof T]: SerializedSmartEnums<T[K]> }\n : T;\n\n/**\n * Revived shape: for keys present in mapping M, the string becomes the\n * corresponding enum item type (derived from the provided enum object);\n * other fields recurse.\n */\nexport type EnumItemFromEnum<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\n/**\n * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).\n * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).\n */\nexport type AnyEnumLike<T = unknown> = {\n tryFromValue: (value?: string | null) => T | undefined;\n tryFromKey: (key?: string | null) => T | undefined;\n} & Record<string, unknown>;\n\nexport type RevivedSmartEnums<T, M extends Record<string, AnyEnumLike>> =\n T extends ReadonlyArray<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends Array<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends object\n ? {\n [K in keyof T]: K extends Extract<keyof M, string>\n ? Enumeration<M[K]>\n : RevivedSmartEnums<T[K], M>;\n }\n : T;\n\nexport type SmartEnumItemSerialized = {\n __smart_enum_type: string;\n value: string;\n};\n\n/** Example shape for transport tests (`reviveAfterTransport` registry). */\nexport type SmartApiHelperConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n};\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Used for database storage.\n */\nexport type DatabaseFormat<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DatabaseFormat<U>>\n : T extends Array<infer U>\n ? DatabaseFormat<U>[]\n : T extends object\n ? { [K in keyof T]: DatabaseFormat<T[K]> }\n : T;\n\n/**\n * Log levels for smart enum mappings\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Configuration for smart enum mappings initialization\n */\nexport type SmartEnumMappingsConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n logLevel?: LogLevel;\n logger?: import('./utilities/logger.js').Logger;\n};\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\n/**\n * Structural fields shared by every enum member (key, value, display, index, optional deprecated).\n * Does not include smart-enum branding or database helpers; see {@link StandardEnumItem}.\n */\nexport type StandardEnumItemBase = {\n readonly key: string;\n readonly value: string;\n readonly display: string;\n readonly index: number;\n readonly deprecated?: boolean;\n};\n\n/**\n * Branded item produced by `enumeration()`: {@link StandardEnumItemBase} plus runtime identity\n * (`__smart_enum_brand`, `__smart_enum_type`) and `toPostgres()`.\n */\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\n readonly toJSON: () => string | { __smart_enum_type: string; value: string };\n readonly equals: <\n This extends { __smart_enum_type: string },\n T extends {\n __smart_enum_type: This['__smart_enum_type'];\n } & StandardEnumItem,\n >(\n this: This,\n other: T,\n ) => this is T;\n};\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n Record<string, unknown>;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\nexport type EmptyEnumInputItem = Record<never, never>;\n\ntype Separator = '-' | '_' | ' ' | '.';\n\ntype IsUpperChar<C extends string> =\n C extends Uppercase<C> ? (C extends Lowercase<C> ? false : true) : false;\n\ntype IsLowerChar<C extends string> =\n C extends Lowercase<C> ? (C extends Uppercase<C> ? false : true) : false;\n\ntype PushUnderscore<S extends string> = S extends '' | `${string}_`\n ? S\n : `${S}_`;\n\ntype TrimUnderscore<S extends string> = S extends `_${infer R}`\n ? TrimUnderscore<R>\n : S extends `${infer R}_`\n ? TrimUnderscore<R>\n : S;\n\ntype CollapseUnderscores<S extends string> = S extends `${infer A}__${infer B}`\n ? CollapseUnderscores<`${A}_${B}`>\n : S;\n\ntype ConstantCaseInternal<\n S extends string,\n Prev extends string = '',\n Out extends string = '',\n> = S extends `${infer C}${infer Rest}`\n ? C extends Separator\n ? ConstantCaseInternal<Rest, C, PushUnderscore<Out>>\n : IsUpperChar<C> extends true\n ? IsLowerChar<Prev> extends true\n ? ConstantCaseInternal<Rest, C, `${PushUnderscore<Out>}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : CollapseUnderscores<TrimUnderscore<Out>>;\n\ntype ConstantCase<S extends string> = string extends S\n ? string\n : ConstantCaseInternal<S>;\n\n/** Segments of a `ConstantCase` string (underscore-separated ALL CAPS words). */\ntype SplitConstantCaseSegments<S extends string> =\n S extends `${infer A}_${infer B}`\n ? [A, ...SplitConstantCaseSegments<B>]\n : [S];\n\n/** First character upper, remainder lower (for ALL-CAPS words from `ConstantCase`). */\ntype TitleCaseAllCapsWord<W extends string> = W extends ''\n ? ''\n : W extends `${infer F}${infer R}`\n ? `${Uppercase<F>}${Lowercase<R>}`\n : W;\n\ntype JoinDisplaySegments<T extends readonly string[]> = T extends readonly [\n infer A extends string,\n ...infer Rest extends readonly string[],\n]\n ? Rest extends readonly []\n ? TitleCaseAllCapsWord<A>\n : `${TitleCaseAllCapsWord<A>} ${JoinDisplaySegments<Rest>}`\n : '';\n\n/**\n * Display string derived from the enum member key: `ConstantCase` → split → title-case words → join with spaces.\n * Matches default runtime `capitalCase(key)` for typical PascalCase / camelCase keys. Member keys that already\n * contain separators may differ from `capitalCase` at runtime; custom `propertyAutoFormatters` for `display`\n * are not reflected in this type.\n */\ntype DisplayCaseFromEnumKey<K extends string> = string extends K\n ? string\n : JoinDisplaySegments<SplitConstantCaseSegments<ConstantCase<K>>>;\n\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\n/** Input-derived fields for one member key (excludes built-ins filled by `enumeration()`). */\nexport type EnumMemberExtra<\n TObj extends ObjectEnumInput,\n K extends keyof TObj,\n> = Omit<TObj[K], BuiltInOverrideKeys>;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n TName extends string = string,\n> = Omit<\n StandardEnumItem,\n 'key' | 'value' | 'display' | '__smart_enum_type'\n> & { __smart_enum_type: TName } & SmartEnumMatch &\n EnumMemberExtra<TObj, K> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? [Extract<V, string>] extends [never]\n ? ConstantCase<Extract<K, string>>\n : Extract<V, string>\n : ConstantCase<Extract<K, string>>;\n readonly display: TObj[K] extends { display?: infer D }\n ? [Extract<D, string>] extends [never]\n ? DisplayCaseFromEnumKey<Extract<K, string>>\n : Extract<D, string>\n : DisplayCaseFromEnumKey<Extract<K, string>>;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<\n TObj extends ObjectEnumInput,\n TName extends string = string,\n> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K, TName>;\n}[keyof TObj];\n\nexport type EnumFromNormalizedObject<\n TObj extends ObjectEnumInput,\n TName extends string = string,\n> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K, TName>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj, TName>>;\n\nexport type UnionKeys<T> = T extends T ? keyof T : never;\n\n/*\nTo widen the type of the OptionalObject from literals to their actual types,\ne.g.\nshape?: \"round\" | \"square\" | \"long\";\nslices?: true;\nlayers?: 2;\n--turns into:--\nshape: string | undefined;\nslices: boolean| undefined;\nlayers: number| undefined;\n\nwe can use the following code:\ntype Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T;\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? Widen<V> : undefined;\n};\n*/\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? V : undefined;\n};\n\ntype ExtraShapeUnion<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: Omit<TObj[K], BuiltInOverrideKeys>;\n}[keyof TObj];\n\nexport type InferredExtraFields<TObj extends ObjectEnumInput> =\n MergeUnionToObject<ExtraShapeUnion<TObj>>;\n\nexport type PropertyAutoFormatter = {\n /** The property name to generate */\n key: string;\n /** Function to transform the key into the property value */\n format: (k: string) => string;\n};\n\nexport type CoreEnumMethods<TItem extends StandardEnumItem> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n /** Matches runtime: `items.map(i => i.value)` (see {@link EnumLikeBase}). */\n values(): readonly TItem['value'][];\n /** Matches runtime: `items.map(i => i.key)` (see {@link EnumLikeBase}). */\n keys(): readonly TItem['key'][];\n};\n\n/**\n * Structural shape of a smart-style enum object: lookup by value/key, list items/values/keys,\n * plus an index signature so registry and mapping types can treat instances as records.\n * Use {@link SmartEnumLike} when items are full {@link StandardEnumItem}s (the usual case).\n */\nexport type EnumLikeBase<\n TItem extends StandardEnumItemBase = StandardEnumItemBase,\n> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n values(): readonly TItem['value'][];\n keys(): readonly TItem['key'][];\n} & Record<string, unknown>;\n\n/**\n * A {@link EnumLikeBase} whose items are branded {@link StandardEnumItem}s (typical `enumeration()` result).\n */\nexport type SmartEnumLike<TItem extends StandardEnumItem = StandardEnumItem> =\n EnumLikeBase<TItem>;\n\n/** Union of branded enum member values on an enum object `T`. */\nexport type SmartEnumMemberUnion<T extends Record<string, unknown>> = {\n [K in keyof T]: T[K] extends StandardEnumItem ? T[K] : never;\n}[keyof T];\n\n/** Keys on `TEnum` whose member matches `Record<P, V>` within `ItemUnion`. */\nexport type SmartEnumSubsetKeys<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = {\n [K in keyof TEnum]: TEnum[K] extends Extract<ItemUnion, Record<P, V>>\n ? K\n : never;\n}[keyof TEnum];\n\nexport type SmartEnumSubsetItemUnion<\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Extract<ItemUnion, Record<P, V>>;\n\nexport type SmartEnumSubsetView<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Pick<TEnum, SmartEnumSubsetKeys<TEnum, ItemUnion, P, V>> &\n CoreEnumMethods<SmartEnumSubsetItemUnion<ItemUnion, P, V>>;\n\n/** Return type of {@link getSubsetByProp} / {@link subsetByProp} for explicit consumer annotations. */\nexport type SubsetByPropResult<\n TEnum extends Record<string, unknown> &\n SmartEnumLike<SmartEnumMemberUnion<TEnum>>,\n P extends keyof SmartEnumMemberUnion<TEnum> & string,\n V extends SmartEnumMemberUnion<TEnum>[P],\n> = SmartEnumSubsetView<TEnum, SmartEnumMemberUnion<TEnum>, P, V>;\n\nexport type FieldEnumMapping = Record<string, SmartEnumLike>;\n\nexport type ReviveRowOptions = {\n fieldEnumMapping: FieldEnumMapping;\n strict?: boolean;\n};\n\nexport type PathEnumMapping = Record<string, SmartEnumLike>;\n\nexport type RevivePayloadOptions = {\n pathEnumMapping: PathEnumMapping;\n strict?: boolean;\n};\n\n/**\n * Serialization mode controls how smart-enum items are serialized to JSON.\n *\n * - 'wrapped' (default): toJSON returns { __smart_enum_type, value }.\n * Use this when payloads need to be self-describing for revival on the\n * receiving end (e.g. REST APIs with explicit revive middleware).\n *\n * - 'value': toJSON returns just the wire value string.\n * Use this when the receiving end already knows the enum types from\n * schema context (e.g. GraphQL boundaries).\n *\n * Resolution order at toJSON call time:\n * 1. Per-enum `serializeAs` option (if set on enumeration())\n * 2. Global default (set via setDefaultSerializationMode)\n * 3. 'wrapped' (built-in default, preserves backward compatibility)\n */\nexport type SerializationMode = 'wrapped' | 'value';\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n serializeAs?: SerializationMode;\n};\n\nexport type Enumeration<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\nexport type FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type' | 'toJSON'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n\n/**\n * Exhaustive branch-on-member. One arm required per member of the *statically\n * known* receiver — miss one and it won't compile. Over a pickEnum view the\n * arms are exhaustive over just the picked members.\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SmartEnumMatch {\n readonly key: string;\n match<R>(handlers: {\n [P in this['key']]: (item: Extract<this, { key: P }>) => R;\n }): R;\n}\n\n/** Member keys of an enum object (excludes the method keys). */\nexport type EnumMemberKeys<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends StandardEnumItem ? K : never;\n}[keyof TEnum];\n\n/**\n * Enum-like view over an explicit list of member keys. Reuses the parent's item\n * references; methods scope to the picked subset. See {@link pickEnum}.\n */\nexport type PickEnumView<\n TEnum extends Record<string, unknown>,\n K extends EnumMemberKeys<TEnum>,\n> = Pick<TEnum, K> & CoreEnumMethods<Extract<TEnum[K], StandardEnumItem>>;\n\nexport type EnumSubset<\n TItems extends StandardEnumItem,\n K extends TItems['key'],\n> = Extract<TItems, { key: K }>;\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\n SmartEnumLike,\n} from '../types.js';\n\n/**\n * Runtime type guard to detect Smart Enum items created by this library.\n * Returns true if the value has the SMART_ENUM_ITEM symbol.\n *\n * @example\n * ```typescript\n * import { Status } from './status';\n * const item = Status.active;\n * isSmartEnumItem(item); // true\n * isSmartEnumItem({ key: 'active', value: 'ACTIVE' }); // false (plain object)\n * if (isSmartEnumItem(x)) {\n * console.log(x.value, x.__smart_enum_type); // narrowed to enum item\n * }\n * ```\n */\nexport const isSmartEnumItem = (\n x: unknown,\n): x is {\n key: string;\n value: string;\n index?: number;\n __smart_enum_type?: string;\n} => {\n return (\n !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM_ITEM) === true\n );\n};\n\n/**\n * Runtime type guard to detect a full Smart Enum object created by this library.\n * Returns true if the object has the SMART_ENUM property.\n *\n * @example\n * ```typescript\n * import { MyEnum } from './blah';\n * isSmartEnum(MyEnum) === true; // true\n * isSmartEnum(MyEnum.one) === false; // false (this is an item, not the enum)\n * ```\n */\nexport const isSmartEnum = (x: unknown): x is SmartEnumLike => {\n return !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM) === true;\n};\n\n/**\n * Runtime type guard to detect a serialized Smart Enum item created by this library.\n * Returns true if the value has `__smart_enum_type` and `value` (wire/database shape).\n *\n * @example\n * ```typescript\n * const wire = { __smart_enum_type: 'Status', value: 'ACTIVE' };\n * isSerializedSmartEnumItem(wire); // true\n * isSerializedSmartEnumItem(Status.active); // false (live enum item)\n * if (isSerializedSmartEnumItem(x)) {\n * reviveItem(x.__smart_enum_type, x.value); // narrowed to SmartEnumItemSerialized\n * }\n * ```\n */\nexport const isSerializedSmartEnumItem = (\n x: unknown,\n): x is SmartEnumItemSerialized => {\n return (\n !!x &&\n typeof x === 'object' &&\n Reflect.has(x, '__smart_enum_type') &&\n Reflect.has(x, 'value')\n );\n};\n","import { SMART_ENUM_ID } from '../types.js';\n\nimport { isSmartEnumItem } from './typeGuards.js';\n\n/** Value-based equality for smart enum items from the same enumeration instance. */\nexport const enumItemsEqual = (a: unknown, b: unknown): boolean => {\n if (!isSmartEnumItem(a) || !isSmartEnumItem(b)) {\n return false;\n }\n\n return (\n Reflect.get(a, SMART_ENUM_ID) === Reflect.get(b, SMART_ENUM_ID) &&\n a.value === b.value\n );\n};\n","import type { CoreEnumMethods, StandardEnumItem } from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nexport const addExtensionMethods = <TItem extends StandardEnumItem>(\n enumItems: readonly TItem[],\n): CoreEnumMethods<TItem> => {\n const findBy = <K extends keyof TItem>(field: K, target: TItem[K]) =>\n enumItems.find(item => item[field] === target);\n\n const requireBy = <K extends keyof TItem>(\n field: K,\n target: TItem[K],\n label: string,\n ) => {\n const item = findBy(field, target);\n if (!item) {\n throw new Error(`No enum ${label} found for '${String(target)}'`);\n }\n return item;\n };\n\n return {\n fromValue: value => requireBy('value', value as TItem['value'], 'value'),\n tryFromValue: value =>\n value ? findBy('value', value as TItem['value']) : undefined,\n\n fromKey: key => requireBy('key', key as TItem['key'], 'key'),\n tryFromKey: key => (key ? findBy('key', key as TItem['key']) : undefined),\n\n equals: enumItemsEqual,\n\n items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\n };\n};\n","import { SerializationMode } from '../types.js';\n\nlet globalDefault: SerializationMode | undefined;\n\n/**\n * Set the global default serialization mode for all smart-enum items\n * that don't have a per-enum serializeAs option.\n *\n * Call once at app startup, before any JSON.stringify happens on enum items.\n *\n * @example\n * setDefaultSerializationMode('value');\n */\nexport const setDefaultSerializationMode = (mode: SerializationMode): void => {\n globalDefault = mode;\n};\n\n/**\n * Reset the global default to its initial unset state.\n * Primarily useful for tests.\n */\nexport const resetDefaultSerializationMode = (): void => {\n globalDefault = undefined;\n};\n\n/**\n * Resolve the effective serialization mode for an enum item.\n * Per-enum option wins, then global, then 'wrapped'.\n */\nexport const resolveSerializationMode = (\n perEnum: SerializationMode | undefined,\n): SerializationMode => perEnum ?? globalDefault ?? 'wrapped';\n","/**\n * Logger interface for @reharik/smart-enum library\n *\n * This interface allows users to inject their own logging implementation\n * or use the default console logger.\n */\n\nexport type Logger = {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n};\n\n/**\n * Default console logger implementation\n */\nconst consoleLogger: Logger = {\n debug(message: string, ...args: unknown[]): void {\n console.debug(`[@reharik/smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[@reharik/smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[@reharik/smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[@reharik/smart-enum:error] ${message}`, ...args);\n },\n};\n\n/**\n * Global logger instance\n * Defaults to console logger\n */\nlet globalLogger: Logger = consoleLogger;\n\n/**\n * Sets the global logger instance\n *\n * @param logger - The logger implementation to use\n *\n * @example\n * ```typescript\n * import { setLogger } from '@reharik/smart-enum';\n *\n * // Use custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, args),\n * info: (msg, ...args) => myLogger.info(msg, args),\n * warn: (msg, ...args) => myLogger.warn(msg, args),\n * error: (msg, ...args) => myLogger.error(msg, args),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n globalLogger = logger;\n}\n\n/**\n * Gets the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n return globalLogger;\n}\n\n// Internal convenience functions for library use\nexport function debug(message: string, ...args: unknown[]): void {\n globalLogger.debug(message, ...args);\n}\n\nexport function info(message: string, ...args: unknown[]): void {\n globalLogger.info(message, ...args);\n}\n\nexport function warn(message: string, ...args: unknown[]): void {\n globalLogger.warn(message, ...args);\n}\n\nexport function error(message: string, ...args: unknown[]): void {\n globalLogger.error(message, ...args);\n}\n","// serializeSmartEnums.ts\nexport { isSmartEnumItem, isSmartEnum } from './typeGuards.js';\nimport type { SerializedSmartEnums, AnyEnumLike } from '../types.js';\n\nimport { debug } from './logger.js';\nimport { isSerializedSmartEnumItem, isSmartEnumItem } from './typeGuards.js';\n\ntype PlainObject = Record<string, unknown>;\n\nconst isPlainObject = (x: unknown): x is PlainObject =>\n typeof x === 'object' &&\n x !== null &&\n Object.getPrototypeOf(x) === Object.prototype;\n\n/**\n * Recursively replaces Smart Enum items with self-describing objects\n * `{ __smart_enum_type, value }` for JSON transport or storage.\n *\n * @param input - Object or array that may contain enum items\n * @returns Same structure with enum items replaced by serialized shape\n *\n * @example\n * ```typescript\n * const dto = { id: '1', status: Status.active, color: Color.red };\n * const wire = serializeSmartEnums(dto);\n * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }\n * ```\n */\n// Overloads:\n// 1) Inferred\nexport function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;\n// 2) Return-type only (constrained to objects/arrays)\nexport function serializeSmartEnums<\n S extends Readonly<PlainObject> | readonly unknown[],\n>(input: unknown): S;\n// Implementation\nexport function serializeSmartEnums(input: unknown): unknown {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n if (isSmartEnumItem(v)) {\n return {\n __smart_enum_type: v.__smart_enum_type,\n value: v.value,\n };\n }\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) {\n arr.push(walk(item));\n }\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n\n return walk(input);\n}\n\n/**\n * Recursively revives serialized enum objects back to Smart Enum items\n * using a registry of enum types. Expects payload to contain\n * `{ __smart_enum_type, value }` where the type exists in the registry.\n *\n * @param input - Serialized payload (e.g. from JSON)\n * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)\n * @returns Payload with serialized enums revived to enum items\n *\n * @example\n * ```typescript\n * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };\n * const revived = reviveSmartEnums(wire, { Status, Color });\n * // revived.status === Status.active\n * ```\n */\nexport function reviveSmartEnums<R>(\n input: unknown,\n registry: Record<string, AnyEnumLike>,\n): R {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n // Handle self-describing enum objects with __smart_enum_type and value\n if (isSerializedSmartEnumItem(v)) {\n debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);\n const enumInstance = registry[v.__smart_enum_type];\n if (enumInstance) {\n debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);\n // Try to find the enum item by value first\n const enumItem = enumInstance.tryFromValue(v.value);\n if (enumItem) {\n debug(`Revived enumItem using value: ${v.value}`);\n return enumItem;\n }\n // If that fails, try to find by key (convert value to key format)\n const key = v.value.toLowerCase();\n const enumItemFromKey = enumInstance.tryFromKey(key);\n if (enumItemFromKey) {\n debug(`Revived enumItem using key: ${key}`);\n return enumItemFromKey;\n }\n }\n // If no matching enum type in registry, return the original serialized object\n return v;\n }\n\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) arr.push(walk(item));\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n return walk(input) as R;\n}\n\n/**\n * Maps a plain string (for example a column value from a database query) to the\n * corresponding Smart Enum item by calling `tryFromValue` on the given enum.\n *\n * Use this when you already know which enum type a field uses and the stored\n * value is the enum’s wire `value` string (same shape `tryFromValue` expects).\n *\n * @param value - Raw value; only strings are resolved—anything else returns `undefined`\n * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)\n * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`\n * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)\n *\n * @example\n * ```typescript\n * const item = reviveEnumField(row.status, UserStatus);\n * const mustMatch = reviveEnumField(row.code, OrderStatus, true);\n * ```\n */\nexport const reviveEnumField = <TItem>(\n value: unknown,\n smartEnum: AnyEnumLike<TItem>,\n strict = false,\n): TItem | undefined => {\n if (typeof value !== 'string') return undefined;\n\n const revived = smartEnum.tryFromValue(value);\n if (revived !== undefined) return revived;\n\n if (strict) {\n throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);\n }\n\n return undefined;\n};\n","import type {\n AnyEnumLike,\n LogLevel,\n SmartEnumMappingsConfig,\n} from '../../types.js';\nimport { info, setLogger, getLogger, type Logger } from '../logger.js';\n\nconst createLevelFilteredLogger = (logger: Logger, level: LogLevel): Logger => {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n const currentLevel = levels[level];\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.debug) {\n logger.debug(message, ...args);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.info) {\n logger.info(message, ...args);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.warn) {\n logger.warn(message, ...args);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.error) {\n logger.error(message, ...args);\n }\n },\n };\n};\n\nlet globalEnumRegistry: Record<string, AnyEnumLike> | undefined;\n\n/**\n * Wire-format registry for `reviveAfterTransport` / `reviveSmartEnums`.\n * Not used for database string revival.\n */\nexport const initializeSmartEnumMappings = (\n config: SmartEnumMappingsConfig,\n): void => {\n globalEnumRegistry = config.enumRegistry;\n\n const logLevel = config.logLevel ?? 'error';\n const logger = config.logger ?? getLogger();\n setLogger(createLevelFilteredLogger(logger, logLevel));\n\n info('Initialized smart enum mappings', {\n enumCount: Object.keys(config.enumRegistry).length,\n enumTypes: Object.keys(config.enumRegistry),\n logLevel,\n });\n};\n\nexport const getGlobalEnumRegistry = ():\n | Record<string, AnyEnumLike>\n | undefined => globalEnumRegistry;\n","import { reviveSmartEnums } from '../transformation.js';\n\nimport { getGlobalEnumRegistry } from './transportRegistry.js';\n\n/**\n * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.\n */\nexport const reviveAfterTransport = <T>(payload: unknown): T => {\n const registry = getGlobalEnumRegistry();\n if (!registry) {\n return payload as T;\n }\n return reviveSmartEnums(payload, registry);\n};\n","import { serializeSmartEnums } from '../transformation.js';\nimport type { SerializedSmartEnums } from '../../types.js';\n\n/**\n * Serializes smart enums for transport (to client or API).\n * Wire payloads include `__smart_enum_type` for `reviveAfterTransport`.\n */\nexport const serializeForTransport = <T>(payload: T): SerializedSmartEnums<T> =>\n serializeSmartEnums(payload);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,2BAA0C;;;ACanC,IAAM,kBAAkB,OAAO,iBAAiB;AAChD,IAAM,gBAAgB,OAAO,eAAe;AAC5C,IAAM,aAAa,OAAO,YAAY;;;ACOtC,IAAM,kBAAkB,CAC7B,MAMG;AACH,SACE,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,QAAQ,IAAI,GAAG,eAAe,MAAM;AAExE;AAaO,IAAM,cAAc,CAAC,MAAmC;AAC7D,SAAO,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,QAAQ,IAAI,GAAG,UAAU,MAAM;AACxE;AAgBO,IAAM,4BAA4B,CACvC,MACiC;AACjC,SACE,CAAC,CAAC,KACF,OAAO,MAAM,YACb,QAAQ,IAAI,GAAG,mBAAmB,KAClC,QAAQ,IAAI,GAAG,OAAO;AAE1B;;;ACpEO,IA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,SAAS,OAAO,UAAU,UAAU;AAC1C,YAAU,0BAA0B,QAAQ,QAAQ,CAAC;AAErD,OAAK,mCAAmC;AAAA,IACtC,WAAW,OAAO,KAAK,OAAO,YAAY,EAAE;AAAA,IAC5C,WAAW,OAAO,KAAK,OAAO,YAAY;AAAA,IAC1C;AAAA,EACF,CAAC;AACH;AAEO,IAAM,wBAAwB,MAEpB;;;AC1DV,IAAM,uBAAuB,CAAI,YAAwB;AAC9D,QAAM,WAAW,sBAAsB;AACvC,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AACA,SAAO,iBAAiB,SAAS,QAAQ;AAC3C;;;ACNO,IAAM,wBAAwB,CAAI,YACvC,oBAAoB,OAAO;","names":[]}
|
package/dist/transport.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { g as SerializedSmartEnums, f as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-
|
|
2
|
-
export { E as Enumeration, d as LogLevel, R as RevivedSmartEnums, h as SmartEnumItemSerialized, w as StandardEnumItem, v as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-
|
|
1
|
+
import { g as SerializedSmartEnums, f as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-CrXfK1cB.cjs';
|
|
2
|
+
export { E as Enumeration, d as LogLevel, R as RevivedSmartEnums, h as SmartEnumItemSerialized, w as StandardEnumItem, v as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-CrXfK1cB.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Revives smart enums after transport. Requires `initializeSmartEnumMappings`.
|
package/dist/transport.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { g as SerializedSmartEnums, f as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-
|
|
2
|
-
export { E as Enumeration, d as LogLevel, R as RevivedSmartEnums, h as SmartEnumItemSerialized, w as StandardEnumItem, v as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-
|
|
1
|
+
import { g as SerializedSmartEnums, f as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-CrXfK1cB.js';
|
|
2
|
+
export { E as Enumeration, d as LogLevel, R as RevivedSmartEnums, h as SmartEnumItemSerialized, w as StandardEnumItem, v as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-CrXfK1cB.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Revives smart enums after transport. Requires `initializeSmartEnumMappings`.
|
package/dist/transport.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/enumerations.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/enumItemsEqual.ts","../src/extensionMethods.ts","../src/utilities/serializationMode.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts","../src/utilities/transport/transportRegistry.ts","../src/utilities/transport/reviveAfterTransport.ts","../src/utilities/transport/serializeForTransport.ts"],"sourcesContent":["import { capitalCase, constantCase } from 'case-anything';\n\nimport { addExtensionMethods } from './extensionMethods.js';\nimport {\n SMART_ENUM,\n SMART_ENUM_ID,\n SMART_ENUM_ITEM,\n SerializationMode,\n type EnumFromNormalizedObject,\n type EnumItemFromNormalizedObject,\n type EnumMemberUnionFromNormalizedObject,\n type EnumerationProps,\n type FinalizableEnumItem,\n type FinalizedEnumFields,\n type NormalizedInputType,\n type ObjectEnumInput,\n type PropertyAutoFormatter,\n type StandardEnumItem,\n} from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nimport { resolveSerializationMode } from './utilities/serializationMode.js';\n\nexport type EnumItem<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends { __smart_enum_brand: true }\n ? TEnum[K]\n : never;\n}[keyof TEnum];\n\nfunction normalizeInput<TInput extends readonly string[] | ObjectEnumInput>(\n input: TInput,\n): NormalizedInputType<TInput> {\n if (Array.isArray(input)) {\n return Object.fromEntries(\n input.map(k => [k, {}]),\n ) as NormalizedInputType<TInput>;\n }\n\n return input as NormalizedInputType<TInput>;\n}\n\nconst finalizeEnumItem = <T extends { value: string; key: string }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\n serializeAs: SerializationMode | undefined,\n): T & FinalizedEnumFields => {\n Object.defineProperty(item, SMART_ENUM_ITEM, {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, SMART_ENUM_ID, {\n value: enumInstanceId,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_brand', {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_type', {\n value: enumType,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toJSON', {\n value: () => {\n const mode = resolveSerializationMode(serializeAs);\n if (mode === 'value') {\n return item.value;\n }\n return { __smart_enum_type: enumType, value: item.value };\n },\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'equals', {\n value: (other: StandardEnumItem) => enumItemsEqual(item, other),\n enumerable: false,\n });\n\n Object.defineProperty(item, 'match', {\n value: (handlers: Record<string, (i: unknown) => unknown>) => {\n const handler = handlers[item.key];\n if (!handler) {\n throw new Error(\n `match: no handler for '${item.key}' on enum '${enumType}'`,\n );\n }\n return handler(item);\n },\n enumerable: false,\n });\n return item as T & FinalizedEnumFields;\n};\n\nconst formatProperties = (\n k: string,\n formatters: PropertyAutoFormatter[],\n): { value: string; display: string } & Record<string, string> =>\n formatters.reduce(\n (acc, formatter) => {\n acc[formatter.key] = formatter.format(k);\n return acc;\n },\n {\n value: constantCase(k),\n display: capitalCase(k),\n } as { value: string; display: string } & Record<string, string>,\n );\n\nfunction buildEnumFromObject<TObj extends ObjectEnumInput>(\n enumType: string,\n input: TObj,\n propertyAutoFormatters?: PropertyAutoFormatter[],\n serializeAs?: SerializationMode,\n): EnumFromNormalizedObject<TObj> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumMemberUnionFromNormalizedObject<TObj>;\n\n const rawEnumItems: Partial<{\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }> = {};\n\n const enumInstanceId = Symbol('smart-enum-instance');\n let index = 0;\n\n for (const key in input) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n const typedKey = key;\n const value = input[typedKey];\n\n const enumItemBase = {\n index,\n key: typedKey,\n ...formatProperties(typedKey, formattersWithDefaults),\n ...value,\n } as FinalizableEnumItem & TObj[typeof typedKey];\n\n const enumItem = finalizeEnumItem(\n enumItemBase,\n enumType,\n enumInstanceId,\n serializeAs,\n ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey as keyof TObj] = enumItem;\n index++;\n }\n }\n\n const extensionMethods = addExtensionMethods<TItem>(\n Object.values(rawEnumItems) as TItem[],\n );\n\n const enumObject = {\n ...rawEnumItems,\n ...extensionMethods,\n } as EnumFromNormalizedObject<TObj>;\n\n Object.defineProperty(enumObject, SMART_ENUM, {\n value: true,\n enumerable: false,\n });\n\n Object.freeze(enumObject);\n\n return enumObject;\n}\n\nexport function enumeration<const TArr extends readonly string[]>(\n enumType: string,\n props: EnumerationProps<TArr>,\n): EnumFromNormalizedObject<NormalizedInputType<TArr>>;\n\nexport function enumeration<const TObj extends ObjectEnumInput>(\n enumType: string,\n props: EnumerationProps<TObj>,\n): EnumFromNormalizedObject<NormalizedInputType<TObj>>;\n\nexport function enumeration(\n enumType: string,\n props: EnumerationProps<readonly string[] | ObjectEnumInput>,\n): EnumFromNormalizedObject<\n NormalizedInputType<readonly string[] | ObjectEnumInput>\n> {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n props.serializeAs,\n );\n}\n","/**\n * Type guard to check if a value is not null or undefined\n * @param value - The value to check\n * @returns True if the value is defined and not null\n */\nexport const notEmpty = <X>(\n value: X | null | undefined,\n): value is NonNullable<X> => {\n // eslint-disable-next-line unicorn/no-null\n return value != null;\n};\n\n// Public symbols used at runtime for detection/identity (not used in type keys)\nexport const SMART_ENUM_ITEM = Symbol('smart-enum-item');\nexport const SMART_ENUM_ID = Symbol('smart-enum-id');\nexport const SMART_ENUM = Symbol('smart-enum');\n\n/**\n * Options for filtering enum items in various methods\n */\nexport type EnumFilterOptions = {\n /** Include items with null/undefined values (default: false) */\n showEmpty?: boolean;\n /** Include deprecated items (default: false) */\n showDeprecated?: boolean;\n};\n\n// export type EnumInput = readonly string[] | ObjectEnumInput;\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Structural detection checks for\n * presence of `key` and `value`.\n */\nexport type SerializedSmartEnums<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<SerializedSmartEnums<U>>\n : T extends Array<infer U>\n ? SerializedSmartEnums<U>[]\n : T extends object\n ? { [K in keyof T]: SerializedSmartEnums<T[K]> }\n : T;\n\n/**\n * Revived shape: for keys present in mapping M, the string becomes the\n * corresponding enum item type (derived from the provided enum object);\n * other fields recurse.\n */\nexport type EnumItemFromEnum<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\n/**\n * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).\n * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).\n */\nexport type AnyEnumLike<T = unknown> = {\n tryFromValue: (value?: string | null) => T | undefined;\n tryFromKey: (key?: string | null) => T | undefined;\n} & Record<string, unknown>;\n\nexport type RevivedSmartEnums<T, M extends Record<string, AnyEnumLike>> =\n T extends ReadonlyArray<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends Array<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends object\n ? {\n [K in keyof T]: K extends Extract<keyof M, string>\n ? Enumeration<M[K]>\n : RevivedSmartEnums<T[K], M>;\n }\n : T;\n\nexport type SmartEnumItemSerialized = {\n __smart_enum_type: string;\n value: string;\n};\n\n/** Example shape for transport tests (`reviveAfterTransport` registry). */\nexport type SmartApiHelperConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n};\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Used for database storage.\n */\nexport type DatabaseFormat<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DatabaseFormat<U>>\n : T extends Array<infer U>\n ? DatabaseFormat<U>[]\n : T extends object\n ? { [K in keyof T]: DatabaseFormat<T[K]> }\n : T;\n\n/**\n * Log levels for smart enum mappings\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Configuration for smart enum mappings initialization\n */\nexport type SmartEnumMappingsConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n logLevel?: LogLevel;\n logger?: import('./utilities/logger.js').Logger;\n};\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\n/**\n * Structural fields shared by every enum member (key, value, display, index, optional deprecated).\n * Does not include smart-enum branding or database helpers; see {@link StandardEnumItem}.\n */\nexport type StandardEnumItemBase = {\n readonly key: string;\n readonly value: string;\n readonly display: string;\n readonly index: number;\n readonly deprecated?: boolean;\n};\n\n/**\n * Branded item produced by `enumeration()`: {@link StandardEnumItemBase} plus runtime identity\n * (`__smart_enum_brand`, `__smart_enum_type`) and `toPostgres()`.\n */\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\n readonly toJSON: () => string | { __smart_enum_type: string; value: string };\n readonly equals: <T extends StandardEnumItem>(other: T) => this is T;\n};\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n Record<string, unknown>;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\nexport type EmptyEnumInputItem = Record<never, never>;\n\ntype Separator = '-' | '_' | ' ' | '.';\n\ntype IsUpperChar<C extends string> =\n C extends Uppercase<C> ? (C extends Lowercase<C> ? false : true) : false;\n\ntype IsLowerChar<C extends string> =\n C extends Lowercase<C> ? (C extends Uppercase<C> ? false : true) : false;\n\ntype PushUnderscore<S extends string> = S extends '' | `${string}_`\n ? S\n : `${S}_`;\n\ntype TrimUnderscore<S extends string> = S extends `_${infer R}`\n ? TrimUnderscore<R>\n : S extends `${infer R}_`\n ? TrimUnderscore<R>\n : S;\n\ntype CollapseUnderscores<S extends string> = S extends `${infer A}__${infer B}`\n ? CollapseUnderscores<`${A}_${B}`>\n : S;\n\ntype ConstantCaseInternal<\n S extends string,\n Prev extends string = '',\n Out extends string = '',\n> = S extends `${infer C}${infer Rest}`\n ? C extends Separator\n ? ConstantCaseInternal<Rest, C, PushUnderscore<Out>>\n : IsUpperChar<C> extends true\n ? IsLowerChar<Prev> extends true\n ? ConstantCaseInternal<Rest, C, `${PushUnderscore<Out>}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : CollapseUnderscores<TrimUnderscore<Out>>;\n\ntype ConstantCase<S extends string> = string extends S\n ? string\n : ConstantCaseInternal<S>;\n\n/** Segments of a `ConstantCase` string (underscore-separated ALL CAPS words). */\ntype SplitConstantCaseSegments<S extends string> =\n S extends `${infer A}_${infer B}`\n ? [A, ...SplitConstantCaseSegments<B>]\n : [S];\n\n/** First character upper, remainder lower (for ALL-CAPS words from `ConstantCase`). */\ntype TitleCaseAllCapsWord<W extends string> = W extends ''\n ? ''\n : W extends `${infer F}${infer R}`\n ? `${Uppercase<F>}${Lowercase<R>}`\n : W;\n\ntype JoinDisplaySegments<T extends readonly string[]> = T extends readonly [\n infer A extends string,\n ...infer Rest extends readonly string[],\n]\n ? Rest extends readonly []\n ? TitleCaseAllCapsWord<A>\n : `${TitleCaseAllCapsWord<A>} ${JoinDisplaySegments<Rest>}`\n : '';\n\n/**\n * Display string derived from the enum member key: `ConstantCase` → split → title-case words → join with spaces.\n * Matches default runtime `capitalCase(key)` for typical PascalCase / camelCase keys. Member keys that already\n * contain separators may differ from `capitalCase` at runtime; custom `propertyAutoFormatters` for `display`\n * are not reflected in this type.\n */\ntype DisplayCaseFromEnumKey<K extends string> = string extends K\n ? string\n : JoinDisplaySegments<SplitConstantCaseSegments<ConstantCase<K>>>;\n\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\n/** Input-derived fields for one member key (excludes built-ins filled by `enumeration()`). */\nexport type EnumMemberExtra<\n TObj extends ObjectEnumInput,\n K extends keyof TObj,\n> = Omit<TObj[K], BuiltInOverrideKeys>;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n> = Omit<StandardEnumItem, 'key' | 'value' | 'display'> &\n SmartEnumMatch &\n EnumMemberExtra<TObj, K> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? [Extract<V, string>] extends [never]\n ? ConstantCase<Extract<K, string>>\n : Extract<V, string>\n : ConstantCase<Extract<K, string>>;\n readonly display: TObj[K] extends { display?: infer D }\n ? [Extract<D, string>] extends [never]\n ? DisplayCaseFromEnumKey<Extract<K, string>>\n : Extract<D, string>\n : DisplayCaseFromEnumKey<Extract<K, string>>;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<TObj extends ObjectEnumInput> =\n {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }[keyof TObj];\n\nexport type EnumFromNormalizedObject<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj>>;\n\nexport type UnionKeys<T> = T extends T ? keyof T : never;\n\n/*\nTo widen the type of the OptionalObject from literals to their actual types,\ne.g.\nshape?: \"round\" | \"square\" | \"long\";\nslices?: true;\nlayers?: 2;\n--turns into:--\nshape: string | undefined;\nslices: boolean| undefined;\nlayers: number| undefined;\n\nwe can use the following code:\ntype Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T;\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? Widen<V> : undefined;\n};\n*/\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? V : undefined;\n};\n\ntype ExtraShapeUnion<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: Omit<TObj[K], BuiltInOverrideKeys>;\n}[keyof TObj];\n\nexport type InferredExtraFields<TObj extends ObjectEnumInput> =\n MergeUnionToObject<ExtraShapeUnion<TObj>>;\n\nexport type PropertyAutoFormatter = {\n /** The property name to generate */\n key: string;\n /** Function to transform the key into the property value */\n format: (k: string) => string;\n};\n\nexport type CoreEnumMethods<TItem extends StandardEnumItem> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n /** Matches runtime: `items.map(i => i.value)` (see {@link EnumLikeBase}). */\n values(): readonly TItem['value'][];\n /** Matches runtime: `items.map(i => i.key)` (see {@link EnumLikeBase}). */\n keys(): readonly TItem['key'][];\n};\n\n/**\n * Structural shape of a smart-style enum object: lookup by value/key, list items/values/keys,\n * plus an index signature so registry and mapping types can treat instances as records.\n * Use {@link SmartEnumLike} when items are full {@link StandardEnumItem}s (the usual case).\n */\nexport type EnumLikeBase<\n TItem extends StandardEnumItemBase = StandardEnumItemBase,\n> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n values(): readonly TItem['value'][];\n keys(): readonly TItem['key'][];\n} & Record<string, unknown>;\n\n/**\n * A {@link EnumLikeBase} whose items are branded {@link StandardEnumItem}s (typical `enumeration()` result).\n */\nexport type SmartEnumLike<TItem extends StandardEnumItem = StandardEnumItem> =\n EnumLikeBase<TItem>;\n\n/** Union of branded enum member values on an enum object `T`. */\nexport type SmartEnumMemberUnion<T extends Record<string, unknown>> = {\n [K in keyof T]: T[K] extends StandardEnumItem ? T[K] : never;\n}[keyof T];\n\n/** Keys on `TEnum` whose member matches `Record<P, V>` within `ItemUnion`. */\nexport type SmartEnumSubsetKeys<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = {\n [K in keyof TEnum]: TEnum[K] extends Extract<ItemUnion, Record<P, V>>\n ? K\n : never;\n}[keyof TEnum];\n\nexport type SmartEnumSubsetItemUnion<\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Extract<ItemUnion, Record<P, V>>;\n\nexport type SmartEnumSubsetView<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Pick<TEnum, SmartEnumSubsetKeys<TEnum, ItemUnion, P, V>> &\n CoreEnumMethods<SmartEnumSubsetItemUnion<ItemUnion, P, V>>;\n\n/** Return type of {@link getSubsetByProp} / {@link subsetByProp} for explicit consumer annotations. */\nexport type SubsetByPropResult<\n TEnum extends Record<string, unknown> &\n SmartEnumLike<SmartEnumMemberUnion<TEnum>>,\n P extends keyof SmartEnumMemberUnion<TEnum> & string,\n V extends SmartEnumMemberUnion<TEnum>[P],\n> = SmartEnumSubsetView<TEnum, SmartEnumMemberUnion<TEnum>, P, V>;\n\nexport type FieldEnumMapping = Record<string, SmartEnumLike>;\n\nexport type ReviveRowOptions = {\n fieldEnumMapping: FieldEnumMapping;\n strict?: boolean;\n};\n\nexport type PathEnumMapping = Record<string, SmartEnumLike>;\n\nexport type RevivePayloadOptions = {\n pathEnumMapping: PathEnumMapping;\n strict?: boolean;\n};\n\n/**\n * Serialization mode controls how smart-enum items are serialized to JSON.\n *\n * - 'wrapped' (default): toJSON returns { __smart_enum_type, value }.\n * Use this when payloads need to be self-describing for revival on the\n * receiving end (e.g. REST APIs with explicit revive middleware).\n *\n * - 'value': toJSON returns just the wire value string.\n * Use this when the receiving end already knows the enum types from\n * schema context (e.g. GraphQL boundaries).\n *\n * Resolution order at toJSON call time:\n * 1. Per-enum `serializeAs` option (if set on enumeration())\n * 2. Global default (set via setDefaultSerializationMode)\n * 3. 'wrapped' (built-in default, preserves backward compatibility)\n */\nexport type SerializationMode = 'wrapped' | 'value';\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n serializeAs?: SerializationMode;\n};\n\nexport type Enumeration<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\nexport type FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type' | 'toJSON'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n\n/**\n * Exhaustive branch-on-member. One arm required per member of the *statically\n * known* receiver — miss one and it won't compile. Over a pickEnum view the\n * arms are exhaustive over just the picked members.\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SmartEnumMatch {\n readonly key: string;\n match<R>(handlers: {\n [P in this['key']]: (item: Extract<this, { key: P }>) => R;\n }): R;\n}\n\n/** Member keys of an enum object (excludes the method keys). */\nexport type EnumMemberKeys<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends StandardEnumItem ? K : never;\n}[keyof TEnum];\n\n/**\n * Enum-like view over an explicit list of member keys. Reuses the parent's item\n * references; methods scope to the picked subset. See {@link pickEnum}.\n */\nexport type PickEnumView<\n TEnum extends Record<string, unknown>,\n K extends EnumMemberKeys<TEnum>,\n> = Pick<TEnum, K> & CoreEnumMethods<Extract<TEnum[K], StandardEnumItem>>;\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\n SmartEnumLike,\n} from '../types.js';\n\n/**\n * Runtime type guard to detect Smart Enum items created by this library.\n * Returns true if the value has the SMART_ENUM_ITEM symbol.\n *\n * @example\n * ```typescript\n * import { Status } from './status';\n * const item = Status.active;\n * isSmartEnumItem(item); // true\n * isSmartEnumItem({ key: 'active', value: 'ACTIVE' }); // false (plain object)\n * if (isSmartEnumItem(x)) {\n * console.log(x.value, x.__smart_enum_type); // narrowed to enum item\n * }\n * ```\n */\nexport const isSmartEnumItem = (\n x: unknown,\n): x is {\n key: string;\n value: string;\n index?: number;\n __smart_enum_type?: string;\n} => {\n return (\n !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM_ITEM) === true\n );\n};\n\n/**\n * Runtime type guard to detect a full Smart Enum object created by this library.\n * Returns true if the object has the SMART_ENUM property.\n *\n * @example\n * ```typescript\n * import { MyEnum } from './blah';\n * isSmartEnum(MyEnum) === true; // true\n * isSmartEnum(MyEnum.one) === false; // false (this is an item, not the enum)\n * ```\n */\nexport const isSmartEnum = (x: unknown): x is SmartEnumLike => {\n return !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM) === true;\n};\n\n/**\n * Runtime type guard to detect a serialized Smart Enum item created by this library.\n * Returns true if the value has `__smart_enum_type` and `value` (wire/database shape).\n *\n * @example\n * ```typescript\n * const wire = { __smart_enum_type: 'Status', value: 'ACTIVE' };\n * isSerializedSmartEnumItem(wire); // true\n * isSerializedSmartEnumItem(Status.active); // false (live enum item)\n * if (isSerializedSmartEnumItem(x)) {\n * reviveItem(x.__smart_enum_type, x.value); // narrowed to SmartEnumItemSerialized\n * }\n * ```\n */\nexport const isSerializedSmartEnumItem = (\n x: unknown,\n): x is SmartEnumItemSerialized => {\n return (\n !!x &&\n typeof x === 'object' &&\n Reflect.has(x, '__smart_enum_type') &&\n Reflect.has(x, 'value')\n );\n};\n","import { SMART_ENUM_ID } from '../types.js';\n\nimport { isSmartEnumItem } from './typeGuards.js';\n\n/** Value-based equality for smart enum items from the same enumeration instance. */\nexport const enumItemsEqual = (a: unknown, b: unknown): boolean => {\n if (!isSmartEnumItem(a) || !isSmartEnumItem(b)) {\n return false;\n }\n\n return (\n Reflect.get(a, SMART_ENUM_ID) === Reflect.get(b, SMART_ENUM_ID) &&\n a.value === b.value\n );\n};\n","import type { CoreEnumMethods, StandardEnumItem } from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nexport const addExtensionMethods = <TItem extends StandardEnumItem>(\n enumItems: readonly TItem[],\n): CoreEnumMethods<TItem> => {\n const findBy = <K extends keyof TItem>(field: K, target: TItem[K]) =>\n enumItems.find(item => item[field] === target);\n\n const requireBy = <K extends keyof TItem>(\n field: K,\n target: TItem[K],\n label: string,\n ) => {\n const item = findBy(field, target);\n if (!item) {\n throw new Error(`No enum ${label} found for '${String(target)}'`);\n }\n return item;\n };\n\n return {\n fromValue: value => requireBy('value', value as TItem['value'], 'value'),\n tryFromValue: value =>\n value ? findBy('value', value as TItem['value']) : undefined,\n\n fromKey: key => requireBy('key', key as TItem['key'], 'key'),\n tryFromKey: key => (key ? findBy('key', key as TItem['key']) : undefined),\n\n equals: enumItemsEqual,\n\n items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\n };\n};\n","import { SerializationMode } from '../types.js';\n\nlet globalDefault: SerializationMode | undefined;\n\n/**\n * Set the global default serialization mode for all smart-enum items\n * that don't have a per-enum serializeAs option.\n *\n * Call once at app startup, before any JSON.stringify happens on enum items.\n *\n * @example\n * setDefaultSerializationMode('value');\n */\nexport const setDefaultSerializationMode = (mode: SerializationMode): void => {\n globalDefault = mode;\n};\n\n/**\n * Reset the global default to its initial unset state.\n * Primarily useful for tests.\n */\nexport const resetDefaultSerializationMode = (): void => {\n globalDefault = undefined;\n};\n\n/**\n * Resolve the effective serialization mode for an enum item.\n * Per-enum option wins, then global, then 'wrapped'.\n */\nexport const resolveSerializationMode = (\n perEnum: SerializationMode | undefined,\n): SerializationMode => perEnum ?? globalDefault ?? 'wrapped';\n","/**\n * Logger interface for @reharik/smart-enum library\n *\n * This interface allows users to inject their own logging implementation\n * or use the default console logger.\n */\n\nexport type Logger = {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n};\n\n/**\n * Default console logger implementation\n */\nconst consoleLogger: Logger = {\n debug(message: string, ...args: unknown[]): void {\n console.debug(`[@reharik/smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[@reharik/smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[@reharik/smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[@reharik/smart-enum:error] ${message}`, ...args);\n },\n};\n\n/**\n * Global logger instance\n * Defaults to console logger\n */\nlet globalLogger: Logger = consoleLogger;\n\n/**\n * Sets the global logger instance\n *\n * @param logger - The logger implementation to use\n *\n * @example\n * ```typescript\n * import { setLogger } from '@reharik/smart-enum';\n *\n * // Use custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, args),\n * info: (msg, ...args) => myLogger.info(msg, args),\n * warn: (msg, ...args) => myLogger.warn(msg, args),\n * error: (msg, ...args) => myLogger.error(msg, args),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n globalLogger = logger;\n}\n\n/**\n * Gets the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n return globalLogger;\n}\n\n// Internal convenience functions for library use\nexport function debug(message: string, ...args: unknown[]): void {\n globalLogger.debug(message, ...args);\n}\n\nexport function info(message: string, ...args: unknown[]): void {\n globalLogger.info(message, ...args);\n}\n\nexport function warn(message: string, ...args: unknown[]): void {\n globalLogger.warn(message, ...args);\n}\n\nexport function error(message: string, ...args: unknown[]): void {\n globalLogger.error(message, ...args);\n}\n","// serializeSmartEnums.ts\nexport { isSmartEnumItem, isSmartEnum } from './typeGuards.js';\nimport type { SerializedSmartEnums, AnyEnumLike } from '../types.js';\n\nimport { debug } from './logger.js';\nimport { isSerializedSmartEnumItem, isSmartEnumItem } from './typeGuards.js';\n\ntype PlainObject = Record<string, unknown>;\n\nconst isPlainObject = (x: unknown): x is PlainObject =>\n typeof x === 'object' &&\n x !== null &&\n Object.getPrototypeOf(x) === Object.prototype;\n\n/**\n * Recursively replaces Smart Enum items with self-describing objects\n * `{ __smart_enum_type, value }` for JSON transport or storage.\n *\n * @param input - Object or array that may contain enum items\n * @returns Same structure with enum items replaced by serialized shape\n *\n * @example\n * ```typescript\n * const dto = { id: '1', status: Status.active, color: Color.red };\n * const wire = serializeSmartEnums(dto);\n * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }\n * ```\n */\n// Overloads:\n// 1) Inferred\nexport function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;\n// 2) Return-type only (constrained to objects/arrays)\nexport function serializeSmartEnums<\n S extends Readonly<PlainObject> | readonly unknown[],\n>(input: unknown): S;\n// Implementation\nexport function serializeSmartEnums(input: unknown): unknown {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n if (isSmartEnumItem(v)) {\n return {\n __smart_enum_type: v.__smart_enum_type,\n value: v.value,\n };\n }\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) {\n arr.push(walk(item));\n }\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n\n return walk(input);\n}\n\n/**\n * Recursively revives serialized enum objects back to Smart Enum items\n * using a registry of enum types. Expects payload to contain\n * `{ __smart_enum_type, value }` where the type exists in the registry.\n *\n * @param input - Serialized payload (e.g. from JSON)\n * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)\n * @returns Payload with serialized enums revived to enum items\n *\n * @example\n * ```typescript\n * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };\n * const revived = reviveSmartEnums(wire, { Status, Color });\n * // revived.status === Status.active\n * ```\n */\nexport function reviveSmartEnums<R>(\n input: unknown,\n registry: Record<string, AnyEnumLike>,\n): R {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n // Handle self-describing enum objects with __smart_enum_type and value\n if (isSerializedSmartEnumItem(v)) {\n debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);\n const enumInstance = registry[v.__smart_enum_type];\n if (enumInstance) {\n debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);\n // Try to find the enum item by value first\n const enumItem = enumInstance.tryFromValue(v.value);\n if (enumItem) {\n debug(`Revived enumItem using value: ${v.value}`);\n return enumItem;\n }\n // If that fails, try to find by key (convert value to key format)\n const key = v.value.toLowerCase();\n const enumItemFromKey = enumInstance.tryFromKey(key);\n if (enumItemFromKey) {\n debug(`Revived enumItem using key: ${key}`);\n return enumItemFromKey;\n }\n }\n // If no matching enum type in registry, return the original serialized object\n return v;\n }\n\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) arr.push(walk(item));\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n return walk(input) as R;\n}\n\n/**\n * Maps a plain string (for example a column value from a database query) to the\n * corresponding Smart Enum item by calling `tryFromValue` on the given enum.\n *\n * Use this when you already know which enum type a field uses and the stored\n * value is the enum’s wire `value` string (same shape `tryFromValue` expects).\n *\n * @param value - Raw value; only strings are resolved—anything else returns `undefined`\n * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)\n * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`\n * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)\n *\n * @example\n * ```typescript\n * const item = reviveEnumField(row.status, UserStatus);\n * const mustMatch = reviveEnumField(row.code, OrderStatus, true);\n * ```\n */\nexport const reviveEnumField = <TItem>(\n value: unknown,\n smartEnum: AnyEnumLike<TItem>,\n strict = false,\n): TItem | undefined => {\n if (typeof value !== 'string') return undefined;\n\n const revived = smartEnum.tryFromValue(value);\n if (revived !== undefined) return revived;\n\n if (strict) {\n throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);\n }\n\n return undefined;\n};\n","import type {\n AnyEnumLike,\n LogLevel,\n SmartEnumMappingsConfig,\n} from '../../types.js';\nimport { info, setLogger, getLogger, type Logger } from '../logger.js';\n\nconst createLevelFilteredLogger = (logger: Logger, level: LogLevel): Logger => {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n const currentLevel = levels[level];\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.debug) {\n logger.debug(message, ...args);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.info) {\n logger.info(message, ...args);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.warn) {\n logger.warn(message, ...args);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.error) {\n logger.error(message, ...args);\n }\n },\n };\n};\n\nlet globalEnumRegistry: Record<string, AnyEnumLike> | undefined;\n\n/**\n * Wire-format registry for `reviveAfterTransport` / `reviveSmartEnums`.\n * Not used for database string revival.\n */\nexport const initializeSmartEnumMappings = (\n config: SmartEnumMappingsConfig,\n): void => {\n globalEnumRegistry = config.enumRegistry;\n\n const logLevel = config.logLevel ?? 'error';\n const logger = config.logger ?? getLogger();\n setLogger(createLevelFilteredLogger(logger, logLevel));\n\n info('Initialized smart enum mappings', {\n enumCount: Object.keys(config.enumRegistry).length,\n enumTypes: Object.keys(config.enumRegistry),\n logLevel,\n });\n};\n\nexport const getGlobalEnumRegistry = ():\n | Record<string, AnyEnumLike>\n | undefined => globalEnumRegistry;\n","import { reviveSmartEnums } from '../transformation.js';\n\nimport { getGlobalEnumRegistry } from './transportRegistry.js';\n\n/**\n * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.\n */\nexport const reviveAfterTransport = <T>(payload: unknown): T => {\n const registry = getGlobalEnumRegistry();\n if (!registry) {\n return payload as T;\n }\n return reviveSmartEnums(payload, registry);\n};\n","import { serializeSmartEnums } from '../transformation.js';\nimport type { SerializedSmartEnums } from '../../types.js';\n\n/**\n * Serializes smart enums for transport (to client or API).\n * Wire payloads include `__smart_enum_type` for `reviveAfterTransport`.\n */\nexport const serializeForTransport = <T>(payload: T): SerializedSmartEnums<T> =>\n serializeSmartEnums(payload);\n"],"mappings":";AAAA,SAAS,aAAa,oBAAoB;;;ACanC,IAAM,kBAAkB,OAAO,iBAAiB;AAChD,IAAM,gBAAgB,OAAO,eAAe;AAC5C,IAAM,aA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,MAC9B;AAAA,IACF;AAAA,IACA,MAAM,CAAC,YAAoB,SAAoB;AAC7C,UAAI,gBAAgB,OAAO,MAAM;AAC/B,eAAO,KAAK,SAAS,GAAG,IAAI;AAAA,MAC9B;AAAA,IACF;AAAA,IACA,OAAO,CAAC,YAAoB,SAAoB;AAC9C,UAAI,gBAAgB,OAAO,OAAO;AAChC,eAAO,MAAM,SAAS,GAAG,IAAI;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAI;AAMG,IAAM,8BAA8B,CACzC,WACS;AACT,uBAAqB,OAAO;AAE5B,QAAM,WAAW,OAAO,YAAY;AACpC,QAAM,SAAS,OAAO,UAAU,UAAU;AAC1C,YAAU,0BAA0B,QAAQ,QAAQ,CAAC;AAErD,OAAK,mCAAmC;AAAA,IACtC,WAAW,OAAO,KAAK,OAAO,YAAY,EAAE;AAAA,IAC5C,WAAW,OAAO,KAAK,OAAO,YAAY;AAAA,IAC1C;AAAA,EACF,CAAC;AACH;AAEO,IAAM,wBAAwB,MAEpB;;;AC1DV,IAAM,uBAAuB,CAAI,YAAwB;AAC9D,QAAM,WAAW,sBAAsB;AACvC,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AACA,SAAO,iBAAiB,SAAS,QAAQ;AAC3C;;;ACNO,IAAM,wBAAwB,CAAI,YACvC,oBAAoB,OAAO;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/enumerations.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/enumItemsEqual.ts","../src/extensionMethods.ts","../src/utilities/serializationMode.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts","../src/utilities/transport/transportRegistry.ts","../src/utilities/transport/reviveAfterTransport.ts","../src/utilities/transport/serializeForTransport.ts"],"sourcesContent":["import { capitalCase, constantCase } from 'case-anything';\n\nimport { addExtensionMethods } from './extensionMethods.js';\nimport {\n SMART_ENUM,\n SMART_ENUM_ID,\n SMART_ENUM_ITEM,\n SerializationMode,\n type EnumFromNormalizedObject,\n type EnumItemFromNormalizedObject,\n type EnumMemberUnionFromNormalizedObject,\n type EnumerationProps,\n type FinalizableEnumItem,\n type FinalizedEnumFields,\n type NormalizedInputType,\n type ObjectEnumInput,\n type PropertyAutoFormatter,\n type StandardEnumItem,\n} from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nimport { resolveSerializationMode } from './utilities/serializationMode.js';\n\nexport type EnumItem<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends { __smart_enum_brand: true }\n ? TEnum[K]\n : never;\n}[keyof TEnum];\n\nfunction normalizeInput<TInput extends readonly string[] | ObjectEnumInput>(\n input: TInput,\n): NormalizedInputType<TInput> {\n if (Array.isArray(input)) {\n return Object.fromEntries(\n input.map(k => [k, {}]),\n ) as NormalizedInputType<TInput>;\n }\n\n return input as NormalizedInputType<TInput>;\n}\n\nconst finalizeEnumItem = <T extends { value: string; key: string }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\n serializeAs: SerializationMode | undefined,\n): T & FinalizedEnumFields => {\n Object.defineProperty(item, SMART_ENUM_ITEM, {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, SMART_ENUM_ID, {\n value: enumInstanceId,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_brand', {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_type', {\n value: enumType,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toJSON', {\n value: () => {\n const mode = resolveSerializationMode(serializeAs);\n if (mode === 'value') {\n return item.value;\n }\n return { __smart_enum_type: enumType, value: item.value };\n },\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'equals', {\n value: (other: StandardEnumItem) => enumItemsEqual(item, other),\n enumerable: false,\n });\n\n Object.defineProperty(item, 'match', {\n value: (handlers: Record<string, (i: unknown) => unknown>) => {\n const handler = handlers[item.key];\n if (!handler) {\n throw new Error(\n `match: no handler for '${item.key}' on enum '${enumType}'`,\n );\n }\n return handler(item);\n },\n enumerable: false,\n });\n return item as T & FinalizedEnumFields;\n};\n\nconst formatProperties = (\n k: string,\n formatters: PropertyAutoFormatter[],\n): { value: string; display: string } & Record<string, string> =>\n formatters.reduce(\n (acc, formatter) => {\n acc[formatter.key] = formatter.format(k);\n return acc;\n },\n {\n value: constantCase(k),\n display: capitalCase(k),\n } as { value: string; display: string } & Record<string, string>,\n );\n\nfunction buildEnumFromObject<\n TName extends string,\n TObj extends ObjectEnumInput,\n>(\n enumType: TName,\n input: TObj,\n propertyAutoFormatters?: PropertyAutoFormatter[],\n serializeAs?: SerializationMode,\n): EnumFromNormalizedObject<TObj, TName> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumMemberUnionFromNormalizedObject<TObj, TName>;\n\n const rawEnumItems: Partial<{\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K, TName>;\n }> = {};\n\n const enumInstanceId = Symbol('smart-enum-instance');\n let index = 0;\n\n for (const key in input) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n const typedKey = key;\n const value = input[typedKey];\n\n const enumItemBase = {\n index,\n key: typedKey,\n ...formatProperties(typedKey, formattersWithDefaults),\n ...value,\n } as FinalizableEnumItem & TObj[typeof typedKey];\n\n const enumItem = finalizeEnumItem(\n enumItemBase,\n enumType,\n enumInstanceId,\n serializeAs,\n ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey as keyof TObj] = enumItem;\n index++;\n }\n }\n\n const extensionMethods = addExtensionMethods<TItem>(\n Object.values(rawEnumItems) as TItem[],\n );\n\n const enumObject = {\n ...rawEnumItems,\n ...extensionMethods,\n } as EnumFromNormalizedObject<TObj, TName>;\n\n Object.defineProperty(enumObject, SMART_ENUM, {\n value: true,\n enumerable: false,\n });\n\n Object.freeze(enumObject);\n\n return enumObject;\n}\n\nexport function enumeration<\n const TArr extends readonly string[],\n const TName extends string = string,\n>(\n enumType: TName,\n props: EnumerationProps<TArr>,\n): EnumFromNormalizedObject<NormalizedInputType<TArr>, TName>;\n\nexport function enumeration<\n const TObj extends ObjectEnumInput,\n const TName extends string = string,\n>(\n enumType: TName,\n props: EnumerationProps<TObj>,\n): EnumFromNormalizedObject<NormalizedInputType<TObj>, TName>;\n\nexport function enumeration<const TName extends string = string>(\n enumType: TName,\n props: EnumerationProps<readonly string[] | ObjectEnumInput>,\n): EnumFromNormalizedObject<\n NormalizedInputType<readonly string[] | ObjectEnumInput>,\n TName\n> {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n props.serializeAs,\n );\n}\n","/**\n * Type guard to check if a value is not null or undefined\n * @param value - The value to check\n * @returns True if the value is defined and not null\n */\nexport const notEmpty = <X>(\n value: X | null | undefined,\n): value is NonNullable<X> => {\n // eslint-disable-next-line unicorn/no-null\n return value != null;\n};\n\n// Public symbols used at runtime for detection/identity (not used in type keys)\nexport const SMART_ENUM_ITEM = Symbol('smart-enum-item');\nexport const SMART_ENUM_ID = Symbol('smart-enum-id');\nexport const SMART_ENUM = Symbol('smart-enum');\n\n/**\n * Options for filtering enum items in various methods\n */\nexport type EnumFilterOptions = {\n /** Include items with null/undefined values (default: false) */\n showEmpty?: boolean;\n /** Include deprecated items (default: false) */\n showDeprecated?: boolean;\n};\n\n// export type EnumInput = readonly string[] | ObjectEnumInput;\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Structural detection checks for\n * presence of `key` and `value`.\n */\nexport type SerializedSmartEnums<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<SerializedSmartEnums<U>>\n : T extends Array<infer U>\n ? SerializedSmartEnums<U>[]\n : T extends object\n ? { [K in keyof T]: SerializedSmartEnums<T[K]> }\n : T;\n\n/**\n * Revived shape: for keys present in mapping M, the string becomes the\n * corresponding enum item type (derived from the provided enum object);\n * other fields recurse.\n */\nexport type EnumItemFromEnum<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\n/**\n * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).\n * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).\n */\nexport type AnyEnumLike<T = unknown> = {\n tryFromValue: (value?: string | null) => T | undefined;\n tryFromKey: (key?: string | null) => T | undefined;\n} & Record<string, unknown>;\n\nexport type RevivedSmartEnums<T, M extends Record<string, AnyEnumLike>> =\n T extends ReadonlyArray<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends Array<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends object\n ? {\n [K in keyof T]: K extends Extract<keyof M, string>\n ? Enumeration<M[K]>\n : RevivedSmartEnums<T[K], M>;\n }\n : T;\n\nexport type SmartEnumItemSerialized = {\n __smart_enum_type: string;\n value: string;\n};\n\n/** Example shape for transport tests (`reviveAfterTransport` registry). */\nexport type SmartApiHelperConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n};\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Used for database storage.\n */\nexport type DatabaseFormat<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DatabaseFormat<U>>\n : T extends Array<infer U>\n ? DatabaseFormat<U>[]\n : T extends object\n ? { [K in keyof T]: DatabaseFormat<T[K]> }\n : T;\n\n/**\n * Log levels for smart enum mappings\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Configuration for smart enum mappings initialization\n */\nexport type SmartEnumMappingsConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n logLevel?: LogLevel;\n logger?: import('./utilities/logger.js').Logger;\n};\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\n/**\n * Structural fields shared by every enum member (key, value, display, index, optional deprecated).\n * Does not include smart-enum branding or database helpers; see {@link StandardEnumItem}.\n */\nexport type StandardEnumItemBase = {\n readonly key: string;\n readonly value: string;\n readonly display: string;\n readonly index: number;\n readonly deprecated?: boolean;\n};\n\n/**\n * Branded item produced by `enumeration()`: {@link StandardEnumItemBase} plus runtime identity\n * (`__smart_enum_brand`, `__smart_enum_type`) and `toPostgres()`.\n */\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\n readonly toJSON: () => string | { __smart_enum_type: string; value: string };\n readonly equals: <\n This extends { __smart_enum_type: string },\n T extends {\n __smart_enum_type: This['__smart_enum_type'];\n } & StandardEnumItem,\n >(\n this: This,\n other: T,\n ) => this is T;\n};\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n Record<string, unknown>;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\nexport type EmptyEnumInputItem = Record<never, never>;\n\ntype Separator = '-' | '_' | ' ' | '.';\n\ntype IsUpperChar<C extends string> =\n C extends Uppercase<C> ? (C extends Lowercase<C> ? false : true) : false;\n\ntype IsLowerChar<C extends string> =\n C extends Lowercase<C> ? (C extends Uppercase<C> ? false : true) : false;\n\ntype PushUnderscore<S extends string> = S extends '' | `${string}_`\n ? S\n : `${S}_`;\n\ntype TrimUnderscore<S extends string> = S extends `_${infer R}`\n ? TrimUnderscore<R>\n : S extends `${infer R}_`\n ? TrimUnderscore<R>\n : S;\n\ntype CollapseUnderscores<S extends string> = S extends `${infer A}__${infer B}`\n ? CollapseUnderscores<`${A}_${B}`>\n : S;\n\ntype ConstantCaseInternal<\n S extends string,\n Prev extends string = '',\n Out extends string = '',\n> = S extends `${infer C}${infer Rest}`\n ? C extends Separator\n ? ConstantCaseInternal<Rest, C, PushUnderscore<Out>>\n : IsUpperChar<C> extends true\n ? IsLowerChar<Prev> extends true\n ? ConstantCaseInternal<Rest, C, `${PushUnderscore<Out>}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : CollapseUnderscores<TrimUnderscore<Out>>;\n\ntype ConstantCase<S extends string> = string extends S\n ? string\n : ConstantCaseInternal<S>;\n\n/** Segments of a `ConstantCase` string (underscore-separated ALL CAPS words). */\ntype SplitConstantCaseSegments<S extends string> =\n S extends `${infer A}_${infer B}`\n ? [A, ...SplitConstantCaseSegments<B>]\n : [S];\n\n/** First character upper, remainder lower (for ALL-CAPS words from `ConstantCase`). */\ntype TitleCaseAllCapsWord<W extends string> = W extends ''\n ? ''\n : W extends `${infer F}${infer R}`\n ? `${Uppercase<F>}${Lowercase<R>}`\n : W;\n\ntype JoinDisplaySegments<T extends readonly string[]> = T extends readonly [\n infer A extends string,\n ...infer Rest extends readonly string[],\n]\n ? Rest extends readonly []\n ? TitleCaseAllCapsWord<A>\n : `${TitleCaseAllCapsWord<A>} ${JoinDisplaySegments<Rest>}`\n : '';\n\n/**\n * Display string derived from the enum member key: `ConstantCase` → split → title-case words → join with spaces.\n * Matches default runtime `capitalCase(key)` for typical PascalCase / camelCase keys. Member keys that already\n * contain separators may differ from `capitalCase` at runtime; custom `propertyAutoFormatters` for `display`\n * are not reflected in this type.\n */\ntype DisplayCaseFromEnumKey<K extends string> = string extends K\n ? string\n : JoinDisplaySegments<SplitConstantCaseSegments<ConstantCase<K>>>;\n\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\n/** Input-derived fields for one member key (excludes built-ins filled by `enumeration()`). */\nexport type EnumMemberExtra<\n TObj extends ObjectEnumInput,\n K extends keyof TObj,\n> = Omit<TObj[K], BuiltInOverrideKeys>;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n TName extends string = string,\n> = Omit<\n StandardEnumItem,\n 'key' | 'value' | 'display' | '__smart_enum_type'\n> & { __smart_enum_type: TName } & SmartEnumMatch &\n EnumMemberExtra<TObj, K> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? [Extract<V, string>] extends [never]\n ? ConstantCase<Extract<K, string>>\n : Extract<V, string>\n : ConstantCase<Extract<K, string>>;\n readonly display: TObj[K] extends { display?: infer D }\n ? [Extract<D, string>] extends [never]\n ? DisplayCaseFromEnumKey<Extract<K, string>>\n : Extract<D, string>\n : DisplayCaseFromEnumKey<Extract<K, string>>;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<\n TObj extends ObjectEnumInput,\n TName extends string = string,\n> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K, TName>;\n}[keyof TObj];\n\nexport type EnumFromNormalizedObject<\n TObj extends ObjectEnumInput,\n TName extends string = string,\n> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K, TName>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj, TName>>;\n\nexport type UnionKeys<T> = T extends T ? keyof T : never;\n\n/*\nTo widen the type of the OptionalObject from literals to their actual types,\ne.g.\nshape?: \"round\" | \"square\" | \"long\";\nslices?: true;\nlayers?: 2;\n--turns into:--\nshape: string | undefined;\nslices: boolean| undefined;\nlayers: number| undefined;\n\nwe can use the following code:\ntype Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T;\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? Widen<V> : undefined;\n};\n*/\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? V : undefined;\n};\n\ntype ExtraShapeUnion<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: Omit<TObj[K], BuiltInOverrideKeys>;\n}[keyof TObj];\n\nexport type InferredExtraFields<TObj extends ObjectEnumInput> =\n MergeUnionToObject<ExtraShapeUnion<TObj>>;\n\nexport type PropertyAutoFormatter = {\n /** The property name to generate */\n key: string;\n /** Function to transform the key into the property value */\n format: (k: string) => string;\n};\n\nexport type CoreEnumMethods<TItem extends StandardEnumItem> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n /** Matches runtime: `items.map(i => i.value)` (see {@link EnumLikeBase}). */\n values(): readonly TItem['value'][];\n /** Matches runtime: `items.map(i => i.key)` (see {@link EnumLikeBase}). */\n keys(): readonly TItem['key'][];\n};\n\n/**\n * Structural shape of a smart-style enum object: lookup by value/key, list items/values/keys,\n * plus an index signature so registry and mapping types can treat instances as records.\n * Use {@link SmartEnumLike} when items are full {@link StandardEnumItem}s (the usual case).\n */\nexport type EnumLikeBase<\n TItem extends StandardEnumItemBase = StandardEnumItemBase,\n> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n equals(a: TItem, b: TItem): boolean;\n items(): readonly TItem[];\n values(): readonly TItem['value'][];\n keys(): readonly TItem['key'][];\n} & Record<string, unknown>;\n\n/**\n * A {@link EnumLikeBase} whose items are branded {@link StandardEnumItem}s (typical `enumeration()` result).\n */\nexport type SmartEnumLike<TItem extends StandardEnumItem = StandardEnumItem> =\n EnumLikeBase<TItem>;\n\n/** Union of branded enum member values on an enum object `T`. */\nexport type SmartEnumMemberUnion<T extends Record<string, unknown>> = {\n [K in keyof T]: T[K] extends StandardEnumItem ? T[K] : never;\n}[keyof T];\n\n/** Keys on `TEnum` whose member matches `Record<P, V>` within `ItemUnion`. */\nexport type SmartEnumSubsetKeys<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = {\n [K in keyof TEnum]: TEnum[K] extends Extract<ItemUnion, Record<P, V>>\n ? K\n : never;\n}[keyof TEnum];\n\nexport type SmartEnumSubsetItemUnion<\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Extract<ItemUnion, Record<P, V>>;\n\nexport type SmartEnumSubsetView<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Pick<TEnum, SmartEnumSubsetKeys<TEnum, ItemUnion, P, V>> &\n CoreEnumMethods<SmartEnumSubsetItemUnion<ItemUnion, P, V>>;\n\n/** Return type of {@link getSubsetByProp} / {@link subsetByProp} for explicit consumer annotations. */\nexport type SubsetByPropResult<\n TEnum extends Record<string, unknown> &\n SmartEnumLike<SmartEnumMemberUnion<TEnum>>,\n P extends keyof SmartEnumMemberUnion<TEnum> & string,\n V extends SmartEnumMemberUnion<TEnum>[P],\n> = SmartEnumSubsetView<TEnum, SmartEnumMemberUnion<TEnum>, P, V>;\n\nexport type FieldEnumMapping = Record<string, SmartEnumLike>;\n\nexport type ReviveRowOptions = {\n fieldEnumMapping: FieldEnumMapping;\n strict?: boolean;\n};\n\nexport type PathEnumMapping = Record<string, SmartEnumLike>;\n\nexport type RevivePayloadOptions = {\n pathEnumMapping: PathEnumMapping;\n strict?: boolean;\n};\n\n/**\n * Serialization mode controls how smart-enum items are serialized to JSON.\n *\n * - 'wrapped' (default): toJSON returns { __smart_enum_type, value }.\n * Use this when payloads need to be self-describing for revival on the\n * receiving end (e.g. REST APIs with explicit revive middleware).\n *\n * - 'value': toJSON returns just the wire value string.\n * Use this when the receiving end already knows the enum types from\n * schema context (e.g. GraphQL boundaries).\n *\n * Resolution order at toJSON call time:\n * 1. Per-enum `serializeAs` option (if set on enumeration())\n * 2. Global default (set via setDefaultSerializationMode)\n * 3. 'wrapped' (built-in default, preserves backward compatibility)\n */\nexport type SerializationMode = 'wrapped' | 'value';\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n serializeAs?: SerializationMode;\n};\n\nexport type Enumeration<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\nexport type FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type' | 'toJSON'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n\n/**\n * Exhaustive branch-on-member. One arm required per member of the *statically\n * known* receiver — miss one and it won't compile. Over a pickEnum view the\n * arms are exhaustive over just the picked members.\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SmartEnumMatch {\n readonly key: string;\n match<R>(handlers: {\n [P in this['key']]: (item: Extract<this, { key: P }>) => R;\n }): R;\n}\n\n/** Member keys of an enum object (excludes the method keys). */\nexport type EnumMemberKeys<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends StandardEnumItem ? K : never;\n}[keyof TEnum];\n\n/**\n * Enum-like view over an explicit list of member keys. Reuses the parent's item\n * references; methods scope to the picked subset. See {@link pickEnum}.\n */\nexport type PickEnumView<\n TEnum extends Record<string, unknown>,\n K extends EnumMemberKeys<TEnum>,\n> = Pick<TEnum, K> & CoreEnumMethods<Extract<TEnum[K], StandardEnumItem>>;\n\nexport type EnumSubset<\n TItems extends StandardEnumItem,\n K extends TItems['key'],\n> = Extract<TItems, { key: K }>;\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\n SmartEnumLike,\n} from '../types.js';\n\n/**\n * Runtime type guard to detect Smart Enum items created by this library.\n * Returns true if the value has the SMART_ENUM_ITEM symbol.\n *\n * @example\n * ```typescript\n * import { Status } from './status';\n * const item = Status.active;\n * isSmartEnumItem(item); // true\n * isSmartEnumItem({ key: 'active', value: 'ACTIVE' }); // false (plain object)\n * if (isSmartEnumItem(x)) {\n * console.log(x.value, x.__smart_enum_type); // narrowed to enum item\n * }\n * ```\n */\nexport const isSmartEnumItem = (\n x: unknown,\n): x is {\n key: string;\n value: string;\n index?: number;\n __smart_enum_type?: string;\n} => {\n return (\n !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM_ITEM) === true\n );\n};\n\n/**\n * Runtime type guard to detect a full Smart Enum object created by this library.\n * Returns true if the object has the SMART_ENUM property.\n *\n * @example\n * ```typescript\n * import { MyEnum } from './blah';\n * isSmartEnum(MyEnum) === true; // true\n * isSmartEnum(MyEnum.one) === false; // false (this is an item, not the enum)\n * ```\n */\nexport const isSmartEnum = (x: unknown): x is SmartEnumLike => {\n return !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM) === true;\n};\n\n/**\n * Runtime type guard to detect a serialized Smart Enum item created by this library.\n * Returns true if the value has `__smart_enum_type` and `value` (wire/database shape).\n *\n * @example\n * ```typescript\n * const wire = { __smart_enum_type: 'Status', value: 'ACTIVE' };\n * isSerializedSmartEnumItem(wire); // true\n * isSerializedSmartEnumItem(Status.active); // false (live enum item)\n * if (isSerializedSmartEnumItem(x)) {\n * reviveItem(x.__smart_enum_type, x.value); // narrowed to SmartEnumItemSerialized\n * }\n * ```\n */\nexport const isSerializedSmartEnumItem = (\n x: unknown,\n): x is SmartEnumItemSerialized => {\n return (\n !!x &&\n typeof x === 'object' &&\n Reflect.has(x, '__smart_enum_type') &&\n Reflect.has(x, 'value')\n );\n};\n","import { SMART_ENUM_ID } from '../types.js';\n\nimport { isSmartEnumItem } from './typeGuards.js';\n\n/** Value-based equality for smart enum items from the same enumeration instance. */\nexport const enumItemsEqual = (a: unknown, b: unknown): boolean => {\n if (!isSmartEnumItem(a) || !isSmartEnumItem(b)) {\n return false;\n }\n\n return (\n Reflect.get(a, SMART_ENUM_ID) === Reflect.get(b, SMART_ENUM_ID) &&\n a.value === b.value\n );\n};\n","import type { CoreEnumMethods, StandardEnumItem } from './types.js';\nimport { enumItemsEqual } from './utilities/enumItemsEqual.js';\nexport const addExtensionMethods = <TItem extends StandardEnumItem>(\n enumItems: readonly TItem[],\n): CoreEnumMethods<TItem> => {\n const findBy = <K extends keyof TItem>(field: K, target: TItem[K]) =>\n enumItems.find(item => item[field] === target);\n\n const requireBy = <K extends keyof TItem>(\n field: K,\n target: TItem[K],\n label: string,\n ) => {\n const item = findBy(field, target);\n if (!item) {\n throw new Error(`No enum ${label} found for '${String(target)}'`);\n }\n return item;\n };\n\n return {\n fromValue: value => requireBy('value', value as TItem['value'], 'value'),\n tryFromValue: value =>\n value ? findBy('value', value as TItem['value']) : undefined,\n\n fromKey: key => requireBy('key', key as TItem['key'], 'key'),\n tryFromKey: key => (key ? findBy('key', key as TItem['key']) : undefined),\n\n equals: enumItemsEqual,\n\n items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\n };\n};\n","import { SerializationMode } from '../types.js';\n\nlet globalDefault: SerializationMode | undefined;\n\n/**\n * Set the global default serialization mode for all smart-enum items\n * that don't have a per-enum serializeAs option.\n *\n * Call once at app startup, before any JSON.stringify happens on enum items.\n *\n * @example\n * setDefaultSerializationMode('value');\n */\nexport const setDefaultSerializationMode = (mode: SerializationMode): void => {\n globalDefault = mode;\n};\n\n/**\n * Reset the global default to its initial unset state.\n * Primarily useful for tests.\n */\nexport const resetDefaultSerializationMode = (): void => {\n globalDefault = undefined;\n};\n\n/**\n * Resolve the effective serialization mode for an enum item.\n * Per-enum option wins, then global, then 'wrapped'.\n */\nexport const resolveSerializationMode = (\n perEnum: SerializationMode | undefined,\n): SerializationMode => perEnum ?? globalDefault ?? 'wrapped';\n","/**\n * Logger interface for @reharik/smart-enum library\n *\n * This interface allows users to inject their own logging implementation\n * or use the default console logger.\n */\n\nexport type Logger = {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n};\n\n/**\n * Default console logger implementation\n */\nconst consoleLogger: Logger = {\n debug(message: string, ...args: unknown[]): void {\n console.debug(`[@reharik/smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[@reharik/smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[@reharik/smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[@reharik/smart-enum:error] ${message}`, ...args);\n },\n};\n\n/**\n * Global logger instance\n * Defaults to console logger\n */\nlet globalLogger: Logger = consoleLogger;\n\n/**\n * Sets the global logger instance\n *\n * @param logger - The logger implementation to use\n *\n * @example\n * ```typescript\n * import { setLogger } from '@reharik/smart-enum';\n *\n * // Use custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, args),\n * info: (msg, ...args) => myLogger.info(msg, args),\n * warn: (msg, ...args) => myLogger.warn(msg, args),\n * error: (msg, ...args) => myLogger.error(msg, args),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n globalLogger = logger;\n}\n\n/**\n * Gets the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n return globalLogger;\n}\n\n// Internal convenience functions for library use\nexport function debug(message: string, ...args: unknown[]): void {\n globalLogger.debug(message, ...args);\n}\n\nexport function info(message: string, ...args: unknown[]): void {\n globalLogger.info(message, ...args);\n}\n\nexport function warn(message: string, ...args: unknown[]): void {\n globalLogger.warn(message, ...args);\n}\n\nexport function error(message: string, ...args: unknown[]): void {\n globalLogger.error(message, ...args);\n}\n","// serializeSmartEnums.ts\nexport { isSmartEnumItem, isSmartEnum } from './typeGuards.js';\nimport type { SerializedSmartEnums, AnyEnumLike } from '../types.js';\n\nimport { debug } from './logger.js';\nimport { isSerializedSmartEnumItem, isSmartEnumItem } from './typeGuards.js';\n\ntype PlainObject = Record<string, unknown>;\n\nconst isPlainObject = (x: unknown): x is PlainObject =>\n typeof x === 'object' &&\n x !== null &&\n Object.getPrototypeOf(x) === Object.prototype;\n\n/**\n * Recursively replaces Smart Enum items with self-describing objects\n * `{ __smart_enum_type, value }` for JSON transport or storage.\n *\n * @param input - Object or array that may contain enum items\n * @returns Same structure with enum items replaced by serialized shape\n *\n * @example\n * ```typescript\n * const dto = { id: '1', status: Status.active, color: Color.red };\n * const wire = serializeSmartEnums(dto);\n * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }\n * ```\n */\n// Overloads:\n// 1) Inferred\nexport function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;\n// 2) Return-type only (constrained to objects/arrays)\nexport function serializeSmartEnums<\n S extends Readonly<PlainObject> | readonly unknown[],\n>(input: unknown): S;\n// Implementation\nexport function serializeSmartEnums(input: unknown): unknown {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n if (isSmartEnumItem(v)) {\n return {\n __smart_enum_type: v.__smart_enum_type,\n value: v.value,\n };\n }\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) {\n arr.push(walk(item));\n }\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n\n return walk(input);\n}\n\n/**\n * Recursively revives serialized enum objects back to Smart Enum items\n * using a registry of enum types. Expects payload to contain\n * `{ __smart_enum_type, value }` where the type exists in the registry.\n *\n * @param input - Serialized payload (e.g. from JSON)\n * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)\n * @returns Payload with serialized enums revived to enum items\n *\n * @example\n * ```typescript\n * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };\n * const revived = reviveSmartEnums(wire, { Status, Color });\n * // revived.status === Status.active\n * ```\n */\nexport function reviveSmartEnums<R>(\n input: unknown,\n registry: Record<string, AnyEnumLike>,\n): R {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n // Handle self-describing enum objects with __smart_enum_type and value\n if (isSerializedSmartEnumItem(v)) {\n debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);\n const enumInstance = registry[v.__smart_enum_type];\n if (enumInstance) {\n debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);\n // Try to find the enum item by value first\n const enumItem = enumInstance.tryFromValue(v.value);\n if (enumItem) {\n debug(`Revived enumItem using value: ${v.value}`);\n return enumItem;\n }\n // If that fails, try to find by key (convert value to key format)\n const key = v.value.toLowerCase();\n const enumItemFromKey = enumInstance.tryFromKey(key);\n if (enumItemFromKey) {\n debug(`Revived enumItem using key: ${key}`);\n return enumItemFromKey;\n }\n }\n // If no matching enum type in registry, return the original serialized object\n return v;\n }\n\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) arr.push(walk(item));\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n return walk(input) as R;\n}\n\n/**\n * Maps a plain string (for example a column value from a database query) to the\n * corresponding Smart Enum item by calling `tryFromValue` on the given enum.\n *\n * Use this when you already know which enum type a field uses and the stored\n * value is the enum’s wire `value` string (same shape `tryFromValue` expects).\n *\n * @param value - Raw value; only strings are resolved—anything else returns `undefined`\n * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)\n * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`\n * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)\n *\n * @example\n * ```typescript\n * const item = reviveEnumField(row.status, UserStatus);\n * const mustMatch = reviveEnumField(row.code, OrderStatus, true);\n * ```\n */\nexport const reviveEnumField = <TItem>(\n value: unknown,\n smartEnum: AnyEnumLike<TItem>,\n strict = false,\n): TItem | undefined => {\n if (typeof value !== 'string') return undefined;\n\n const revived = smartEnum.tryFromValue(value);\n if (revived !== undefined) return revived;\n\n if (strict) {\n throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);\n }\n\n return undefined;\n};\n","import type {\n AnyEnumLike,\n LogLevel,\n SmartEnumMappingsConfig,\n} from '../../types.js';\nimport { info, setLogger, getLogger, type Logger } from '../logger.js';\n\nconst createLevelFilteredLogger = (logger: Logger, level: LogLevel): Logger => {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n const currentLevel = levels[level];\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.debug) {\n logger.debug(message, ...args);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.info) {\n logger.info(message, ...args);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.warn) {\n logger.warn(message, ...args);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.error) {\n logger.error(message, ...args);\n }\n },\n };\n};\n\nlet globalEnumRegistry: Record<string, AnyEnumLike> | undefined;\n\n/**\n * Wire-format registry for `reviveAfterTransport` / `reviveSmartEnums`.\n * Not used for database string revival.\n */\nexport const initializeSmartEnumMappings = (\n config: SmartEnumMappingsConfig,\n): void => {\n globalEnumRegistry = config.enumRegistry;\n\n const logLevel = config.logLevel ?? 'error';\n const logger = config.logger ?? getLogger();\n setLogger(createLevelFilteredLogger(logger, logLevel));\n\n info('Initialized smart enum mappings', {\n enumCount: Object.keys(config.enumRegistry).length,\n enumTypes: Object.keys(config.enumRegistry),\n logLevel,\n });\n};\n\nexport const getGlobalEnumRegistry = ():\n | Record<string, AnyEnumLike>\n | undefined => globalEnumRegistry;\n","import { reviveSmartEnums } from '../transformation.js';\n\nimport { getGlobalEnumRegistry } from './transportRegistry.js';\n\n/**\n * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.\n */\nexport const reviveAfterTransport = <T>(payload: unknown): T => {\n const registry = getGlobalEnumRegistry();\n if (!registry) {\n return payload as T;\n }\n return reviveSmartEnums(payload, registry);\n};\n","import { serializeSmartEnums } from '../transformation.js';\nimport type { SerializedSmartEnums } from '../../types.js';\n\n/**\n * Serializes smart enums for transport (to client or API).\n * Wire payloads include `__smart_enum_type` for `reviveAfterTransport`.\n */\nexport const serializeForTransport = <T>(payload: T): SerializedSmartEnums<T> =>\n serializeSmartEnums(payload);\n"],"mappings":";AAAA,SAAS,aAAa,oBAAoB;;;ACanC,IAAM,kBAAkB,OAAO,iBAAiB;AAChD,IAAM,gBAAgB,OAAO,eAAe;AAC5C,IAAM,aAAa,OAAO,YAAY;;;ACOtC,IAAM,kBAAkB,CAC7B,MAMG;AACH,SACE,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,QAAQ,IAAI,GAAG,eAAe,MAAM;AAExE;AAaO,IAAM,cAAc,CAAC,MAAmC;AAC7D,SAAO,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,QAAQ,IAAI,GAAG,UAAU,MAAM;AACxE;AAgBO,IAAM,4BAA4B,CACvC,MACiC;AACjC,SACE,CAAC,CAAC,KACF,OAAO,MAAM,YACb,QAAQ,IAAI,GAAG,mBAAmB,KAClC,QAAQ,IAAI,GAAG,OAAO;AAE1B;;;ACpEO,IAAM,iBAAiB,CAAC,GAAY,MAAwB;AACjE,MAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,gBAAgB,CAAC,GAAG;AAC9C,WAAO;AAAA,EACT;AAEA,SACE,QAAQ,IAAI,GAAG,aAAa,MAAM,QAAQ,IAAI,GAAG,aAAa,KAC9D,EAAE,UAAU,EA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