### Import and Use 'yourFunction' from 'vite-setup' Source: https://github.com/hussseinkizz/regist/blob/main/GUIDE.md A basic TypeScript example demonstrating how to import and utilize a function named 'yourFunction' from the 'vite-setup' library. This serves as a starting point for integrating library functionality into your application. ```typescript import { yourFunction } from 'vite-setup'; // Your usage example here ``` -------------------------------- ### Install vite-setup Package Source: https://github.com/hussseinkizz/regist/blob/main/GUIDE.md Instructions for installing the 'vite-setup' library using different package managers like npm, yarn, and pnpm. This is the initial step to integrate the library into your project. ```bash npm install vite-setup # or yarn add vite-setup # or pnpm add vite-setup ``` -------------------------------- ### Install Regist Library Source: https://github.com/hussseinkizz/regist/blob/main/README.md Installs the Regist library using npm. This is the first step to using Regist in your project. No specific inputs or outputs beyond package installation. ```bash npm install @regist/regist ``` -------------------------------- ### Basic String Transformation Examples in TypeScript Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/stringtransform-api.mdx Demonstrates basic usage of the stringTransform API for converting a string to snake_case and sanitizing a string. It shows how to import the function and chain transformation methods, concluding with `.try()` to get the result. ```typescript import { stringTransform } from 'regist'; // Example: Convert a string to snake_case const snakeCase = stringTransform('someStringToConvert').toSnakeCase().try(); // Result: 'some_string_to_convert' // Example: Sanitize a string by removing spaces and special characters const sanitized = stringTransform(' Hello World! ').sanitize({ removeSpaces: true, removeSpecial: true }).try(); // Result: 'HelloWorld' ``` -------------------------------- ### String Transformation with Regist Source: https://github.com/hussseinkizz/regist/blob/main/README.md Shows how to transform strings using Regist's `stringTransform` API. This example chains `trim`, `toLowerCase`, and `toSnakeCase` to format a filename. Returns the transformed string. ```typescript import { stringTransform } from "regist"; stringTransform(" myFileName.TXT ") .trim() .toLowerCase() .toSnakeCase() .try(); // "my_file_name.txt" ``` -------------------------------- ### Check if value starts with substring (assertThat.startsWith) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Validates if a string begins with a specific substring. This is commonly implemented using regular expressions with the caret `^` anchor. ```javascript assertThat(value).startsWith(substring); // Regex Equivalent: /^substring/ ``` -------------------------------- ### Regist for Algorithm Challenges (Palindrome, Anagram, Hashing) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Provides examples of using Regist for common algorithm problem patterns. Includes case/space insensitive palindrome check, anagram comparison, and string hashing using djb2. Useful for competitive programming or algorithm practice. ```typescript // Palindrome check (case/space insensitive) stringTransform("A man a plan a canal Panama") .sanitize({ removeSpaces: true }) .toLowerCase() .assertThat() .isPalindrome() .try(); // true // Anagram check assertThat("listen").anagram("silent").try(); // true assertThat("foo").anagram("bar").try(); // false // Quick hashing with djb2 (great for grouping or hash-based problems) const hash = stringTransform("anagram").toHash().try(); // e.g. "182755666" // djb2 is a fast, well-known string hash: hash = 5381; for each char: hash = hash * 33 + code // Example: group words by hash for anagram buckets const words = ["listen", "silent", "enlist", "foo"]; const buckets = new Map(); for (const word of words) { const h = stringTransform(word).toHash().try(); buckets.set(h, [...(buckets.get(h) || []), word]); } console.log(buckets); // Words with the same hash are likely anagrams (for small inputs, djb2 is often enough) ``` -------------------------------- ### Regist Chaining and Interoperability Example Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/how-it-works.mdx Illustrates how to seamlessly switch between Regist's validation (assertThat) and transformation (stringTransform) APIs within a single fluent chain. This allows for combined validation and transformation logic. ```typescript import { assertThat, stringTransform } from 'regist'; // Start with a transformation, switch to assertion, and then back to transformation const finalResult = stringTransform(" regist is awesome ") .trim() // -> "regist is awesome" .assertThat() // Switch to assertion API .startsWith("regist") // -> true .stringTransform() // Switch back to transformation API .toPascalCase() // -> "RegistIsAwesome" .try(); console.log(finalResult); // "RegistIsAwesome" ``` -------------------------------- ### Regist Reusability Example Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/how-it-works.mdx Shows how Regist chains, due to lazy evaluation, are highly reusable. A base chain can be created and then extended for specialized purposes without altering the original chain. ```typescript import { stringTransform } from 'regist'; // Create a base chain to sanitize a username const baseUsername = stringTransform(' Test_User-123 ') .trim() .toLowerCase(); // Reuse the base chain for different purposes const asSnakeCase = baseUsername.toSnakeCase().try(); // "test_user_123" const asPascalCase = baseUsername.toPascalCase().try(); // "TestUser123" // The original chain remains unaffected const original = baseUsername.try(); // "test_user_123" ``` -------------------------------- ### String Padding Source: https://github.com/hussseinkizz/regist/blob/main/README.md Pads a string to a specified length using a given character. The `where` parameter determines if padding is applied at the 'start', 'end', or 'both'. ```javascript const shortString = "abc"; console.log(shortString.pad(7, "*", "end")); // "abc****" console.log(shortString.pad(7, "-", "start")); // "----abc" console.log(shortString.pad(7, "+", "both")); // "++abc++" ``` -------------------------------- ### Regist Lazy Evaluation Example Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/how-it-works.mdx Demonstrates Regist's lazy evaluation principle where operations are not performed until .try() is called. This code initializes a transformation chain without immediate execution, highlighting its blueprint nature. ```typescript import { stringTransform } from 'regist'; // This chain doesn't do any work yet. It's just a plan. const trimAndUpper = stringTransform(' hello world ').trim().toUpperCase(); // The magic happens now, when .try() is called. const result = trimAndUpper.try(); // "HELLO WORLD" ``` -------------------------------- ### String Extraction Methods Source: https://github.com/hussseinkizz/regist/blob/main/README.md Extracts parts of a string using various criteria: a regex pattern (`.extract(pattern)`), start and end indices (`.extractInRange(start, end)`), or substrings between two markers (`.extractWhenBetween(prefix, suffix)`). ```javascript const sentence = "The price is $19.99 today."; const htmlContent = "

