### Quick Start Example Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/installation.mdx After installation, import the functions you need and use them. ```typescript import { ok, err, map, Result } from "@deessejs/fp"; // Create a Result - explicit about potential failure const divide = (a: number, b: number): Result => { if (b === 0) return err("Cannot divide by zero"); return ok(a / b); }; // Use it - TypeScript forces you to handle errors const result = divide(10, 2) .map(x => x * 2) .getOrElse(0); console.log(result); // 5 ``` -------------------------------- ### The "Hello World" Pattern Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Starting each concept with the simplest possible example. ```markdown Start each concept with the simplest possible example: ```markdown ``` -------------------------------- ### Running Examples Source: https://github.com/nesalia-inc/fp/blob/main/examples/README.md Instructions on how to install tsx and run an example. ```bash # Install tsx globally if needed npm install -g tsx # Run an example tzx examples/http-api/index.ts ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/conversions/README.md Command to run the conversion example. ```bash tsx examples/conversions/index.ts ``` -------------------------------- ### All Exports Example Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/installation.mdx Import everything if needed. ```typescript import * as Deesse from "@deessejs/fp"; Deesse.ok(42); Deesse.err("error"); ``` -------------------------------- ### React Documentation Structure Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md An example of the documentation structure used by React. ```markdown /learn/ # Tutorials /reference/react/ # Hooks API reference /community/ # Community resources ``` -------------------------------- ### Introduction Section Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Example content for the introduction section of a documentation page, explaining the 'what' and 'why'. ```markdown ## Introduction Error handling in TypeScript is traditionally complex. Exceptions can escape unexpectedly, error types are not statically verified, and error handling code quickly becomes nested and difficult to maintain. The `Result` type solves this by making errors **explicit in the type signature**. Instead of hoping a function won't throw, the return type clearly indicates whether the operation can fail. ``` -------------------------------- ### Page Frontmatter Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Example of YAML frontmatter for a documentation page. ```yaml --- title: Result description: Type-safe success and failure handling --- ``` -------------------------------- ### Development Setup Source: https://github.com/nesalia-inc/fp/blob/main/CONTRIBUTING.md Commands to install dependencies and enable husky hooks for development. ```bash pnpm install pnpm prepare ``` -------------------------------- ### Quick Start Examples Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/async-result.md Demonstrates creating success and failure AsyncResults, and wrapping promises. ```typescript import { okAsync, errAsync, fromPromise, isOk, isErr } from '@deessejs/fp'; // Create a success const success: AsyncResult = okAsync(42); // Create a failure const failure: AsyncResult = errAsync('Something went wrong'); // Wrap a promise const result = fromPromise(fetch('https://api.example.com')); ``` -------------------------------- ### Creation Section Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Example content for the creation section of a documentation page, explaining how to create a Result type. ```markdown ## Creating a Result There are two ways to create a Result: success or failure. ``` -------------------------------- ### Code-First Approach - FastAPI Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Example of a code-first approach in FastAPI documentation, showing code before explanation. ```markdown The simplest FastAPI file could look like this: ```python from fastapi import FastAPI app = FastAPI() @app.get("/") async def root(): return {"message": "Hello World"} ``` Copy that to a file `main.py`. Run the live server: ... ``` -------------------------------- ### CommonJS Import Example Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/installation.mdx If you're using CommonJS, import like this. ```typescript import { ok } from "@deessejs/fp/index.js"; ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/auth/README.md Command to run the authentication example. ```bash tsx examples/auth/index.ts ``` -------------------------------- ### Step-by-Step Writing Style - FastAPI Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Example of a step-by-step writing style in FastAPI documentation. ```markdown ## Step 1: Import FastAPI ```python from fastapi import FastAPI ``` ## Step 2: Create the App ```python app = FastAPI() ``` ## Step 3: Define a Route ... ``` -------------------------------- ### FastAPI Documentation Structure Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md An example of the documentation structure used by FastAPI. ```markdown /learn/ /tutorial/ # First Steps, Path Parameters, Query Parameters... /advanced/ # Advanced topics /deployment/ # Deployment guides /reference/ # FastAPI, Request, Response... /how-to/ # Recipes ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/file-system/README.md Command to run the file system example. ```bash tsx examples/file-system/index.ts ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/parallel-fetch/README.md Command to run the parallel fetch example. ```bash tsx examples/parallel-fetch/index.ts ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/resilience/README.md Command to run the resilience example. ```bash tsx examples/resilience/index.ts ``` -------------------------------- ### Install the Package Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/installation.mdx Install `@deessejs/fp` using your preferred package manager. ```bash # pnpm (recommended) pnpm add @deessejs/fp # npm npm install @deessejs/fp # yarn yarn add @deessejs/fp ``` -------------------------------- ### Quick Start Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/result.md A basic example showing how to create success and failure Result instances. ```typescript import { ok, err, isOk, isErr } from '@deessejs/fp'; // Success const success: Result = ok(42); // Failure const failure: Result = err('Something went wrong'); ``` -------------------------------- ### Getting Started with @deessejs/fp Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/what-is.mdx An example demonstrating basic usage of Result and Maybe types from @deessejs/fp. ```typescript import { ok, err, map, getOrElse, some, none } from "@deessejs/fp"; // Create a Result const success = ok(42); const failure = err("Something went wrong"); // Transform without losing error context const result = ok(10) .map(x => x * 2) .map(x => x + 1); // Extract the value const value = result.getOrElse(0); // Work with optional values const name = some("Alice"); const noName = none(); const greeting = name .map(n => `Hello, ${n}!`) .getOrElse("Hello, stranger!"); ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/cli-args/README.md Examples of how to run the CLI tool with different arguments and flags. ```bash # Basic usage tsx examples/cli-args/index.ts --input in.txt --output out.txt # With flags tsx examples/cli-args/index.ts --input in.txt --output out.txt --verbose --threads 4 # Subcommands tsx examples/cli-args/index.ts build --prod --verbose # Show help tsx examples/cli-args/index.ts --help ``` -------------------------------- ### Installation Source: https://github.com/nesalia-inc/fp/blob/main/docs/learnings/fumadocs/components/steps.md Install the steps component using the Fumadocs CLI. ```bash npx @fumadocs/cli add steps ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/config/README.md Commands to set environment variables and run the TypeScript example. ```bash # Set some environment variables for testing export PORT=8080 export DEBUG=true export NODE_ENV=production tsx examples/config/index.ts ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/form-validation/README.md Command to execute the form validation example. ```bash tsx examples/form-validation/index.ts ``` -------------------------------- ### Good Example: Transforming Values with map Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md An example of documentation that explains the 'why' and 'how' of using the map function, including error handling. ```typescript ## Transforming Values When working with a `Result`, you often want to transform the value it contains without losing the error context. This is exactly what `map` does. Imagine you have a function that divides two numbers: ```typescript const divide = (a: number, b: number): Result => { if (b === 0) return err("Division by zero"); return ok(a / b); }; const result = divide(10, 2); // How do we transform this result to get the square of the quotient? ``` Use `map` to apply a transformation: ```typescript const quotient = divide(10, 2) .map(x => x * x); // Transforms 5 to 25 quotient.value; // 25 ``` If the result is an error, `map` does nothing—the error is preserved: ```typescript const failed = divide(10, 0) .map(x => x * x); failed.error; // "Division by zero" - error is preserved ``` ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/http-api/README.md Command to run the example from the project root. ```bash # From the project root tsx examples/http-api/index.ts ``` -------------------------------- ### Quick Start Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/retry.md Provides basic examples for using both synchronous (`retry`) and asynchronous (`retryAsync`) retry utilities. ```typescript import { retry, retryAsync } from '@deessejs/fp'; // Sync operations const result = retry(() => riskyOperation()); // Async operations (recommended) const result = await retryAsync(() => fetch('/api/data')); ``` -------------------------------- ### Pattern 1: Good Opening Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md An example of a good opening for documentation, starting with the problem the function solves. ```markdown ## Transforming Values Without Losing Context When you're working with a Result, you often need to transform the value it contains—but you can't just call a regular function on it. If you do, you'll lose the error context. For example, say you have a division function that returns a Result... ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/logging/README.md Command to run the logging example. ```bash tsx examples/logging/index.ts ``` -------------------------------- ### Installation Source: https://github.com/nesalia-inc/fp/blob/main/README.md Install the core package using npm, pnpm, or yarn. ```bash # Install core npm install @deessejs/fp # Or using pnpm pnpm add @deessejs/fp # Or using yarn yarn add @deessejs/fp ``` -------------------------------- ### Step-by-Step Writing Example - Import Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md Example of a step-by-step writing pattern for importing. ```typescript import { ok, err } from '@deessejs/fp'; ``` -------------------------------- ### React Structure Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md Example of how React structures its documentation. ```text /learn/ # Tutorials /reference/react/ # Hooks API ``` -------------------------------- ### Running the Example Source: https://github.com/nesalia-inc/fp/blob/main/examples/json-parsing/README.md Command to run the TypeScript example. ```bash tsx examples/json-parsing/index.ts ``` -------------------------------- ### Installation Source: https://github.com/nesalia-inc/fp/blob/main/docs/learnings/fumadocs/components/banner.md Install the banner component using the Fumadocs CLI. ```bash npx @fumadocs/cli add banner ``` -------------------------------- ### Installation Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/analysis/neverthrow.md Install the @deessejs/fp package using npm. ```bash npm install @deessejs/fp ``` -------------------------------- ### Explain 'Why' Not Just 'What' Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/rules/writing-style.md An example contrasting a 'what only' explanation with one that includes the 'why'. ```mdx // Just what Use `context` for static dependencies. // What and why Use `context` for static dependencies. This is simpler and works great when your services are already initialized at module load time. ``` -------------------------------- ### Step-by-Step Writing Example - Create Success Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md Example of a step-by-step writing pattern for creating a success Result. ```typescript const result = ok(42); ``` -------------------------------- ### FastAPI Structure Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md Example of how FastAPI structures its documentation. ```text /learn/tutorial/ # First Steps, Path Params, Query Params... /reference/ # FastAPI, Request, Response... /how-to/ # Recipes ``` -------------------------------- ### Step-by-Step Writing Example - Handle Failure Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md Example of a step-by-step writing pattern for handling failure. ```typescript const failed = err("Error message"); ``` -------------------------------- ### Default Starting Tab Source: https://github.com/nesalia-inc/fp/blob/main/docs/learnings/fumadocs/components/tabs.md Illustrates how to set the default starting tab using the `defaultIndex` prop. ```mdx ... ... ``` -------------------------------- ### Complete Example Source: https://github.com/nesalia-inc/fp/blob/main/skills/rules/sleep-retry.md An example demonstrating how to fetch data with retries and timeouts using the @deessejs/fp library. ```typescript import { retryAsync, sleep, withTimeout } from '@deessejs/fp'; const fetchWithRetry = async (url: string, options = {}) => { const { attempts = 3, delay = 1000, timeout = 5000 } = options; return withTimeout( retryAsync( () => fetch(url).then(async r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); }), { attempts, delay, backoff: 'exponential', maxDelay: 10000, jitter: true } ), timeout ); }; try { const data = await fetchWithRetry('/api/users/1', { attempts: 5 }); } catch (e) { if (e.name === 'TIMEOUT') { console.error('Request timed out after retries'); } else { console.error('Request failed:', e.message); } } ``` -------------------------------- ### Avoid Isolated Examples Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Contrasts an isolated code example with a preferred example that shows chaining and real use cases. ```typescript // You have a validation function const validateEmail = (email: string): Result => { if (!email.includes('@')) return err("Invalid email"); return ok(email); }; // How to chain with transformation? const result = ok("user@example.com") .flatMap(validateEmail) .map(email => email.toLowerCase()); ``` -------------------------------- ### Recap at the End of Every Page - FastAPI Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Example of a recap section at the end of a FastAPI documentation page. ```markdown ## Recap - Import FastAPI - Create an app instance - Define routes with decorators - Run the server [Next: Path Parameters →] ``` -------------------------------- ### Walkthrough Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md Demonstrates how to trace the execution of a Result object, explaining success and failure cases. ```typescript const result = ok(10) .map(x => x * 2) .getOrElse(0); // Let's trace through this: // 1. ok(10) creates Ok(10) // 2. .map(x => x * 2) transforms to Ok(20) // 3. .getOrElse(0) extracts 20 because it's a success // If any step had been an error, getOrElse would return 0 instead ``` -------------------------------- ### Technical Details in Collapsible Sections - FastAPI Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Example of using collapsible sections for technical details in FastAPI documentation. ```markdown ## Step 2: Create the App ```python app = FastAPI() ``` Here the `app` variable will be an "instance" of the class `FastAPI`. > **Technical Details** > > `FastAPI` is a class that inherits directly from `Starlette`. > You can use all Starlette functionality with `FastAPI` too. ``` -------------------------------- ### Result.allSettled Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/deps/DEP-0001-RESULT.md Example demonstrating the usage of Result.allSettled to get all outcomes, including errors. ```typescript const results = await Result.allSettled([ fetchUser("1"), fetchUser("2"), fetchUser("3"), ]); // Ok[]> // Each element is either { ok: true, value: User } or { ok: false, error: UserError } results.value.forEach(outcome => { if (outcome.ok) { console.log("Success:", outcome.value); } else { console.error("Failed:", outcome.error); } }); ``` -------------------------------- ### Installation (agents) Source: https://github.com/nesalia-inc/fp/blob/main/docs/reports/design/homepage-first-version.md The command to add the @deessejs/fp package using agents. ```bash npx skills add deessejs/fp ``` -------------------------------- ### Correct Documentation Style Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md An example of documentation that focuses on the problem and its solution. ```markdown ## Type-Safe Error Handling Every JavaScript developer faces this problem: you call a function that can fail, but there's no way to know from the type system whether it throws or what it throws. Exceptions escape, error types are unknown, and the compiler can't help you. This guide explains how to handle errors in a way that: - Makes potential failures explicit in the type signature - Forces the compiler to verify you've handled every error case - Turns runtime errors into compile-time errors ``` -------------------------------- ### Create Results Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/index.md Create Results using the ok() and err() factory functions. ```typescript import { ok, err, isOk } from '@deessejs/fp'; // Create a success result const success = ok(42); // { ok: true, value: 42 } // Create a failure result const failure = err('Something went wrong'); // { ok: false, error: 'Something went wrong' } ``` -------------------------------- ### Parsing Function with Exception Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md An example of a parsing function that throws an exception and how to handle it with try-catch. ```typescript const parseInt = (s: string): number => { const n = Number(s); if (isNaN(n)) throw new Error("Invalid number"); return n; }; try { const n = parseInt(userInput); // ... } catch (e) { // How to handle this error? } ``` -------------------------------- ### File Operations Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/core/try.mdx This example shows how to safely read and parse a JSON configuration file. ```typescript import { attempt } from '@deessejs/fp'; import { readFileSync } from 'fs'; const readJsonFile = (path: string) => attempt(() => JSON.parse(readFileSync(path, 'utf-8'))); const config = readJsonFile('./config.json'); if (config.ok) { console.log('Config loaded:', config.value); } else { console.error('Failed:', config.error.message); } ``` -------------------------------- ### Incorrect Documentation Style Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md An example of documentation that focuses on the API rather than the problem it solves. ```markdown ## Result The Result type represents a value that can be either a success or a failure. ``` -------------------------------- ### Composing with pipe Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/index.md Shows how to use the pipe function from @deessejs/fp for readable function composition. ```typescript import { pipe } from '@deessejs/fp'; const result = pipe( ' hello world ', s => s.trim(), s => s.toUpperCase(), s => s.split('').reverse().join('') ); // 'DLROW OLLEH' ``` -------------------------------- ### Validation Function returning Result Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md An example of a validation function that returns a `Result` to enforce error handling. ```typescript const validateAge = (age: number): Result => { if (age < 0) return err("Age cannot be negative"); if (age > 150) return err("Invalid age"); return ok(age); }; ``` -------------------------------- ### Quick Start Imports Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/conversions.md Imports necessary conversion utilities from the @deessejs/fp library. ```typescript import { toResult, toMaybeFromResult, fromUndefinedable } from '@deessejs/fp'; ``` -------------------------------- ### Quick Start Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/maybe.md Shows how to create present and absent Maybe values, and how to convert nullable types to Maybe. ```typescript import { some, none, fromNullable, isSome, isNone } from '@deessejs/fp'; // Present value const present: Maybe = some(42); // Absent value const absent: Maybe = none(); // From nullable (null or undefined becomes None) const maybe = fromNullable(getUserById(123)); ``` -------------------------------- ### Migration Path Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/analysis/roadmap/10-enterprise-trust.md Addresses CTO concerns about future breaking changes by listing available migration guides. ```markdown ## Migration Guide - [Migrating from v2 to v3](./docs/migration/v2-to-v3.md) - In progress - [Migrating from neverthrow](./docs/migration/neverthrow.md) - Complete - [Migrating from fp-ts](./docs/migration/fp-ts.md) - Complete Future migration guides will be published alongside major releases. ``` -------------------------------- ### API Reference vs. Guide Documentation Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Illustrates the difference between listing API methods and explaining how to solve a problem. ```markdown - **Reference API**: "What methods does Result have?" - **Guide Documentation**: "How do I handle errors safely in TypeScript?" ``` -------------------------------- ### Chaining (flatMap) Source: https://github.com/nesalia-inc/fp/blob/main/docs/deps/DEP-0003-MAYBE.md Examples of chaining operations that can return a Maybe using flatMap, in both direct and pipeable styles. Includes finding a user and getting their email. ```typescript interface User { id: number; name: string; } const findUser = (id: number): Maybe => id > 0 ? some({ id, name: 'John' }) : none(); const getEmail = (user: User): Maybe => some(user.name.toLowerCase() + '@example.com'); const email = some(1).flatMap(findUser).flatMap(getEmail); // Some('john@example.com') const noEmail = some(-1).flatMap(findUser).flatMap(getEmail); // None // Pipeable style: const email = pipe( some(1), Maybe.flatMap(findUser), Maybe.flatMap(getEmail) ); ``` -------------------------------- ### Quick Start Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/try.md Shows basic usage of attempt and attemptAsync for synchronous and asynchronous operations. ```typescript import { attempt, attemptAsync, isOk, isErr } from '@deessejs/fp'; // Sync: wrap any throwing function const result = attempt(() => JSON.parse('{"valid": true}')); // Async: wrap async functions that might reject const asyncResult = await attemptAsync(fetch('https://api.example.com')); ``` -------------------------------- ### Installation Source: https://github.com/nesalia-inc/fp/blob/main/docs/learnings/fumadocs/twoslash.md Install fumadocs-twoslash and twoslash packages. ```bash npm install fumadocs-twoslash twoslash ``` -------------------------------- ### Safe Division Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/index.md Demonstrates how to handle division by zero using the Result type from @deessejs/fp. ```typescript import { ok, err, flatMap, getOrElse } from '@deessejs/fp'; const safeDivide = (a: number, b: number) => b === 0 ? err('Cannot divide by zero') : ok(a / b); // Usage const result = safeDivide(10, 2) .flatMap(x => safeDivide(x, 2)) // 10 / 2 = 5, then 5 / 2 = 2.5 .flatMap(x => safeDivide(x, 0)); // Error! console.log(getOrElse(result, 0)); // 0 (because of the error) ``` -------------------------------- ### Using try/catch vs Result for Expected Errors Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/index.md Demonstrates why using Result is preferred over try/catch for expected error conditions. ```typescript // ❌ Bad: Using exceptions for expected failures function findUser(id: string): User { const user = database.find(id); if (!user) throw new Error('User not found'); // Exceptions are for UNEXPECTED errors return user; } // ✅ Good: Use Result for expected failures import { ok, err } from '@deessejs/fp'; function findUser(id: string): Result { const user = database.find(id); if (!user) return err(new Error('User not found')); return ok(user); } ``` -------------------------------- ### Do This: Show the ugly before the clean Source: https://github.com/nesalia-inc/fp/blob/main/docs/reports/reddit/guidelines/01-posting-principles.md An example of code that demonstrates the 'ugly' before the 'clean' solution, highlighting the problem. ```typescript // Show the ugly before the clean try { const user = JSON.parse(data); const post = await fetchPost(user.id); const comment = await fetchComment(post.commentId); } catch (e) { // Which step failed? No idea. } ``` -------------------------------- ### Install the library Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/what-is.mdx Command to install the @deessejs/fp library using pnpm. ```bash pnpm add @deessejs/fp ``` -------------------------------- ### Creating a Successful Result Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Demonstrates the simplest way to create a successful Result instance. ```typescript const result = ok(42); ``` -------------------------------- ### The problem with try/catch Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/index.md Illustrates the type safety issue with traditional try/catch blocks. ```typescript // ❌ The problem with try/catch function parseJSON(input: string): User { return JSON.parse(input); // Type says returns User, but can throw! } // TypeScript has no idea this can fail const user = parseJSON(data); // Might crash! ``` -------------------------------- ### Individual Imports Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/installation.mdx Import only what you need for smaller bundles. ```typescript import { ok, err, map, getOrElse } from "@deessejs/fp"; ``` -------------------------------- ### Third Person Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/rules/writing-style.md Another example of third-person phrasing to avoid. ```mdx "The context should be kept minimal to avoid unnecessary overhead." ``` -------------------------------- ### Usage Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/learnings/fumadocs/layouts/docs-layout.md Example of how to use the DocsLayout component in a React application. ```tsx import { DocsLayout } from 'fumadocs-ui/layouts/docs'; import { source } from '@/lib/source'; export default function Layout({ children }) { return ( {children} ); } ``` -------------------------------- ### Explicit error handling with @deessejs/fp Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/content/docs/index.md Demonstrates how @deessejs/fp enforces explicit error handling, making code safer. ```typescript // ✅ Explicit error handling import { ok, err, isOk } from '@deessejs/fp'; function parseJSON(input: string): Result { try { return ok(JSON.parse(input)); } catch (e) { return err(e instanceof Error ? e : new Error(String(e))); } } // Now TypeScript knows this can fail const result = parseJSON(data); if (isOk(result)) { console.log(result.value.name); // Safe! } else { console.error('Parse failed:', result.error.message); } ``` -------------------------------- ### Real-World Example: With AsyncResult Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/pipe.md Demonstrates the current approach for working with AsyncResult types. ```typescript import { okAsync, mapAsync, flatMapAsync, match } from '@deessejs/fp'; // Current approach const result = await okAsync(userId) .flatMapAsync(fetchUser) .mapAsync(u => u.email) .match( email => sendEmail(email), err => handleError(err) ); ``` -------------------------------- ### Quick Start Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/features/sleep.md Demonstrates the basic usage of `sleep`, `withTimeout`, and `sleepWithSignal` for common asynchronous delay and timeout patterns. ```typescript import { sleep, withTimeout, sleepWithSignal } from '@deessejs/fp'; // Simple delay await sleep(1000); // Wait 1 second // With timeout const result = await withTimeout(fetch('/api/data'), 5000); // Cancellable sleep const controller = new AbortController(); await sleepWithSignal(5000, controller.signal); controller.abort(); // Cancels the sleep ``` -------------------------------- ### Installation Source: https://github.com/nesalia-inc/fp/blob/main/docs/learnings/fumadocs/components/graph-view.md Install the Graph View component using the Fumadocs CLI. ```bash npx @fumadocs/cli add graph-view ``` -------------------------------- ### Installation Source: https://github.com/nesalia-inc/fp/blob/main/docs/learnings/fumadocs/components/auto-type-table.md Command to install the necessary package for the AutoTypeTable functionality. ```bash npm i fumadocs-typescript ``` -------------------------------- ### Code-First Approach - Apply to Our Docs Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/README.md Applying the code-first approach to our documentation. ```markdown The simplest example creates a successful Result: ```typescript const result = ok(42); ``` That's it. You've created a Result that represents a successful operation with the value `42`. But what if something goes wrong? ... ``` -------------------------------- ### Second Person Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/rules/writing-style.md A corresponding example using the preferred second-person phrasing. ```mdx "Keep your context minimal to avoid unnecessary overhead." ``` -------------------------------- ### Development Server Commands Source: https://github.com/nesalia-inc/fp/blob/main/apps/web/README.md Commands to run the development server using npm, pnpm, or yarn. ```bash npm run dev # or pnpm dev # or yarn dev ``` -------------------------------- ### Recap Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/internal/guides/documentation/PATTERNS.md Example of a recap section at the end of a documentation page. ```markdown ## Recap - Use `ok(value)` for successful operations - Use `err(message)` for failures - TypeScript forces you to handle both cases [See also: Chaining Operations →] ``` -------------------------------- ### Approach 4: Better Documentation Example Source: https://github.com/nesalia-inc/fp/blob/main/docs/reports/issues/303-usability-deep-analysis.md An example of how documentation could show correct imports for actual working code. ```typescript // In docs - show actual working code import { attempt, mapTry, flatMapTry } from '@deessejs/fp'; const result = mapTry(attempt(() => 42), x => x * 2); ```