@reharik/smart-enum 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isSmartEnumItem
3
- } from "./chunk-E3FO4SL3.js";
3
+ } from "./chunk-WKWS4GCV.js";
4
4
 
5
5
  // src/db/prepareForDatabase.ts
6
6
  var isPlainObject = (x) => typeof x === "object" && x !== null && Object.getPrototypeOf(x) === Object.prototype;
@@ -181,4 +181,4 @@ export {
181
181
  reviveRowFromDatabase,
182
182
  revivePayloadFromDatabase
183
183
  };
184
- //# sourceMappingURL=chunk-X2DQHWNN.js.map
184
+ //# sourceMappingURL=chunk-ILNPYTU2.js.map
@@ -136,10 +136,131 @@ var isSerializedSmartEnumItem = (x) => {
136
136
  return !!x && typeof x === "object" && Reflect.has(x, "__smart_enum_type") && Reflect.has(x, "value");
137
137
  };
138
138
 
139
+ // src/utilities/logger.ts
140
+ var consoleLogger = {
141
+ debug(message, ...args) {
142
+ console.debug(`[ts-smart-enum:debug] ${message}`, ...args);
143
+ },
144
+ info(message, ...args) {
145
+ console.info(`[ts-smart-enum:info] ${message}`, ...args);
146
+ },
147
+ warn(message, ...args) {
148
+ console.warn(`[ts-smart-enum:warn] ${message}`, ...args);
149
+ },
150
+ error(message, ...args) {
151
+ console.error(`[ts-smart-enum:error] ${message}`, ...args);
152
+ }
153
+ };
154
+ var globalLogger = consoleLogger;
155
+ function setLogger(logger) {
156
+ globalLogger = logger;
157
+ }
158
+ function getLogger() {
159
+ return globalLogger;
160
+ }
161
+ function debug(message, ...args) {
162
+ globalLogger.debug(message, ...args);
163
+ }
164
+ function info(message, ...args) {
165
+ globalLogger.info(message, ...args);
166
+ }
167
+
168
+ // src/utilities/transformation.ts
169
+ var isPlainObject = (x) => typeof x === "object" && x !== null && Object.getPrototypeOf(x) === Object.prototype;
170
+ function serializeSmartEnums(input) {
171
+ const seen = /* @__PURE__ */ new WeakMap();
172
+ const walk = (v) => {
173
+ if (isSmartEnumItem(v)) {
174
+ return {
175
+ __smart_enum_type: v.__smart_enum_type,
176
+ value: v.value
177
+ };
178
+ }
179
+ if (typeof v === "object" && v !== null && seen.has(v)) {
180
+ return seen.get(v);
181
+ }
182
+ if (Array.isArray(v)) {
183
+ const arr = [];
184
+ seen.set(v, arr);
185
+ for (const item of v) {
186
+ arr.push(walk(item));
187
+ }
188
+ return arr;
189
+ }
190
+ if (isPlainObject(v)) {
191
+ const out = {};
192
+ seen.set(v, out);
193
+ for (const [k, val] of Object.entries(v)) {
194
+ out[k] = walk(val);
195
+ }
196
+ return out;
197
+ }
198
+ return v;
199
+ };
200
+ return walk(input);
201
+ }
202
+ function reviveSmartEnums(input, registry) {
203
+ const seen = /* @__PURE__ */ new WeakMap();
204
+ const walk = (v) => {
205
+ if (isSerializedSmartEnumItem(v)) {
206
+ debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);
207
+ const enumInstance = registry[v.__smart_enum_type];
208
+ if (enumInstance) {
209
+ debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);
210
+ const enumItem = enumInstance.tryFromValue(v.value);
211
+ if (enumItem) {
212
+ debug(`Revived enumItem using value: ${v.value}`);
213
+ return enumItem;
214
+ }
215
+ const key = v.value.toLowerCase();
216
+ const enumItemFromKey = enumInstance.tryFromKey(key);
217
+ if (enumItemFromKey) {
218
+ debug(`Revived enumItem using key: ${key}`);
219
+ return enumItemFromKey;
220
+ }
221
+ }
222
+ return v;
223
+ }
224
+ if (typeof v === "object" && v !== null && seen.has(v)) {
225
+ return seen.get(v);
226
+ }
227
+ if (Array.isArray(v)) {
228
+ const arr = [];
229
+ seen.set(v, arr);
230
+ for (const item of v) arr.push(walk(item));
231
+ return arr;
232
+ }
233
+ if (isPlainObject(v)) {
234
+ const out = {};
235
+ seen.set(v, out);
236
+ for (const [k, val] of Object.entries(v)) {
237
+ out[k] = walk(val);
238
+ }
239
+ return out;
240
+ }
241
+ return v;
242
+ };
243
+ return walk(input);
244
+ }
245
+ var reviveEnumField = (value, smartEnum, strict = false) => {
246
+ if (typeof value !== "string") return void 0;
247
+ const revived = smartEnum.tryFromValue(value);
248
+ if (revived !== void 0) return revived;
249
+ if (strict) {
250
+ throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);
251
+ }
252
+ return void 0;
253
+ };
254
+
139
255
  export {
140
256
  enumeration,
141
257
  isSmartEnumItem,
142
258
  isSmartEnum,
143
- isSerializedSmartEnumItem
259
+ setLogger,
260
+ getLogger,
261
+ info,
262
+ serializeSmartEnums,
263
+ reviveSmartEnums,
264
+ reviveEnumField
144
265
  };
