UNPKG

@rzl-zone/utils-js

Version:

A modern, lightweight set of JavaScript utility functions with TypeScript support for everyday development, crafted to enhance code readability and maintainability.

747 lines (739 loc) 31.6 kB
/*! * ==================================================== * Rzl Utils-JS. * ---------------------------------------------------- * Version: 3.11.0. * Author: Rizalvin Dwiky. * Repository: https://github.com/rzl-zone/utils-js. * ==================================================== */ /** ---------------------------------------------------------- * * ***Type-Utility: `QueryParamPairs`.*** * ---------------------------------------------------------- * **Represents a non-empty array of key–value pairs.** * @description * Type for `queryParams` parameter, the second parameter of ***`constructURL` utility function***. * - **Behavior:** * - Each inner tuple strictly follows the `[string, string | number]` shape. * - Ensures the outer array contains **at least one pair** (non-empty). * - Commonly used for URL construction parameters, * query string segments, or other key–value structured data. * @example * // ✅ valid usage * const params: QueryParamPairs = [ * ["foo", 1], * ["bar", "baz"] * ]; * constructURL("https://example.com", params); * * // ❌ invalid: must contain at least one item * const empty: QueryParamPairs = []; * * // ❌ invalid: key without value pairs. * const empty2: QueryParamPairs = [["key"]]; */ type QueryParamPairs = [[string, string | number], ...[string, string | number][]]; /** --------------------------------- * * ***Utility: `constructURL`.*** * --------------------------------- * **Constructs a valid URL with optional query parameters and allows selective removal of duplicate parameters.** * @param {string | URL} baseUrl The base URL to build upon. Must include protocol (e.g., `"https://"`), `domain`, and may include port and existing query parameters. * @param {Iterable<[string, string]> | URLSearchParamsIterator<[string, string]> | QueryParamPairs} [queryParams] * Additional query parameters to append or overwrite on the URL. * - Accepts any iterable of key-value pairs (like `new URLSearchParams().entries()` and `[[string, string | number]...]`). * @param {string[]} [removeParams] * A list of query parameter keys to remove from the final URL, whether they were in the base URL or provided queryParams. * @returns {URL} A new URL object representing the constructed URL with merged and cleaned query parameters. * @throws **{@link TypeError | `TypeError`}** if `baseUrl` is not a valid non-empty string or URL object, or if `queryParams` is not iterable, or if `removeParams` is not an array of strings. * @example * 1. #### Basic Usage: * ```ts * constructURL( * "https://example.com/path", * new URLSearchParams({ a: "1", b: "2" }).entries() * ); * // ➔ URL { href: "https://example.com/path?a=1&b=2", ... } * ``` * 2. #### Remove parameters from Base and Added: * ```ts * // with new URLSearchParams({ ... }).entries(); * constructURL( * "https://example.com/path?foo=1&bar=2", * new URLSearchParams({ bar: "ignored", baz: "3" }).entries(), * ["bar"] * ); * // ➔ URL { href: "https://example.com/path?foo=1&baz=3", ... } * * // with [[string, string | number]...] * constructURL( * "https://example.com/path?foo=1&bar=2", * [["bar", "ignored"],["baz", 3]], * ["bar"] * ); * // ➔ URL { href: "https://example.com/path?foo=1&baz=3", ... } * * const params: QueryParamPairs = [ * ["foo", 1], * ["bar", 2], * ["baz", 3] * ]; * * constructURL("https://example.com", params, ["bar"]); * // ➔ URL { href: "https://example.com/?foo=1&baz=3", ... } * ``` */ declare const constructURL: (baseUrl: string | URL, queryParams?: URLSearchParamsIterator<[string, string | number]> | QueryParamPairs, removeParams?: string[]) => URL; /** --------------------------------- * * ***Utility: `extractURLs`.*** * --------------------------------- * **Extracts all valid URLs from a given string.** * @description * This function scans the input url and returns an array of URLs * that match a valid `http` or `https` format. * - **Supports:** * - Internationalized domain names (IDN), e.g. `https://münich.de` * - Unicode & emoji paths, e.g. `https://example.com/🎉/page` * - Long URLs with multiple queries & fragments, e.g. `https://example.com/path?foo=1#hash` * - **Ignores:** * - Non-string inputs * - Empty or whitespace-only strings * - Non-HTTP(S) protocols (ftp, mailto, etc) * @param {string | null | undefined} url - The input string containing potential URLs. * @returns {string[] | null} An array of extracted URLs or `null` if no URLs are found. * @example * extractURLs("Visit https://example.com and https://例子.公司"); * // ➔ ["https://example.com", "https://例子.公司"] * extractURLs("Here: https://example.com/🎉/page"); * // ➔ ["https://example.com/🎉/page"] * extractURLs("ftp://example.com http://example.com"); * // ➔ ["http://example.com"] */ declare const extractURLs: (url: string | null | undefined) => string[] | null; /** -------------------------------------------------------- * * ***Utility: `getFirstPrefixPathname`.*** * -------------------------------------------------------- * **Extract First Valid Prefix from Path Array or String.** * - **Main Purpose:** * - This function helps extract the first valid URL prefix from various possible inputs. * - It is especially useful in routing systems, middleware, or frontend apps that need to * decide layout, active navigation, or permissions based on the first segment (or prefix) of a pathname. * - **Typical uses include:** * - Determining which layout to render (e.g., `/admin` vs `/dashboard` vs `/`). * - Highlighting the active menu item in a sidebar based on the current URL. * - Enforcing route guards or access controls depending on the URL prefix. * - Parsing multi-level route prefixes and selecting the most relevant one. * - **Behavior:** * - It works as follows: * - If `result` is an array of strings, it normalizes each element and returns * the first non-root path (i.e., not just `"/"`). * - If all items normalize to `"/"`, * it returns the `defaultValue` (normalized). * - If `result` is a single string, it normalizes it and returns it if valid, * otherwise falls back to the normalized `defaultValue`. * - If `result` is `null` or `undefined`, it returns the normalized `defaultValue`. * - **Validation & Errors:** * - Throws a `TypeError` if: * - `defaultValue` is not a string or empty-string. * - `result` is an array that contains non-string elements. * - `result` is a value that is neither `string`, `string[]`, nor `null`. * @example * 1. #### For React (*Determining layout*): * ```ts * const prefix = getFirstPrefixPathname( * getPrefixPathname( * "/admin/settings", * ["/admin", "/dashboard"] * ) * ); * * if (prefix === "/admin") { * renderAdminLayout(); * } * ``` * * 2. #### Setting active menu state: * ```ts * const activeSection = getFirstPrefixPathname(["", "/dashboard", "/profile"]); * // ➔ "/dashboard" * ``` * * 3. #### Providing graceful fallback: * ```ts * const section = getFirstPrefixPathname([], "/home"); * // ➔ "/home" * ``` * 4. #### ✅ Using with an Array of Pathnames: * ```ts * const result = getPrefixPathname([" ", "/dashboard", "/settings"]); * console.log(getFirstPrefixPathname(result)); * // ➔ "/dashboard" * ``` * * 5. #### ✅ Using with Single String: * ```ts * console.log(getFirstPrefixPathname("/profile/settings")); * // ➔ "/profile/settings" * console.log(getFirstPrefixPathname(" ")); * // ➔ "/" * ``` * * 6. #### ✅ Fallback to Custom Default: * ```ts * console.log(getFirstPrefixPathname([" ", ""], "/home")); * // ➔ "/home" * console.log(getFirstPrefixPathname(null, "/dashboard")); * // ➔ "/dashboard" * ``` * * 7. #### ✅ Throws on Invalid Input: * ```ts * getFirstPrefixPathname([1, 2] as any); // ➔ ❌ throws TypeError * getFirstPrefixPathname({} as any); // ➔ ❌ throws TypeError * getFirstPrefixPathname(null, " "); // ➔ ❌ throws TypeError * ``` * @param {string | string[] | null | undefined} result * ***The pathname(s) to process, can be:*** * - A string path (e.g. `"/profile"`), * - An array of string paths (e.g. `[" ", "/dashboard"]`), * - Or `null`. * @param {string} [defaultValue="/"] * ***A custom default path to use if `result` is null or no valid prefix is found, behavior:*** * - Must be a string and non-empty string. * - Defaults to `"/"`. * @returns {string} * ***The first valid normalized pathname, or the normalized default.*** * @throws **{@link TypeError | `TypeError`}** ***if `result` is not a valid type, or `defaultValue` is not a string or empty-string.*** */ declare const getFirstPrefixPathname: (result: string | string[] | null | undefined, defaultValue?: string) => string; type GetPrefixPathnameOptions = { /** The number of levels to include in the prefix (default is `1`). * * - For example, with `levels = 2`, the function will return the first two parts of the URL. * * @default 1 */ levels?: number; /** Whether to remove duplicates from the result if multiple URLs are passed (default is `true`). * * @default true */ removeDuplicates?: boolean; }; /** -------------------------------------------------------- * * ***Utility: `getPrefixPathname`.*** * -------------------------------------------------------- * **Get Prefix from URL with Optional Base or Auto-detection (Supports String or Array of URLs).** * - **This function extracts the prefix from one or more URLs. It can either:** * - Use a provided `base` string or an array of strings to check and return the matching prefix. * - Automatically detect the prefix if no `base` is provided by analyzing the first part of the URL. * - **The function is flexible and can handle both scenarios:** * 1. **When the base is provided as a single string or an array of strings**: * - The function will check if the URL starts with one of the provided base(s) and return the matching base. * 2. **When the base is not provided**: * - The function will automatically detect the prefix by splitting the URL or using a regex. * - **Important Notes**: * - If a base (or an array of bases) is provided, the URL must start with one of the given base(s). * - If no base is provided, the function will attempt to detect the prefix automatically. * - The `url` parameter can be either a string or an array of strings. * - Supports deduplication of results (enabled by default). * - Automatically returns a single string if only one unique result exists after processing. * @param {string|string[]} url * ***The full URL(s) from which the prefix should be extracted, can be a `string` or an `array of strings`.*** * @param {string|string[]|null} [base=null] * ***The base URL(s) (e.g., `"/settings"`), behavior:*** * - It can be a `string`, an `array of strings`, or `null`. * - If `provided`, it will be used to check the URL(s). * - If `not provided`, the prefix will be auto-detected. * @param {GetPrefixPathnameOptions} [options] * ***Additional options object:*** * - `levels` (default `1`): The number of segments to include when auto-detecting the prefix (e.g. `/foo/bar` for `levels: 2`). * - `removeDuplicates` (default `true`): Whether to remove duplicate prefixes from the final array result. * @returns {string|string[]|null} * ***Returns one of:*** * - A single string if only one unique prefix/base is found. * - An array of strings if multiple different prefixes/bases are found. * - `null` if no matching base is found when using `base`. * @throws **{@link TypeError | `TypeError`}** * ***if:*** * - `url` is `not a string` or `not an array of strings`. * - `base` is `not a string`, `array of strings`, or `null`. * - `options` is `not an object`. * - `levels` is `not a number`. * - `removeDuplicates` is `not a boolean`. * @example * - #### ✅ **Correct Usage (With an Array of URLs and Base):** * ```ts * const routes = [ * "/settings/profile", * "/settings/password", * "/settings/other-path", * "/other-path/xyz", * ]; * * // With base provided as a string * routes.forEach(route => { * console.log(getPrefixPathname(route, '/settings')); * // ➔ "/settings" * }); * * // With base provided as an array * routes.forEach(route => { * console.log(getPrefixPathname(route, ['/settings', '/admin'])); * // ➔ "/settings" or "/admin" depending on the current URL. * }); * ``` * - #### ✅ **Correct Usage (With Single URL and Single Base):** * ```ts * const result = getPrefixPathname("/settings/profile", "/settings"); * console.log(result); // ➔ "/settings" * ``` * - #### ✅ **Correct Usage (With Multiple URLs and Single Base):** * ```ts * const result = getPrefixPathname( * ["/settings/profile", "/settings/password"], * "/settings" * ); * console.log(result); // ➔ "/settings" * * const result2 = getPrefixPathname( * ["/settings/profile", "/other/password"], * "/other" * ); * console.log(result2); // ➔ "/other" * ``` * - #### ✅ **Correct Usage (With Multiple URLs and Multiple Bases)** * ```ts * const result = getPrefixPathname( * ["/settings/profile", "/admin/password"], * ["/settings", "/admin"] * ); * console.log(result); // ➔ ["/settings", "/admin"] * ``` * - #### ✅ **Auto-detection of Prefix** * ```ts * const result = getPrefixPathname("/settings/profile"); * console.log(result); // ➔ "/settings" * * const result2 = getPrefixPathname( * "/settings/profile/info", * null, * { levels: 2 } * ); * console.log(result2); // ➔ "/settings/profile" * ``` * - #### ✅ **Multiple URLs with Auto-detection** * ```ts * const result = getPrefixPathname(["/admin/profile", "/settings/password"]); * console.log(result); // ➔ ["/admin", "/settings"] * ``` * - #### ✅ **Handling Duplicates** * ```ts * const result = getPrefixPathname( * ["/settings/profile", "/settings/password"], * "/settings" * ); * console.log(result); // ➔ "/settings" (deduped to single string) * * const result2 = getPrefixPathname( * ["/settings/profile", "/settings/profile"], * "/settings", * { removeDuplicates: false } * ); * console.log(result2); // ➔ ["/settings", "/settings"] * ``` * - #### ❌ **Incorrect Usage (URL Does Not Match Base)** * ```ts * const result = getPrefixPathname("/other-path/profile", "/settings"); * console.log(result); // ➔ null * ``` */ declare const getPrefixPathname: (url: string | string[], base?: string | string[] | null, options?: GetPrefixPathnameOptions) => string | string[] | null; /** Options when `keepNullable` is false (default). * * Returns `defaultPath` if `pathname` is empty or invalid. */ type UnKeepNullableOptions = { /** * ***Fallback value returned if `pathname` is empty-string or invalid.*** * * Must be a **`non-empty string`**, defaultValue: `"/"`. * * @defaultValue `"/"`. */ defaultPath?: string; /** * ***Whether to preserve `null` or `undefined`, defaultValue: `false`.*** * * @defaultValue `false`. */ keepNullable?: false; }; /** Options when `keepNullable` is true. * * Preserves `null` or `undefined` instead of returning `defaultPath`. */ type KeepNullableOptions = { /** * ***Fallback path is ignored when `keepNullable` is true **(except if * `pathname` is empty-string or invalid, even this `true`)**, * defaultValue: `"/"`.*** * * @defaultValue `"/"`. */ defaultPath?: string; /** * ***Preserve `null` or `undefined` as-is if `true` (defaultValue: `false`).*** * * - ***⚠️ Notes:*** * - Keep returning `defaultPath` if `pathname` is empty-string, even this `true`. * * **Must be `true` in this type.** */ keepNullable?: true; }; type MainNormalizePathnameOptions = { /** -------------------------------------------------------- * * ***Preserve trailing slash at the end of the normalized pathname, defaultValue: `false`.*** * -------------------------------------------------------- * * @defaultValue `false` */ keepTrailingSlash?: boolean; /** -------------------------------------------------------- * * ***Allow special localhost domain at the beginning of the pathname.*** * -------------------------------------------------------- * @description * If `true`, the first segment of the pathname that is `/localhost` or `localhost` * (with or without a port, e.g., `localhost:3000`) will be treated as a special domain * and **removed** from the normalized pathname. * * - **Examples (`localhostDomain: true`)**: * - `"/localhost/path"``"/path"` * - `"localhost:3000/path"``"/path"` * - `"localhost"``"/"` (entire path removed) * * - Only the **first path segment** is affected. Any subsequent occurrences of `"localhost"` * will remain intact. * * @defaultValue `false` */ localhostDomain?: boolean; /** * -------------------------------------------------------- * * ***Custom list of file extensions that prevent the first path segment from being treated as a domain.*** * -------------------------------------------------------- * * **Description:** * - The first segment of a pathname is often interpreted as a domain (e.g., `example.com`). * - If this first segment ends with any of the extensions listed here, it will **not** be considered a domain, * and will instead be preserved as part of the relative path. * - This is useful for cases where filenames appear at the start of a path and you want them treated as relative paths, * such as `"image.png?version=2"` or `"archive.tar.gz#download"`. * - Only the **first path segment** is affected; all other segments are processed normally. * - **Ignored** if: * 1. The pathname starts with a full URL protocol (`http://` or `https://`), e.g., `"https://example.com/file.png"`. * 2. The first path segment is already a valid domain, e.g., `"example.com/image.png"`. * * **Type & Validation:** * - Must be a `Set<string>` or `string[]`. * - Each string **must include the leading dot**, e.g., `.png`, `.tar.gz`. * - Multi-part extensions (like `.tar.gz`, `.tar.bz`) are supported. * - Throws a **TypeError** if: * 1. The type is not a `Set<string>` or `string[]`. * 2. Any string in the array/set is empty. * 3. Any string does not start with a dot (`.`). * * **Usage Notes:** * - Only applied when the first segment is otherwise domain-like **and** pathname is relative or domain-like without protocol. * - Query strings (`?x=1`) and hash fragments (`#section`) are preserved. * * **Examples (relative paths, option active):** * ```ts * normalizePathname("image.png?version=2", { * ignoreDomainExtensions: [".png", ".jpg"] * }); * // ➔ "/image.png?version=2" * * normalizePathname("archive.tar.gz#download", { * ignoreDomainExtensions: new Set([".tar.gz"]) * }); * // ➔ "/archive.tar.gz#download" * * normalizePathname("script.js?module=true#top", { * ignoreDomainExtensions: [".js"] * }); * // ➔ "/script.js?module=true#top" * ``` * * **Examples (full URL or explicit domain - option ignored):** * ```ts * normalizePathname("https://example.com/image.png?version=2", { * ignoreDomainExtensions: [".png"] * }); * // ➔ "/image.png?version=2" // URL is parsed normally; ignoreDomainExtensions has no effect * * normalizePathname("example.com/script.js?module=true#top", { * ignoreDomainExtensions: [".js"] * }); * // ➔ "/script.js?module=true#top" // domain recognized; option ignored * ``` * * **Notes:** * - Only the **first path segment** is checked. * - Prevents false-positive domain stripping for filenames that look like domains. * - Throws **TypeError** if invalid type or invalid string is provided. * * @defaultValue `undefined` (feature inactive if not provided) */ ignoreDomainExtensions?: Set<string> | string[]; }; type NormalizePathnameOptionsKeepNullableTrue = MainNormalizePathnameOptions & KeepNullableOptions; type NormalizePathnameOptionsKeepNullableFalse = MainNormalizePathnameOptions & UnKeepNullableOptions; type ResUnKeepNullable<T> = T extends undefined ? string : T extends null ? string : T extends null | undefined ? string : string; type ResKeepNullable<T> = T extends string ? string : T extends undefined ? undefined : T extends null ? null : T extends null | undefined ? null | undefined : string | null | undefined; /** -------------------------------------------------------- * * ***Utility: `normalizePathname`.*** * -------------------------------------------------------- * * - **Description:** * Normalizes any pathname or URL string to a clean, predictable format. * Useful for routing, file paths, and URL handling. * - Handles: * - Leading/trailing spaces * - Internal spaces in path segments * - Redundant slashes (`//`) * - Full URLs vs relative paths * - Query (`?`) and hash (`#`) preservation * - Unicode & emoji characters * - Optional nullable preservation (`keepNullable`) * - Optional trailing slash preservation (`keepTrailingSlash`) * - Optional removal of localhost first segment (`localhostDomain`) * - Prevention of false-positive domain stripping (`ignoreDomainExtensions`) * * - **Key Steps Internally:** * 1. Validate `options` (plain object, correct types) * 2. Validate `defaultPath` (non-empty string if `keepNullable` is false) * 3. Validate `ignoreDomainExtensions` (Set<string> | string[], each starts with `.`) * 4. Handle nullable: * - Returns `null` / `undefined` if `keepNullable: true` * - Otherwise uses `defaultPath` * 5. Trim spaces, remove internal spaces * 6. If full URL: parse using `URL` constructor * 7. If relative path or domain-like: * - Remove `localhost`/`localhost:port` if `localhostDomain` * - Remove first segment if domain-like and **not** in `ignoreDomainExtensions` * 8. Normalize slashes * 9. Ensure leading slash * 10. Handle trailing slash * 11. Decode Unicode safely * 12. Return normalized pathname + search + hash * * - **Error Handling:** * - **TypeError**: * - `defaultPath` invalid (non-string or empty) when `keepNullable: false` * - `keepNullable`, `keepTrailingSlash`, `localhostDomain` not boolean * - `ignoreDomainExtensions` invalid * - **NormalizePathnameError** (extends ***Error***): * - Invalid URL parsing * - Unexpected normalization errors * * - **Options:** * ```ts * { * // fallback if invalid path, default: "/" * defaultPath?: string; * // preserve null/undefined, default: false * keepNullable?: boolean; * // preserve trailing slash, default: false * keepTrailingSlash?: boolean; * // remove localhost:port first segment, default: false * localhostDomain?: boolean; * // prevent domain stripping, default: undefined * ignoreDomainExtensions?: Set<string> | string[]; * } * ``` * * @example * // Basic path cleaning * normalizePathname(" /foo//bar "); * //"/foo/bar" * * // Trailing slash control * normalizePathname("/api//v1//user//", { keepTrailingSlash: true }); * //"/api/v1/user/" * normalizePathname("/api//v1//user//", { keepTrailingSlash: false }); * //"/api/v1/user" * * // Full URL normalization * normalizePathname("https://example.com//path///to/resource?x=1#hash"); * //"/path/to/resource?x=1#hash" * * // Null/undefined preservation * normalizePathname(null, { keepNullable: true }); * // ➔ null * normalizePathname(undefined, { keepNullable: true }); * // ➔ undefined * * // Default fallback * normalizePathname("", { defaultPath: "/home" }); * //"/home" * * // Localhost removal * normalizePathname("localhost:3000/path/to/resource", { localhostDomain: true }); * //"/path/to/resource" * * // Prevent false-positive domain stripping * normalizePathname("archive.tar.gz#download", { ignoreDomainExtensions: [".tar.gz"] }); * //"/archive.tar.gz#download" * normalizePathname("image.png?version=2", { ignoreDomainExtensions: [".png"] }); * //"/image.png?version=2" * * // Emojis and Unicode * normalizePathname("🔥//deep//path///🚀"); * //"/🔥/deep/path/🚀" * * // Query-only or hash-only * normalizePathname("?page=2"); * //"/?page=2" * normalizePathname("#section3"); * //"/#section3" * * // Complex nested paths * normalizePathname(" //nested///folder//file.txt "); * //"/nested/folder/file.txt" * * // Invalid URL triggers error * try { * normalizePathname("http://"); * } catch (e) { * // console.log(e); * } * * // First segment is domain but ignored due to extension * normalizePathname("example.tar.bz/file", { ignoreDomainExtensions: [".tar.bz"] }); * //"/example.tar.bz/file" */ declare function normalizePathname<T>(pathname: T, options?: NormalizePathnameOptionsKeepNullableFalse): ResUnKeepNullable<T>; declare function normalizePathname<T>(pathname: T, options?: NormalizePathnameOptionsKeepNullableTrue): ResKeepNullable<T>; type FormatEnvPortOptions = { /** Add prefix with a colon, defaultValue: `false`. * * @default false */ prefixColon?: boolean; }; /** ----------------------------------------------- * * ***Utility: `formatEnvPort`.*** * ----------------------------------------------- * **Retrieves and formats an environment port variable.** * - **Behavior:** * - Extracts only digits from the input. * - If no digits found, returns an empty string. * - By default does NOT prefix with a colon. * - Use `{ prefixColon: true }` to prefix with a colon. * @param {string | null | undefined} envVar The environment variable string. * @param {FormatEnvPortOptions} [options] Optional object: `{ prefixColon?: boolean }`. * @returns {string} A string like `":8080"` or `"8080"`, or `""` if no digits. * @throws **{@link TypeError | `TypeError`}** if `options` is not an object or `prefixColon` is not boolean. * @example * formatEnvPort("port:8080"); * //"8080" * formatEnvPort("port:8080", { prefixColon: true }); * //":8080" */ declare const formatEnvPort: (envVar: string | null | undefined, options?: FormatEnvPortOptions) => string; /** --------------------------------------------------------- * * ***Constants for `Punycode-UtilsJS` algorithm.*** * --------------------------------------------------------- * These constants are used internally for encoding and decoding. * * Unicode domain names to ASCII (`Punycode-UtilsJS`) and vice versa. */ type PunycodeUtilsJS = { /** --------------------------------------------------------- * * ***Version of the `Punycode-UtilsJS` implementation.*** * --------------------------------------------------------- * * @example * console.log(punycodeUtilsJS.version); // "1.0.0" */ version: string; /** --------------------------------------------------------- * * ***UCS-2 utility functions.*** * --------------------------------------------------------- */ ucs2: { /** --------------------------------------------------------- * * ***Decodes a UCS-2 encoded string to an array of Unicode code points.*** * --------------------------------------------------------- * * @param input - The UCS-2 string to decode. * @returns Array of Unicode code points. * @example * punycodeUtilsJS.ucs2.decode("𐍈"); * // ➔ [66376] */ decode: (input: string) => number[]; /** --------------------------------------------------------- * * ***Encodes an array of Unicode code points to a UCS-2 string.*** * --------------------------------------------------------- * * @param points - Array of Unicode code points. * @returns Encoded string. * @example * punycodeUtilsJS.ucs2.encode([66376]); * //"𐍈" */ encode: (points: number[]) => string; }; /** --------------------------------------------------------- * * ***Decodes a `Punycode-UtilsJS` string to a Unicode string.*** * --------------------------------------------------------- * * @param input - The `Punycode-UtilsJS` string to decode. * @returns Decoded Unicode string. * @example * punycodeUtilsJS.decode("xn--fsq"); * //"ü" */ decode: (input: string) => string; /** --------------------------------------------------------- * * ***Encodes a Unicode string to `Punycode-UtilsJS`.*** * --------------------------------------------------------- * * @param input - Unicode string to encode. * @returns `Punycode-UtilsJS` string. * @example * punycodeUtilsJS.encode("ü"); * //"xn--fsq" */ encode: (input: string) => string; /** --------------------------------------------------------- * * ***Converts a Unicode domain or label to ASCII (`Punycode-UtilsJS`).*** * --------------------------------------------------------- * * @param input - Domain or label string. * @returns ASCII string suitable for DNS. * @example * punycodeUtilsJS.toASCII("пример.рф"); * //"xn--e1afmkfd.xn--p1ai" */ toASCII: (input: string) => string; /** --------------------------------------------------------- * * ***Converts an ASCII (`Punycode-UtilsJS`) domain or label to Unicode.*** * --------------------------------------------------------- * * @param input - ASCII string (with xn-- prefix if needed). * @returns Unicode string. * @example * punycodeUtilsJS.toUnicode("xn--e1afmkfd.xn--p1ai"); * //"пример.рф" */ toUnicode: (input: string) => string; }; /** --------------------------------------------------------- * * ***`Punycode-UtilsJS` object exposing all API functions and version.*** * --------------------------------------------------------- * Provides encoding and decoding of Unicode domain names to ASCII (`Punycode-UtilsJS`) * and vice versa. * * - Useful for IDN (Internationalized Domain Names) support. */ declare const punycodeUtilsJS: PunycodeUtilsJS; export { type QueryParamPairs, constructURL, extractURLs, formatEnvPort, getFirstPrefixPathname, getPrefixPathname, normalizePathname, punycodeUtilsJS };