Some text

"; const data = "key=value&another=thing"; console.log(sentence.extract(/\$\d+\.\d+/)); // "$19.99" console.log(sentence.extractInRange(14, 18)); // "19.99" console.log(htmlContent.extractWhenBetween("<", ">")); // "div" console.log(data.extractWhenBetween("=", "&")); // "value" ``` -------------------------------- ### Check for substring between markers (assertThat.isBetween) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Asserts the existence of a substring located between two specified start and end markers. This uses lookbehind and lookahead assertions in regex. ```javascript assertThat(value).isBetween('startMarker', 'endMarker'); // Regex Equivalent: /(?<=startMarker).*?(?=endMarker)/ ``` -------------------------------- ### Chaining Multiple Assertions with assertThat in TypeScript Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/asserthat-api.mdx Illustrates how to chain multiple assertion methods together using the `assertThat` API for comprehensive string validation. This example validates a username for alphanumeric characters and specific length constraints. It requires importing `assertThat` from the 'regist' library and uses `.try()` to execute the chain. ```typescript import { assertThat } from 'regist'; // Example: Validate a username const isValidUsername = assertThat('testuser') .isAlphaNumeric() .lengthIs({ min: 3, max: 20 }) .try(); // Returns true ``` -------------------------------- ### Chaining Regist API: Validate then Transform (TypeScript) Source: https://context7.com/hussseinkizz/regist/llms.txt This example demonstrates validating a string with `assertThat()` first, followed by transforming it using `stringTransform()` methods like `toUpperCase()`. The `try()` method executes the pipeline and returns the transformed string or null if validation fails. ```typescript import { assertThat, stringTransform } from "regist"; // Validate then transform const result = assertThat("test") .isAlpha() .stringTransform() .toUpperCase() .try(); // "TEST" ``` -------------------------------- ### Custom String Transformations with Regist Source: https://context7.com/hussseinkizz/regist/llms.txt Enables extending string transformations with custom functions for domain-specific operations. Examples include reversing strings, applying case changes, formatting currency, parsing markdown, implementing ROT13 cipher, and chaining custom transforms with built-in ones for username formatting. ```typescript import { stringTransform } from "regist"; // Simple custom transformation stringTransform("hello") .customTransform(str => str.split("").reverse().join("")) .try(); // "olleh" // Chain multiple custom transforms stringTransform("test") .customTransform(str => str.toUpperCase()) .customTransform(str => `[${str}]`) .customTransform(str => str.repeat(2)) .try(); // "[TEST][TEST]" // Domain-specific transformation function formatCurrency(amount: string): string { return stringTransform(amount) .customTransform(str => { const num = parseFloat(str); return num.toFixed(2); }) .customTransform(str => `$${str}`) .try() || "$0.00"; } formatCurrency("123.4"); // "$123.40" formatCurrency("99"); // "$99.00" // Markdown formatter function formatMarkdown(text: string): string { return stringTransform(text) .customTransform(str => str.replace(/\\*\\*(.*?)\\*\\*/g, "$1")) .customTransform(str => str.replace(/\\*(.*?)\\*/g, "$1")) .customTransform(str => str.replace(/`(.*?)`/g, "$1")) .try() || ""; } formatMarkdown("This is **bold** and *italic* with `code`"); // "This is bold and italic with code" // ROT13 cipher function rot13(text: string): string { return stringTransform(text) .customTransform(str => str.replace(/[a-zA-Z]/g, char => { const start = char <= "Z" ? 65 : 97; return String.fromCharCode(((char.charCodeAt(0) - start + 13) % 26) + start); }) ) .try() || ""; } rot13("hello"); // "uryyb" rot13("uryyb"); // "hello" (symmetric) // Chaining with built-in transforms function formatUsername(username: string): string { return stringTransform(username) .toLowerCase() .trim() .sanitize({ removeSpaces: true, removeSpecial: true }) .customTransform(str => str.slice(0, 20)) // Max length .customTransform(str => str || "user") // Default value .try() || "user"; } formatUsername(" John Doe! "); // "johndoe" formatUsername(""); // "user" ``` -------------------------------- ### Extract Data with Regex using Regist Source: https://context7.com/hussseinkizz/regist/llms.txt Showcases the use of the `extract` method with regular expressions to find and retrieve specific patterns within strings. Examples include extracting digits, email addresses, words, hashtags, version numbers, and phone numbers. The `try` method is used to handle cases where no match is found, returning null. ```typescript import { stringTransform } from "regist"; // Extract digits stringTransform("Order #12345").extract(/\d+/).try(); // "12345" stringTransform("Price: $99.99").extract(/\d+\.\d+/).try(); // "99.99" // Extract email const text = "Contact us at info@example.com"; stringTransform(text).extract(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/).try(); // "info@example.com" // Extract words stringTransform("Hello World 123").extract(/[a-zA-Z]+/) .try(); // "Hello" // Extract hashtags function extractHashtag(tweet: string): string | null { return stringTransform(tweet) .extract(/#[a-zA-Z0-9_]+/) .try((err) => null); } extractHashtag("This is #awesome!"); // "#awesome" extractHashtag("No hashtags here"); // null // Extract version numbers function extractVersion(versionString: string): { major: number; minor: number; patch: number } | null { const version = stringTransform(versionString) .extract(/v?(\d+)\.(\d+)\.(\d+)/) .try((err) => null); if (!version) return null; const match = version.match(/(\d+)\.(\d+)\.(\d+)/); if (!match) return null; return { major: parseInt(match[1]), minor: parseInt(match[2]), patch: parseInt(match[3]) }; } extractVersion("v1.2.3"); // { major: 1, minor: 2, patch: 3 } extractVersion("version 2.0.1"); // { major: 2, minor: 0, patch: 1 } // Extract phone numbers function extractPhone(text: string): string | null { return stringTransform(text) .extract(/\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/) .try((err) => null); } extractPhone("Call me at (555) 123-4567"); // "(555) 123-4567" extractPhone("My number is 555-123-4567"); // "555-123-4567" ``` -------------------------------- ### Development Scripts for vite-setup Source: https://github.com/hussseinkizz/regist/blob/main/GUIDE.md A list of common development scripts provided by the 'vite-setup' project, managed via pnpm. These scripts cover building, testing (including watch mode and coverage), type checking, linting, formatting, bundle analysis, and CI checks. ```bash | Script | Description | |-------------------- | ----------------------------- | | `pnpm build` | Build the library | | `pnpm test` | Run tests | | `pnpm test:watch` | Run tests in watch mode | | `pnpm test:coverage` | Generate test coverage report | | `pnpm type-check` | Run TypeScript type checking | | `pnpm lint` | Lint the codebase | | `pnpm format` | Format code with Prettier | | `pnpm size` | Check bundle size | | `pnpm size:analyze` | Analyze bundle size in detail | | `pnpm check-exports` | Validate package exports | | `pnpm ci` | Run all CI checks | ``` -------------------------------- ### Creating a Changeset for Version Management Source: https://github.com/hussseinkizz/regist/blob/main/GUIDE.md Command to generate a new changeset file, used by the 'changesets' tool for managing package versions and changelogs. This is a crucial step before committing changes for a new release. ```bash pnpm changeset ``` -------------------------------- ### Contributing Workflow Source: https://github.com/hussseinkizz/regist/blob/main/GUIDE.md Standard Git commands for contributing to the project. This includes forking the repository, creating a feature branch, committing changes, and pushing to the remote for a pull request. ```bash git checkout -b feature/new-feature git commit -am 'Add new feature' git push origin feature/new-feature ``` -------------------------------- ### Check if all characters are whitespace (assertThat.isWhitespace) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Asserts that a string contains only whitespace characters. The regex pattern checks for one or more whitespace characters from start to end. ```javascript assertThat(value).isWhitespace(); // Regex Equivalent: /^\s+$/ ``` -------------------------------- ### Running Quality Checks in Development Source: https://github.com/hussseinkizz/regist/blob/main/GUIDE.md A sequence of commands to execute essential quality checks during development. This includes TypeScript type checking, ESLint linting, and running unit tests to ensure code integrity. ```bash pnpm type-check pnpm lint pnpm test ``` -------------------------------- ### Check if all letters are uppercase (assertThat.hasAllUppercase) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Verifies that all alphabetic characters within a string are uppercase. The regex pattern ensures that only uppercase letters are present from start to end. ```javascript assertThat(value).hasAllUppercase(); // Regex Equivalent: /^[A-Z]+$/ ``` -------------------------------- ### Initiate String Transformation Chain (JavaScript) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Switches the current chain context to a transformation chain, allowing for string manipulations like changing case, replacing characters, etc. The current string value is passed to the transformation methods. ```javascript str.stringTransform(); ``` -------------------------------- ### Check if all characters are letters (assertThat.isAlpha) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Validates that a string consists solely of alphabetic characters (a-z, A-Z). This is achieved using a regex that anchors to the start and end of the string. ```javascript assertThat(value).isAlpha(); // Regex Equivalent: /^[A-Za-z]+$/ ``` -------------------------------- ### Switching to Assertion API Source: https://github.com/hussseinkizz/regist/blob/main/README.md The `.assertThat()` method is used to switch from the transformation chain to the assertion API, allowing for string validation and assertions. ```javascript // Assuming an assertion library is available or implemented // Example placeholder: // const assert = require('assert'); // This method is a bridge to another API, actual assertion code would follow. // "test string".assertThat().isEqual("test string"); // Placeholder example ``` -------------------------------- ### String Extraction, Splitting, and Joining with Regist Source: https://github.com/hussseinkizz/regist/blob/main/README.md Demonstrates advanced string manipulation using Regist. Includes extracting substrings between delimiters, chunking strings, splitting strings into arrays, and joining array elements back into a string. Returns the manipulated string or array. ```typescript stringTransform("abc[foo]def").extractWhenBetween("[", "]").try(); // "foo" stringTransform("abcdef").chunk(2, "-").try(); // "ab-cd-ef" stringTransform("a,b,c").split(",").takeThatAt(1).try(); // "b" stringTransform("a,b,c").split(",").join("-").try(); // "a-b-c" ``` -------------------------------- ### Extract Substring with Indices - TypeScript Source: https://context7.com/hussseinkizz/regist/llms.txt The extractInRange function allows extraction of substrings based on start and end indices. It supports both positive and negative indices (counting from the end) and is useful for parsing fixed-width data and extracting date components. ```typescript import { stringTransform } from "regist"; // Basic range extraction stringTransform("Hello World").extractInRange(0, 5).try(); // "Hello" stringTransform("Hello World").extractInRange(6, 11).try(); // "World" // Negative indices (from end) stringTransform("Hello World").extractInRange(-5, -1).try(); // "Worl" // Extract middle portion stringTransform("abcdefgh").extractInRange(2, 6).try(); // "cdef" // Parse fixed-width data interface FixedWidthRecord { id: string; name: string; age: string; } function parseFixedWidth(line: string): FixedWidthRecord { return { id: stringTransform(line).extractInRange(0, 5).try() || "", name: stringTransform(line).extractInRange(5, 25).try() || "", age: stringTransform(line).extractInRange(25, 28).try() || "" }; } const record = "00123John Doe 030"; parseFixedWidth(record); // { id: "00123", name: "John Doe ", age: "030" } // Extract date components function parseDateString(dateStr: string): { year: string; month: string; day: string } | null { if (dateStr.length !== 8) return null; return { year: stringTransform(dateStr).extractInRange(0, 4).try() || "", month: stringTransform(dateStr).extractInRange(4, 6).try() || "", day: stringTransform(dateStr).extractInRange(6, 8).try() || "" }; } parseDateString("20240115"); // { year: "2024", month: "01", day: "15" } ``` -------------------------------- ### String Format Conversions (Hex, Binary, URL-Safe) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Converts a string to its hexadecimal (`.toHex()`) or binary (`.toBinary()`) representation. The `.toURLSafe()` method percent-encodes the string for safe use in URLs. ```javascript const message = "Hello"; const unsafeUrl = "search query with spaces"; console.log(message.toHex()); // "48656c6c6f" console.log(message.toBinary()); // "0100100001100101011011000110110001101111" console.log(unsafeUrl.toURLSafe()); // "search%20query%20with%20spaces" ``` -------------------------------- ### String Splitting and Joining Operations Source: https://github.com/hussseinkizz/regist/blob/main/README.md Provides methods to split a string by a separator and either pick an element at a specific index (`.split(separator).takeThatAt(idx)`) or join the split parts with a new separator (`.split(separator).join(sep)`). ```javascript const dataString = "apple,banana,cherry"; // Split and pick the second element (index 1) console.log(dataString.split(',').takeThatAt(1)); // "banana" // Split by comma and join with hyphen console.log(dataString.split(',').join('-')); // "apple-banana-cherry" ``` -------------------------------- ### Adding Prefixes and Suffixes Source: https://github.com/hussseinkizz/regist/blob/main/README.md Appends a prefix and/or a suffix to a string using the `.add()` method. The method accepts an object specifying the `prefix` and `suffix` to be added. ```javascript const baseString = "world"; console.log(baseString.add({ prefix: "hello ", suffix: "!" })); // "hello world!" ``` -------------------------------- ### String Transformation API (`stringTransform`) Source: https://github.com/hussseinkizz/regist/blob/main/README.md This section details the various methods available for transforming string data. Each method modifies the string in a specific way, such as changing its case, trimming whitespace, or replacing characters. ```APIDOC ## String Transformation Methods ### Description A collection of methods to manipulate and transform string values. ### Methods - **`.toUpperCase()`**: Uppercase the string. - **`.toLowerCase()`**: Lowercase the string. - **`.toPascalCase()`**: Convert the string to PascalCase. - **`.toSnakeCase()`**: Convert the string to snake_case. - **`.toCamelCase()`**: Convert the string to camelCase. - **`.trim()`**: Remove leading and trailing whitespace from the string. - **`.split(separator).takeThatAt(idx)`**: Split the string by a separator and return the element at the specified index. - **`.split(separator).join(newSeparator)`**: Split the string by a separator and then join the resulting array elements with a new separator. - **`.getCharacterAt(idx)`**: Retrieve the character at a specific index within the string. - **`.getRandomFrom()`**: Select and return a random character from the string. - **`.replace(search, replacement)`**: Replace the first occurrence of a search string with a replacement string. - **`.replaceAll(search, replacement)`**: Replace all occurrences of a search string with a replacement string. - **`.removeFirst(search)`**: Remove the first occurrence of a specified search string. - **`.removeAll(search)`**: Remove all occurrences of a specified search string. - **`.add(options)`**: Add a prefix and/or suffix to the string. `options` should be an object like `{prefix: '...', suffix: '...'}`. - **`.pad(length, character, position)`**: Pad the string to a specified length using a given character. `position` can be 'start', 'end', or 'both'. - **`.randomize()`**: Shuffle the characters within the string randomly. - **`.chunk(size, separator?)`**: Split the string into chunks of a specified size. Each chunk can optionally be joined by a separator. - **`.breakToLines(lineLength)`**: Wrap the string into multiple lines, ensuring each line does not exceed `lineLength`. - **`.extract(pattern)`**: Extract the first match of a given pattern (regex or string) from the string. - **`.extractInRange(startIndex, endIndex)`**: Extract a substring between the specified start and end indices. - **`.extractWhenBetween(prefix, suffix)`**: Extract the substring that appears between the first occurrence of `prefix` and `suffix`. - **`.toHex()`**: Convert the string to its hexadecimal representation. - **`.toBinary()`**: Convert the string to its binary representation. - **`.toURLSafe()`**: Encode the string for safe use in URLs (percent-encoding). - **`.toHash()`**: Generate a non-cryptographic hash (djb2 algorithm) of the string. - **`.customTransform(function)`**: Apply a custom transformation function to the string. - **`.sanitize(options)`**: Sanitize the string by removing specified characters (e.g., spaces, digits, specials). `options` is an object specifying what to remove. - **`.escapeString()`**: Escape special characters in the string that have meaning in regular expressions. - **`.unEscapeString()`**: Unescape previously escaped regular expression special characters. - **`.assertThat()`**: Switch to an assertion API for validating string properties. - **`.try(handler?)`**: Execute the current transformation chain. If an error occurs, it will return the result or call the provided `handler` function. ### Example Usage ```javascript // Example for toUpperCase const myString = 'hello world'; const upperString = myString.toUpperCase(); // 'HELLO WORLD' // Example for trim const spacedString = ' some text '; const trimmedString = spacedString.trim(); // 'some text' // Example for replaceAll const sentence = 'The quick brown fox jumps over the lazy dog.'; const newSentence = sentence.replaceAll('the', 'a'); // 'A quick brown fox jumps over a lazy dog.' // Example for extractWhenBetween const data = 'User ID: 12345, Status: Active'; const userId = data.extractWhenBetween('User ID: ', ', Status:'); // '12345' // Example for add const textToAdd = 'example'; const suffixedText = textToAdd.add({ suffix: '-suffix' }); // 'example-suffix' const prefixedText = textToAdd.add({ prefix: 'prefix-' }); // 'prefix-example' const bothAddedText = textToAdd.add({ prefix: 'prefix-', suffix: '-suffix' }); // 'prefix-example-suffix' // Example for sanitize const dirtyString = ' Hello 123 World! '; const cleanedString = dirtyString.sanitize({ spaces: true, digits: true }); // 'HelloWorld!' ``` ``` -------------------------------- ### Check for exact string match (assertThat.isExactly) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Tests if a string is exactly equal to a given value, with no extra characters. This can be done with a strict equality check or a regex matching the entire string. ```javascript assertThat(value).isExactly(exactString); // Regex Equivalent: /^exactString$/ or str === "exactString" ``` -------------------------------- ### Integrate Regist with Zod for Data Validation (TypeScript) Source: https://context7.com/hussseinkizz/regist/llms.txt This snippet shows how to use Regist's validation functions within Zod schemas for advanced data validation. It requires Zod and Regist libraries. Examples include validating alphanumeric strings, email formats, strong passwords, phone numbers with country codes, and complex form structures. It also demonstrates parsing and handling validation errors. ```typescript import { z } from "zod"; import { assertThat } from "regist"; // Username validation schema const usernameSchema = z.string().refine( val => assertThat(val) .isAlphaNumeric() .lengthIs({ min: 3, max: 20 }) .try(), { message: "Username must be 3-20 alphanumeric characters" } ); usernameSchema.parse("user123"); // "user123" try { usernameSchema.parse("ab"); // throws ZodError } catch (error) { console.error(error.errors); } // Email schema with custom validation const emailSchema = z.string() .refine(val => assertThat(val).isEmail().try(), { message: "Invalid email address" }) .transform(val => val.toLowerCase()); emailSchema.parse("User@EXAMPLE.COM"); // "user@example.com" // Strong password schema const passwordSchema = z.string().refine( val => assertThat(val).isStrongPassword().try(), { message: "Password must be 8+ chars with uppercase, lowercase, digit, and special character" } ); // Phone number schema with regional validation const phoneSchema = z.object({ number: z.string(), country: z.enum(["US", "UG", "DEFAULT"]) }).refine( data => assertThat(data.number).isPhone(data.country).try(), { message: "Invalid phone number for specified country" } ); phoneSchema.parse({ number: "(555) 123-4567", country: "US" }); // Valid // User registration form schema const userRegistrationSchema = z.object({ username: z.string().refine( val => assertThat(val) .isAlphaNumeric() .lengthIs({ min: 3, max: 20 }) .try(), { message: "Invalid username" } ), email: z.string().refine( val => assertThat(val).isEmail().try(), { message: "Invalid email" } ), password: z.string().refine( val => assertThat(val).isStrongPassword().try(), { message: "Password too weak" } ), confirmPassword: z.string() }).refine( data => data.password === data.confirmPassword, { message: "Passwords don't match", path: ["confirmPassword"] } ); // Parse form data const formData = { username: "johndoe", email: "john@example.com", password: "MyP@ss123", confirmPassword: "MyP@ss123" }; const validated = userRegistrationSchema.parse(formData); // All validations pass // API request body validation const createProductSchema = z.object({ name: z.string() .min(1) .refine(val => assertThat(val).hasNoEmoji().try(), { message: "Product name cannot contain emojis" }), slug: z.string() .refine(val => assertThat(val).isUrlSafe().try(), { message: "Slug must be URL-safe" }), price: z.string() .refine(val => assertThat(val).isNumeric().try(), { message: "Price must be numeric" }) }); createProductSchema.parse({ name: "Product Name", slug: "product-name", price: "29.99" }); // Valid ``` -------------------------------- ### Check if value is equal to any of provided values (assertThat.anyOf) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Asserts that the input string is strictly equal to at least one of the values provided in the arguments. This is useful for checking against a set of allowed strings. ```javascript assertThat(value).anyOf('option1', 'option2', 'option3'); // Regex Equivalent: /^(option1|option2|option3)$/ ``` -------------------------------- ### String Trimming and Whitespace Manipulation Source: https://github.com/hussseinkizz/regist/blob/main/README.md Removes leading and trailing whitespace from a string using `.trim()`. The regex equivalent demonstrates how this can be achieved using regular expressions. ```javascript const spacedString = " Trim me "; console.log(spacedString.trim()); // "Trim me" // Regex equivalent: /^\s+|\s+$/g ``` -------------------------------- ### Reusable Regist Chains and Zod Integration Source: https://github.com/hussseinkizz/regist/blob/main/README.md Shows how to create reusable transformation chains and integrate Regist with Zod for schema validation. Reusable chains allow building a transformation sequence once and applying it multiple times with different modifications. Zod integration uses Regist for custom validation rules within Zod schemas. ```typescript const snake = stringTransform("fooBar").toSnakeCase(); snake.try(); // "foo_bar" snake.toUpperCase().try(); // "FOO_BAR" import { z } from "zod"; import { assertThat } from "regist"; const usernameSchema = z.string().refine( val => assertThat(val).isAlphaNumeric().lengthIs({ min: 3, max: 20 }).try() ); usernameSchema.parse("user123"); // passes usernameSchema.parse("!@#"); // throws ZodError ``` -------------------------------- ### Check for valid URL format (assertThat.isUrl) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Tests if a string represents a valid URL. The provided regex is an approximation and may not cover all edge cases of URL formats. ```javascript assertThat(value).isUrl(); // Regex Equivalent: /^(https?://)?[w-]+(.[w-]+)+[/#?]?.*$/ (approx) ``` -------------------------------- ### Chain Regist's stringTransform and assertThat APIs Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/advanced-examples.mdx Demonstrates seamless interoperability between Regist's `stringTransform` and `assertThat` APIs within a single fluent chain. This allows for transformations followed by assertions. ```typescript import { stringTransform } from 'regist'; const result = stringTransform(" Hello World! ") .trim() .toLowerCase() .assertThat() // Switch to the assertion API .isExactly("hello world!") .try(); // Returns true ``` -------------------------------- ### Chaining Multiple String Transformations in TypeScript Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/stringtransform-api.mdx Illustrates the chainable nature of the stringTransform API by applying multiple transformations sequentially: trimming whitespace, converting to uppercase, and then to snake_case. The `.try()` method is used to execute the chain. ```typescript import { stringTransform } from 'regist'; const transformed = stringTransform(' some string ') .trim() .toUpperCase() .toSnakeCase() .try(); // Result: 'SOME_STRING' ``` -------------------------------- ### Custom Logic and Error Handling in Regist Source: https://github.com/hussseinkizz/regist/blob/main/README.md Illustrates how to implement custom validation logic using `customCheck` and how to handle errors gracefully using the `.try(handler)` method. The handler function receives error details, the step where the error occurred, and the value before that step. ```typescript // Custom check (palindrome) assertThat("racecar") .customCheck(str => str === str.split("").reverse().join("")) .try(); // true // Handle errors gracefully stringTransform("abc") .extract(/\d+/) .try((err, step, valueBefore) => { // err.message contains "No match found" // step === "extract" // valueBefore === "abc" }); // => null ``` -------------------------------- ### String Validation with Regist Source: https://github.com/hussseinkizz/regist/blob/main/README.md Demonstrates various string validation techniques using Regist's `assertThat` API. It covers strong password, email, URL, and phone number validation. Returns true or false based on the validation criteria. ```typescript import { assertThat } from "regist"; // Strong password (at least 8 chars, uppercase, lowercase, digit, special char) assertThat("Aa1!aa11").isStrongPassword().try(); // true assertThat("weakpass").isStrongPassword().try(); // false // Email and URL validation assertThat("foo@bar.com").isEmail().try(); // true assertThat("not-an-email").isEmail().try(); // false assertThat("https://foo.com").isUrl().try(); // true assertThat("not a url").isUrl().try(); // false // Phone validation (US) assertThat("123-456-7890").isPhone("US").try(); // true assertThat("notaphone").isPhone("US").try(); // false ``` -------------------------------- ### Regist Error Handling with try...catch Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/how-it-works.mdx Shows how Regist errors are thrown and can be caught using standard JavaScript try...catch blocks when no explicit error handler is provided to the .try() method. ```typescript import { stringTransform } from 'regist'; // If no handler is provided, errors are thrown try { stringTransform("no-digits-here").extract(/\d+/).try(); } catch (e) { console.log(e.message); // "No match found for pattern: /\d+/" } ``` -------------------------------- ### Regist Pipeline: Password Strength Check and Hashing Prep (TypeScript) Source: https://context7.com/hussseinkizz/regist/llms.txt This function checks if a password meets strength criteria using `assertThat().isStrongPassword()` and prepares a hash using `stringTransform().toHash()`. It returns an object containing the hash and a boolean indicating strength, or null if hashing fails. ```typescript import { assertThat, stringTransform } from "regist"; // Password validation and hashing prep function preparePassword(password: string): { hash: string; isStrong: boolean } | null { // Check strength const isStrong = assertThat(password).isStrongPassword().try(); // Generate hash regardless (for comparison) const hash = stringTransform(password) .toHash() .try((err) => null); if (!hash) return null; return { hash, isStrong }; } preparePassword("MyP@ss123"); // { hash: "...", isStrong: true } preparePassword("weak"); // { hash: "...", isStrong: false } ``` -------------------------------- ### Custom Transformations and Error Handling Source: https://github.com/hussseinkizz/regist/blob/main/README.md Applies a custom JavaScript function for string transformation using `.customTransform(fn)`. The `.try(handler?)` method executes the transformation chain and handles potential errors by calling an optional handler function. ```javascript const transformFn = (str) => str.split('').reverse().join(''); const failingFn = () => { throw new Error('Failed transformation'); }; console.log("hello".customTransform(transformFn)); // "olleh" try { const result = "world".customTransform(failingFn).try(); console.log(result); } catch (e) { console.error("Caught error:", e.message); } // With handler "world".customTransform(failingFn).try((err) => console.error("Handled error:", err.message)); ``` -------------------------------- ### Chunking and Line Breaking Source: https://github.com/hussseinkizz/regist/blob/main/README.md Splits a string into chunks of a specified size, optionally joined by a separator (`.chunk(size, sep?)`). The `.breakToLines(lineLen)` method wraps the string into lines of a given length. ```javascript const longString = "abcdefghijklmnopqrstuvwxyz"; console.log(longString.chunk(5, "-")); // "abcde-fghij-klmno-pqrst-uvwxy-z" console.log(longString.breakToLines(10)); // "abcdefghij\nklmnopqrst\nuvwxyz" ``` -------------------------------- ### Reusable Regist chains and Zod integration Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/advanced-examples.mdx Illustrates how Regist chains can be defined once and reused, and how they integrate with schema validation libraries like Zod. Custom validation logic from Regist can be used within Zod's `refine`. ```typescript import { z } from "zod"; import { assertThat, stringTransform } from 'regist'; // Reusable chain const snakeCaseChain = stringTransform("fooBar").toSnakeCase(); const snake = snakeCaseChain.try(); // "foo_bar" const upperSnake = snakeCaseChain.toUpperCase().try(); // "FOO_BAR" // Integration with Zod for schema validation const usernameSchema = z.string().refine( val => assertThat(val).isAlphaNumeric().lengthIs({ min: 3, max: 20 }).try(), { message: "Username must be 3-20 alphanumeric characters." } ); usernameSchema.parse("user123"); // Passes // usernameSchema.parse("!@#"); // Throws a ZodError ``` -------------------------------- ### Custom validation and error handling with Regist Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/advanced-examples.mdx Showcases how to implement custom validation logic using `customCheck` and how to handle potential errors gracefully during transformations using a callback with `try()`. ```typescript import { assertThat, stringTransform } from 'regist'; // Custom validation check const isPalindrome = assertThat("racecar") .customCheck(str => str === str.split("").reverse().join("")) .try(); // Returns true // Graceful error handling stringTransform("abc") .extract(/\d+/) // This will fail .try((err, step, valueBefore) => { console.error(`Error during step: ${step}`); // 'extract' console.error(`Input value was: ${valueBefore}`); // 'abc' // err.message will contain "No match found" }); // Returns null and calls the handler ``` -------------------------------- ### Regist Error Handling with Handler Function Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/how-it-works.mdx Demonstrates how to handle errors gracefully in Regist using an optional handler function passed to `.try()`. The handler receives error details, step name, and the value at failure. ```typescript import { stringTransform } from 'regist'; // Example: Handling an error gracefully const result = stringTransform("no-digits-here") .extract(/\d+/) // This step will fail because there are no digits .try((error, stepName, valueAtFailure) => { console.error(`An error occurred during the '${stepName}' step.`); console.error(`The input value was: '${valueAtFailure}'`); console.error(`Error message: ${error.message}`); // You can add custom logic here, like logging to a service }); if (result === null) { console.log("The transformation failed as expected."); } ``` -------------------------------- ### Chaining Validation and Transformation in Regist Source: https://github.com/hussseinkizz/regist/blob/main/README.md Illustrates chaining methods from both `stringTransform` and `assertThat` APIs within a single operation. This allows for transformations followed by assertions or vice-versa. Returns the result of the final operation (boolean for assertion, transformed string for transformation). ```typescript import { stringTransform, assertThat } from "regist"; // Transform then Assert stringTransform(" Hello World! ") .trim() .toLowerCase() .assertThat() .isExactly("hello world!") .try(); // true // Assert then Transform assertThat("foo") .isExactly("foo") .stringTransform() .toUpperCase() .try(); // "FOO" ``` -------------------------------- ### Basic String Validation with assertThat in TypeScript Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/asserthat-api.mdx Demonstrates the basic usage of the `assertThat` API for validating email addresses and strong passwords. It requires importing `assertThat` from the 'regist' library. The `.try()` method is used to execute the assertion and return a boolean result. ```typescript import { assertThat } from 'regist'; // Example: Check if a string is a valid email address const isValidEmail = assertThat('test@example.com').isEmail().try(); // Returns true // Example: Validate a strong password const isStrong = assertThat('Password123!').isStrongPassword().try(); // Returns true ``` -------------------------------- ### Slugify a blog post title using Regist Source: https://github.com/hussseinkizz/regist/blob/main/docs/content/docs/advanced-examples.mdx Converts a blog post title into a URL-friendly slug by converting to lowercase, removing special characters, and replacing spaces with hyphens. This utilizes `stringTransform` for sequential modifications. ```typescript import { stringTransform } from 'regist'; const title = 'My Awesome Blog Post!'; const slug = stringTransform(title) .toLowerCase() .sanitize({ removeSpecial: true }) .replaceAll(' ', '-') .try(); // 'my-awesome-blog-post' ``` -------------------------------- ### String Replacement and Removal Source: https://github.com/hussseinkizz/regist/blob/main/README.md Methods for replacing the first occurrence (`.replace(search, rep)`) or all occurrences (`.replaceAll(search, rep)`) of a substring. It also includes `.removeFirst(search)` and `.removeAll(search)` for deleting occurrences. ```javascript const text = "The quick brown fox jumps over the lazy dog."; console.log(text.replace("fox", "cat")); // "The quick brown cat jumps over the lazy dog." console.log(text.replaceAll("the", "a")); // "A quick brown fox jumps over a lazy dog." console.log(text.removeFirst("brown ")); // "The quick fox jumps over the lazy dog." console.log(text.removeAll(" ")); // "Thequickbrownfoxjumpsoverthelazydog." ``` -------------------------------- ### String Case Conversion Methods Source: https://github.com/hussseinkizz/regist/blob/main/README.md Converts a string to different cases: uppercase, lowercase, PascalCase, snake_case, and camelCase. These methods do not require external dependencies and operate directly on the string. ```javascript const myString = "hello world"; console.log(myString.toUpperCase()); // HELLO WORLD console.log(myString.toLowerCase()); // hello world console.log(myString.toPascalCase()); // HelloWorld console.log(myString.toSnakeCase()); // hello_world console.log(myString.toCamelCase()); // helloWorld ``` -------------------------------- ### Execute Chain with Error Handling (JavaScript) Source: https://github.com/hussseinkizz/regist/blob/main/README.md Executes the current chain of operations. It returns true if successful, false if an error occurs during execution, or calls an optional handler function if provided, passing the error object to it. ```javascript chain.try(); chain.try(errorHandler); ```