145
- //# sourceMappingURL=chunk-E3FO4SL3.js.map
266
+ //# sourceMappingURL=chunk-WKWS4GCV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/enumerations.ts","../src/extensionMethods.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/logger.ts","../src/utilities/transformation.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 StandardEnumItem,\n} from './types.js';\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n object;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\ntype 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\ntype ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\ntype NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\ntype UnionKeys<T> = T extends T ? keyof T : never;\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 EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n> = Omit<StandardEnumItem, 'key' | 'value'> &\n InferredExtraFields<TObj> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? Extract<V, string> extends never\n ? string\n : Extract<V, string>\n : string;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<TObj extends ObjectEnumInput> =\n {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }[keyof TObj];\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 items(): readonly TItem[];\n values(): readonly string[];\n keys(): readonly string[];\n};\n\nexport type EnumFromNormalizedObject<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj>>;\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n};\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\nexport type PropertyAutoFormatter = {\n key: string;\n format: (k: string) => string;\n};\n\ntype FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type'\n>;\n\ntype FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\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 }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\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: () => ({ __smart_enum_type: enumType, value: item.value }),\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\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): EnumFromNormalizedObject<TObj> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumItemFromNormalizedObject<TObj>;\n\n const rawEnumItems = {} as {\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 ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey] = 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) {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n );\n}\n","import type { CoreEnumMethods, StandardEnumItem } from './types.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 items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\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 SmartEnumLike<T = unknown> = {\n tryFromValue: (value: string) => T | undefined;\n fromValue: (value: string) => T | undefined;\n};\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\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\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\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\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\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem;\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n> = Omit<StandardEnumItem, 'key'> &\n InferredExtraFields<TObj> & {\n readonly key: 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 items(): readonly TItem[];\n values(): readonly string[];\n keys(): readonly string[];\n};\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\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'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\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): boolean => {\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","/**\n * Logger interface for ts-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(`[ts-smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[ts-smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[ts-smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[ts-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 'ts-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"],"mappings":";AAAA,SAAS,aAAa,oBAAoB;;;ACCnC,IAAM,sBAAsB,CACjC,cAC2B;AAC3B,QAAM,SAAS,CAAwB,OAAU,WAC/C,UAAU,KAAK,UAAQ,KAAK,KAAK,MAAM,MAAM;AAE/C,QAAM,YAAY,CAChB,OACA,QACA,UACG;AACH,UAAM,OAAO,OAAO,OAAO,MAAM;AACjC,QAAI,CAAC,MAAM;AACT,YAAM,IAAI,MAAM,WAAW,KAAK,eAAe,OAAO,MAAM,CAAC,GAAG;AAAA,IAClE;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,WAAW,WAAS,UAAU,SAAS,OAAyB,OAAO;AAAA,IACvE,cAAc,WACZ,QAAQ,OAAO,SAAS,KAAuB,IAAI;AAAA,IAErD,SAAS,SAAO,UAAU,OAAO,KAAqB,KAAK;AAAA,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MAAM,QAAQ,KAAK,IAAI,CAAC,GAAG;AACtD,aAAO,KAAK,IAAI,CAAC;AAAA,IACnB;AAEA,QAAI,MAAM,QAAQ,CAAC,GAAG;AACpB,YAAM,MAAiB,CAAC;AACxB,WAAK,IAAI,GAAG,GAAG;AACf,iBAAW,QAAQ,EAAG,KAAI,KAAK,KAAK,IAAI,CAAC;AACzC,aAAO;AAAA,IACT;AACA,QAAI,cAAc,CAAC,GAAG;AACpB,YAAM,MAAmB,CAAC;AAC1B,WAAK,IAAI,GAAG,GAAG;AACf,iBAAW,CAAC,GAAG,GAAG,KAAK,OAAO,QAAQ,CAAC,GAAG;AACxC,YAAI,CAAC,IAAI,KAAK,GAAG;AAAA,MACnB;AACA,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AACA,SAAO,KAAK,KAAK;AACnB;AAoBO,IAAM,kBAAkB,CAC7B,OACA,WACA,SAAS,UACa;AACtB,MAAI,OAAO,UAAU,SAAU,QAAO;AAEtC,QAAM,UAAU,UAAU,aAAa,KAAK;AAC5C,MAAI,YAAY,OAAW,QAAO;AAElC,MAAI,QAAQ;AACV,UAAM,IAAI,MAAM,uBAAuB,KAAK,UAAU,KAAK,CAAC,EAAE;AAAA,EAChE;AAEA,SAAO;AACT;","names":[]}
@@ -0,0 +1,73 @@
1
+ import {
2
+ getLogger,
3
+ info,
4
+ reviveSmartEnums,
5
+ serializeSmartEnums,
6
+ setLogger
7
+ } from "./chunk-WKWS4GCV.js";
8
+
9
+ // src/utilities/transport/transportRegistry.ts
10
+ var createLevelFilteredLogger = (logger, level) => {
11
+ const levels = {
12
+ debug: 0,
13
+ info: 1,
14
+ warn: 2,
15
+ error: 3
16
+ };
17
+ const currentLevel = levels[level];
18
+ return {
19
+ debug: (message, ...args) => {
20
+ if (currentLevel <= levels.debug) {
21
+ logger.debug(message, ...args);
22
+ }
23
+ },
24
+ info: (message, ...args) => {
25
+ if (currentLevel <= levels.info) {
26
+ logger.info(message, ...args);
27
+ }
28
+ },
29
+ warn: (message, ...args) => {
30
+ if (currentLevel <= levels.warn) {
31
+ logger.warn(message, ...args);
32
+ }
33
+ },
34
+ error: (message, ...args) => {
35
+ if (currentLevel <= levels.error) {
36
+ logger.error(message, ...args);
37
+ }
38
+ }
39
+ };
40
+ };
41
+ var globalEnumRegistry;
42
+ var initializeSmartEnumMappings = (config) => {
43
+ globalEnumRegistry = config.enumRegistry;
44
+ const logLevel = config.logLevel ?? "error";
45
+ const logger = config.logger ?? getLogger();
46
+ setLogger(createLevelFilteredLogger(logger, logLevel));
47
+ info("Initialized smart enum mappings", {
48
+ enumCount: Object.keys(config.enumRegistry).length,
49
+ enumTypes: Object.keys(config.enumRegistry),
50
+ logLevel
51
+ });
52
+ };
53
+ var getGlobalEnumRegistry = () => globalEnumRegistry;
54
+
55
+ // src/utilities/transport/reviveAfterTransport.ts
56
+ var reviveAfterTransport = (payload) => {
57
+ const registry = getGlobalEnumRegistry();
58
+ if (!registry) {
59
+ return payload;
60
+ }
61
+ return reviveSmartEnums(payload, registry);
62
+ };
63
+
64
+ // src/utilities/transport/serializeForTransport.ts
65
+ var serializeForTransport = (payload) => serializeSmartEnums(payload);
66
+
67
+ export {
68
+ initializeSmartEnumMappings,
69
+ getGlobalEnumRegistry,
70
+ reviveAfterTransport,
71
+ serializeForTransport
72
+ };
73
+ //# sourceMappingURL=chunk-XM5MNKBQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utilities/transport/transportRegistry.ts","../src/utilities/transport/reviveAfterTransport.ts","../src/utilities/transport/serializeForTransport.ts"],"sourcesContent":["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":";;;;;;;;;AAOA,IAAM,4BAA4B,CAAC,QAAgB,UAA4B;AAC7E,QAAM,SAAmC;AAAA,IACvC,OAAO;AAAA,IACP,MA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22
22
  } ? string : T extends ReadonlyArray<infer U> ? ReadonlyArray<SerializedSmartEnums<U>> : T extends Array<infer U> ? SerializedSmartEnums<U>[] : T extends object ? {
23
23
  [K in keyof T]: SerializedSmartEnums<T[K]>;
24
24
  } : T;
