A library of assertion functions.
+If the assertion is false an AssertionError
will be thrown which will
+result in pretty-printed diff of the failing assertion.
This module is browser compatible, but do not rely on good formatting of +values for AssertionError messages in browsers.
+ +```js +import { assert } from "@std/assert"; + +assert("I am truthy"); // Doesn't throw +assert(false); // Throws `AssertionError` +``` + +### Add to your project + +```sh +deno add jsr:@std/assert +``` + +See all +symbols in @std/assert on + + + + +## What is an assertion? + +An assertion is a check that must be true. If it isn’t, the program throws an +`AssertionError` with a helpful message and diff so you can quickly spot what +went wrong. + +In tests, assertions verify behavior. In application code, they can document and +guard invariants (preconditions/postconditions). In TypeScript, some assertions +(like `assert(condition)`) also narrow types after the check. + +## When to use @std/assert? + +The utilities in this package make test failures clear and actionable ( allowing +for pretty diffs and focused messages). Improve the readability of your tests by +codifying expectations in-line. + +Assertions help to prevent silent bugs by failing fast when assumptions are +violated. + +Use assertions liberally in your tests to verify behavior and catch regressions. + +## Examples + +```ts +import { + assert, + assertAlmostEquals, + assertArrayIncludes, + assertEquals, + assertExists, + assertFalse, + assertMatch, + assertNotEquals, + assertObjectMatch, + assertRejects, + assertStrictEquals, + assertThrows, +} from "@std/assert"; + +// Basic truthiness and type narrowing +const value: unknown = "hello"; +assert(typeof value === "string", "Expected a string"); +// value is now narrowed to string + +// Deep structural equality (objects/arrays) +assertEquals({ a: 1, b: [1, 2] }, { a: 1, b: [1, 2] }); +assertNotEquals([1, 2], [1, 2, 3]); + +// Strict (reference/identity) equality for primitives/refs +assertStrictEquals(1, 1); +assertFalse(false); +assertExists("non-empty"); // not null or undefined + +// Pattern & numeric comparisons +assertMatch("deno.land", /deno/); +assertAlmostEquals(0.1 + 0.2, 0.3, 1e-15); + +// Collections +assertArrayIncludes([1, 2, 3], [2, 3]); +assertObjectMatch( + { id: 42, name: "A", meta: { ok: true } }, + { name: "A", meta: { ok: true } }, // subset must match +); + +// Errors: sync vs async +assertThrows(() => JSON.parse("not json"), SyntaxError); +await assertRejects(() => fetch("https://deno.land/404")); +``` + +## Choosing the right equality + +Assertions for equality come in two main flavors: + +### `assertEquals` + +Compares values recursively by structure and content. For arrays, order matters; +for plain objects, key order doesn’t. It’s best for comparing serialized-style +data (objects, arrays, numbers, strings, booleans). + +### `assertStrictEquals` + +Checks that both operands are the exact same value (for primitives) or reference +(for objects), using semantics similar to `Object.is`. + +For example:Provide helpers with asynchronous tasks like delays
,
+debouncing
, retrying
, or
+pooling
.
Helper functions for working with
+Uint8Array
+byte slices.
In-memory cache utilities, such as memoization and caches with different +expiration policies.
+ +```js +import { memoize, LruCache, type MemoizationCacheResult } from "@std/cache"; +import { assertEquals } from "@std/assert"; + +const cache = new LruCacheConcise Binary Object Representation (CBOR) is a binary data serialisation +format optimised for compactness and efficiency. It is designed to encode a +wide range of data types, including integers, strings, arrays, and maps, in a +space-efficient manner. +RFC 8949 - Concise Binary Object Representation (CBOR) +spec.
+Functions and classes may have more specific limitations listed.
+ +```js +import { assert, assertEquals } from "@std/assert"; +import { decodeCbor, encodeCbor } from "@std/cbor"; + +const rawMessage = "I am a raw Message!"; + +const encodedMessage = encodeCbor(rawMessage); +const decodedMessage = decodeCbor(encodedMessage); + +assert(typeof decodedMessage === "string"); +assertEquals(decodedMessage, rawMessage); +``` + +### Add to your project + +```sh +deno add jsr:@std/cbor +``` + +See all symbols +in @std/cbor on + + + + +## What is CBOR? + +CBOR (Concise Binary Object Representation) is like a binary version of JSON. It +stores data in a compact binary format instead of text, which reduces size and +speeds up parsing. + +It supports all the common types (numbers, strings, booleans, null, arrays, +maps) plus binary data and big integers. CBOR is typically used for sending data +over the network (ideal for IoT or mobile devices where there is limited +bandwidth), storing compact payloads, and interop between languages. + +## Why use @std/cbor? + +This package provides simple functions to encode JavaScript objects to CBOR +binary and decode CBOR binary back to JavaScript objects. + +## Examples + +```ts +import { decodeCbor, encodeCbor } from "@std/cbor"; + +const obj = { t: "temp", v: 21.5, ts: Date.now() }; +const bin = encodeCbor(obj); +const back = decodeCbor(bin); +``` + +### Binary data (Uint8Array) + +```ts +import { decodeCbor, encodeCbor } from "@std/cbor"; + +const bytes = new TextEncoder().encode("hello"); +const encoded = encodeCbor(bytes); +const decoded = decodeCbor(encoded); + +if (!(decoded instanceof Uint8Array)) throw new Error("expected bytes"); +console.log(new TextDecoder().decode(decoded)); // "hello" +``` + +### Big integers behavior + +Integers larger than 2**32 decode as bigint: + +```ts +import { decodeCbor, encodeCbor } from "@std/cbor"; + +const bigNumber = 5_000_000_000; // > 2**32 +const bigBytes = encodeCbor(bigNumber); +const bigValue = decodeCbor(bigBytes); + +console.log(typeof bigValue); // "bigint" +console.log(bigValue === 5_000_000_000n); // true + +const smallValue = decodeCbor(encodeCbor(42)); +console.log(typeof smallValue); // "number" +``` + +### Sequences (multiple values) + +```ts +import { decodeCborSequence, encodeCborSequence } from "@std/cbor"; + +const packet = encodeCborSequence([{ id: 1 }, { id: 2 }, "done" as const]); +const values = decodeCborSequence(packet); +// values: [{ id: 1 }, { id: 2 }, "done"] +``` + +### Tagged values (dates) + +Use CBOR Tag 1 for epoch-based time (seconds since Unix epoch). How you +interpret tags on decode is up to your app. + +```ts +import { decodeCbor, encodeCbor } from "@std/cbor"; +import { CborTag } from "@std/cbor/tag"; + +const nowSeconds = Math.floor(Date.now() / 1000); +const tagged = new CborTag(1, nowSeconds); +const buf = encodeCbor(tagged); + +const out = decodeCbor(buf) as CborTag; +console.log(out.tagNumber); // 1 +console.log(out.tagContent); // epoch seconds +``` + +### Decode guard pattern + +When consuming untrusted bytes, check shapes after decode. + +```ts +import { decodeCbor } from "@std/cbor"; + +function isRecord(x: unknown): x is RecordTools for creating interactive command line tools.
+ +```js +import { parseArgs } from "@std/cli/parse-args"; +import { assertEquals } from "@std/assert"; + +// Same as running `deno run example.ts --foo --bar=baz ./quux.txt` +const args = parseArgs(["--foo", "--bar=baz", "./quux.txt"]); +assertEquals(args, { foo: true, bar: "baz", _: ["./quux.txt"] }); +``` + +### Add to your project + +```sh +deno add jsr:@std/cli +``` + +See all symbols +in @std/cli on + + + + +## Why use @std/cli? + +This package helps you build command‑line tools with great developer experience. +It focuses on the essentials: + +- Parsing flags and arguments (`parseArgs`) without heavy frameworks +- Prompting for sensitive input (`promptSecret`) +- Measuring display width reliably (`unicodeWidth`) for clean TTY output +- Unstable extras to enhance UX: spinners, progress bars, ANSI cursor control, + and interactive selects + +Use it when you want a lightweight, composable toolkit for CLI utilities. For +more complex CLIs with subcommands, rich help, and config systems, you can still +start with `parseArgs` and layer in your own structure. + +## Examples + +```ts +import { parseArgs } from "@std/cli/parse-args"; +import { promptSecret } from "@std/cli/prompt-secret"; + +const args = parseArgs(Deno.args, { + alias: { v: "verbose" }, + boolean: ["verbose"], + string: ["out"], +}); + +if (args.verbose) console.log("Verbose mode on"); +const token = await promptSecret("Enter API token: "); +console.log(`Writing to: ${args.out ?? "stdout"}`); +``` + +- `parseArgs` is lightweight and unopinionated—great for simple tools; for + complex CLIs consider subcommands and help text patterns. +- Booleans default to false unless present; use `--no-flag` support if needed + via `booleanNegation` options. +- Use `stopEarly` to treat `--` as end of options and pass-through remaining + args. + +### parseArgs: aliases, defaults, collect, negatable, unknown, and -- + +```ts +import { parseArgs } from "@std/cli/parse-args"; + +const argv = [ + "-v", + "--out=dist/file.txt", + "--tag", + "alpha", + "--tag", + "beta", + "--no-cache", + "--", + "--literally-a-file-flag", +]; + +const args = parseArgs(argv, { + alias: { v: "verbose" }, + boolean: ["verbose", "cache"], + string: ["out"], + default: { out: "stdout" }, + collect: ["tag"], + negatable: ["cache"], + unknown: (flag) => { + if (flag.startsWith("--") && flag !== "--") { + console.warn(`Unknown flag: ${flag}`); + return false; // drop it from parsed output + } + return true; + }, + "--": true, +}); + +// args.tag -> ["alpha", "beta"] +// args.cache -> false (because of --no-cache) +// args.verbose -> true (because of -v) +// args.out -> "dist/file.txt" +// args["--"] -> ["--literally-a-file-flag"] (pass-through) +``` + +### promptSecret: masking and clearing + +```ts +import { promptSecret } from "@std/cli/prompt-secret"; + +const token = await promptSecret("Enter token: ", { mask: "*" }); +// Optionally clear the prompt line after entry +await promptSecret("Press Enter to continue", { mask: "", clear: true }); +``` + +### unicodeWidth: simple column alignment + +```ts +import { unicodeWidth } from "@std/cli/unicode-width"; + +const rows = [ + ["Name", "Width"], + ["hello", String(unicodeWidth("hello"))], + ["你好", String(unicodeWidth("你好"))], + ["🐙octo", String(unicodeWidth("🐙octo"))], +]; + +const col1Width = Math.max(...rows.map((r) => unicodeWidth(r[0]))); +for (const [a, b] of rows) { + const pad = " ".repeat(col1Width - unicodeWidth(a)); + console.log(`${a}${pad} ${b}`); +} +``` + +### Unstable UI helpers: spinner and progress bar + +These APIs are marked unstable and may change. + +```ts +// Spinner +import { Spinner } from "@std/cli/unstable-spinner"; + +const spinner = new Spinner({ message: "Fetching data..." }); +spinner.start(); +await new Promise((r) => setTimeout(r, 800)); +spinner.stop(); + +// ProgressBar +import { ProgressBar } from "@std/cli/unstable-progress-bar"; + +const bar = new ProgressBar({ max: 5 }); +for (let i = 0; i < 5; i++) { + await new Promise((r) => setTimeout(r, 300)); + bar.value = i + 1; +} +bar.stop(); +``` + + diff --git a/runtime/reference/std/collections.md b/runtime/reference/std/collections.md new file mode 100644 index 000000000..525512f28 --- /dev/null +++ b/runtime/reference/std/collections.md @@ -0,0 +1,157 @@ +--- +title: "@std/collections" +description: "Pure functions for common tasks related to collection types like arrays and objects" +jsr: jsr:@std/collections +pkg: collections +version: 1.1.3 +generated: true +stability: stable +--- + + + +## Overview + +Pure functions for common tasks around collection types like arrays and +objects.
+Inspired by +Kotlin's Collections +package and Lodash.
+ +```js +import { intersect, pick, sample } from "@std/collections"; +import { assertArrayIncludes, assertEquals } from "@std/assert"; + +const lisaInterests = ["Cooking", "Music", "Hiking"]; +const kimInterests = ["Music", "Tennis", "Cooking"]; + +assertEquals(intersect(lisaInterests, kimInterests), ["Cooking", "Music"]); + +assertArrayIncludes(lisaInterests, [sample(lisaInterests)]); + +const cat = { name: "Lulu", age: 3, breed: "Ragdoll" }; + +assertEquals(pick(cat, ["name", "breed"]), { name: "Lulu", breed: "Ragdoll" }); +``` + +### Add to your project + +```sh +deno add jsr:@std/collections +``` + +See all +symbols in @std/collections on + + + + +## What are collection types? + +Collection types are data structures that hold multiple values, such as arrays +and objects. They allow you to group related data together and perform +operations on them, like filtering, transforming, and aggregating. + +This package provides small, focused functions to work with these types, +allowing you to compose complex operations from simple building blocks. + +## Why use @std/collections? + +The collections package provides small, pure helpers (intersect, pick, groupBy, +partition) to use instead of pulling a large utility library. + +## Examples + +### Distinct and distinctBy + +```ts +import { distinct, distinctBy } from "@std/collections"; + +const tags = ["a", "b", "a", "c"]; +console.log(distinct(tags)); // ["a", "b", "c"] + +const people = [ + { id: 1, name: "Alice" }, + { id: 1, name: "Alice v2" }, + { id: 2, name: "Bob" }, +]; +console.log(distinctBy(people, (p) => p.id)); +// [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }] +``` + +### Map records: mapValues, mapKeys + +```ts +import { mapKeys, mapValues } from "@std/collections"; + +const rec = { a: 1, b: 2 }; +console.log(mapValues(rec, (v) => v * 2)); // { a: 2, b: 4 } +console.log(mapKeys(rec, (k) => k.toUpperCase())); // { A: 1, B: 2 } +``` + +### Deep merge nested objects + +```ts +import { deepMerge } from "@std/collections/deep-merge"; + +const a = { cfg: { retries: 2, mode: "fast" } }; +const b = { cfg: { retries: 3 } }; +console.log(deepMerge(a, b)); +// { cfg: { retries: 3, mode: "fast" } } +``` + +### Sliding windows (with options) + +```ts +import { slidingWindows } from "@std/collections"; + +console.log(slidingWindows([1, 2, 3, 4], 3)); +// [[1,2,3],[2,3,4]] + +console.log(slidingWindows([1, 2, 3, 4, 5], 3, { step: 2, partial: true })); +// [[1,2,3],[3,4,5],[5]] +``` + +### Sort by derived keys + +```ts +import { sortBy } from "@std/collections"; + +const items = [{ v: 2 }, { v: 5 }, { v: 1 }]; +console.log(sortBy(items, (i) => i.v)); +// [{ v: 1 }, { v: 2 }, { v: 5 }] +console.log(sortBy(items, (i) => i.v, { order: "desc" })); +// [{ v: 5 }, { v: 2 }, { v: 1 }] +``` + +### Partition entries of an object + +```ts +import { partitionEntries } from "@std/collections"; + +const user = { id: 1, name: "Sam", active: true, score: 42 }; +const [numbers, rest] = partitionEntries( + user, + ([, v]) => typeof v === "number", +); +// numbers: { id: 1, score: 42 } +// rest: { name: "Sam", active: true } +``` + +### Produce joined strings + +```ts +import { joinToString } from "@std/collections"; + +console.log( + joinToString([1, 2, 3], { prefix: "[", separator: ", ", suffix: "]" }), +); +// "[1, 2, 3]" +``` + +## Tips + +- Functions are pure and data-first; they don’t mutate your inputs. +- Prefer these primitives to keep dependencies light and code clear. + + diff --git a/runtime/reference/std/crypto.md b/runtime/reference/std/crypto.md new file mode 100644 index 000000000..f98f2c9be --- /dev/null +++ b/runtime/reference/std/crypto.md @@ -0,0 +1,169 @@ +--- +title: "@std/crypto" +description: "Extensions to the Web Crypto API" +jsr: jsr:@std/crypto +pkg: crypto +version: 1.0.5 +generated: true +stability: stable +--- + + + +## Overview + +Extensions to the +Web Crypto +supporting additional encryption APIs, but also delegating to the built-in +APIs when possible.
+ +```js +import { crypto } from "@std/crypto/crypto"; + +const message = "Hello, Deno!"; +const encoder = new TextEncoder(); +const data = encoder.encode(message); + +await crypto.subtle.digest("BLAKE3", data); +``` + +### Add to your project + +```sh +deno add jsr:@std/crypto +``` + +See all +symbols in @std/crypto on + + + + +## What is web crypto? + +The Web Crypto API is a standard set of low-level cryptographic primitives +available in web browsers and other environments like Deno. It provides secure +methods for hashing, encryption, decryption, signing, and verifying data, useful +when you need to protect sensitive information. + +## Why use @std/crypto? + +This package provides Web Crypto–compatible helpers and algorithms (like +[BLAKE3](https://github.com/BLAKE3-team/BLAKE3/)) with a familiar API. Use it +in: + +- API clients and SDKs: sign/verify payloads, compute request checksums, or + derive cache validators (ETag‑like) with BLAKE3. +- CLI tools and build systems: fingerprint files and directories for caching, + artifact integrity, or change detection. +- Edge/serverless apps: verify webhooks and JWT parts, hash bodies before + storage, or compare secrets in constant time. +- Data pipelines: de‑duplicate blobs via fast hashing; generate stable IDs from + content. + +## Examples + +### Hashing + +```ts +import { crypto } from "@std/crypto/crypto"; + +const data = new TextEncoder().encode("hello"); +const hash = await crypto.subtle.digest("BLAKE3", data); +console.log(new Uint8Array(hash)); +``` + +### Hash to hex + +```ts +import { crypto } from "@std/crypto/crypto"; + +const toHex = (bytes: Uint8Array) => + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); + +const data = new TextEncoder().encode("hello"); +const buf = await crypto.subtle.digest("BLAKE3", data); +console.log(toHex(new Uint8Array(buf))); // e.g. "ea..." +``` + +### Hash a file (BLAKE3) + +```ts +import { crypto } from "@std/crypto/crypto"; + +const file = await Deno.readFile("./README.md"); +const buf = await crypto.subtle.digest("BLAKE3", file); +console.log(new Uint8Array(buf)); +``` + +### Constant‑time compare + +```ts +import { crypto } from "@std/crypto/crypto"; +import { timingSafeEqual } from "@std/crypto/timing-safe-equal"; + +const enc = new TextEncoder(); +const a = new Uint8Array( + await crypto.subtle.digest("BLAKE3", enc.encode("abc")), +); +const b = new Uint8Array( + await crypto.subtle.digest("BLAKE3", enc.encode("abd")), +); + +console.log(timingSafeEqual(a, b)); // false +``` + +### Synchronous hashing (scripts) + +```ts +import { crypto } from "@std/crypto/crypto"; + +const data = new TextEncoder().encode("fast"); +const buf = crypto.subtle.digestSync("BLAKE3", data); +console.log(new Uint8Array(buf)); +``` + +### Random bytes + +```ts +import { crypto } from "@std/crypto/crypto"; + +const iv = new Uint8Array(12); +crypto.getRandomValues(iv); +console.log(iv); +``` + +### AES‑GCM encrypt/decrypt (Web Crypto) + +```ts +import { crypto } from "@std/crypto/crypto"; + +const key = await crypto.subtle.generateKey( + { name: "AES-GCM", length: 256 }, + true, + ["encrypt", "decrypt"], +); + +const iv = crypto.getRandomValues(new Uint8Array(12)); +const data = new TextEncoder().encode("secret message"); + +const ciphertext = await crypto.subtle.encrypt( + { name: "AES-GCM", iv }, + key, + data, +); +const plaintext = await crypto.subtle.decrypt( + { name: "AES-GCM", iv }, + key, + ciphertext, +); + +console.log(new TextDecoder().decode(new Uint8Array(plaintext))); // "secret message" +``` + +## Tips + +- Prefer Web Crypto primitives; avoid rolling your own crypto. +- Encode inputs with `TextEncoder` and compare results as bytes or hex. + + diff --git a/runtime/reference/std/csv.md b/runtime/reference/std/csv.md new file mode 100644 index 000000000..624c5aac8 --- /dev/null +++ b/runtime/reference/std/csv.md @@ -0,0 +1,245 @@ +--- +title: "@std/csv" +description: "Reading and writing of comma-separated values (CSV) files" +jsr: jsr:@std/csv +pkg: csv +version: 1.0.6 +generated: true +stability: stable +--- + + + +## Overview + +Reads and writes comma-separated values (CSV) files.
+There are many kinds of CSV files; this module supports the format described +in RFC 4180.
+A csv file contains zero or more records of one or more fields per record. +Each record is separated by the newline character. The final record may +optionally be followed by a newline character.
+ +```js +field1, field2, field3; +``` + +White space is considered part of a field.
+Carriage returns before newline characters are silently removed.
+Blank lines are ignored. A line with only whitespace characters (excluding +the ending newline character) is not considered a blank line.
+Fields which start and stop with the quote character " are called +quoted-fields. The beginning and ending quote are not part of the field.
+The source:
+ +```js +normal string,"quoted-field" +``` + +results in the fields
+ +```js +[`normal string`, `quoted-field`]; +``` + +Within a quoted-field a quote character followed by a second quote character is considered a single quote.
+ +```js +"the ""word"" is true","a ""quoted-field""" +``` + +results in
+ +```js +[`the "word" is true`, `a "quoted-field"`]; +``` + +Newlines and commas may be included in a quoted-field
+ +```js +"Multi-line +field","comma is ," +``` + +results in
+ +```js +[ + `Multi-line +field`, + `comma is ,`, +]; +``` + +### Add to your project + +```sh +deno add jsr:@std/csv +``` + +See all symbols +in @std/csv on + + + + +## What is a CSV? + +CSV (Comma-Separated Values) is a simple text format for storing tabular data, +where each line represents a row and each value within the row is separated by a +comma. It’s widely used for data exchange between applications, especially +spreadsheets and databases. + +## When to use @std/csv + +This package is great for reading and writing CSV files in your applications. It +supports parsing CSV into arrays or objects, stringifying data back to CSV, and +streaming for large files. + +## Tips + +- Use `skipFirstRow: true` to treat the first row as headers. +- For objects, specify `columns` when stringifying. +- Prefer streaming parsers for multi-GB datasets. + + diff --git a/runtime/reference/std/data-structures.md b/runtime/reference/std/data-structures.md new file mode 100644 index 000000000..71516d99d --- /dev/null +++ b/runtime/reference/std/data-structures.md @@ -0,0 +1,110 @@ +--- +title: "@std/data-structures" +description: "Common data structures like red-black trees and binary heaps" +jsr: jsr:@std/data-structures +pkg: data-structures +version: 1.0.9 +generated: true +stability: stable +--- + + + +## Overview + +Data structures for use in algorithms and other data manipulation.
+ +```js +import { BinarySearchTree } from "@std/data-structures"; +import { assertEquals } from "@std/assert"; + +const values = [3, 10, 13, 4, 6, 7, 1, 14]; +const tree = new BinarySearchTreeUtilities for dealing with Date
objects.
Parses and loads environment variables from a .env
file into the current
+process, or stringify data into a .env
file format.
Note: The key needs to match the pattern /^[a-zA-Z_][a-zA-Z0-9_]*$/.
+ +```js +// Automatically load environment variables from a `.env` file +import "@std/dotenv/load"; +``` + +```js +import { parse, stringify } from "@std/dotenv"; +import { assertEquals } from "@std/assert"; + +assertEquals(parse("GREETING=hello world"), { GREETING: "hello world" }); +assertEquals(stringify({ GREETING: "hello world" }), "GREETING='hello world'"); +``` + +### Add to your project + +```sh +deno add jsr:@std/dotenv +``` + +See all +symbols in @std/dotenv on + + + + +## What is dotenv? + +`dotenv` is a popular way to manage environment variables in development. It +loads key-value pairs from a `.env` file into `process.env`, making it easy to +configure your app without hardcoding values. + +## When to use @std/dotenv + +Use this package to load local configuration during development, for preview +builds, or in simple deployments where your platform doesn’t inject environment +variables for you, keeping secrets and config out of source code. + +## Examples + +```ts +// Auto-load from .env at process start +import "@std/dotenv/load"; + +// Or load manually +import { load } from "@std/dotenv"; + +const env = await load({ + envPath: ".env.local", // where to read variables from (default: .env) + defaultsPath: ".env.defaults", // optional defaults if a key is missing + examplePath: ".env.example", // assert required keys exist + export: true, // also export to the process environment + allowEmptyValues: true, // allow empty values in example/defaults + override: false, // do not overwrite existing env vars by default +}); + +// Values are available both from the returned object and (when export: true) +// via the runtime’s environment API (e.g., Deno.env) +console.log(env.DATABASE_URL); +// Deno.env.get("DATABASE_URL"); +``` + +```ts +// Parse and stringify +import { parse, stringify } from "@std/dotenv"; + +const text = ` +GREETING="hello world" # comment +PORT=8080 +`; + +parse(text); // { GREETING: "hello world", PORT: "8080" } + +stringify({ GREETING: "hello world" }); +// "GREETING='hello world'" +``` + +## Tips + +- Don’t commit secrets. Add `.env` to your project's `.gitignore` file. + + diff --git a/runtime/reference/std/encoding.md b/runtime/reference/std/encoding.md new file mode 100644 index 000000000..acbdad01c --- /dev/null +++ b/runtime/reference/std/encoding.md @@ -0,0 +1,211 @@ +--- +title: "@std/encoding" +description: "Utilities for encoding and decoding common formats like hex, base64, and varint" +jsr: jsr:@std/encoding +pkg: encoding +version: 1.0.10 +generated: true +stability: stable +--- + + + +## Overview + +Utilities for encoding and decoding common formats like hex, base64, and varint.
+Learn more from the protobuf Varint encoding docs.
+ +```js +import { decodeVarint, encodeVarint } from "@std/encoding"; +import { assertEquals } from "@std/assert"; + +// Varint encoding support +assertEquals(encodeVarint(9601n), [new Uint8Array([129, 75]), 2]); + +// Decode a varint +const bytes = new Uint8Array([129, 75]); +assertEquals(decodeVarint(bytes), [9601n, 2]); +``` + +### Add to your project + +```sh +deno add jsr:@std/encoding +``` + +See all +symbols in @std/encoding on + + + + +## What is encoding? + +Encoding is the process of converting data from one format to another, often to +make it suitable for transmission or storage. Common encoding formats include +Base64, Hex, and Varint. + +## Why use @std/encoding? + +This package provides simple, reliable functions for encoding and decoding data +in various formats. You will use encoding for: + +- Interop: exchange binary data in human/transmissible forms (URLs, JSON, + command line, logs). +- Safety: decode helpers throw on malformed inputs (e.g., hex) rather than + silently truncating. +- Portability: single API surface across runtimes. +- Control: choose URL‑safe Base64 to avoid +, /, = in URLs. + +## Examples + +```ts +import { + decodeBase64Url, + decodeHex, + encodeBase64Url, + encodeHex, +} from "@std/encoding"; + +// Strings <-> bytes +const bytes = new TextEncoder().encode("hello"); +const text = new TextDecoder().decode(bytes); + +// URL-safe tokens +const token = encodeBase64Url(bytes); // aGVsbG8 +const roundtrip = new TextDecoder().decode(decodeBase64Url(token)); + +// Hex utilities +const hex = encodeHex(bytes); // 68656c6c6f +const fromHex = decodeHex(hex); +``` + +```ts +// Other supported encodings +import { + decodeAscii85, + decodeBase32, + decodeBase58, + decodeBase64, + encodeAscii85, + encodeBase32, + encodeBase58, + encodeBase64, +} from "@std/encoding"; + +encodeBase64("Hello world!"); // "SGVsbG8gd29ybGQh" +encodeBase32("Hello world!"); // "JBSWY3DPEB3W64TMMQQQ====" +encodeBase58("Hello world!"); // "2NEpo7TZRhna7vSvL" +encodeAscii85("Hello world!"); // "87cURD]j7BEbo80" + +new TextDecoder().decode(decodeBase64("SGVsbG8gd29ybGQh")); // "Hello world!" +``` + +```ts +// Varint (compact integer encoding) +import { decodeVarint, encodeVarint } from "@std/encoding"; + +const [buf, end] = encodeVarint(9601n); +const [num, next] = decodeVarint(buf); +``` + +## Tips + +- All encoders/decoders work with `Uint8Array`. Use `TextEncoder`/`TextDecoder` + for string ↔ bytes. +- Prefer Base64URL for tokens/query params; standard Base64 may include + characters that need escaping. +- Hex helpers return lowercase by default. +- Varint encodes integers compactly; it’s not for arbitrary binary payloads. + + diff --git a/runtime/reference/std/expect.md b/runtime/reference/std/expect.md new file mode 100644 index 000000000..afdba96bb --- /dev/null +++ b/runtime/reference/std/expect.md @@ -0,0 +1,179 @@ +--- +title: "@std/expect" +description: "Jest compatible `expect` assertion functions" +jsr: jsr:@std/expect +pkg: expect +version: 1.0.17 +generated: true +stability: stable +--- + + + +## Overview + +This module provides Jest compatible expect assertion functionality.
+ +```js +import { expect } from "@std/expect"; + +const x = 6 * 7; +expect(x).toEqual(42); +expect(x).not.toEqual(0); + +await expect(Promise.resolve(x)).resolves.toEqual(42); +``` + +Currently this module supports the following functions:
+toBe
toEqual
toStrictEqual
toMatch
toMatchObject
toBeDefined
toBeUndefined
toBeNull
toBeNaN
toBeTruthy
toBeFalsy
toContain
toContainEqual
toHaveLength
toBeGreaterThan
toBeGreaterThanOrEqual
toBeLessThan
toBeLessThanOrEqual
toBeCloseTo
toBeInstanceOf
toThrow
toHaveProperty
toHaveBeenCalled
toHaveBeenCalledTimes
toHaveBeenCalledWith
toHaveBeenLastCalledWith
toHaveBeenNthCalledWith
toHaveReturned
toHaveReturnedTimes
toHaveReturnedWith
toHaveLastReturnedWith
toHaveNthReturnedWith
expect.addSnapshotSerializer
expect.assertions
expect.addEqualityTester
expect.extend
expect.hasAssertions
Only these functions are still not available:
+toMatchSnapshot
toMatchInlineSnapshot
toThrowErrorMatchingSnapshot
toThrowErrorMatchingInlineSnapshot
The tracking issue to add support for unsupported parts of the API is +https://github.com/denoland/std/issues/3964.
+This module is largely inspired by +x/expect module by +Allain Lalonde.
+ +### Add to your project + +```sh +deno add jsr:@std/expect +``` + +See all +symbols in @std/expect on + + + + +## What is expect? + +A Jest‑compatible fluent assertion API. Instead of standalone assert functions, +you write expectations like `expect(value).toBe(1)` and can chain modifiers like +`.not`, `.resolves`, and `.rejects`. + +## When to use @std/expect + +If you prefer a Jest-like API for fluent, readable assertions with rich +matchers, especially when migrating from Jest. + +## Examples + +```ts +import { expect } from "@std/expect"; + +expect({ a: 1, b: 2 }).toMatchObject({ a: 1 }); +await expect(Promise.resolve(42)).resolves.toBe(42); +expect([1, 2, 3]).toContain(2); + +// Throwing and async rejections +expect(() => JSON.parse("{")) + .toThrow(SyntaxError); +await expect(Promise.reject(new Error("boom"))) + .rejects.toThrow("boom"); + +// Close-to for floating point, regex matching +expect(0.1 + 0.2).toBeCloseTo(0.3, 15); +expect("hello world").toMatch(/world/); + +// Using asymmetric matchers +expect({ id: 1, name: "Ada" }) + .toEqual(expect.objectContaining({ name: expect.stringMatching(/^A/) })); +``` + +## Use with Deno.test + +```ts +import { expect } from "@std/expect"; +Deno.test("basic expect", () => { + const value = 2 + 2; + expect(value).toBe(4); +}); +``` + +For more information on testing in Deno, see the +[testing docs](/runtime/fundamentals/testing/). + +## Tips + +- Use `toEqual` for deep data comparisons and `toBe` for identity. +- Prefer `.resolves` / `.rejects` helpers for promises. +- Prefer `.resolves` / `.rejects` helpers for promises. +- Use `toStrictEqual` for stricter deep checks (no extra props, etc.). +- Extend with custom matchers via `expect.extend` when needed. + + diff --git a/runtime/reference/std/fmt.md b/runtime/reference/std/fmt.md new file mode 100644 index 000000000..ec66d2d42 --- /dev/null +++ b/runtime/reference/std/fmt.md @@ -0,0 +1,121 @@ +--- +title: "@std/fmt" +description: "Utilities for formatting values, such as adding colors to text, formatting durations, printf utils, formatting byte numbers." +jsr: jsr:@std/fmt +pkg: fmt +version: 1.0.8 +generated: true +stability: stable +--- + + + +## Overview + +Provides utilities for formatting text of different types:
+ + +```js +import { format } from "@std/fmt/bytes"; +import { red } from "@std/fmt/colors"; + +console.log(red(format(1337))); // Prints "1.34 kB" +``` + +bytes,
+colors, and
+duration supports all major runtimes.
+printf is mostly compatible with major
+runtimes, however some of features, such as %v
, %i
and %I
format
+specifiers, are only available in Deno. See the API docs for details.
Extracts +front matter +from strings. Adapted from +jxson/front-matter.
+extract
and test
support the following
+delimiters.
extract
and test
support the following
+delimiters.
extract
and test
support the following
+delimiters.
Helpers for working with the filesystem.
+ +```js +import { copy, ensureDir, ensureFile, move } from "@std/fs"; + +await ensureFile("example.txt"); + +await copy("example.txt", "example_copy.txt"); + +await ensureDir("subdir"); + +await move("example_copy.txt", "subdir/example_copy.txt"); +``` + +### Add to your project + +```sh +deno add jsr:@std/fs +``` + +See all symbols in +@std/fs on + + + + +## Why use @std/fs? + +Reach for it when you want higher-level filesystem operations (such as ensuring +files/dirs, copying, moving, walking directories) than the bare +[Deno APIs](/examples/#filesystem). + +## Examples + +```ts +import { ensureDir, expandGlob, walk } from "@std/fs"; + +await ensureDir("./out/assets"); + +for await (const entry of expandGlob("src/**/*.{ts,tsx}")) { + console.log(entry.path); +} + +for await ( + const f of walk("./content", { includeDirs: false, exts: [".md"] }) +) { + console.log(f.path); +} +``` + +## Tips + +- Most helpers are async, don’t forget the `await`! +- Combine with `@std/path` to build cross-platform paths. +- Use `copy` with `overwrite: true` explicitly when replacing files. + + diff --git a/runtime/reference/std/html.md b/runtime/reference/std/html.md new file mode 100644 index 000000000..d2615668b --- /dev/null +++ b/runtime/reference/std/html.md @@ -0,0 +1,64 @@ +--- +title: "@std/html" +description: "Functions for HTML, such as escaping or unescaping HTML entities" +jsr: jsr:@std/html +pkg: html +version: 1.0.5 +generated: true +stability: stable +--- + + + +## Overview + +Functions for HTML tasks such as escaping or unescaping HTML entities.
+ +```js +import { unescape } from "@std/html/entities"; +import { assertEquals } from "@std/assert"; + +assertEquals(unescape("<>'&AA"), "<>'&AA"); +assertEquals(unescape("þð"), "þð"); +``` + +### Add to your project + +```sh +deno add jsr:@std/html +``` + +See all symbols +in @std/html on + + + + +## What is this package? + +A utility library for safely escaping and unescaping HTML entities to prevent +XSS vulnerabilities when inserting user-provided content into HTML. + +## Why use @std/html? + +Your application may need to display user-generated content within HTML. To +prevent cross-site scripting (XSS) attacks, it is crucial to escape special +characters like `<`, `>`, `&`, `"`, and `'` before embedding user input into +HTML. + +## Examples + +```ts +import { escape, unescape } from "@std/html/entities"; + +const safe = escape(`Provides user-friendly serve
on top of Deno's native HTTP server
+and other utilities for creating HTTP servers and clients.
A small program for serving local files over HTTP.
+ +```js +deno run --allow-net --allow-read jsr:@std/http/file-server +Listening on: +- Local: http://localhost:8000 +``` + +When the --allow-sys=networkInterfaces
permission is provided, the file
+server will also display the local area network addresses that can be used to
+access the server.
Helper for processing status code and status text.
+Provides error classes for each HTTP error status code as well as utility +functions for handling HTTP errors in a structured way.
+Provides helper functions and types to work with HTTP method strings safely.
+A set of functions which can be used to negotiate content types, encodings and +languages when responding to requests.
+++Note: some libraries include accept charset functionality by analyzing the +
+Accept-Charset
header. This is a legacy header that +clients omit and servers should ignore +therefore is not provided.
The UserAgent
class provides user agent string parsing, allowing
+a user agent flag to be semantically understood.
For example to integrate the user agent provided in the header User-Agent
+in an http request would look like this:
route
provides an easy way to route requests to different
+handlers based on the request path and method.
parse
and stringify
for handling
+INI encoded data, such as the
+Desktop Entry specification.
+Values are parsed as strings by default to preserve data parity from the original.
+Customization is possible in the form of reviver/replacer functions like those in JSON.parse
and JSON.stringify
.
+Nested sections, repeated key names within a section, and key/value arrays are not supported,
+but will be preserved when using IniMap
. Multi-line values are not supported and will throw a syntax error.
+White space padding and lines starting with '#', ';', or '//' will be treated as comments.
Optionally, IniMap
may be used for finer INI handling. Using this class will permit preserving
+comments, accessing values like a map, iterating over key/value/section entries, and more.
The reviver and replacer APIs can be used to extend the behavior of IniMap, such as adding support +for duplicate keys as if they were arrays of values.
+ +```js +import { IniMap } from "@std/ini/ini-map"; +import { assertEquals } from "@std/assert"; + +const iniFile = `# Example of key/value arrays +[section1] +key1=This key +key1=is non-standard +key1=but can be captured!`; + +const ini = new IniMap({ assignment: "=", deduplicate: true }); +ini.parse(iniFile, (key, value, section) => { + if (section) { + if (ini.has(section, key)) { + const exists = ini.get(section, key); + if (Array.isArray(exists)) { + exists.push(value); + return exists; + } else { + return [exists, value]; + } + } + } + return value; +}); + +assertEquals( + ini.get("section1", "key1"), + ["This key", "is non-standard", "but can be captured!"], +); + +const result = ini.toString((key, value) => { + if (Array.isArray(value)) { + return value.join( + `${ini.formatting.lineBreak}${key}${ini.formatting.assignment}`, + ); + } + return value; +}); + +assertEquals(result, iniFile); +``` + +### Add to your project + +```sh +deno add jsr:@std/ini +``` + +See all symbols +in @std/ini on + + + + +## What is an INI file? + +INI files are simple text files used for configuration. They consist of +key-value pairs grouped into sections, making them easy to read and edit by +humans. INI files are commonly used for application settings, preferences, and +other configuration data. + +## Why use @std/ini? + +- INI is loosely specified; favor simple key/value usage and flat sections for + best interoperability. +- Values parse as strings by default. Use reviver/replacer to coerce to + numbers/dates/booleans explicitly. +- Multi-line values and arrays aren’t standard; use `IniMap` plus custom + reviver/replacer to emulate if needed. +- Comments begin with `#`, `;`, or `//` and are preserved by `IniMap`. + +## Examples + +Coercing types + +```ts +import * as ini from "@std/ini"; + +const cfg = ini.parse(text, { + reviver(key, value) { + if (/^(true|false)$/i.test(value)) return value.toLowerCase() === "true"; + if (/^\d+$/.test(value)) return Number(value); + return value; + }, +}); +``` + +Custom assignment operator and pretty formatting + +```ts +import * as ini from "@std/ini"; + +const txt = `name: Deno\nversion: 1`; + +// Use ':' instead of '=' when parsing +const parsed = ini.parse(txt, { assignment: ":" }); + +// And keep using ':' and pretty spacing on write +const out = ini.stringify(parsed, { assignment: ":", pretty: true }); +// out => "name : Deno\nversion : 1" +``` + +Preserve comments and order with IniMap + +```ts +import { IniMap } from "@std/ini/ini-map"; + +const text = `# Global +[app] +# Port to listen on +port=8080`; + +const im = new IniMap(); +im.parse(text); + +// Modify a value while preserving comments and ordering +im.set("app", "port", "9090"); + +// Comments and structure are kept in the output +const roundTrip = im.toString(); +``` + +Merge layered configs (base + local overrides) + +```ts +import { IniMap } from "@std/ini/ini-map"; + +const baseText = `[db]\nhost=localhost\nport=5432\n[app]\nmode=prod`; +const localText = `[db]\nport=6543\n[app]\nmode=dev`; + +const base = new IniMap(); +base.parse(baseText); + +const local = new IniMap(); +local.parse(localText); + +// Overlay values from local onto base +const overlay = (target: IniMap, source: IniMap) => { + const obj = source.toObject() as RecordUtilities for working with Deno's readers, writers, and web streams.
+Reader
and Writer
interfaces are deprecated in Deno, and so many of these
+utilities are also deprecated. Consider using web streams instead.
Utilities for parsing streaming JSON data.
+ +```js +import { JsonStringifyStream } from "@std/json"; +import { assertEquals } from "@std/assert"; + +const stream = ReadableStream.from([{ foo: "bar" }, { baz: 100 }]) + .pipeThrough(new JsonStringifyStream()); + +assertEquals(await Array.fromAsync(stream), [ + `{"foo":"bar"}\n`, + `{"baz":100}\n`, +]); +``` + +### Add to your project + +```sh +deno add jsr:@std/json +``` + +See all symbols +in @std/json on + + + + +## What is JSON streaming? + +JSON streaming is a technique for processing JSON data in a continuous flow, +rather than loading the entire dataset into memory at once. This is particularly +useful for handling large JSON files or real-time data feeds. + +## Why use @std/json? + +To stream JSON in and out to handle large datasets without loading everything in +memory. + +## Examples + +Parse concatenated JSON (multiple JSON values back-to-back) + +```ts +import { + ConcatenatedJsonParseStream, +} from "@std/json/concatenated-json-parse-stream"; + +// Stream contains two JSON documents back-to-back without delimiters. +const input = ReadableStream.from([ + '{"a":1}{', + '"b":2}', +]); + +const parsed = input.pipeThrough(new ConcatenatedJsonParseStream()); +console.log(await Array.fromAsync(parsed)); // [{ a: 1 }, { b: 2 }] +``` + +Produce NDJSON (JSON Lines) from objects + +```ts +import { JsonStringifyStream } from "@std/json/stringify-stream"; + +const data = [{ id: 1 }, { id: 2 }, { id: 3 }]; + +// Add a trailing newline after each JSON value for NDJSON +const ndjson = ReadableStream + .from(data) + .pipeThrough(new JsonStringifyStream({ suffix: "\n" })); + +// Post to a server that accepts application/x-ndjson +await fetch("/ingest", { + method: "POST", + headers: { "content-type": "application/x-ndjson" }, + body: ndjson, +}); +``` + +Consume NDJSON safely (split lines across chunk boundaries) + +```ts +import { JsonParseStream } from "@std/json/parse-stream"; + +// Split by newlines, even if a line is split across chunks +function lineSplitter() { + let buffer = ""; + return new TransformStreamProvides tools for working with +JSONC +(JSON with comments).
+Currently, this module only provides a means of parsing JSONC. JSONC +serialization is not yet supported.
+ +```js +import { parse } from "@std/jsonc"; +import { assertEquals } from "@std/assert"; + +assertEquals(parse('{"foo": "bar", } // comment'), { foo: "bar" }); +assertEquals(parse('{"foo": "bar", } /* comment *\/'), { foo: "bar" }); +``` + +### Add to your project + +```sh +deno add jsr:@std/jsonc +``` + +See all symbols +in @std/jsonc on + + + + +## What is JSONC? + +JSONC (JSON with Comments) is a variant of JSON that allows comments and +trailing commas. It is commonly used for configuration files where human +readability and maintainability are important, such as in Visual Studio Code +settings files. + +### Why use @std/jsonc? + +This package allows you to easily parse JSONC files, which are not supported by +the standard JSON parser. It is useful for reading configuration files that may +contain comments or trailing commas, making them more user-friendly. + +## Examples + +Parse with comments and trailing commas + +```ts +import { parse } from "@std/jsonc"; + +const text = `{ + // Service config + "host": "localhost", + "port": 8000, // trailing comma allowed +}`; + +const cfg = parse(text); +// => { host: "localhost", port: 8000 } +``` + +Merge user config over defaults + +```ts +import { parse } from "@std/jsonc"; + +const defaults = { host: "127.0.0.1", port: 3000 } as const; +const userText = `{ + // Only override port + "port": 8080, +}`; + +const user = parse(userText) as PartialUtility functions for media types (MIME types).
+This API is inspired by the GoLang mime
+package and jshttp/mime-types,
+and is designed to integrate and improve the APIs from
+x/media_types.
The vendor
folder contains copy of the
+jshttp/mime-db db.json
file,
+along with its license.
This module provides functions to encode and decode MessagePack.
+MessagePack is an efficient binary serialization format that is language +agnostic. It is like JSON, but generally produces much smaller payloads. +Learn more about MessagePack.
+ +```js +import { decode, encode } from "@std/msgpack"; +import { assertEquals } from "@std/assert"; + +const obj = { + str: "deno", + arr: [1, 2, 3], + bool: true, + nil: null, + map: { + foo: "bar", + }, +}; + +const encoded = encode(obj); +assertEquals(encoded.length, 42); + +const decoded = decode(encoded); +assertEquals(decoded, obj); +``` + +MessagePack supports encoding and decoding the following types:
+number
bigint
string
boolean
null
Uint8Array
Network utilities.
+ +```js +import { getAvailablePort } from "@std/net"; + +const command = new Deno.Command(Deno.execPath(), { + args: ["test.ts", "--port", getAvailablePort().toString()], +}); + +// ... +``` + +### Add to your project + +```sh +deno add jsr:@std/net +``` + +See all symbols +in @std/net on + + + + +## What is @std/net? + +Utilities to help with common networking tasks that complement Deno's core APIs: + +- Finding or reserving an open port. +- Discovering a machine's LAN address to bind servers. +- Validating IP versions and checking if an address belongs to a CIDR subnet. + +## Why use @std/net? + +- To pick safe ports and interfaces: + - Prefer ephemeral ports via `Deno.listen({ port: 0 })` when you control the + listener. + - Use `getAvailablePort()` when you need a free port value to pass to other + processes before binding (then bind immediately to avoid races). +- Bind to the right network: use `getNetworkAddress()` to serve on your LAN’s + IPv4 or IPv6 address instead of loopback. +- Validate and filter traffic: `isIPv4`/`isIPv6` and `match*Subnet` helpers let + you build allow/deny lists or feature gates by IP ranges. + +## Examples + +```ts +const listener = Deno.listen({ hostname: "127.0.0.1", port: 0 }); +const { port } = listener.addr as Deno.NetAddr; +// start server on listener ... +``` + +### Bind to a LAN address (not just localhost) + +```ts +import { getNetworkAddress } from "@std/net/unstable-get-network-address"; + +const hostname = getNetworkAddress() ?? "127.0.0.1"; // default IPv4 +Deno.serve({ hostname, port: 0 }, () => new Response("Hello from LAN")); +``` + +### Validate incoming IP family + +```ts +import { isIPv4, isIPv6 } from "@std/net/unstable-ip"; + +function describe(ip: string): string { + if (isIPv4(ip)) return "IPv4"; + if (isIPv6(ip)) return "IPv6"; + return "unknown"; +} +``` + +### Allowlist requests by subnet (IPv4 and IPv6) + +```ts +import { matchSubnets } from "@std/net/unstable-ip"; + +const allowlist = [ + "192.168.1.0/24", // home LAN + "2001:db8::/64", // docs example IPv6 prefix +]; + +Deno.serve((req, info) => { + const ip = (info.remoteAddr as Deno.NetAddr).hostname; + if (!matchSubnets(ip, allowlist)) { + return new Response("Forbidden", { status: 403 }); + } + return new Response("OK"); +}); +``` + +### Pass a free port to a child process + +```ts +import { getAvailablePort } from "@std/net"; + +const port = getAvailablePort(); +// Immediately reserve it in your process if possible to avoid races +const listener = Deno.listen({ hostname: "127.0.0.1", port }); + +const child = new Deno.Command("deno", { + args: ["run", "--allow-net", "./child_server.ts", String(port)], +}); +child.spawn(); +``` + +## Tips + +- Prefer `Deno.listen({ port: 0 })` when possible; use `getAvailablePort()` only + when you must pass a port value to another process first. +- After obtaining a port number, bind right away in the same process to avoid + TOCTOU race conditions. +- `unstable-ip` helpers are great for allow/deny lists but avoid putting full + access control solely in client-controlled headers like `X-Forwarded-For`. + + diff --git a/runtime/reference/std/path.md b/runtime/reference/std/path.md new file mode 100644 index 000000000..97af4fadd --- /dev/null +++ b/runtime/reference/std/path.md @@ -0,0 +1,280 @@ +--- +title: "@std/path" +description: "Utilities for working with file system paths" +jsr: jsr:@std/path +pkg: path +version: 1.1.2 +generated: true +stability: stable +--- + + + +## Overview + +Utilities for working with OS-specific file paths.
+Functions from this module will automatically switch to support the path style
+of the current OS, either windows
for Microsoft Windows, or posix
for
+every other operating system, eg. Linux, MacOS, BSD etc.
To use functions for a specific path style regardless of the current OS +import the modules from the platform sub directory instead.
+For POSIX-specific functions:
+ +```js +import { fromFileUrl } from "@std/path/posix/from-file-url"; +import { assertEquals } from "@std/assert"; + +assertEquals(fromFileUrl("file:///home/foo"), "/home/foo"); +``` + +For Windows-specific functions:
+ +```js +import { fromFileUrl } from "@std/path/windows/from-file-url"; +import { assertEquals } from "@std/assert"; + +assertEquals(fromFileUrl("file:///home/foo"), "\\home\\foo"); +``` + +Functions for working with URLs can be found in +@std/path/posix.
+ +### Add to your project + +```sh +deno add jsr:@std/path +``` + +See all symbols +in @std/path on + + + + +## When to use @std/path + +Use it anywhere you build, normalize, or inspect file paths. It handles POSIX +and Windows differences so your code stays portable. + +## Examples + +```ts +import { basename, dirname, extname, join, resolve } from "@std/path"; + +const file = join("content", "posts", "hello.md"); +console.log(dirname(file)); // content/posts +console.log(basename(file)); // hello.md +console.log(extname(file)); // .md +console.log(resolve(".", "assets")); // absolute path +``` + +## Tips + +- Prefer `join` over string concatenation. +- Use `fromFileUrl`/`toFileUrl` when moving between file URLs and paths. +- For OS-specific logic, import from `@std/path/posix` or `@std/path/windows`. + + diff --git a/runtime/reference/std/random.md b/runtime/reference/std/random.md new file mode 100644 index 000000000..e94075522 --- /dev/null +++ b/runtime/reference/std/random.md @@ -0,0 +1,71 @@ +--- +title: "@std/random" +description: "Various utilities using random number generators. The package also provides seeded pseudo-random number generator." +jsr: jsr:@std/random +pkg: random +version: 0.1.3 +generated: true +stability: unstable +--- + + + +:::info Unstable + +This @std package is experimental and its API may change without a major version +bump. + +::: + +## Overview + +Utilities for generating random numbers.
+ +```js +import { randomIntegerBetween } from "@std/random"; +import { randomSeeded } from "@std/random"; +import { assertEquals } from "@std/assert"; + +const prng = randomSeeded(1n); + +assertEquals(randomIntegerBetween(1, 10, { prng }), 3); +``` + +### Add to your project + +```sh +deno add jsr:@std/random +``` + +See all +symbols in @std/random on + + + + +## Why use @std/random? + +Random number generation is useful for simulations, games, sampling,and +randomized algorithms. This package provides both convenience functions for +common use cases and a way to create reproducible pseudo-random sequences via +seeding. + +## Examples + +```ts +import { randomIntegerBetween, randomSeeded } from "@std/random"; + +const prng = randomSeeded(123n); +const roll = randomIntegerBetween(1, 6, { prng }); +``` + +## Tips + +- For reproducible tests and simulations, use `randomSeeded(seed)` and pass the + PRNG to helpers. +- For security-sensitive randomness (tokens, keys), use the Web Crypto API + (`crypto.getRandomValues`) instead of PRNG utilities. +- Distribution helpers like `randomIntegerBetween` are inclusive of both bounds; + document this in APIs to avoid off-by-one confusion. + + diff --git a/runtime/reference/std/regexp.md b/runtime/reference/std/regexp.md new file mode 100644 index 000000000..0c1a712f9 --- /dev/null +++ b/runtime/reference/std/regexp.md @@ -0,0 +1,76 @@ +--- +title: "@std/regexp" +description: "Utilities for working with RegExp" +jsr: jsr:@std/regexp +pkg: regexp +version: 1.0.1 +generated: true +stability: stable +--- + + + +## Overview + +Functions for tasks related to +regular expression (regexp), +such as escaping text for interpolation into a regexp.
+ +```js +import { escape } from "@std/regexp/escape"; +import { assertEquals, assertMatch, assertNotMatch } from "@std/assert"; + +const re = new RegExp(`^${escape(".")}$`, "u"); + +assertEquals("^\\.$", re.source); +assertMatch(".", re); +assertNotMatch("a", re); +``` + +### Add to your project + +```sh +deno add jsr:@std/regexp +``` + +See all +symbols in @std/regexp on + + + + +## What is RegExp? + +RegExp (regular expressions) are patterns used to match character combinations +in strings. In JavaScript, they are implemented via the `RegExp` object and +literal syntax (e.g., `/pattern/flags`). + +### Why use @std/regexp? + +This package provides small utilities to make working with regexps safer and +easier: + +- Use `escape()` when interpolating user input into a RegExp to avoid unintended + meta-characters. +- Prefer the `u` (unicode) flag for correctness; it changes how escapes and + character classes behave. +- Anchors: `^` and `$` match start/end of string; use `m` flag to make them + line-based. +- When performance matters, precompile your regex once and reuse it. + +## Examples + +```ts +import { escape } from "@std/regexp/escape"; + +const user = "hello.+(world)"; +const safe = new RegExp(`^${escape(user)}$`, "u"); +safe.test("hello.+(world)"); // true +safe.test("helloX(world)"); // false + +// Multiline anchors +const re = /^error:.+$/mu; +re.test("ok\nerror: bad\nnext"); // true +``` + + diff --git a/runtime/reference/std/semver.md b/runtime/reference/std/semver.md new file mode 100644 index 000000000..10e2d02a5 --- /dev/null +++ b/runtime/reference/std/semver.md @@ -0,0 +1,293 @@ +--- +title: "@std/semver" +description: "Parsing and comparing of semantic versions (SemVer)" +jsr: jsr:@std/semver +pkg: semver +version: 1.0.6 +generated: true +stability: stable +--- + + + +## Overview + +The Semantic Version parser.
+Adapted directly from semver.
+ +```js +import { format, greaterThan, lessThan, parse, parseRange } from "@std/semver"; +import { assertEquals } from "@std/assert"; + +const semver = parse("1.2.3"); +assertEquals(semver, { + major: 1, + minor: 2, + patch: 3, + prerelease: [], + build: [], +}); + +assertEquals(format(semver), "1.2.3"); + +const range = parseRange("1.x || >=2.5.0 || 5.0.0 - 7.2.3"); + +const s0 = parse("1.2.3"); +const s1 = parse("9.8.7"); + +assertEquals(greaterThan(s0, s1), false); +assertEquals(lessThan(s0, s1), true); +``` + +A "version" is described by the v2.0.0
specification found at
+https://semver.org.
A leading "="
or "v"
character is stripped off and ignored.
Semantic versions can be formatted as strings, by default they
+are formatted as full
. Below is a diagram showing the various
+formatting options.
A version Range
is a set of Comparator
s which specify
+versions that satisfy the range.
A Comparator
is composed of an Operator
and a
+SemVer. The set of primitive operators
is:
<
Less than<=
Less than or equal to>
Greater than>=
Greater than or equal to=
Equal. If no operator is specified, then equality is assumed, so this
+operator is optional, but MAY be included.For example, the comparator >=1.2.7
would match the versions 1.2.7
, 1.2.8
,
+2.5.3
, and 1.3.9
, but not the versions 1.2.6
or 1.1.0
.
Comparators can be joined by whitespace to form a comparator set
, which is
+satisfied by the intersection of all of the comparators it includes.
A range is composed of one or more comparator sets, joined by ||
. A version
+matches a range if and only if every comparator in at least one of the
+||
-separated comparator sets is satisfied by the version.
For example, the range >=1.2.7 <1.3.0
would match the versions 1.2.7
,
+1.2.8
, and 1.2.99
, but not the versions 1.2.6
, 1.3.0
, or 1.1.0
.
The range 1.2.7 || >=1.2.9 <2.0.0
would match the versions 1.2.7
, 1.2.9
,
+and 1.4.6
, but not the versions 1.2.8
or 2.0.0
.
If a version has a prerelease tag (for example, 1.2.3-alpha.3
) then it will
+only be allowed to satisfy comparator sets if at least one comparator with the
+same [major, minor, patch]
tuple also has a prerelease tag.
For example, the range >1.2.3-alpha.3
would be allowed to match the version
+1.2.3-alpha.7
, but it would not be satisfied by 3.4.5-alpha.9
, even though
+3.4.5-alpha.9
is technically "greater than" 1.2.3-alpha.3
according to the
+SemVer sort rules. The version range only accepts prerelease tags on the 1.2.3
+version. The version 3.4.5
would satisfy the range, because it does not have
+a prerelease flag, and 3.4.5
is greater than 1.2.3-alpha.7
.
The purpose for this behavior is twofold. First, prerelease versions frequently +are updated very quickly, and contain many breaking changes that are (by the +author"s design) not yet fit for public consumption. Therefore, by default, they +are excluded from range matching semantics.
+Second, a user who has opted into using a prerelease version has clearly +indicated the intent to use that specific set of alpha/beta/rc versions. By +including a prerelease tag in the range, the user is indicating that they are +aware of the risk. However, it is still not appropriate to assume that they have +opted into taking a similar risk on the next set of prerelease versions.
+The method increment
takes an additional identifier
string
+argument that will append the value of the string as a prerelease identifier:
Build metadata is .
delimited alpha-numeric string.
+When parsing a version it is retained on the build: string[]
field
+of the SemVer instance. When incrementing there is an additional parameter that
+can set the build metadata on the SemVer instance.
Advanced range syntax desugars to primitive comparators in deterministic ways.
+Advanced ranges may be combined in the same way as primitive comparators using
+white space or ||
.
X.Y.Z - A.B.C
Specifies an inclusive set.
+1.2.3 - 2.3.4
:= >=1.2.3 <=2.3.4
If a partial version is provided as the first version in the inclusive range, +then the missing pieces are replaced with zeroes.
+1.2 - 2.3.4
:= >=1.2.0 <=2.3.4
If a partial version is provided as the second version in the inclusive range, +then all versions that start with the supplied parts of the tuple are accepted, +but nothing that would be greater than the provided tuple parts.
+1.2.3 - 2.3
:= >=1.2.3 <2.4.0
1.2.3 - 2
:= >=1.2.3 <3.0.0
1.2.x
1.X
1.2.*
*
Any of X
, x
, or *
may be used to "stand in" for one of the numeric values
+in the [major, minor, patch]
tuple.
*
:= >=0.0.0
(Any version satisfies)1.x
:= >=1.0.0 <2.0.0
(Matching major version)1.2.x
:= >=1.2.0 <1.3.0
(Matching major and minor versions)A partial version range is treated as an X-Range, so the special character is in +fact optional.
+""
(empty string) := *
:= >=0.0.0
1
:= 1.x.x
:= >=1.0.0 <2.0.0
1.2
:= 1.2.x
:= >=1.2.0 <1.3.0
~1.2.3
~1.2
~1
Allows patch-level changes if a minor version is specified on the comparator. +Allows minor-level changes if not.
+~1.2.3
:= >=1.2.3 <1.(2+1).0
:= >=1.2.3 <1.3.0
~1.2
:= >=1.2.0 <1.(2+1).0
:= >=1.2.0 <1.3.0
(Same as 1.2.x
)~1
:= >=1.0.0 <(1+1).0.0
:= >=1.0.0 <2.0.0
(Same as 1.x
)~0.2.3
:= >=0.2.3 <0.(2+1).0
:= >=0.2.3 <0.3.0
~0.2
:= >=0.2.0 <0.(2+1).0
:= >=0.2.0 <0.3.0
(Same as 0.2.x
)~0
:= >=0.0.0 <(0+1).0.0
:= >=0.0.0 <1.0.0
(Same as 0.x
)~1.2.3-beta.2
:= >=1.2.3-beta.2 <1.3.0
Note that prereleases in the
+1.2.3
version will be allowed, if they are greater than or equal to
+beta.2
. So, 1.2.3-beta.4
would be allowed, but 1.2.4-beta.2
would not,
+because it is a prerelease of a different [major, minor, patch]
tuple.^1.2.3
^0.2.5
^0.0.4
Allows changes that do not modify the left-most non-zero element in the
+[major, minor, patch]
tuple. In other words, this allows patch and minor
+updates for versions 1.0.0
and above, patch updates for versions
+0.X >=0.1.0
, and no updates for versions 0.0.X
.
Many authors treat a 0.x
version as if the x
were the major
+"breaking-change" indicator.
Caret ranges are ideal when an author may make breaking changes between 0.2.4
+and 0.3.0
releases, which is a common practice. However, it presumes that
+there will not be breaking changes between 0.2.4
and 0.2.5
. It allows for
+changes that are presumed to be additive (but non-breaking), according to
+commonly observed practices.
^1.2.3
:= >=1.2.3 <2.0.0
^0.2.3
:= >=0.2.3 <0.3.0
^0.0.3
:= >=0.0.3 <0.0.4
^1.2.3-beta.2
:= >=1.2.3-beta.2 <2.0.0
Note that prereleases in the
+1.2.3
version will be allowed, if they are greater than or equal to
+beta.2
. So, 1.2.3-beta.4
would be allowed, but 1.2.4-beta.2
would not,
+because it is a prerelease of a different [major, minor, patch]
tuple.^0.0.3-beta
:= >=0.0.3-beta <0.0.4
Note that prereleases in the 0.0.3
+version only will be allowed, if they are greater than or equal to beta
.
+So, 0.0.3-pr.2
would be allowed.When parsing caret ranges, a missing patch
value desugars to the number 0
,
+but will allow flexibility within that value, even if the major and minor
+versions are both 0
.
^1.2.x
:= >=1.2.0 <2.0.0
^0.0.x
:= >=0.0.0 <0.1.0
^0.0
:= >=0.0.0 <0.1.0
A missing minor
and patch
values will desugar to zero, but also allow
+flexibility within those values, even if the major version is zero.
^1.x
:= >=1.0.0 <2.0.0
^0.x
:= >=0.0.0 <1.0.0
Putting all this together, here is a Backus-Naur grammar for ranges, for the +benefit of parser authors:
+ +```js +range-set ::= range ( logical-or range ) * +logical-or ::= ( " " ) * "||" ( " " ) * +range ::= hyphen | simple ( " " simple ) * | "" +hyphen ::= partial " - " partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( "<" | ">" | ">=" | "<=" | "=" ) partial +partial ::= xr ( "." xr ( "." xr qualifier ? )? )? +xr ::= "x" | "X" | "*" | nr +nr ::= "0" | ["1"-"9"] ( ["0"-"9"] ) * +tilde ::= "~" partial +caret ::= "^" partial +qualifier ::= ( "-" pre )? ( "+" build )? +pre ::= parts +build ::= parts +parts ::= part ( "." part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +Note that, since ranges may be non-contiguous, a version might not be greater
+than a range, less than a range, or satisfy a range! For example, the range
+1.2 <1.2.9 || >2.0.0
would have a hole from 1.2.9
until 2.0.0
, so the
+version 1.2.10
would not be greater than the range (because 2.0.1
satisfies,
+which is higher), nor less than the range (since 1.2.8
satisfies, which is
+lower), and it also does not satisfy the range.
If you want to know if a version satisfies or does not satisfy a range, use the
+satisfies
function.
Utilities for working with the +Streams API.
+Includes buffering and conversion.
+ +```js +import { toText } from "@std/streams"; +import { assertEquals } from "@std/assert"; + +const stream = ReadableStream.from(["Hello, world!"]); +const text = await toText(stream); + +assertEquals(text, "Hello, world!"); +``` + +### Add to your project + +```sh +deno add jsr:@std/streams +``` + +See all +symbols in @std/streams on + + + + +## What are Web Streams? + +Web Streams provide a standard way to handle streaming data in JavaScript. They +allow you to process data piece by piece as it arrives, rather than waiting for +the entire dataset to be available. This is particularly useful for handling +large files, network requests, or any situation where data is produced over +time. + +## Why use @std/streams? + +Use for buffering, converting, and composing Web Streams efficiently. + +### Examples + +```ts +import { copy, readerFromStreamReader, writeAll } from "@std/streams"; + +// Copy from a file to another file via streams +const r = await Deno.open("input.txt"); +const w = await Deno.open("output.txt", { + create: true, + write: true, + truncate: true, +}); +await copy(r, w); +r.close(); +w.close(); + +// Convert a ReadableStreamDefaultReader to a Deno.Reader +const res = await fetch("https://deno.land"); +const denoReader = readerFromStreamReader(res.body!.getReader()); +await writeAll( + Deno.stdout, + new Uint8Array(await new Response(denoReader).arrayBuffer()), +); +``` + +## Tips + +- Prefer streaming for large payloads to reduce memory pressure. +- Use helpers like `toText`, `toArrayBuffer`, and `iterateReader` for + conversions. + + diff --git a/runtime/reference/std/tar.md b/runtime/reference/std/tar.md new file mode 100644 index 000000000..4bebdf6a8 --- /dev/null +++ b/runtime/reference/std/tar.md @@ -0,0 +1,94 @@ +--- +title: "@std/tar" +description: "Streaming utilities for working with tar archives." +jsr: jsr:@std/tar +pkg: tar +version: 0.1.9 +generated: true +stability: unstable +--- + + + +:::info Unstable + +This @std package is experimental and its API may change without a major version +bump. + +::: + +## Overview + +Streaming utilities for working with tar archives.
+Files are not compressed, only collected into the archive.
+ +```js +import { UntarStream } from "@std/tar/untar-stream"; +import { dirname, normalize } from "@std/path"; + +for await ( + const entry of (await Deno.open("./out.tar.gz")) + .readable + .pipeThrough(new DecompressionStream("gzip")) + .pipeThrough(new UntarStream()) +) { + const path = normalize(entry.path); + await Deno.mkdir(dirname(path), { recursive: true }); + await entry.readable?.pipeTo((await Deno.create(path)).writable); +} +``` + +### Add to your project + +```sh +deno add jsr:@std/tar +``` + +See all symbols +in @std/tar on + + + + +## What is tar? + +Tar (tape archive) is a widely-used file format for collecting multiple files +into a single archive file, often for easier distribution or backup. It +preserves file metadata like permissions and timestamps, making it suitable for +system backups and software distribution. + +## Why use @std/tar? + +Use this package to create or extract tar archives in a streaming fashion, which +is efficient for large datasets and avoids high memory usage. + +- This module is streaming-first: use Web Streams to read/write entries without + buffering whole archives. +- Security: sanitize entry paths and guard against path traversal (".." + segments) before writing to disk. +- Tar is an archive format, not compression. Layer + `CompressionStream`/`DecompressionStream` for gzip. +- Preserve permissions/mtime if present in headers when extracting to maintain + fidelity. + +## Examples + +```ts +import { UntarStream } from "@std/tar/untar-stream"; +import { dirname, isAbsolute, normalize } from "@std/path"; + +const outDir = "/safe/root"; + +for await (const entry of file.readable.pipeThrough(new UntarStream())) { + const normalized = normalize(entry.path); + // Prevent writing outside outDir + if (normalized.includes("..") || isAbsolute(normalized)) continue; + const dest = `${outDir}/${normalized}`; + await Deno.mkdir(dirname(dest), { recursive: true }); + if (entry.readable) { + await entry.readable.pipeTo((await Deno.create(dest)).writable); + } +} +``` + + diff --git a/runtime/reference/std/testing.md b/runtime/reference/std/testing.md new file mode 100644 index 000000000..837383a25 --- /dev/null +++ b/runtime/reference/std/testing.md @@ -0,0 +1,161 @@ +--- +title: "@std/testing" +description: "Tools for testing Deno code like snapshot testing, bdd testing, and time mocking" +jsr: jsr:@std/testing +pkg: testing +version: 1.0.16 +generated: true +stability: stable +--- + + + +## Overview + +This package provides utilities for testing.
+Utility functions for working with text.
+ +```js +import { compareSimilarity, toCamelCase } from "@std/text"; +import { assertEquals } from "@std/assert"; + +assertEquals(toCamelCase("snake_case"), "snakeCase"); + +const words = ["hi", "help", "hello"]; + +// Words most similar to "hep" will be at the front +assertEquals(words.sort(compareSimilarity("hep")), ["help", "hi", "hello"]); +``` + +### Add to your project + +```sh +deno add jsr:@std/text +``` + +See all symbols +in @std/text on + + + + +## Why use @std/text? + +Reach for it when you need reliable, well-tested text manipulation utilities +such as case conversions, string similarity, and common text ops. + +## Examples + +```ts +import { compareSimilarity, toKebabCase } from "@std/text"; + +console.log(toKebabCase("HelloWorld")); + +const candidates = ["install", "init", "info"]; +console.log(candidates.sort(compareSimilarity("in"))); +``` + +### Find the closest suggestion + +```ts +import { closestString } from "@std/text/closest-string"; + +const options = ["length", "size", "help"]; +console.log(closestString("hep", options)); // "help" +``` + +### Compute edit distance + +```ts +import { levenshteinDistance } from "@std/text"; + +console.log(levenshteinDistance("kitten", "sitting")); // 3 +``` + +### Sort a list by similarity + +```ts +import { wordSimilaritySort } from "@std/text"; + +const cmds = ["install", "init", "info", "inspect"]; +console.log(wordSimilaritySort("in", cmds)); +// e.g., ["init", "info", "install", "inspect"] +``` + +### Dedent a multiline string (unstable) + +```ts +import { dedent } from "@std/text/unstable-dedent"; + +const msg = dedent` + Line one + Line two + Line three +`; +console.log(msg); +// "Line one\n Line two\nLine three\n" +``` + +### Unicode-aware reverse (unstable) + +```ts +import { reverse } from "@std/text/unstable-reverse"; + +console.log(reverse("mañana")); // "anañam" +// Preserve grapheme clusters like emoji sequences +console.log(reverse("👩❤️💋👨", { handleUnicode: true })); +``` + +## Tips + +- Use similarity comparisons for CLI fuzzy matching and suggestions. +- Prefer these utils over ad-hoc regex when readability matters. +- Use `closestString()` when you need one best suggestion; use + `wordSimilaritySort()` to rank many. +- Some utilities are marked unstable; import them via `@std/text/unstable-*` and + expect potential API changes. + + diff --git a/runtime/reference/std/toml.md b/runtime/reference/std/toml.md new file mode 100644 index 000000000..9556ec49e --- /dev/null +++ b/runtime/reference/std/toml.md @@ -0,0 +1,144 @@ +--- +title: "@std/toml" +description: "Parsing and serializing of TOML files" +jsr: jsr:@std/toml +pkg: toml +version: 1.0.11 +generated: true +stability: stable +--- + + + +## Overview + +parse
and stringify
for handling
+TOML encoded data.
Be sure to read the supported types as not every spec is supported at the +moment and the handling in TypeScript side is a bit different.
+Supported with warnings see Warning.
+Due to the spec, there is no flag to detect regex properly in a TOML +declaration. So the regex is stored as string.
+For Binary / Octal / Hexadecimal numbers, they are stored as string +to be not interpreted as Decimal.
+Because local time does not exist in JavaScript, the local time is stored as a +string.
+At the moment only simple declarations like below are supported:
+ +```js +[[bin]]; +name = "deno"; +path = "cli/main.rs"[[bin]]; +name = "deno_core"; +path = "src/foo.rs"[[nib]]; +name = "node"; +path = "not_found"; +``` + +will output:
+ +```js +{ + "bin": [ + { "name": "deno", "path": "cli/main.rs" }, + { "name": "deno_core", "path": "src/foo.rs" } + ], + "nib": [{ "name": "node", "path": "not_found" }] +} +``` + +```js +import { parse, stringify } from "@std/toml"; +import { assertEquals } from "@std/assert"; + +const obj = { + bin: [ + { name: "deno", path: "cli/main.rs" }, + { name: "deno_core", path: "src/foo.rs" }, + ], + nib: [{ name: "node", path: "not_found" }], +}; + +const tomlString = stringify(obj); +assertEquals( + tomlString, + ` +[[bin]] +name = "deno" +path = "cli/main.rs" + +[[bin]] +name = "deno_core" +path = "src/foo.rs" + +[[nib]] +name = "node" +path = "not_found" +`, +); + +const tomlObject = parse(tomlString); +assertEquals(tomlObject, obj); +``` + +### Add to your project + +```sh +deno add jsr:@std/toml +``` + +See all symbols +in @std/toml on + + + + +## What is TOML? + +TOML (Tom's Obvious, Minimal Language) is a configuration file format that is +easy to read due to its simple syntax. It supports various data types like +strings, numbers, booleans, dates, arrays, and tables, making it versatile for +configurations. + +## Why use @std/toml? + +This module provides a simple and efficient way to parse and stringify TOML data +in JavaScript. Use it to read configuration files or generate TOML content +programmatically. + +## Tips + +- Mind the supported types: some TOML constructs are represented as strings in + JS. +- Use arrays-of-tables for repeated sections; keep structures simple for + clarity. + + diff --git a/runtime/reference/std/ulid.md b/runtime/reference/std/ulid.md new file mode 100644 index 000000000..8f8408718 --- /dev/null +++ b/runtime/reference/std/ulid.md @@ -0,0 +1,82 @@ +--- +title: "@std/ulid" +description: "Generation of Universally Unique Lexicographically Sortable Identifiers (ULIDs)" +jsr: jsr:@std/ulid +pkg: ulid +version: 1.0.0 +generated: true +stability: stable +--- + + + +## Overview + +Utilities for generating and working with +Universally Unique Lexicographically Sortable Identifiers (ULIDs).
+To generate a ULID use the ulid
function. This will generate a
+ULID based on the current time.
ulid
does not guarantee that the ULIDs will be strictly
+increasing for the same current time. If you need to guarantee that the ULIDs
+will be strictly increasing, even for the same current time, use the
+monotonicUlid
function.
Because each ULID encodes the time it was generated, you can extract the
+timestamp from a ULID using the decodeTime
function.
Generators and validators for +RFC 9562 UUIDs for +versions v1, v3, v4, v5, v6 and v7.
+Use the built-in
+crypto.randomUUID()
+function instead of this package, if you only need to generate v4 UUIDs.
Based on npm:uuid
.
Utilities for interacting with the +WebGPU API.
+ +```js +import { createTextureWithData } from "@std/webgpu"; + +const adapter = await navigator.gpu.requestAdapter(); +const device = await adapter?.requestDevice()!; + +createTextureWithData(device, { + format: "bgra8unorm-srgb", + size: { + width: 3, + height: 2, + }, + usage: GPUTextureUsage.COPY_SRC, +}, new Uint8Array([1, 1, 1, 1, 1, 1, 1])); +``` + +### Add to your project + +```sh +deno add jsr:@std/webgpu +``` + +See all +symbols in @std/webgpu on + + + + +## What is the WebGPU API? + +WebGPU is a modern graphics API that provides high-performance 3D graphics and +computation capabilities in web applications. It is designed to be a successor +to WebGL, offering lower-level access to GPU hardware and improved performance +for complex graphics and compute tasks. + +## Why use @std/webgpu? + +Use for common WebGPU patterns and utilities to simplify setup and resource +management: + +- Request the adapter/device once and reuse; feature/limit negotiation up front + avoids runtime failures. +- Set texture `usage` bits to match all intended operations (COPY_SRC, COPY_DST, + TEXTURE_BINDING, RENDER_ATTACHMENT). +- Prefer `device.queue.writeBuffer`/`writeTexture` for small uploads; use + staging buffers for large transfers. + +## Examples + +### Writing to a buffer + +```ts +const buf = device.createBuffer({ + size: 16, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.UNIFORM, +}); +device.queue.writeBuffer(buf, 0, new Uint32Array([1, 2, 3, 4])); +``` + +### Describe a texture format + +```ts +import { describeTextureFormat } from "@std/webgpu"; + +const info = describeTextureFormat("rgba8unorm"); +console.log(info.sampleType); // e.g. "float" +console.log(info.allowedUsages.includes(GPUTextureUsage.RENDER_ATTACHMENT)); +console.log(info.blockSize, info.blockDimensions); // bytes per block and block size +``` + +### Copy a texture to a buffer (with padding) + +```ts +import { + describeTextureFormat, + getRowPadding, + resliceBufferWithPadding, +} from "@std/webgpu"; + +const format: GPUTextureFormat = "rgba8unorm"; +const size = { width: 320, height: 200 }; +const tex = device.createTexture({ + format, + size, + usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT, +}); + +// Compute bytesPerRow with required alignment for buffer copies +const { blockSize, blockDimensions } = describeTextureFormat(format); +const bytesPerPixel = blockSize / + (blockDimensions.width * blockDimensions.height); +const { padded: bytesPerRow } = getRowPadding(size.width * bytesPerPixel); +const bufferSize = bytesPerRow * size.height; + +const out = device.createBuffer({ + size: bufferSize, + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, +}); + +const encoder = device.createCommandEncoder(); +encoder.copyTextureToBuffer( + { texture: tex }, + { buffer: out, bytesPerRow, rowsPerImage: size.height }, + size, +); +device.queue.submit([encoder.finish()]); + +await out.mapAsync(GPUMapMode.READ); +const padded = out.getMappedRange(); +const pixels = resliceBufferWithPadding( + new Uint8Array(padded), + bytesPerRow, + size, +); +// `pixels` is tightly packed RGBA rows, suitable for encoding/saving +``` + +### Capture a render target into a buffer + +```ts +import { createCapture } from "@std/webgpu"; + +const { texture, outputBuffer } = createCapture(device, { + size: { width: 256, height: 256 }, + format: "rgba8unorm", +}); + +// draw to `texture` as a color attachment, then copy it into `outputBuffer` internally +// later map the buffer to read pixels +await outputBuffer.mapAsync(GPUMapMode.READ); +const data = new Uint8Array(outputBuffer.getMappedRange()); +// use `data`... +``` + +## Tips + +- Check for WebGPU support with `if (!navigator.gpu) { ... }`. +- Request the adapter/device once and reuse; feature/limit negotiation up front + avoids runtime failures. +- Set texture `usage` bits to match all intended operations (COPY_SRC, COPY_DST, + TEXTURE_BINDING, RENDER_ATTACHMENT). + + diff --git a/runtime/reference/std/yaml.md b/runtime/reference/std/yaml.md new file mode 100644 index 000000000..90fb2f054 --- /dev/null +++ b/runtime/reference/std/yaml.md @@ -0,0 +1,202 @@ +--- +title: "@std/yaml" +description: "Parsing and serializing of YAML files" +jsr: jsr:@std/yaml +pkg: yaml +version: 1.0.10 +generated: true +stability: stable +--- + + + +## Overview + +parse
and stringify
for handling
+YAML encoded data.
Ported from +js-yaml v3.13.1.
+Use parseAll
for parsing multiple documents in a single YAML
+string.
This package generally supports +YAML 1.2.x (latest) and some +YAML 1.1 features that are +commonly used in the wild.
+Supported YAML 1.1 features include:
+<<
symbol)Unsupported YAML 1.1 features include:
+3:25:45
)binary
type is currently not stable. tags
+function sanitizeOverviewHtml(html: string): string {
+ let out = html;
+ // 1) Remove copy buttons injected by JSR docs (match on class copyButton)
+ out = out.replace(
+ /