UNPKG

couponjs

Version:
899 lines (883 loc) 28.1 kB
"use strict"; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { CouponJS: () => CouponJS, default: () => src_default }); module.exports = __toCommonJS(src_exports); // src/helpers/index.ts function randomInteger(min, max) { return Math.floor(Math.random() * (Math.floor(max) - Math.ceil(min) + 1)) + Math.ceil(min); } function sumOf(values) { return values.reduce((sum, size) => sum + size); } function attachPrefix(prefix = "") { return function attachPrefixFn(coupon) { return `${prefix}${coupon}`; }; } function attachSuffix(suffix = "") { return function attachSuffixFn(coupon) { return `${coupon}${suffix}`; }; } function pipe(operators) { return function(value) { return operators.reduce((enrichedValue, operator) => operator(enrichedValue), value); }; } function identity(value) { return value; } function omit(values, valuesToOmit) { return values.filter((value) => !valuesToOmit.includes(value)); } function uniqueCharacters(characters) { return [...new Set(characters.join(""))]; } function shallowMerge(...sourceObjects) { return Object.assign({}, ...sourceObjects); } // src/constants/index.ts var MIN_NUMBER_OF_COUPONS_TO_GENERATE = 1; var MAX_NUMBER_OF_COUPONS_TO_GENERATE = 1e5; var DEFAULT_NUMBER_OF_COUPONS_TO_GENERATE = MIN_NUMBER_OF_COUPONS_TO_GENERATE; var MAX_LENGTH = 128; var MIN_LENGTH = 1; var DEFAULT_LENGTH = 6; var DEFAULT_PREFIX = ""; var DEFAULT_SUFFIX = ""; var ALPHABET_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var ALPHABET_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"; var DIGIT = "0123456789"; var BINARY = "01"; var OCTAL = "01234567"; var HEX = "0123456789ABCDEF"; var HEX_LOWER = "0123456789abcdef"; var ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var CHARSET_ALPHA = "CHARSET_ALPHA"; var CHARSET_ALPHA_LOWER = "CHARSET_ALPHA_LOWER"; var CHARSET_DIGIT = "CHARSET_DIGIT"; var CHARSET_ALNUM = "CHARSET_ALNUM"; var CHARSET_BINARY = "CHARSET_BINARY"; var CHARSET_OCTAL = "CHARSET_OCTAL"; var CHARSET_HEX = "CHARSET_HEX"; var CHARSET_HEX_LOWER = "CHARSET_HEX_LOWER"; var DEFAULT_OMIT_CHARACTERS = []; var UNDEFINED = "UNDEFINED"; var DEFAULT_COUPON_FORMAT = UNDEFINED; var DEFAULT_CUSTOM_CHARACTER_SET = []; var DEFAULT_BUILTIN_CHARACTER_SET = [CHARSET_ALPHA]; var DEFAULT_CHARACTER_SET_OPTION = { builtIn: DEFAULT_BUILTIN_CHARACTER_SET, custom: DEFAULT_CUSTOM_CHARACTER_SET }; // src/constants/error-constants.ts var ERROR_TYPE_VALIDATION_ERROR = "COUPONJS_VALIDATION_ERROR"; var ERROR_TYPE_CHARACTER_SET_ERROR = "COUPONJS_CHARACTER_SET_ERROR"; var ERROR_TYPE_FORMAT_ERROR = "COUPONJS_FORMAT_ERROR"; var ERROR_TYPE_GENERATE_COUPON_CONFIGURATION_ERROR = "COUPONJS_GENERATE_COUPON_CONFIGURATION_ERROR"; var ERROR_TYPE_COUPON_ENGINE_CONFIGURATION_ERROR = "COUPONJS_COUPON_ENGINE_CONFIGURATION_ERROR"; var ERROR_CONSTANTS = { [ERROR_TYPE_VALIDATION_ERROR]: { type: ERROR_TYPE_VALIDATION_ERROR, message: "Validation error" }, [ERROR_TYPE_CHARACTER_SET_ERROR]: { type: ERROR_TYPE_CHARACTER_SET_ERROR, message: "Character set error" }, [ERROR_TYPE_FORMAT_ERROR]: { type: ERROR_TYPE_FORMAT_ERROR, message: "Format error" }, [ERROR_TYPE_GENERATE_COUPON_CONFIGURATION_ERROR]: { type: ERROR_TYPE_GENERATE_COUPON_CONFIGURATION_ERROR, message: "Generate coupon configuration error" }, [ERROR_TYPE_COUPON_ENGINE_CONFIGURATION_ERROR]: { type: ERROR_TYPE_COUPON_ENGINE_CONFIGURATION_ERROR, message: "Coupon engine configuration error" } }; // src/error/validation-error.ts var ValidationError = class extends Error { constructor({ message, errors = [] }) { super(message); this.type = ERROR_CONSTANTS.COUPONJS_VALIDATION_ERROR.type; this.errors = errors; } }; // src/validators/index.ts function isBoolean(value) { return typeof value === "boolean"; } function isObject(value) { return typeof value === "object" && value !== null && value.constructor === Object; } function isString(value) { return typeof value === "string"; } function isUndefined(value) { return typeof value === "undefined"; } function isInteger(value) { return Number.isInteger(value) && Number.isFinite(value); } function isArray(value) { return Array.isArray(value); } function isEmptyArray(value) { return isArray(value) && value.length === 0; } // src/validators/generate-coupon-config-validator.ts var throwValidationError = ({ message, field }) => { throw new ValidationError({ message, errors: [ { message, field, type: ERROR_CONSTANTS.COUPONJS_GENERATE_COUPON_CONFIGURATION_ERROR.type } ] }); }; function validateLength(length) { if (!isUndefined(length)) { if (!isInteger(length)) { throwValidationError({ message: `The field 'length' must be of type integer.`, field: "length" }); } if (length < MIN_LENGTH) { throwValidationError({ message: `Minimum value for 'length' is ${MIN_LENGTH}.`, field: "length" }); } if (length > MAX_LENGTH) { throwValidationError({ message: `Maximum value for length is ${MAX_LENGTH}.`, field: "length" }); } return length; } throwValidationError({ message: `The field 'length' must be defined.`, field: "length" }); } function validateNumberOfCoupons(numberOfCoupons, maxNumberOfCouponsToGenerate, totalNumberOfPossibleCoupons) { if (!isUndefined(numberOfCoupons)) { if (!isInteger(numberOfCoupons)) { throwValidationError({ message: `The field 'numberOfCoupons' must be of type integer.`, field: "numberOfCoupons" }); } if (numberOfCoupons < MIN_NUMBER_OF_COUPONS_TO_GENERATE) { throwValidationError({ message: `Minimum value for numberOfCoupons is ${MIN_NUMBER_OF_COUPONS_TO_GENERATE}.`, field: "numberOfCoupons" }); } if (numberOfCoupons > maxNumberOfCouponsToGenerate) { throwValidationError({ message: `Maximum value for numberOfCoupons is ${maxNumberOfCouponsToGenerate}.`, field: "numberOfCoupons" }); } if (numberOfCoupons > totalNumberOfPossibleCoupons) { throwValidationError({ message: `Total number of possible coupons that can be generated is ${totalNumberOfPossibleCoupons} for the given length and characterSet.`, field: "numberOfCoupons" }); } return numberOfCoupons; } throwValidationError({ message: `The field 'numberOfCoupons' must be defined.`, field: "numberOfCoupons" }); } function validateOmitCharacters(omitCharacters) { if (!isUndefined(omitCharacters)) { if (!isArray(omitCharacters)) { throwValidationError({ message: `The field 'omitCharacters' must be of type array.`, field: "omitCharacters" }); } const errors = omitCharacters.reduce((error, omitCharacter, index) => { if (isString(omitCharacter)) { return error; } return [ ...error, { field: "omitCharacters", message: `The field 'omitCharacters' must be an array of string. Non-string value found at index ${index}.`, type: ERROR_CONSTANTS.COUPONJS_GENERATE_COUPON_CONFIGURATION_ERROR.type } ]; }, []); if (!isEmptyArray(errors)) { throw new ValidationError({ errors, message: `The field 'omitCharacters' must be an array of strings.` }); } return omitCharacters; } throwValidationError({ message: `The field 'omitCharacters' must be defined.`, field: "omitCharacters" }); } function validatePrefix(prefix) { if (isUndefined(prefix)) { throwValidationError({ message: `The field 'prefix' must be defined.`, field: "prefix" }); } if (!isString(prefix)) { throwValidationError({ message: `The field 'prefix' must be of type string.`, field: "prefix" }); } return prefix; } function validateSuffix(suffix) { if (isUndefined(suffix)) { throwValidationError({ message: `The field 'suffix' must be defined.`, field: "suffix" }); } if (!isString(suffix)) { throwValidationError({ message: `The field 'suffix' must be of type string.`, field: "suffix" }); } return suffix; } function validateCharacterSetOption(characterSetOption) { if (isUndefined(characterSetOption)) { throwValidationError({ message: `The field 'characterSet' must be defined.`, field: "characterSet" }); } if (!isObject(characterSetOption)) { throwValidationError({ message: `The field 'characterSet' must be of type object.`, field: "characterSet" }); } const { builtIn, custom } = characterSetOption; if (!isUndefined(builtIn)) { if (!isArray(builtIn)) { throwValidationError({ message: `The field 'characterSet.builtIn' must be an array.`, field: "characterSet.builtIn" }); } const builtInErrors = builtIn.reduce((error, charSet, index) => { if (isString(charSet)) { return error; } return [ ...error, { field: "characterSet.builtIn", message: `The field 'characterSet.builtIn' must be an array of string. Non-string value found at index ${index}.`, type: ERROR_CONSTANTS.COUPONJS_GENERATE_COUPON_CONFIGURATION_ERROR.type } ]; }, []); if (!isEmptyArray(builtInErrors)) { throw new ValidationError({ errors: builtInErrors, message: `The field 'characterSet.builtIn' must be an array of strings.` }); } } if (!isUndefined(custom)) { if (!isArray(custom)) { throwValidationError({ message: `The field 'characterSet.custom' must be an array.`, field: "characterSet.custom" }); } const customErrors = custom.reduce((error, charSet, index) => { if (isString(charSet)) { return error; } return [ ...error, { field: "characterSet.custom", message: `The field 'characterSet.custom' must be an array of string. Non-string value found at index ${index}.`, type: ERROR_CONSTANTS.COUPONJS_GENERATE_COUPON_CONFIGURATION_ERROR.type } ]; }, []); if (!isEmptyArray(customErrors)) { throw new ValidationError({ errors: customErrors, message: `The field 'characterSet.custom' must be an array of strings.` }); } } return characterSetOption; } // src/validators/formatter-validator.ts var getErrorsInGroups = (groups) => { return groups.reduce((error, group, index) => { if (isInteger(group)) { return error; } return [ ...error, { field: "groups", message: `Format object must only have integer elements in 'groups' array. Found error at index ${index}.`, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type } ]; }, []); }; var getErrorsInSeparators = (separators) => { return separators.reduce((error, separator, index) => { if (isString(separator)) { return error; } return [ ...error, { field: "separators", message: `Format object must only have string elements in 'separators' array. Found error at index ${index}.`, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type } ]; }, []); }; function validateFormatRuleString(ruleString) { const isValidFormatRuleString = /^([x]+-?[x]*)*?x$/g.test(ruleString); if (isValidFormatRuleString) { const groups = ruleString.split("-").map((group) => group.length); const totalCharactersInGroup = sumOf(groups); const separators = "-".repeat(groups.length - 1).split(""); return { groups, separators, totalCharactersInGroup }; } throw new ValidationError({ message: "Invalid characters used in the format rule.", errors: [ { type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "format", message: "Invalid characters used in the format rule. Only x and - are allowed. And only one - inbetween like xxx-xxx." } ] }); } function validateFormatRuleObject(ruleObject) { const { separators, groups } = ruleObject; if (!isArray(separators)) { const message = `Format object must have field 'separators' of type array.`; throw new ValidationError({ message, errors: [ { message, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "separators" } ] }); } if (!isArray(groups)) { const message = `Format object must have field 'groups' of type array.`; throw new ValidationError({ message, errors: [ { message, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "groups" } ] }); } if (isEmptyArray(groups)) { const message = `Format object must have at least one element in the array field 'groups'.`; throw new ValidationError({ message, errors: [ { message, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "groups" } ] }); } if (separators.length >= groups.length) { const message = `Format object must not have 'separators' array with more elements than 'groups' array.`; throw new ValidationError({ message, errors: [ { message, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "separators" } ] }); } if (separators.length !== groups.length - 1) { const message = `Format object has ${groups.length} elements in 'groups' array so, it must have ${groups.length - 1} elements in 'separators' array.`; throw new ValidationError({ message, errors: [ { message, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "separators" } ] }); } const separatorElementTypeErrors = getErrorsInSeparators(separators); if (separatorElementTypeErrors.length > 0) { const message = `Format object has errors in 'separators' field.`; throw new ValidationError({ message, errors: separatorElementTypeErrors }); } const groupsElementTypeErrors = getErrorsInGroups(groups); if (groupsElementTypeErrors.length > 0) { const message = `Format object has errors in 'groups' field.`; throw new ValidationError({ message, errors: groupsElementTypeErrors }); } return { separators, groups, totalCharactersInGroup: sumOf(groups) }; } function hasEqualSumOfGroupsAndCouponLength(coupon, totalCharactersInGroup) { return coupon.length === totalCharactersInGroup; } // src/formatter.ts var Formatter = class { constructor(formatRule) { this.formatRule = formatRule; this.formatRuleResult = this.validate(formatRule); } getConfig() { return this.formatRuleResult; } format(coupon) { const { separators, groups, totalCharactersInGroup } = this.formatRuleResult; if (!hasEqualSumOfGroupsAndCouponLength(coupon, totalCharactersInGroup)) { const message = "Coupon length is not equal to the sum of groups in the format."; throw new ValidationError({ message, errors: [ { message: `Coupon length: ${coupon.length} and sum of groups: ${groups.join( "+" )} = ${totalCharactersInGroup}`, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "format" } ] }); } const { chunks } = this.getCouponInGroups(coupon, groups); return this.getFormattedCoupon(chunks, separators); } getFormattedCoupon(couponChunks, separators) { const separatorLength = separators.length; return couponChunks.reduce((formattedCoupon, currentChunk, index) => { return index < separatorLength ? `${formattedCoupon}${currentChunk}${separators[index]}` : `${formattedCoupon}${currentChunk}`; }, ""); } getCouponInGroups(coupon, groups) { return groups.reduce( (result, currentGroupSize) => { const { chunks, lengthCovered } = result; const chunk = coupon.substring(lengthCovered, lengthCovered + currentGroupSize); return { chunks: [...chunks, chunk], lengthCovered: lengthCovered + currentGroupSize }; }, { chunks: [], lengthCovered: 0 } ); } validate(format) { if (isUndefined(format)) { const message = "Format rule is not specified."; throw new ValidationError({ message, errors: [ { message, type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "format" } ] }); } else if (isString(format)) { const result = validateFormatRuleString(format); const { groups, totalCharactersInGroup, separators } = result; return { groups, totalCharactersInGroup, separators }; } else if (isObject(format)) { const result = validateFormatRuleObject(format); const { groups, totalCharactersInGroup, separators } = result; return { groups, totalCharactersInGroup, separators }; } throw new ValidationError({ message: "Invalid format rule.", errors: [ { message: "Invalid format rule.", type: ERROR_CONSTANTS.COUPONJS_FORMAT_ERROR.type, field: "format" } ] }); } }; // src/character-set.ts function characterSet(charSetName) { const possibleCharacterSets = { [CHARSET_ALPHA]: ALPHABET_UPPERCASE, [CHARSET_ALPHA_LOWER]: ALPHABET_LOWERCASE, [CHARSET_DIGIT]: DIGIT, [CHARSET_ALNUM]: ALNUM, [CHARSET_BINARY]: BINARY, [CHARSET_OCTAL]: OCTAL, [CHARSET_HEX]: HEX, [CHARSET_HEX_LOWER]: HEX_LOWER }; const validCharSets = Object.keys(possibleCharacterSets); const matchingCharacterSet = possibleCharacterSets[charSetName]; if (!matchingCharacterSet) { const message = `Invalid builtIn characterSet specified. Allowed values: ${validCharSets.join(", ")}`; throw new ValidationError({ message, errors: [ { type: ERROR_CONSTANTS.COUPONJS_CHARACTER_SET_ERROR.type, field: "builtIn", message: `Invalid character set ${charSetName}` } ] }); } return matchingCharacterSet; } // src/helpers/character-list.ts function characterList(characterSetOptions, omitCharacters = DEFAULT_OMIT_CHARACTERS) { const { builtIn = [], custom = [] } = characterSetOptions; const charactersToOmit = uniqueCharacters(omitCharacters); const charactersFromCharacterSetOptions = uniqueCharacters([ ...builtIn.map((characterSetName) => characterSet(characterSetName)), ...custom ]); return omit(charactersFromCharacterSetOptions, charactersToOmit); } // src/engine.ts var Engine = class { constructor({ randomInteger: randomInteger2, characterSetOption = DEFAULT_CHARACTER_SET_OPTION, length = DEFAULT_LENGTH, prefix = DEFAULT_PREFIX, suffix = DEFAULT_SUFFIX, numberOfCoupons = DEFAULT_NUMBER_OF_COUPONS_TO_GENERATE, omitCharacters = DEFAULT_OMIT_CHARACTERS, format = UNDEFINED, maxNumberOfCouponsToGenerate = MAX_NUMBER_OF_COUPONS_TO_GENERATE }) { validatePrefix(prefix); validateSuffix(suffix); validateLength(length); validateOmitCharacters(omitCharacters); validateCharacterSetOption(characterSetOption); this.characters = characterList(characterSetOption, omitCharacters); this.charactersLength = this.characters.length; const totalNumberOfPossibleCoupons = Math.pow(this.charactersLength, length); validateNumberOfCoupons( numberOfCoupons, maxNumberOfCouponsToGenerate, totalNumberOfPossibleCoupons ); this.randomInteger = randomInteger2; this.length = length; this.prefix = prefix; this.suffix = suffix; this.numberOfCoupons = numberOfCoupons; this.characterSetOption = characterSetOption; this.maxNumberOfCouponsToGenerate = maxNumberOfCouponsToGenerate; this.formatter = format !== UNDEFINED ? new Formatter(format) : { format: identity }; } generateCoupon() { const generatedCouponCharacters = []; for (let i = 0; i < this.length; i++) { generatedCouponCharacters.push( this.characters[this.randomInteger(0, this.charactersLength - 1)] ); } const coupon = generatedCouponCharacters.join(""); return this.formatter.format( pipe([ attachPrefix(this.prefix), attachSuffix(this.suffix) ])(coupon) ); } generateSingleCoupon() { return this.generateCoupon(); } generateMultipleCoupons() { const couponSet = /* @__PURE__ */ new Set(); while (couponSet.size < this.numberOfCoupons) { couponSet.add(this.generateCoupon()); } return Array.from(couponSet); } run() { if (this.numberOfCoupons === 1) { return this.generateSingleCoupon(); } return this.generateMultipleCoupons(); } }; // src/configs/option.ts var options = { defaultCouponEngineOption: { verbose: false, logPerformance: false, maxNumberOfCouponsToGenerate: MAX_NUMBER_OF_COUPONS_TO_GENERATE }, defaultCouponGenerationOption: { length: DEFAULT_LENGTH, prefix: DEFAULT_PREFIX, suffix: DEFAULT_SUFFIX, characterSet: DEFAULT_CHARACTER_SET_OPTION, numberOfCoupons: DEFAULT_NUMBER_OF_COUPONS_TO_GENERATE, omitCharacters: DEFAULT_OMIT_CHARACTERS, format: DEFAULT_COUPON_FORMAT } }; var option_default = options; // src/helpers/performance.ts var Performance = class { constructor() { this.startedAt = 0; this.endedAt = 0; } startTimer() { this.startedAt = (/* @__PURE__ */ new Date()).getTime(); } stopTimer() { this.endedAt = (/* @__PURE__ */ new Date()).getTime(); } stats() { const milli = this.endedAt - this.startedAt; return { duration: { nano: milli * 1e6, micro: milli * 1e3, milli, second: milli / 1e3 } }; } }; // src/validators/coupon-config-validator.ts function couponConfigValidator(config) { const { verbose, logPerformance, maxNumberOfCouponsToGenerate } = config; if (!isUndefined(verbose) && !isBoolean(verbose)) { throw new ValidationError({ message: `Coupon engine configuration field 'verbose' must be of type boolean.`, errors: [ { type: ERROR_CONSTANTS.COUPONJS_COUPON_ENGINE_CONFIGURATION_ERROR.type, field: "verbose", message: `Coupon engine configuration field 'verbose' must be of type boolean.` } ] }); } if (!isUndefined(logPerformance) && !isBoolean(logPerformance)) { throw new ValidationError({ message: `Coupon engine configuration field 'logPerformance' must be of type boolean.`, errors: [ { type: ERROR_CONSTANTS.COUPONJS_COUPON_ENGINE_CONFIGURATION_ERROR.type, field: "logPerformance", message: `Coupon engine configuration field 'logPerformance' must be of type boolean.` } ] }); } if (!isUndefined(maxNumberOfCouponsToGenerate) && !isInteger(maxNumberOfCouponsToGenerate)) { throw new ValidationError({ message: `Coupon engine configuration field 'maxNumberOfCouponsToGenerate' must be of type integer.`, errors: [ { type: ERROR_CONSTANTS.COUPONJS_COUPON_ENGINE_CONFIGURATION_ERROR.type, field: "maxNumberOfCouponsToGenerate", message: `Coupon engine configuration field 'maxNumberOfCouponsToGenerate' must be of type integer.` } ] }); } if (maxNumberOfCouponsToGenerate < 1) { throw new ValidationError({ message: `Coupon engine configuration field 'maxNumberOfCouponsToGenerate' must be greater than 0.`, errors: [ { type: ERROR_CONSTANTS.COUPONJS_COUPON_ENGINE_CONFIGURATION_ERROR.type, field: "maxNumberOfCouponsToGenerate", message: `Coupon engine configuration field 'maxNumberOfCouponsToGenerate' must be greater than 0.` } ] }); } } // src/index.ts var { defaultCouponGenerationOption, defaultCouponEngineOption } = option_default; var CouponJS = class { constructor(config) { this.config = config != null ? config : {}; this.performance = new Performance(); const { verbose, logPerformance, maxNumberOfCouponsToGenerate } = shallowMerge( defaultCouponEngineOption, config ); couponConfigValidator({ verbose, logPerformance, maxNumberOfCouponsToGenerate }); this.maxNumberOfCouponsToGenerate = maxNumberOfCouponsToGenerate; this.logPerformance = logPerformance; this.verbose = verbose; } // eslint-disable-next-line @typescript-eslint/no-explicit-any generate(option) { this.performance.startTimer(); const { numberOfCoupons, length, prefix, suffix, omitCharacters, format, characterSet: characterSetOption } = shallowMerge(defaultCouponGenerationOption, option); try { const engine = new Engine({ randomInteger, characterSetOption, length, prefix, suffix, numberOfCoupons, omitCharacters, format, maxNumberOfCouponsToGenerate: this.maxNumberOfCouponsToGenerate }); const generatedCoupons = engine.run(); this.performance.stopTimer(); const performanceStats = this.logPerformance ? { performance: this.performance.stats() } : {}; const verboseResult = __spreadProps(__spreadValues({}, performanceStats), { numberOfCoupons, status: "success", coupons: numberOfCoupons === 1 ? [generatedCoupons] : generatedCoupons }); return this.verbose ? verboseResult : generatedCoupons; } catch (e) { this.performance.stopTimer(); const performanceStats = this.logPerformance ? { performance: this.performance.stats() } : {}; if (this.verbose) { return __spreadValues({ status: "error", error: { message: e.message, type: e.type, errors: e.errors } }, performanceStats); } else { throw e; } } } }; var src_default = CouponJS; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CouponJS }); //# sourceMappingURL=index.js.map