25
- type AnyEnumLike = {
26
- tryFromValue: (value?: string | null) => unknown;
27
- tryFromKey: (key?: string | null) => unknown;
25
+ /**
26
+ * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).
27
+ * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).
28
+ */
29
+ type AnyEnumLike<T = unknown> = {
30
+ tryFromValue: (value?: string | null) => T | undefined;
31
+ tryFromKey: (key?: string | null) => T | undefined;
28
32
  } & Record<string, unknown>;
29
33
  type SmartEnumLike<T = unknown> = {
30
34
  tryFromValue: (value: string) => T | undefined;
35
+ fromValue: (value: string) => T | undefined;
31
36
  };
32
37
  type FieldEnumMapping = Record<string, SmartEnumLike>;
33
38
  type ReviveRowOptions = {
@@ -185,4 +190,58 @@ declare const isSmartEnumItem: (x: unknown) => x is {
185
190
  */
186
191
  declare const isSmartEnum: (x: unknown) => boolean;
187
192
 
188
- export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SmartApiHelperConfig as S, isSmartEnum as a, type LogLevel as b, type SmartEnumMappingsConfig as c, type SerializedSmartEnums as d, enumeration as e, type SmartEnumItemSerialized as f, type SmartEnumLike as g, type ReviveRowOptions as h, isSmartEnumItem as i, type RevivePayloadOptions as j, type StandardEnumItemBase as k };
193
+ type PlainObject = Record<string, unknown>;
194
+ /**
195
+ * Recursively replaces Smart Enum items with self-describing objects
196
+ * `{ __smart_enum_type, value }` for JSON transport or storage.
197
+ *
198
+ * @param input - Object or array that may contain enum items
199
+ * @returns Same structure with enum items replaced by serialized shape
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const dto = { id: '1', status: Status.active, color: Color.red };
204
+ * const wire = serializeSmartEnums(dto);
205
+ * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }
206
+ * ```
207
+ */
208
+ declare function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;
209
+ declare function serializeSmartEnums<S extends Readonly<PlainObject> | readonly unknown[]>(input: unknown): S;
210
+ /**
211
+ * Recursively revives serialized enum objects back to Smart Enum items
212
+ * using a registry of enum types. Expects payload to contain
213
+ * `{ __smart_enum_type, value }` where the type exists in the registry.
214
+ *
215
+ * @param input - Serialized payload (e.g. from JSON)
216
+ * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)
217
+ * @returns Payload with serialized enums revived to enum items
218
+ *
219
+ * @example
220
+ * ```typescript
221
+ * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };
222
+ * const revived = reviveSmartEnums(wire, { Status, Color });
223
+ * // revived.status === Status.active
224
+ * ```
225
+ */
226
+ declare function reviveSmartEnums<R>(input: unknown, registry: Record<string, AnyEnumLike>): R;
227
+ /**
228
+ * Maps a plain string (for example a column value from a database query) to the
229
+ * corresponding Smart Enum item by calling `tryFromValue` on the given enum.
230
+ *
231
+ * Use this when you already know which enum type a field uses and the stored
232
+ * value is the enum’s wire `value` string (same shape `tryFromValue` expects).
233
+ *
234
+ * @param value - Raw value; only strings are resolved—anything else returns `undefined`
235
+ * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)
236
+ * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`
237
+ * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * const item = reviveEnumField(row.status, UserStatus);
242
+ * const mustMatch = reviveEnumField(row.code, OrderStatus, true);
243
+ * ```
244
+ */
245
+ declare const reviveEnumField: <TItem>(value: unknown, smartEnum: AnyEnumLike<TItem>, strict?: boolean) => TItem | undefined;
246
+
247
+ export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SmartApiHelperConfig as S, isSmartEnum as a, reviveEnumField as b, type LogLevel as c, type SmartEnumMappingsConfig as d, enumeration as e, type SerializedSmartEnums as f, type SmartEnumItemSerialized as g, type SmartEnumLike as h, isSmartEnumItem as i, type ReviveRowOptions as j, type RevivePayloadOptions as k, type StandardEnumItemBase as l, reviveSmartEnums as r, serializeSmartEnums as s };
@@ -22,12 +22,17 @@ type SerializedSmartEnums<T> = T extends {
22
22
  } ? string : T extends ReadonlyArray<infer U> ? ReadonlyArray<SerializedSmartEnums<U>> : T extends Array<infer U> ? SerializedSmartEnums<U>[] : T extends object ? {
23
23
  [K in keyof T]: SerializedSmartEnums<T[K]>;
24
24
  } : T;
25
- type AnyEnumLike = {
26
- tryFromValue: (value?: string | null) => unknown;
27
- tryFromKey: (key?: string | null) => unknown;
25
+ /**
26
+ * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).
27
+ * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).
28
+ */
29
+ type AnyEnumLike<T = unknown> = {
30
+ tryFromValue: (value?: string | null) => T | undefined;
31
+ tryFromKey: (key?: string | null) => T | undefined;
28
32
  } & Record<string, unknown>;
29
33
  type SmartEnumLike<T = unknown> = {
30
34
  tryFromValue: (value: string) => T | undefined;
35
+ fromValue: (value: string) => T | undefined;
31
36
  };
32
37
  type FieldEnumMapping = Record<string, SmartEnumLike>;
33
38
  type ReviveRowOptions = {
@@ -185,4 +190,58 @@ declare const isSmartEnumItem: (x: unknown) => x is {
185
190
  */
186
191
  declare const isSmartEnum: (x: unknown) => boolean;
187
192
 
188
- export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SmartApiHelperConfig as S, isSmartEnum as a, type LogLevel as b, type SmartEnumMappingsConfig as c, type SerializedSmartEnums as d, enumeration as e, type SmartEnumItemSerialized as f, type SmartEnumLike as g, type ReviveRowOptions as h, isSmartEnumItem as i, type RevivePayloadOptions as j, type StandardEnumItemBase as k };
193
+ type PlainObject = Record<string, unknown>;
194
+ /**
195
+ * Recursively replaces Smart Enum items with self-describing objects
196
+ * `{ __smart_enum_type, value }` for JSON transport or storage.
197
+ *
198
+ * @param input - Object or array that may contain enum items
199
+ * @returns Same structure with enum items replaced by serialized shape
200
+ *
201
+ * @example
202
+ * ```typescript
203
+ * const dto = { id: '1', status: Status.active, color: Color.red };
204
+ * const wire = serializeSmartEnums(dto);
205
+ * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }
206
+ * ```
207
+ */
208
+ declare function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;
209
+ declare function serializeSmartEnums<S extends Readonly<PlainObject> | readonly unknown[]>(input: unknown): S;
210
+ /**
211
+ * Recursively revives serialized enum objects back to Smart Enum items
212
+ * using a registry of enum types. Expects payload to contain
213
+ * `{ __smart_enum_type, value }` where the type exists in the registry.
214
+ *
215
+ * @param input - Serialized payload (e.g. from JSON)
216
+ * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)
217
+ * @returns Payload with serialized enums revived to enum items
218
+ *
219
+ * @example
220
+ * ```typescript
221
+ * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };
222
+ * const revived = reviveSmartEnums(wire, { Status, Color });
223
+ * // revived.status === Status.active
224
+ * ```
225
+ */
226
+ declare function reviveSmartEnums<R>(input: unknown, registry: Record<string, AnyEnumLike>): R;
227
+ /**
228
+ * Maps a plain string (for example a column value from a database query) to the
229
+ * corresponding Smart Enum item by calling `tryFromValue` on the given enum.
230
+ *
231
+ * Use this when you already know which enum type a field uses and the stored
232
+ * value is the enum’s wire `value` string (same shape `tryFromValue` expects).
233
+ *
234
+ * @param value - Raw value; only strings are resolved—anything else returns `undefined`
235
+ * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)
236
+ * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`
237
+ * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)
238
+ *
239
+ * @example
240
+ * ```typescript
241
+ * const item = reviveEnumField(row.status, UserStatus);
242
+ * const mustMatch = reviveEnumField(row.code, OrderStatus, true);
243
+ * ```
244
+ */
245
+ declare const reviveEnumField: <TItem>(value: unknown, smartEnum: AnyEnumLike<TItem>, strict?: boolean) => TItem | undefined;
246
+
247
+ export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SmartApiHelperConfig as S, isSmartEnum as a, reviveEnumField as b, type LogLevel as c, type SmartEnumMappingsConfig as d, enumeration as e, type SerializedSmartEnums as f, type SmartEnumItemSerialized as g, type SmartEnumLike as h, isSmartEnumItem as i, type ReviveRowOptions as j, type RevivePayloadOptions as k, type StandardEnumItemBase as l, reviveSmartEnums as r, serializeSmartEnums as s };
package/dist/core.cjs CHANGED
@@ -22,7 +22,8 @@ var core_exports = {};
22
22
  __export(core_exports, {
23
23
  enumeration: () => enumeration,
24
24
  isSmartEnum: () => isSmartEnum,
25
- isSmartEnumItem: () => isSmartEnumItem
25
+ isSmartEnumItem: () => isSmartEnumItem,
26
+ reviveEnumField: () => reviveEnumField
26
27
  });
27
28
  module.exports = __toCommonJS(core_exports);
28
29
 
@@ -160,10 +161,22 @@ var isSmartEnumItem = (x) => {
160
161
  var isSmartEnum = (x) => {
161
162
  return !!x && typeof x === "object" && Reflect.get(x, SMART_ENUM) === true;
162
163
  };
164
+
165
+ // src/utilities/transformation.ts
166
+ var reviveEnumField = (value, smartEnum, strict = false) => {
167
+ if (typeof value !== "string") return void 0;
168
+ const revived = smartEnum.tryFromValue(value);
169
+ if (revived !== void 0) return revived;
170
+ if (strict) {
171
+ throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);
172
+ }
173
+ return void 0;
174
+ };
163
175
  // Annotate the CommonJS export names for ESM import in node:
164
176
  0 && (module.exports = {
165
177
  enumeration,
166
178
  isSmartEnum,
167
- isSmartEnumItem
179
+ isSmartEnumItem,
180
+ reviveEnumField
168
181
  });
169
182
  //# sourceMappingURL=core.cjs.map