### Install Async Queue using Yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/async-queue/README.md This command installs the @alwatr/async-queue package using the Yarn package manager. Ensure you have Yarn installed globally. ```bash yarn add @alwatr/async-queue ``` -------------------------------- ### Install @alwatr/nano-build Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Install the @alwatr/nano-build package as a development dependency using Yarn. ```bash yarn add -D @alwatr/nano-build ``` -------------------------------- ### Install Flatomise Package Source: https://github.com/alwatr/nanolib/blob/next/packages/flatomise/README.md This command installs the Flatomise utility package using Yarn. Ensure you have Yarn installed to use this command. This is the first step before you can use Flatomise in your project. ```bash yarn add @alwatr/flatomise ``` -------------------------------- ### Install Alwatr Local Storage Provider Source: https://github.com/alwatr/nanolib/blob/next/packages/local-storage/README.md Instructions for installing the Alwatr Local Storage Provider package using either Yarn or npm. ```bash # with yarn yarn add @alwatr/local-storage # with npm npm install @alwatr/local-storage ``` -------------------------------- ### Install hash-string Package Source: https://github.com/alwatr/nanolib/blob/next/packages/hash-string/README.md Install the hash-string package using either yarn or npm package manager. ```bash yarn add @alwatr/hash-string # or npm install @alwatr/hash-string ``` -------------------------------- ### Install Alwatr Local Storage Provider Source: https://github.com/alwatr/nanolib/blob/next/packages/local-storage/README.md Instructions for installing the @alwatr/local-storage package using either yarn or npm. This is the first step to using the library in your project. ```bash # Using yarn yarn add @alwatr/local-storage # Using npm npm install @alwatr/local-storage ``` -------------------------------- ### URL Resolution Examples Source: https://github.com/alwatr/nanolib/blob/next/packages/resolve-url/README.md Provides various examples of the `resolveUrl` function's behavior with different input strings. These examples illustrate how the library handles leading, trailing, and multiple slashes, as well as base URLs. ```typescript resolveUrl('foo', 'bar'); // 'foo/bar' resolveUrl('/foo', 'bar'); // '/foo/bar' resolveUrl('/foo/', 'bar'); // '/foo/bar' resolveUrl('/foo//', 'bar'); // '/foo/bar' resolveUrl('/foo/', '/bar/'); // '/foo/bar' resolveUrl('https://example.com', 'foo', 'bar'); // 'https://example.com/foo/bar' resolveUrl('https://example.com/', '/foo/', '/bar/'); // 'https://example.com/foo/bar' ``` -------------------------------- ### Install @alwatr/delay with npm or yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/delay/README.md Installs the @alwatr/delay package using either npm or yarn. This is the first step before using the library in your project. ```bash # Using npm npm install @alwatr/delay # Using yarn yarn add @alwatr/delay ``` -------------------------------- ### Install Alwatr Logger with npm or yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/logger/README.md This snippet shows how to install the Alwatr Logger library using either npm or yarn package managers. Ensure you have Node.js and npm/yarn installed to use these commands. ```bash npm install @alwatr/logger ``` ```bash yarn add @alwatr/logger ``` -------------------------------- ### Install @alwatr/env Package Source: https://github.com/alwatr/nanolib/blob/next/packages/env/README.md Installs the @alwatr/env library using npm. This is the first step to using the environment variable utility. ```bash npm install @alwatr/env ``` -------------------------------- ### Install Object.hasOwn Polyfill with npm Source: https://github.com/alwatr/nanolib/blob/next/packages/polyfill-has-own/README.md Installs the @alwatr/polyfill-has-own package using npm. This makes the Object.hasOwn polyfill available for use in your project. ```bash npm install @alwatr/polyfill-has-own ``` -------------------------------- ### Install @alwatr/exit-hook using Yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/exit-hook/README.md This command installs the @alwatr/exit-hook package using the Yarn package manager. Ensure Yarn is installed and configured in your project. ```bash yarn add @alwatr/exit-hook ``` -------------------------------- ### Install @alwatr/node-fs Source: https://github.com/alwatr/nanolib/blob/next/packages/node-fs/README.md This command installs the @alwatr/node-fs package using yarn. It is a prerequisite for using the file system utilities provided by the library. ```bash yarn add @alwatr/node-fs ``` -------------------------------- ### Install @alwatr/fetch using npm, yarn, or pnpm Source: https://github.com/alwatr/nanolib/blob/next/packages/fetch/README.md Instructions for installing the @alwatr/fetch package using common JavaScript package managers. This package enhances the native fetch API. ```bash # npm npm i @alwatr/fetch # yarn yarn add @alwatr/fetch # pnpm pnpm add @alwatr/fetch ``` -------------------------------- ### Install and Run Yarn Upgrade Locally Source: https://github.com/alwatr/nanolib/blob/next/packages/yarn-upgrade/README.md Install @alwatr/yarn-upgrade as a development dependency and run it using a custom script. This approach is useful for projects that frequently use the tool. ```bash yarn add -D @alwatr/yarn-upgrade ``` ```bash yarn upd ``` -------------------------------- ### npm Installation for Alwatr Debounce Source: https://github.com/alwatr/nanolib/blob/next/packages/debounce/README.md Provides the command-line instructions for installing the `@alwatr/debounce` package using different package managers: npm, yarn, and pnpm. ```bash # با استفاده از npm npm i @alwatr/debounce # با استفاده از yarn yarn add @alwatr/debounce # با استفاده از pnpm pnpm add @alwatr/debounce ``` -------------------------------- ### TypeScript HTTP Headers Example Source: https://github.com/alwatr/nanolib/blob/next/packages/http-primer/README.md Illustrates the usage of HttpRequestHeaders and HttpResponseHeaders types from @alwatr/http-primer. These types help in defining and working with request and response headers in a structured manner. ```typescript import {HttpRequestHeaders, HttpResponseHeaders} from '@alwatr/http-primer'; const requestHeaders: HttpRequestHeaders = { accept: 'application/json', authorization: 'Bearer my-token', }; const responseHeaders: HttpResponseHeaders = { 'content-type': 'application/json', 'content-length': 1234, }; ``` -------------------------------- ### Install @alwatr/synapse using npm, yarn, or pnpm Source: https://github.com/alwatr/nanolib/blob/next/packages/synapse/README.md Provides installation commands for @alwatr/synapse using popular package managers: npm, yarn, and pnpm. This is the first step to integrate the library into your project. ```bash # npm npm i @alwatr/synapse # yarn yarn add @alwatr/synapse # pnpm pnpm i @alwatr/synapse ``` -------------------------------- ### TypeScript HTTP Methods Example Source: https://github.com/alwatr/nanolib/blob/next/packages/http-primer/README.md Demonstrates how to import and use the HttpMethods type from the @alwatr/http-primer package. This type provides a standardized way to represent HTTP request methods. ```typescript import {HttpMethods} from '@alwatr/http-primer'; const method = HttpMethods.GET; ``` -------------------------------- ### Install @alwatr/deep-clone with Yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/deep-clone/README.md This snippet shows how to install the @alwatr/deep-clone package using the Yarn package manager. It is a prerequisite for using the deepClone function. ```bash yarn add @alwatr/deep-clone ``` -------------------------------- ### Install @alwatr/random Source: https://github.com/alwatr/nanolib/blob/next/packages/random/README.md Install the @alwatr/random library using Yarn or NPM. This package provides various random generation utilities. ```bash yarn add @alwatr/random # or npm install @alwatr/random ``` -------------------------------- ### Install TypeScript Type Helpers Source: https://github.com/alwatr/nanolib/blob/next/packages/type-helper/README.md Installs the `@alwatr/type-helper` package as a development dependency using Yarn. This package provides utility types for TypeScript projects. ```bash yarn add -D @alwatr/type-helper ``` -------------------------------- ### Install @alwatr/resolve-url Source: https://github.com/alwatr/nanolib/blob/next/packages/resolve-url/README.md Install the @alwatr/resolve-url package using npm. This is the only dependency required to use the URL resolution functionality. ```bash npm install @alwatr/resolve-url ``` -------------------------------- ### Install Object.hasOwn Polyfill with Yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/polyfill-has-own/README.md Installs the @alwatr/polyfill-has-own package using Yarn. This is an alternative to npm for package management and achieves the same result of making the polyfill available. ```bash yarn add @alwatr/polyfill-has-own ``` -------------------------------- ### Install djb2-hash using Yarn or npm Source: https://github.com/alwatr/nanolib/blob/next/packages/djb2-hash/README.md Installs the @alwatr/djb2-hash package into your project using either Yarn or npm package managers. ```bash # yarn yarn add @alwatr/djb2-hash # npm npm install @alwatr/djb2-hash ``` -------------------------------- ### Install @alwatr/global-this Source: https://github.com/alwatr/nanolib/blob/next/packages/global-this/README.md Install the @alwatr/global-this package using Yarn. This package provides access to globalThis across different JavaScript environments. ```bash yarn add @alwatr/global-this ``` -------------------------------- ### TypeScript MIME Types Example Source: https://github.com/alwatr/nanolib/blob/next/packages/http-primer/README.md Demonstrates how to import and use the MimeTypes type from the @alwatr/http-essentials package (a related package). This type provides constants for common MIME types, simplifying their use in applications. ```typescript import {MimeTypes} from '@alwatr/http-essentials'; const contentType = MimeTypes.JSON; // 'application/json' ``` -------------------------------- ### TypeScript Configuration for Nano Build Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Configure your tsconfig.json file to integrate with @alwatr/nano-build, ensuring proper compilation and declaration file generation. This setup is essential for TypeScript projects. ```jsonc { "extends": "@alwatr/tsconfig-base/tsconfig.json", "compilerOptions": { "rootDir": "src", "outDir": "dist", "emitDeclarationOnly": true, "composite": true, "types": ["@alwatr/nano-build"], }, "include": ["src/**/*.ts"], } ``` -------------------------------- ### Install Alwatr TypeScript Base Config Source: https://github.com/alwatr/nanolib/blob/next/packages/tsconfig-base/README.md Installs the base TypeScript configuration package for Alwatr projects as a development dependency using Yarn. ```bash yarn add -D @alwatr/tsconfig-base ``` -------------------------------- ### Install @alwatr/cyrb53 Package Source: https://github.com/alwatr/nanolib/blob/next/packages/cyrb53/README.md Installs the @alwatr/cyrb53 package using the Yarn package manager. This is the first step to using the hashing functionality in your project. ```bash yarn add @alwatr/cyrb53 ``` -------------------------------- ### Install Unicode Digits with Yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/unicode-digits/README.md This command installs the Unicode Digits library using the Yarn package manager. It is a direct dependency for using the library in your project. ```bash yarn add @alwatr/unicode-digits ``` -------------------------------- ### Install Alwatr Prettier Config (Yarn) Source: https://github.com/alwatr/nanolib/blob/next/packages/prettier-config/README.md Installs the `@alwatr/prettier-config` package as a development dependency using Yarn. This package provides Alwatr's standard Prettier rules. ```bash yarn add -D @alwatr/prettier-config ``` -------------------------------- ### Basic Usage Examples for nanoHash (TypeScript) Source: https://github.com/alwatr/nanolib/blob/next/packages/hash-string/README.md Illustrates fundamental use cases of the nanoHash function, including hashing strings and numbers, and verifying consistent output for identical inputs. ```typescript // Generate a hash for a string anoHash('hello world', 'msg-'); // => 'msg-k7f2h9d' // Generate a hash for a number anoHash(42, 'id-'); // => 'id-p83b2e4' // Same input produces the same output anoHash('test', 'x-') === nanoHash('test', 'x-'); // => true // Different inputs produce different outputs anoHash('test1', 'x-') !== nanoHash('test2', 'x-'); // => true ``` -------------------------------- ### TypeScript HTTP Status Codes Example Source: https://github.com/alwatr/nanolib/blob/next/packages/http-primer/README.md Shows how to import and utilize HttpStatusCodes from the @alwatr/http-primer package. This type offers predefined constants for various HTTP status codes, enhancing code readability and reducing errors. ```typescript import {HttpStatusCodes} from '@alwatr/http-primer'; const statusCode = HttpStatusCodes.Success_200_OK; ``` -------------------------------- ### Install ESLint Dependencies with Yarn Source: https://github.com/alwatr/nanolib/blob/next/packages/eslint-config/README.md Installs the necessary ESLint and related TypeScript and import plugins using Yarn. This command ensures all required packages for linting are available as development dependencies. ```bash yarn add -D @alwatr/eslint-config \ eslint \ @typescript-eslint/parser \ @typescript-eslint/eslint-plugin \ eslint-plugin-import \ eslint-import-resolver-typescript ``` -------------------------------- ### Quick Start: Fetch Data with Enhanced Options in TypeScript Source: https://github.com/alwatr/nanolib/blob/next/packages/fetch/README.md Demonstrates how to import and use the enhanced fetch function from @alwatr/fetch in TypeScript. It shows how to send JSON and URL parameters, set caching strategies, and handle timeouts. ```typescript import {fetch} from '@alwatr/fetch'; async function fetchProducts() { try { console.log('Fetching product list...'); const response = await fetch('/api/products', { queryParams: {limit: 10, category: 'electronics'}, cacheStrategy: 'stale_while_revalidate', timeout: '5s', // Use string duration }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); console.log('Products:', data); } catch (error) { console.error('Failed to fetch products:', error); } } fetchProducts(); ``` -------------------------------- ### Import and Use Random Utilities Source: https://github.com/alwatr/nanolib/blob/next/packages/random/README.md Demonstrates importing and using various random generation functions from the @alwatr/random library. Includes examples for numbers, integers, floats, strings, UUIDs, booleans, and colors. ```typescript import { randNumber, randInteger, randFloat, randString, randStep, randShuffle, randPick, randUuid, randBoolean, randColor, randArray, bytesToHex, } from '@alwatr/random'; // Get random number between 0 and 1 console.log(randNumber()); // 0.7124123 // Get random integer in range console.log(randInteger(1, 10)); // 7 // Get random float in range console.log(randFloat(1, 10)); // 7.214124 // Get random string with fixed length console.log(randString(6)); // "A1b2C3" // Get random string with variable length console.log(randString(3, 6)); // "X2fg" // Get random string with custom character set console.log(randString(5, undefined, '01')); // "10101" // Get random value with step console.log(randStep(0, 10, 2)); // 0, 2, 4, 6, 8, or 10 // Shuffle an array const array = [1, 2, 3, 4, 5]; console.log(randShuffle([...array])); // [3, 1, 5, 2, 4] // Pick a random item from array console.log(randPick(array)); // 3 // Generate UUID console.log(randUuid()); // "a1b2c3d4-e5f6-47a8-b9c0-d1e2f3a4b5c6" // Generate random boolean console.log(randBoolean()); // true or false (50% chance) console.log(randBoolean(0.8)); // true or false (80% chance of true) // Generate random color console.log(randColor()); // "#a1b2c3" // Convert bytes to hexadecimal string const bytes = new Uint8Array([10, 255, 0, 16]); console.log(bytesToHex(bytes)); // "0aff0010" ``` -------------------------------- ### DJB2 Hash Function API Source: https://github.com/alwatr/nanolib/blob/next/packages/djb2-hash/README.md This section details the `djb2Hash` function, its parameters, return type, and provides an example of its usage. ```APIDOC ## djb2Hash(str: string): number ### Description Generates a 32-bit unsigned integer hash from a given string using the DJB2 algorithm. This function is optimized for performance and is suitable for non-cryptographic use cases. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A (This is a function, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { djb2Hash } from '@alwatr/djb2-hash'; const myHash = djb2Hash('hello world'); console.log(myHash); ``` ### Response #### Success Response (number) - **hash** (number) - A 32-bit unsigned integer representing the hash of the input string. #### Response Example ```json { "hash": 2616892229 } ``` ### Security Note `djb2Hash` is a **non-cryptographic** hash function and should **not** be used for security-sensitive applications. For such use cases, employ standard cryptographic hash functions like SHA-256 or Argon2. ``` -------------------------------- ### TypeScript JSON Object Example Source: https://github.com/alwatr/nanolib/blob/next/packages/type-helper/README.md Provides an example of creating a TypeScript object that conforms to the `JSONObject` type. This illustrates how to use the type helpers to define structured JSON-like data. ```typescript const obj: JSONObject = { foo: 'bar', baz: { qux: 1, arr: [1, 2, 3], }, qux: true, }; ``` -------------------------------- ### Configure tsconfig.json with Alwatr Base Source: https://github.com/alwatr/nanolib/blob/next/packages/tsconfig-base/README.md Example of a tsconfig.json file that extends the Alwatr base TypeScript configuration and specifies root and output directories, along with included files. ```json { "extends": "@alwatr/tsconfig-base", "compilerOptions": { "rootDir": "src", "outDir": "dist" }, "include": ["src/**/*.ts"] } ``` -------------------------------- ### Yarn Upgrade Execution Steps Source: https://github.com/alwatr/nanolib/blob/next/packages/yarn-upgrade/README.md The sequence of commands executed by the @alwatr/yarn-upgrade tool to perform dependency maintenance. This includes updating Yarn, interactive upgrades, recursive upgrades, SDK setup, deduplication, and syncpack operations. ```bash yarn set version latest yarn upgrade-interactive yarn up "@*/*" "*" --recursive yarn dlx @yarnpkg/sdks vscode yarn dedupe yarn syncpack format yarn syncpack fix yarn syncpack lint --sort count ``` -------------------------------- ### Usage Example of djb2Hash function Source: https://github.com/alwatr/nanolib/blob/next/packages/djb2-hash/README.md Demonstrates how to import and use the djb2Hash function to generate a numeric hash from a string in TypeScript. ```typescript import { djb2Hash } from '@alwatr/djb2-hash'; // Generate a numeric hash from a string const myHash = djb2Hash('hello world'); console.log(myHash); // Outputs: 2616892229 ``` -------------------------------- ### Bootstrap Directives Example (TypeScript) Source: https://github.com/alwatr/nanolib/blob/next/packages/synapse/README.md Demonstrates how to use bootstrapDirectives to initialize directives on dynamically added content. This function is idempotent and ensures directives are only processed once per element. ```typescript // Imagine new content is added to the page const newContent = document.createElement('div'); newContent.innerHTML = ''; document.body.appendChild(newContent); // You can safely bootstrap again, and it will only process the new button bootstrapDirectives(newContent); ``` -------------------------------- ### Usage Example: Hashing Strings with cyrb53 Source: https://github.com/alwatr/nanolib/blob/next/packages/cyrb53/README.md Demonstrates how to import and use the cyrb53 hashing function in TypeScript. It shows basic string hashing and hashing with a custom seed for varied results. The output hash fits within JavaScript's safe integer limits. ```typescript import {cyrb53} from '@alwatr/cyrb53'; const myString = 'Hello, Alwatr!'; const hash = cyrb53(myString); console.log(`The hash of "${myString}" is ${hash}`); // Output: The hash of "Hello, Alwatr!" is 3535973453205730 // Using a seed for varied hashing const hashWithSeed = cyrb53(myString, 123); console.log(`The hash with seed 123 is ${hashWithSeed}`); // Output: The hash with seed 123 is 3160286127194783 ``` -------------------------------- ### Nano Build Default Preset Configuration Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md The default preset for @alwatr/nano-build, providing a baseline configuration for building libraries. It includes settings for entry points, output directory, logging, target, minification, and more. ```javascript { entryPoints: ['src/*.ts'], outdir: 'dist', logLevel: 'info', target: 'es2020', minify: true, minifyWhitespace: true, treeShaking: true, sourcemap: false, sourcesContent: false, bundle: true, charset: 'utf8', legalComments: 'linked', define: { __package_name__: packageJson.name, __package_version__: packageJson.version, __dev_mode__: process.env.NODE_ENV !== 'production', }, banner: { js: "/* __package_name__ v__package_version__ */" }, } ``` -------------------------------- ### Nano Build --preset=module3 Configuration Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Configuration for the `--preset=module3` option, which builds multiple entry points in the src directory for multiple exports modules without bundling. It uses ESM format and includes sourcemaps. ```javascript { ...defaultPreset, entryPoints: ['src/**/*.ts'], bundle: false, platform: 'node', format: 'esm', minify: false, cjs: true, packages: 'external', sourcemap: true, sourcesContent: true } ``` -------------------------------- ### Nano Build --preset=module2 Configuration Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Configuration for the `--preset=module2` option, designed for building and bundling multiple entry points in the root of the src directory for multiple exports modules. It uses ESM format and includes sourcemaps. ```javascript { ...defaultPreset, entryPoints: ['src/*.ts'], bundle: true, platform: 'node', format: 'esm', minify: false, cjs: true, packages: 'external', sourcemap: true, sourcesContent: true } ``` -------------------------------- ### Nano Build --preset=module Configuration Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Configuration for the `--preset=module` option in @alwatr/nano-build, optimized for building and bundling single export modules. It sets the format to ESM and enables sourcemaps. ```javascript { ...defaultPreset, entryPoints: ['src/main.ts'], bundle: true, platform: 'node', format: 'esm', minify: false, cjs: true, packages: 'external', sourcemap: true, sourcesContent: true } ``` -------------------------------- ### Nano Build --preset=pwa Configuration Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Configuration for the `--preset=pwa` option in @alwatr/nano-build, tailored for Progressive Web Applications. It targets browsers with specific ES versions and formats the output as IIFE. ```javascript { ...defaultPreset, entryPoints: ['site/_ts/*.ts'], outdir: 'dist/es', platform: 'browser', format: 'iife', mangleProps: '_$', target: [ 'es2018', 'chrome62', 'edge79', 'firefox78', 'safari11', ], ...(devMode ? developmentOverwriteOptions : productionOverwriteOptions), } ``` -------------------------------- ### Configure build scripts in package.json Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Add build and watch scripts to your package.json file to utilize @alwatr/nano-build for your project. This enables easy command-line execution of build tasks. ```json { "scripts": { "build": "nano-build --preset=module", "watch": "yarn run build --watch" } } ``` -------------------------------- ### Create Local Storage Provider Instance Source: https://github.com/alwatr/nanolib/blob/next/packages/local-storage/README.md Demonstrates how to create a typed instance of a LocalStorageProvider using the `createLocalStorageProvider` factory function. This function encapsulates the instantiation logic and provides a clean API. ```typescript import {createLocalStorageProvider} from '@alwatr/local-storage'; // Define your data structure interface UserSettings { theme: 'light' | 'dark'; notifications: boolean; lastLogin: number | null; } // Create a provider for user settings const userSettingsProvider = createLocalStorageProvider({ name: 'user-settings', schemaVersion: 1, }); ``` -------------------------------- ### Bootstrap @alwatr/synapse Directives in Main Entry Point Source: https://github.com/alwatr/nanolib/blob/next/packages/synapse/README.md Shows how to initialize @alwatr/synapse in your application's main entry point ('main.ts'). It imports custom directives and calls `bootstrapDirectives()` after the DOM content has been fully loaded. ```typescript // src/main.ts import {bootstrapDirectives} from '@alwatr/synapse'; import './copy-button.js'; // Import the directive to register it document.addEventListener('DOMContentLoaded', () => { bootstrapDirectives(); }); ``` -------------------------------- ### Create Local Storage Provider Instance (TypeScript) Source: https://github.com/alwatr/nanolib/blob/next/packages/local-storage/README.md Demonstrates how to create an instance of a LocalStorageProvider using the `createLocalStorageProvider` factory function. It includes defining the data shape with an interface and configuring the provider with a name and schema version. ```typescript import {createLocalStorageProvider} from '@alwatr/local-storage'; // Define the shape of your data interface UserSettings { theme: 'light' | 'dark'; notifications: boolean; lastLogin: number | null; } // Create a provider for user settings const userSettingsProvider = createLocalStorageProvider({ name: 'user-settings', schemaVersion: 1, }); ``` -------------------------------- ### Nano-Build: ECMAScript/TypeScript Build Tool Source: https://context7.com/alwatr/nanolib/llms.txt A fast, zero-setup build and bundling tool for ECMAScript, TypeScript, and JavaScript libraries. It leverages esbuild for performance and offers various presets for different project types like modules, PWAs, and microservices. ```bash # Installation yarn add -D @alwatr/nano-build # Package.json scripts ``` ```json { "scripts": { "build": "nano-build --preset=module", "build:watch": "nano-build --preset=module --watch", "build:prod": "NODE_ENV=production nano-build --preset=module" } } ``` ```typescript // TypeScript configuration (tsconfig.json) { "extends": "@alwatr/tsconfig-base/tsconfig.json", "compilerOptions": { "rootDir": "src", "outDir": "dist", "emitDeclarationOnly": true, "composite": true, "types": ["@alwatr/nano-build"] }, "include": ["src/**/*.ts"] } // Custom configuration in package.json { "nano-build": { "bundle": true, "minify": false }, "nano-build-development": { "sourcemap": true, "minify": false }, "nano-build-production": { "sourcemap": false, "minify": true, "dropLabels": ["__dev_mode__"] } } ``` ```bash # Build commands yarn build # Build with module preset yarn build --preset=pwa # Build PWA yarn build --preset=microservice # Build microservice yarn build --watch # Watch mode NODE_ENV=production yarn build # Production build # Available presets: # - module: Single export module with bundling # - module2: Multiple exports from src/*.ts # - module3: Multiple exports without bundling # - pwa: Progressive Web App (browser, IIFE) # - microservice: Node.js service # - weaver: Browser component library ``` -------------------------------- ### Install and Use FlatString in TypeScript Source: https://github.com/alwatr/nanolib/blob/next/packages/flat-string/README.md This snippet shows how to install the '@alwatr/flat-string' package using yarn and then import and use the flatString function within a TypeScript application. The flatString function is designed to optimize string memory usage. ```bash yarn add @alwatr/flat-string ``` ```typescript import {flatString} from '@alwatr/flat-string'; myStr = flatString(myStr); ``` -------------------------------- ### Get Required Environment Variable Source: https://github.com/alwatr/nanolib/blob/next/packages/env/README.md Demonstrates how to get a required environment variable (API_KEY). If the API_KEY environment variable is not set, this call will throw an error, ensuring the application doesn't proceed without critical configuration. ```typescript const apiKey = getEnv({name: 'API_KEY'}); // Throws an error if API_KEY is not set ``` -------------------------------- ### Logger Instance Methods Source: https://github.com/alwatr/nanolib/blob/next/packages/logger/README.md The `createLogger` function returns a logger instance with various methods for logging messages, properties, method calls, and errors. Some methods are optional and only available in debug mode. ```APIDOC ## Logger Instance Methods The `createLogger` function returns a logger instance with the following methods. Methods marked with `?` (optional chaining) are only available when `debugMode` is `true`. ### `debugMode: boolean` Indicates if debug mode is active. ### `banner(message: string)` Logs a large, prominent banner message. Useful for versioning or startup messages. ### `logProperty?(propertyName: string, value: unknown)` Logs a property name and its value. Ideal for tracking state. ### `logMethod?(methodName: string)` Logs the entry into a function or method. ### `logMethodArgs?(methodName: string, args: unknown)` Logs a method call along with its arguments. ### `logMethodFull?(methodName: string, args: unknown, result: unknown)` Logs a method call with its arguments and the returned result. ### `logStep?(methodName: string, stepName: string, props?: unknown)` Logs specific steps within a method, useful for tracking progress in complex functions. ### `incident?(methodName: string, code: string, ...args: unknown[])` Logs an expected event or incident (informational). This uses `console.log` and is styled to be noticeable but not alarming. _Example: A user cancels a request._ ### `accident(methodName: string, code: string, ...args: unknown[])` Logs an unexpected incident or a handled error (warning) using `console.warn`. _Example: A file was not found, but the application can recover._ ### `error(methodName: string, code: string, ...args: unknown[])` Logs a critical, unexpected error using `console.error`. _Example: A database connection fails._ ### `logOther?(...args: unknown[])` A general-purpose logger with the standard scope styling. ### `time?(label: string)` / `timeEnd?(label: string)` Starts and ends a timer to measure performance. The label is automatically prefixed with the logger's scope. ``` -------------------------------- ### Run Yarn Upgrade CLI Tool Source: https://github.com/alwatr/nanolib/blob/next/packages/yarn-upgrade/README.md Execute the @alwatr/yarn-upgrade tool directly using Yarn's dlx command or npx. This is the primary method for running the upgrade process. ```bash yarn dlx @alwatr/yarn-upgrade ``` ```bash npx @alwatr/yarn-upgrade ``` -------------------------------- ### Overwrite Nano Build Configuration Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Customize @alwatr/nano-build behavior by adding configuration fields to your package.json. This allows for project-specific adjustments to bundling, minification, and sourcemaps. ```json { "nano-build": { "bundle": true }, "nano-build-development": { "minify": false, "sourcemap": true }, "nano-build-production": { "minify": true, "sourcemap": false } } ``` -------------------------------- ### Access GlobalThis Property with setTimeout in TypeScript Source: https://github.com/alwatr/nanolib/blob/next/packages/global-this/README.md Shows how to access a property set on globalThis within a setTimeout callback using TypeScript. This example highlights the persistence of global variables. ```typescript import {getGlobalThis} from '@alwatr/global-this'; getGlobalThis().setTimeout(() => { console.log(getGlobalThis<{alwatr: {foo: string}}>().alwatr.foo); // 'bar' }, 1_000); ``` -------------------------------- ### Validate Iranian National Code with ESM Source: https://github.com/alwatr/nanolib/blob/next/packages/iranian-national-code-validator/README.md Demonstrates how to import and use the `isValidIranianNationalCode` function from the library using ECMAScript modules (ESM). It shows examples of valid and invalid codes, including checks for format. ```typescript // src/main.ts import {isValidIranianNationalCode} from '@alwatr/iranian-national-code-validator'; console.log(`'0018550152' is valid: ${isValidIranianNationalCode('0018550152')}`); // true console.log(`'0018550153' is valid: ${isValidIranianNationalCode('0018550153')}`); // false // It also checks for the correct format (10 digits) console.log(`'12345' is valid: ${isValidIranianNationalCode('12345')}`); // false console.log(`'not-a-number' is valid: ${isValidIranianNationalCode('not-a-number')}`); // false ``` -------------------------------- ### Basic Logger Usage in TypeScript Source: https://github.com/alwatr/nanolib/blob/next/packages/logger/README.md Demonstrates the basic usage of Alwatr Logger in TypeScript. It shows how to create a logger instance with a scope, log method calls with arguments, and handle unexpected incidents. ```typescript import {createLogger} from '@alwatr/logger'; // Create a logger with a specific scope const logger = createLogger('my-app:main'); function greet(name: string) { // Log the method call with its arguments logger.logMethodArgs?.('greet', {name}); if (!name) { // Log an unexpected incident (a warning) logger.accident('greet', 'name_is_empty', 'Guest name was not provided.'); return; } console.log(`Hello, ${name}!`); } greet('Ali'); greet(''); ``` -------------------------------- ### Platform-Info: Detect Runtime Environment (TypeScript) Source: https://context7.com/alwatr/nanolib/llms.txt The Platform-Info module identifies the environment where the script is executing, such as browser, Node.js, Deno, Electron, or web workers. It provides the platform name, detects development mode (based on NODE_ENV or localhost), and offers boolean flags for various platform types. This enables conditional logic and feature loading based on the runtime. ```typescript import {platformInfo} from '@alwatr/platform-info'; // Platform identification console.log(platformInfo.name); // Outputs: 'browser' | 'node' | 'semi-node' | 'unknown' // Development mode detection if (platformInfo.development) { console.log('Running in development mode'); // Enable debug features, verbose logging, etc. } // Platform-specific logic if (platformInfo.isBrowser) { console.log('Running in browser'); // Use window, document, localStorage document.getElementById('app')?.classList.add('active'); } if (platformInfo.isNode) { console.log('Running in Node.js'); // Use fs, path, process import('fs').then(fs => { console.log('File system available'); }); } if (platformInfo.isWebWorker) { console.log('Running in Web Worker'); // Use self, postMessage self.postMessage({type: 'ready'}); } // Special runtime detection if (platformInfo.isDeno) { console.log('Running in Deno'); } if (platformInfo.isElectron) { console.log('Running in Electron app'); } if (platformInfo.isNw) { console.log('Running in NW.js'); } // Conditional feature loading async function loadFeatures() { if (platformInfo.isBrowser) { await import('./browser-features.js'); } else if (platformInfo.isNode) { await import('./node-features.js'); } } // Development vs Production behavior const apiUrl = platformInfo.development ? 'http://localhost:3000/api' : 'https://api.example.com'; ``` -------------------------------- ### Get API URL with Development Fallback Source: https://github.com/alwatr/nanolib/blob/next/packages/env/README.md Illustrates retrieving an API_URL environment variable. It provides a production default and a development-specific value. This is useful for switching between local and deployed API endpoints. ```typescript const apiUrl = getEnv({ name: 'API_URL', defaultValue: 'https://api.example.com', developmentValue: 'http://localhost:3000', }); ``` -------------------------------- ### Nano Build --preset=weaver Configuration Source: https://github.com/alwatr/nanolib/blob/next/packages/nano-build/README.md Configuration for the `--preset=weaver` option, similar to the PWA preset but potentially for different use cases. It targets browsers with specific ES versions and formats the output as IIFE. ```javascript { ...defaultPreset, entryPoints: ['src/ts/*.ts'], outdir: 'dist/es', platform: 'browser', format: 'iife', mangleProps: '_$', target: [ 'es2018', 'chrome62', 'edge79', 'firefox78', 'safari11', ], ...(devMode ? developmentOverwriteOptions : productionOverwriteOptions), } ``` -------------------------------- ### Validate Iranian National Code with CJS Source: https://github.com/alwatr/nanolib/blob/next/packages/iranian-national-code-validator/README.md Illustrates how to import and use the `isValidIranianNationalCode` function using CommonJS (CJS) modules. This example shows the same validation logic as the ESM version but adapted for Node.js environments that use `require`. ```javascript // main.js const {isValidIranianNationalCode} = require('@alwatr/iranian-national-code-validator'); console.log(`'0018550152' is valid: ${isValidIranianNationalCode('0018550152')}`); // true console.log(`'0018550153' is valid: ${isValidIranianNationalCode('0018550153')}`); // false ``` -------------------------------- ### Implement Cache Strategies with Nanolib Fetch Source: https://github.com/alwatr/nanolib/blob/next/packages/fetch/README.md Leverage browser Cache API with `cacheStrategy`. Options include 'network_only', 'cache_first', 'network_first', and 'stale_while_revalidate' for optimized content delivery. ```typescript // Serve news from cache instantly, but update it in the background for the next visit. const response = await fetch('/api/news', { cacheStrategy: 'stale_while_revalidate', revalidateCallback: (freshResponse) => { console.log('Cache updated with fresh data!'); // You can use freshResponse to update the UI if needed } }); ``` -------------------------------- ### Enable Alwatr Prettier Config in package.json Source: https://github.com/alwatr/nanolib/blob/next/packages/prettier-config/README.md Configures Prettier to use Alwatr's shareable configurations by adding a `prettier` property to the `package.json` file. This enables consistent code formatting across the project. ```json { "prettier": "@alwatr/prettier-config" } ``` -------------------------------- ### Create and Trigger Debouncer Instance (TypeScript) Source: https://github.com/alwatr/nanolib/blob/next/packages/debounce/README.md Demonstrates how to create a debouncer instance using the `createDebouncer` factory function and trigger it multiple times. This example shows the default trailing edge behavior where the function executes after a delay. ```typescript import {createDebouncer} from '@alwatr/debounce'; // 1. Create a debouncer instance const debouncer = createDebouncer({ // The function you want to debounce func: (query: string) => { console.log(`Searching for: ${query}`); }, // The delay in milliseconds delay: 300, }); // 2. Trigger it multiple times console.log('User is typing...'); debouncer.trigger('Alw'); debouncer.trigger('Alwat'); debouncer.trigger('Alwatr'); // After 300ms of inactivity, the console will log: // "Searching for: Alwatr" ``` -------------------------------- ### TypeScript Usage with Duration Types (TypeScript) Source: https://github.com/alwatr/nanolib/blob/next/packages/parse-duration/README.md Shows how to leverage TypeScript's type safety with the Alwatr Parse Duration library. It includes examples of using the imported types like `DurationUnit` and `Duration` for more robust code. ```typescript import {parseDuration, DurationUnit, Duration} from '@alwatr/parse-duration'; // Type-safe unit parameter function waitFor(time: Duration): Promise { const ms = parseDuration(time); return new Promise((resolve) => setTimeout(resolve, ms)); } // Usage await waitFor('5s'); ``` -------------------------------- ### Get Environment Variable with Default and Development Values Source: https://github.com/alwatr/nanolib/blob/next/packages/env/README.md Demonstrates how to retrieve an environment variable using getEnv. It includes a name, a default value for production, and a specific value for development environments. The output will prioritize the development value if the code is run in a development context. ```typescript import {getEnv} from '@alwatr/env'; const env = getEnv({ name: 'MY_ENV_VAR', defaultValue: 'default-value', developmentValue: 'development-value', }); console.log(env); // Output: 'development-value' in development mode, 'default-value' if MY_ENV_VAR is not set in production mode. ``` -------------------------------- ### Basic Flatomise Usage in TypeScript Source: https://github.com/alwatr/nanolib/blob/next/packages/flatomise/README.md Demonstrates how to create and use a Flatomise promise in TypeScript. It shows importing the utility, creating a promise, attaching a .then() handler, and then resolving the promise externally. This is useful for scenarios requiring manual promise control. ```typescript import {newFlatomise} from '@alwatr/flatomise'; const flatomise = newFlatomise(); flatomise.promise.then(() => { console.log('flatomise resolved'); }); flatomise.resolve(); ``` -------------------------------- ### Convert Bytes to Hexadecimal String (TypeScript) Source: https://github.com/alwatr/nanolib/blob/next/packages/random/README.md The `bytesToHex` function transforms a `Uint8Array` or a number array into a hexadecimal string. It ensures each byte is represented by two hexadecimal characters, padding with a leading zero when necessary. Example usage demonstrates converting both `Uint8Array` and number arrays. ```typescript const bytes = new Uint8Array([10, 255, 0, 16]); const hex = bytesToHex(bytes); // "0aff0010" const array = [171, 205, 3]; const hex2 = bytesToHex(array); // "abcd03" ``` -------------------------------- ### Query Parameters Source: https://github.com/alwatr/nanolib/blob/next/packages/fetch/README.md Demonstrates how to use the `queryParams` option to easily append search parameters to the request URL. ```APIDOC ## Query Parameters The `queryParams` option simplifies adding search parameters to your request URL. ### Method `fetch` ### Endpoint `/api/users` ### Parameters #### Query Parameters - **`page`** (number) - Optional - The page number. - **`sort`** (string) - Optional - The sorting order (e.g., 'asc', 'desc'). ### Request Example ```javascript // This will make a GET request to: // /api/users?page=2&sort=asc const response = await fetch('/api/users', { queryParams: { page: 2, sort: 'asc', }, }); ``` ### Response #### Success Response (200) - **`response`** (Response) - The standard Fetch API Response object. ``` -------------------------------- ### Plain Class Example with Debouncer Source: https://github.com/alwatr/nanolib/blob/next/packages/debounce/README.md Demonstrates how to use `createDebouncer` within a plain JavaScript class. It shows event listener attachment and the crucial `cancel()` call in the `destroy` method to prevent memory leaks, ensuring the debouncer's internal timers do not hold references to the component. ```typescript class MyComponent { private debouncer = createDebouncer({ func: this.doSomething, thisContext: this, // Bind `this` correctly! delay: 500, }); constructor() { window.addEventListener('resize', this.debouncer.trigger); } doSomething() { console.log('Window resized!', this); } // The crucial cleanup method destroy() { window.removeEventListener('resize', this.debouncer.trigger); this.debouncer.cancel(); // Prevents memory leaks! console.log('Component destroyed and debouncer cleaned up.'); } } ``` -------------------------------- ### Generate Hashes with nanoHash and djb2Hash - TypeScript Source: https://context7.com/alwatr/nanolib/llms.txt Generates simple, fast, non-cryptographic hash strings from input values using the nanoHash function. Supports string and number inputs, configurable complexity via repeat parameters, and includes the DJB2 algorithm for numeric hashes. Useful for IDs, cache keys, and checksums. Requires installation of '@alwatr/hash-string'. ```typescript import {nanoHash, djb2Hash} from '@alwatr/hash-string'; // Generate hash with prefix const userId = nanoHash('john.doe@example.com', 'user-'); console.log(userId); // 'user-k7f2h9d' // Hash for cache key const cacheKey = nanoHash( JSON.stringify({page: 1, filter: 'active'}), 'cache-' ); console.log(cacheKey); // 'cache-p83b2e4' // Adjust complexity (more repeats = more complex) const simpleHash = nanoHash('password', 'pwd-', 1); // Fast const complexHash = nanoHash('password', 'pwd-', 5); // More secure // Same input always produces same output const hash1 = nanoHash('test', 'x-'); const hash2 = nanoHash('test', 'x-'); console.log(hash1 === hash2); // true // Different inputs produce different outputs console.log( nanoHash('test1', 'x-') !== nanoHash('test2', 'x-') ); // true // DJB2 algorithm for numeric hash const numericHash = djb2Hash('hello world'); console.log(numericHash); // 894552257 (32-bit unsigned integer) // Use cases const contentId = nanoHash(articleContent, 'article-'); const sessionToken = nanoHash(userId + timestamp, 'session-', 3); const checksum = nanoHash(fileContent, 'cs-'); ```