typia
Version:
Superfast runtime validators with only one line
51 lines • 2.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports._randomHostnameLabels = exports._randomFormatHostname = void 0;
const _randomInteger_1 = require("./_randomInteger");
const _randomString_1 = require("./_randomString");
const _randomFormatHostname = (props) => {
if ((props === null || props === void 0 ? void 0 : props.minLength) === undefined && (props === null || props === void 0 ? void 0 : props.maxLength) === undefined)
return `${random(10)}.${random(3)}`;
// A hostname is dot-joined labels of 1..63 chars whose total is capped at 253,
// so the requested length is realized by splitting it across enough labels.
return (0, exports._randomHostnameLabels)(pickLength(props));
};
exports._randomFormatHostname = _randomFormatHostname;
const MAX_TOTAL = 253;
const MAX_LABEL = 63;
const pickLength = (props) => {
let low = props.minLength === undefined ? 1 : props.minLength;
if (low < 1)
low = 1;
const high = props.maxLength === undefined
? Math.min(MAX_TOTAL, low + 14)
: Math.min(MAX_TOTAL, props.maxLength);
if (high < low)
throw new Error("unable to generate a random hostname satisfying both the format and the length constraints.");
return (0, _randomInteger_1._randomInteger)({ type: "integer", minimum: low, maximum: high });
};
/**
* Builds dot-joined hostname labels totaling exactly `length` characters, each
* label within 63 chars. Shared with the idn-hostname generator, which reserves
* a fixed `.<tld>` suffix and realizes the rest as these leading labels.
*/
const _randomHostnameLabels = (length) => {
const parts = [];
let remaining = length;
while (remaining > MAX_LABEL + 1) {
// one full label plus its joining dot
parts.push(random(MAX_LABEL));
remaining -= MAX_LABEL + 1;
}
if (remaining <= MAX_LABEL)
parts.push(random(remaining));
else {
// remaining === MAX_LABEL + 1: two labels keep every label within 63 chars
parts.push(random(MAX_LABEL - 1));
parts.push(random(1));
}
return parts.join(".");
};
exports._randomHostnameLabels = _randomHostnameLabels;
const random = (length) => (0, _randomString_1._randomString)({ type: "string", minLength: length, maxLength: length });
//# sourceMappingURL=_randomFormatHostname.js.map