### CLI Installation and Usage Source: https://github.com/rohal12/twee-ts/blob/main/docs/index.md Commands to install the twee-ts package, initialize a new project structure, and compile Twee source files into a single HTML output file. ```shell npm install @rohal12/twee-ts npx @rohal12/twee-ts --init npx @rohal12/twee-ts -o story.html src/ ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md A basic configuration file specifying source directories and the output file. ```APIDOC ## Minimal Config ```json { "sources": ["src/"], "output": "story.html" } ``` With this in place, run `npx @rohal12/twee-ts` with no arguments. ``` -------------------------------- ### Twee-TS Basic Compilation Examples Source: https://github.com/rohal12/twee-ts/blob/main/docs/cli.md Examples demonstrating basic compilation of Twee source files using the Twee-TS CLI. Covers compiling to stdout, to a file with a specific format, and decompiling HTML back to Twee source. ```sh # Compile a directory to stdout twee-ts src/ # Compile to a file with a specific format twee-ts -o story.html -f harlowe-3 src/ # Decompile an HTML file back to Twee 3 source twee-ts -d -o story.twee story.html ``` -------------------------------- ### CLI Usage Source: https://github.com/rohal12/twee-ts/blob/main/docs/index.md Instructions on how to install and use the twee-ts command-line interface. ```APIDOC ## CLI Usage ### Description This section covers the installation and basic usage of the twee-ts command-line interface (CLI). ### Installation ```sh npm install @rohal12/twee-ts ``` ### Initialization To initialize a new twee-ts project: ```sh npx @rohal12/twee-ts --init ``` ### Compilation To compile your Twee project into an HTML file: ```sh npx @rohal12/twee-ts -o story.html src/ ``` - **-o, --output**: Specifies the output file path for the compiled HTML. - **src/**: The directory containing your Twee source files. ``` -------------------------------- ### Install twee-ts via npm Source: https://github.com/rohal12/twee-ts/blob/main/README.md Installs the twee-ts package using npm. This is the first step to using the compiler in your project. ```sh npm install @rohal12/twee-ts ``` -------------------------------- ### Twee TS Configuration File Example Source: https://context7.com/rohal12/twee-ts/llms.txt An example of a `twee-ts.config.json` file used for project settings. This file allows customization of sources, output, format, tag aliases, and more. It follows a specific JSON schema. ```json { "$schema": "https://unpkg.com/@rohal12/twee-ts/schemas/twee-ts.config.schema.json", "sources": ["src/"], "output": "story.html", "outputMode": "html", "formatId": "sugarcube-2", "startPassage": "Start", "formatPaths": ["./storyformats"], "modules": ["src/analytics.js", "src/custom.css"], "headFile": "src/head.html", "trim": true, "twee2Compat": false, "testMode": false, "noRemote": false, "sourceInfo": false, "wordCountMethod": "tweego", "tagAliases": { "library": "script", "theme": "stylesheet", "dev-note": "annotation" } } ``` -------------------------------- ### Load and Validate Configuration with Twee-ts Source: https://github.com/rohal12/twee-ts/blob/main/docs/api.md This example demonstrates loading configuration files and validating them using the '@rohal12/twee-ts' library. It covers loading configuration from the current working directory (`loadConfig`), from a specific file path (`loadConfigFile`), validating a configuration object (`validateConfig`), and scaffolding a default configuration JSON (`scaffoldConfig`). ```typescript import { loadConfig, loadConfigFile, validateConfig, scaffoldConfig } from '@rohal12/twee-ts'; const config = loadConfig(); // from cwd const config2 = loadConfigFile('my-config.json'); // from path const errors = validateConfig({ sources: 42 }); // validation const json = scaffoldConfig(); // default config JSON ``` -------------------------------- ### Implement Minimal Story Format Package Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md Provides a complete example of a package.json and the main index.js entry point required to export format metadata for twee-ts. ```json { "name": "@twine-formats/sugarcube-2", "version": "2.37.3", "type": "module", "exports": { ".": "./index.js" }, "files": ["index.js", "format.js"] } ``` ```javascript import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; const __dirname = dirname(fileURLToPath(import.meta.url)); const raw = readFileSync(join(__dirname, 'format.js'), 'utf-8'); const json = JSON.parse(raw.slice(raw.indexOf('{'), raw.lastIndexOf('}') + 1)); export const name = json.name; export const version = json.version; export const source = json.source; export const proofing = json.proofing ?? false; ``` -------------------------------- ### Vitest Testing Example Source: https://github.com/rohal12/twee-ts/blob/main/CLAUDE.md Illustrates the basic structure of unit tests using Vitest, a fast unit test framework. It shows the use of `describe`, `it`, and `expect` for defining test suites, individual test cases, and assertions. ```typescript import { describe, it, expect } from 'vitest'; describe('parser', () => { it('should parse simple passage', () => { const input = ':: Passage Name\nThis is passage content.'; const result = parse(input); expect(result.length).toBe(1); expect(result[0].name).toBe('Passage Name'); }); }); ``` -------------------------------- ### Configure Twee-ts Vite Plugin Source: https://github.com/rohal12/twee-ts/blob/main/docs/plugins.md Integrates the twee-ts plugin into a Vite configuration file. It demonstrates basic setup and advanced options like custom start passages and module inclusion. ```typescript import { defineConfig } from 'vite'; import { tweeTsPlugin } from '@rohal12/twee-ts/vite'; export default defineConfig({ plugins: [ tweeTsPlugin({ sources: ['src/story'], format: 'sugarcube-2', outputFilename: 'index.html', compileOptions: { startPassage: 'Prologue', tagAliases: { library: 'script', theme: 'stylesheet' }, modules: ['src/extra.js'], trim: true, }, }), ], }); ``` -------------------------------- ### Development Commands for twee-ts Source: https://github.com/rohal12/twee-ts/blob/main/README.md Lists essential development commands for the twee-ts project, including installation, testing, type checking, building, and documentation generation. ```sh pnpm install pnpm test # run tests pnpm run typecheck # type-check pnpm run build # bundle pnpm run docs:dev # local docs dev server pnpm run docs:build # build docs for deployment ``` -------------------------------- ### Twee-TS Advanced Compilation Options Source: https://github.com/rohal12/twee-ts/blob/main/docs/cli.md Examples showcasing advanced Twee-TS CLI features such as watch mode, logging, using tag aliases, compiling with remote formats via URL, and using custom configuration files. ```sh # Watch mode with stats logging twee-ts -w -l -o story.html src/ # Use tag aliases from the CLI twee-ts --tag-alias library=script --tag-alias theme=stylesheet -o story.html src/ # Compile with a remote format by direct URL twee-ts --format-url https://example.com/my-format/format.js -o story.html src/ # Use a custom config file twee-ts -c configs/production.json src/ ``` -------------------------------- ### Compile Story using twee-ts Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md Demonstrates how to install and use a story format package within a TypeScript project. ```bash npm install @twine-formats/my-format ``` ```typescript import * as myFormat from '@twine-formats/my-format'; import { compile } from 'twee-ts'; const result = await compile({ sources: ['src/'], format: myFormat, }); ``` -------------------------------- ### Configure Tag Aliases via Twee-TS CLI Source: https://github.com/rohal12/twee-ts/blob/main/docs/tag-aliases.md This command-line interface example shows how to set up tag aliases using the `--tag-alias` flag. Multiple alias pairs can be provided, and they are merged with any aliases defined in the config file, with CLI values taking precedence. This is useful for quick configuration changes or project-specific overrides. ```sh twee-ts --tag-alias library=script --tag-alias theme=stylesheet -o story.html src/ ``` -------------------------------- ### Vite Plugin for twee-ts Source: https://github.com/rohal12/twee-ts/blob/main/README.md Provides an example of integrating the twee-ts compiler into a Vite build process using the provided `tweeTsPlugin`. This simplifies the build pipeline for projects using Vite. ```typescript // vite.config.ts import { tweeTsPlugin } from '@rohal12/twee-ts/vite'; export default { plugins: [tweeTsPlugin({ sources: ['src/'] })], }; ``` -------------------------------- ### Integrating Twee TS with Vite Plugin Source: https://context7.com/rohal12/twee-ts/llms.txt Provides an example of integrating Twee TS into a Vite project using the `tweeTsPlugin`. This enables hot reloading and optimized builds by watching `.tw` files and triggering page reloads. Requires '@rohal12/twee-ts/vite'. ```typescript // vite.config.ts import { defineConfig } from 'vite'; import { tweeTsPlugin } from '@rohal12/twee-ts/vite'; export default defineConfig({ plugins: [ tweeTsPlugin({ sources: ['src/story'], format: 'sugarcube-2', outputFilename: 'index.html', compileOptions: { startPassage: 'Prologue', tagAliases: { library: 'script', theme: 'stylesheet', }, modules: ['src/analytics.js'], trim: true, }, }), ], }); ``` -------------------------------- ### Inspect Compiled Story with Twee-ts Source: https://github.com/rohal12/twee-ts/blob/main/docs/api.md This code example shows how to compile a story using '@rohal12/twee-ts' and then inspect the compiled output. The `compile` function processes source files, and `storyInspect` provides detailed information about the story structure, including a passage map and a list of broken links. The output of `compile` is used as input for `storyInspect`. ```typescript import { compile, storyInspect } from '@rohal12/twee-ts'; const result = await compile({ sources: ['src/'], outputMode: 'json' }); const info = storyInspect(result.story); console.log(info.passageMap); // Map of passage name → passage console.log(info.brokenLinks); // passages with links to nonexistent passages ``` -------------------------------- ### Discover Available Story Formats Source: https://context7.com/rohal12/twee-ts/llms.txt This code snippet demonstrates how to discover and enumerate available story formats using Twee TS. It shows how to get the configured story format search directories (including custom paths and environment variables) and then use `discoverFormats` to find all available formats. This is essential for tools that need to know which story formats are supported. ```typescript import { discoverFormats, getFormatSearchDirs, parseFormatJSON } from '@rohal12/twee-ts'; // Get all format search directories const dirs = getFormatSearchDirs(['/custom/formats']); console.log(dirs); // ['/custom/formats', '~/.local/share/tweego/storyformats', ...] // Discover all formats const formats = discoverFormats(dirs); for (const [id, format] of formats) { console.log(`${id}: ${format.name} ${format.version} (${format.formatType})`); } // sugarcube-2: SugarCube 2.37.3 (twine2) // harlowe-3: Harlowe 3.3.9 (twine2) ``` -------------------------------- ### Twee Source Example with Tag Aliases Source: https://github.com/rohal12/twee-ts/blob/main/docs/tag-aliases.md This Twee source code demonstrates the usage of custom tag aliases like 'library', 'theme', and 'dev-note' within passage definitions. These aliases are later resolved by Twee-TS to their corresponding special tags, affecting how the passages are processed and included in the final output. ```twee :: StoryData {"ifid": "D674C58C-DEFA-4F70-B7A2-27742230C0FC"} :: StoryTitle My Story :: Start Hello, world! :: Utils [library] window.utils = { greet: () => "hi" }; :: Dark Theme [theme] body { background: #1a1a1a; color: #eee; } :: Design Notes [dev-note] This passage is excluded from the compiled output. ``` -------------------------------- ### Parse Twee Source Files with Lexer and Parser Source: https://context7.com/rohal12/twee-ts/llms.txt This code snippet showcases the low-level Twee TS APIs for lexing and parsing Twee source files. It includes examples of using the `tweeLexer` to tokenize the source and `parseTwee` to directly convert it into passage objects. These APIs are valuable for developing custom tooling, analysis applications, or integrating Twee parsing into other systems. ```typescript import { tweeLexer, parseTwee } from '@rohal12/twee-ts'; const source = `:: Start [tag1 tag2] Hello, world! [[Go somewhere|Destination]] :: Destination You arrived!`; // Low-level lexer (generator) for (const item of tweeLexer(source, 'story.tw')) { console.log(item.type, item.val); // ItemType.PASSAGE_HEADER "Start" // ItemType.TAG "tag1" // ItemType.TAG "tag2" // ItemType.PASSAGE_BODY "Hello, world!\n[[Go somewhere|Destination]]" // ... } // Parse directly to passages const passages = parseTwee(source, 'story.tw'); for (const p of passages) { console.log(`${p.name} [${p.tags.join(', ')}]: ${p.text.slice(0, 30)}...`); } ``` -------------------------------- ### CLI Configuration and Overrides Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Explains how to manage configuration settings, override them via CLI flags, and handle tag aliases. ```APIDOC ## CLI Configuration and Overrides ### Description Configure twee-ts behavior using a JSON configuration file or override settings directly via CLI flags. CLI flags take precedence over config file values. ### Parameters #### Request Body (twee-ts.config.json) - **tagAliases** (Record) - Optional - Map custom tag names to canonical special tags. - **formatId** (string) - Optional - The target format ID (e.g., sugarcube-2). - **startPassage** (string) - Optional - The name of the starting passage. ### Request Example { "formatId": "sugarcube-2", "startPassage": "Begin" } ### CLI Usage Example `twee-ts -f harlowe-3` ### Note For `tagAliases`, CLI `--tag-alias` flags are merged on top of config values. ``` -------------------------------- ### Initialize Project Scaffolding Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Uses the npx command to initialize a new twee-ts project. This generates a default configuration file and starter source files. ```shell npx @rohal12/twee-ts --init ``` -------------------------------- ### List Available Story Formats Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-formats.md Use the CLI to display all locally discovered and cached remote story formats available to the project. ```shell twee-ts --list-formats ``` -------------------------------- ### Override Configuration via CLI Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Demonstrates how to provide a configuration file and override specific settings using command-line flags. The CLI flags take precedence over the values defined in the JSON configuration file. ```json { "formatId": "sugarcube-2", "startPassage": "Begin" } ``` ```shell twee-ts -f harlowe-3 ``` -------------------------------- ### Complete Configuration Reference Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md A comprehensive list of all available configuration keys with their default values. ```APIDOC ## Complete Reference Every key with its default value: ```json { "sources": ["src/"], "output": "story.html", "outputMode": "html", "formatId": "sugarcube-2", "startPassage": "Start", "formatPaths": [], "formatIndices": [], "formatUrls": [], "useTweegoPath": true, "modules": [], "headFile": "", "trim": true, "twee2Compat": false, "testMode": false, "noRemote": false, "tagAliases": {}, "sourceInfo": false, "wordCountMethod": "tweego" } ``` ``` -------------------------------- ### Embed Story Stylesheet Source: https://github.com/rohal12/twee-ts/blob/main/specs/twine2-htmloutput-spec.md CSS rules are defined within a ``` -------------------------------- ### Basic twee-ts CLI Usage Source: https://github.com/rohal12/twee-ts/blob/main/README.md Demonstrates common command-line interface commands for twee-ts, including project initialization, compilation, and watch mode. ```sh npx @rohal12/twee-ts --init # scaffold a new project npx @rohal12/twee-ts -o story.html src/ # compile npx @rohal12/twee-ts -w -o story.html src/ # watch mode ``` -------------------------------- ### Compile to HTML Source: https://github.com/rohal12/twee-ts/blob/main/docs/output-modes.md Generates a playable HTML file using a story format template. Defaults to sugarcube-2 if no format is specified. ```sh twee-ts -o story.html src/ ``` -------------------------------- ### Define StoryData Metadata in Twee Source: https://github.com/rohal12/twee-ts/blob/main/specs/twee3-spec.md This snippet demonstrates the JSON structure for StoryData, which includes the required IFID, format details, starting passage, and tag-color mappings. It is recommended to pretty-print this JSON for readability within the Twee file. ```Twee :: StoryData { "ifid": "D674C58C-DEFA-4F70-B7A2-27742230C0FC", "format": "SugarCube", "format-version": "2.28.2", "start": "My Starting Passage", "tag-colors": { "bar": "green", "foo": "red", "qaz": "blue" }, "zoom": 0.25 } ``` -------------------------------- ### Scaffolding a new project Source: https://github.com/rohal12/twee-ts/blob/main/docs/cli.md Initializes a new twee-ts project by generating a default configuration file and starter passage files in the current working directory. ```shell twee-ts --init ``` -------------------------------- ### Import Public Types from Twee-ts Source: https://github.com/rohal12/twee-ts/blob/main/docs/api.md This snippet demonstrates how to import all public types provided by the '@rohal12/twee-ts' library. These types are re-exported from the main entry point and can be used for type checking and defining interfaces within your project. Importing types requires the '@rohal12/twee-ts' package to be installed. ```typescript import type { CompileOptions, CompileToFileOptions, WatchOptions, CompileResult, CompileStats, Diagnostic, Story, Passage, PassageMetadata, StoryFormatInfo, OutputMode, SourceInput, InlineSource, LexerItem, ItemType, SFAIndex, SFAIndexEntry, SourceLocation, TweeTsConfig, LintResult, CachedFormatEntry, } from '@rohal12/twee-ts'; ``` -------------------------------- ### Utilize Type Support in Story Scripts Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md Demonstrates how to leverage type-checked configurations and macro contexts within story scripts, including explicit type imports. ```typescript // story-script.ts Config.passages.start = 'Prologue'; Macro.add('greet', { handler() { this.output.append('Hello!'); }, }); import type { MacroContext } from '@twine-formats/my-format'; function myHelper(ctx: MacroContext): void { // ... } ``` -------------------------------- ### Apply Tag Aliases Directly with Twee-TS Lower-Level API Source: https://github.com/rohal12/twee-ts/blob/main/docs/tag-aliases.md This TypeScript example demonstrates the direct use of the `applyTagAliases` function from the Twee-TS library. It shows how to manually apply tag aliases to an array of `Passage` objects, modifying their tags in place. This is useful for advanced scenarios or custom passage processing. ```typescript import { applyTagAliases } from '@rohal12/twee-ts'; import type { Passage } from '@rohal12/twee-ts'; const passages: Passage[] = [{ name: 'Utils', tags: ['library'], text: 'window.x = 1;' }]; applyTagAliases(passages, { library: 'script' }); // passages[0].tags is now ['library', 'script'] ``` -------------------------------- ### Configure Output Mode Source: https://github.com/rohal12/twee-ts/blob/main/docs/output-modes.md Sets the default output mode via the configuration file. CLI flags will override these settings. ```json { "outputMode": "html" } ``` -------------------------------- ### Project Scaffolding Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Initializes a new twee-ts project with default configuration and source files. ```APIDOC ## CLI Initialization ### Description Generates a starter configuration file and base source files for a new project. ### Command `npx @rohal12/twee-ts --init` ### Generated Files - **twee-ts.config.json**: Contains `sources` and `output` configuration. - **src/StoryData.tw**: Contains a generated IFID. - **src/Start.tw**: Contains a starter passage. ``` -------------------------------- ### Generate and Validate Interactive Fiction Identifiers (IFIDs) Source: https://context7.com/rohal12/twee-ts/llms.txt This example illustrates the use of Twee TS functions for generating and validating Interactive Fiction Identifiers (IFIDs). It covers generating a new random IFID, checking the validity of an IFID string, and creating a type-safe IFID using `createIFID`. IFIDs are crucial for uniquely identifying interactive fiction projects. ```typescript import { generateIFID, validateIFID, createIFID } from '@rohal12/twee-ts'; import type { IFID } from '@rohal12/twee-ts'; // Generate a new random IFID const ifid = generateIFID(); console.log(ifid); // "A1B2C3D4-E5F6-7890-ABCD-EF1234567890" // Validate an IFID string console.log(validateIFID('D674C58C-DEFA-4F70-B7A2-27742230C0FC')); // true console.log(validateIFID('invalid-ifid')); // false // Create a branded IFID type for compile-time safety const branded: IFID = createIFID('D674C58C-DEFA-4F70-B7A2-27742230C0FC'); ``` -------------------------------- ### twee-ts Configuration File Usage Source: https://github.com/rohal12/twee-ts/blob/main/README.md Shows how to use a JSON configuration file (`twee-ts.config.json`) to specify project sources and output file for the twee-ts compiler. ```json { "sources": ["src/"], "output": "story.html" } ``` ```sh npx @rohal12/twee-ts ``` -------------------------------- ### Field Reference: Sources & Output Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Details on configuring input sources and output file paths. ```APIDOC ### Sources & Output | Key | Type | Default | Description | | ------------ | ---------- | -------- | ------------------------------------------------------------------ | | `sources` | `string[]` | — | Files or directories to compile. Directories are walked recursively. | | `output` | `string` | stdout | Output file path. | | `outputMode` | `string` | `"html"` | One of `html`, `twee3`, `twee1`, `twine2-archive`, `twine1-archive`, `json`. | ``` -------------------------------- ### HTML Comment Patterns for Twine Build Info Source: https://github.com/rohal12/twee-ts/blob/main/specs/twine1-htmloutput-doc.md Demonstrates the two standard HTML comment structures used to store Twine version and build information. These patterns are typically located within the head element of the generated story file. ```html ``` ```html ``` -------------------------------- ### Twine 1 Story Settings Passage (HTML) Source: https://github.com/rohal12/twee-ts/blob/main/specs/twine1-htmloutput-doc.md Illustrates the HTML structure for the 'StorySettings' passage, which contains newline-separated key-value pairs for configuring story behavior like undo, bookmarking, and obfuscation. ```html
jquery:off nhash:off bookmark:on modernizr:off undo:off obfuscate:rot13 exitprompt:off blankcss:off ``` -------------------------------- ### Complete Twee-TS Configuration Reference Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md A comprehensive twee-ts configuration file showing all available keys with their default values. This serves as a reference for all possible settings. ```json { "sources": ["src/"], "output": "story.html", "outputMode": "html", "formatId": "sugarcube-2", "startPassage": "Start", "formatPaths": [], "formatIndices": [], "formatUrls": [], "useTweegoPath": true, "modules": [], "headFile": "", "trim": true, "twee2Compat": false, "testMode": false, "noRemote": false, "tagAliases": {}, "sourceInfo": false, "wordCountMethod": "tweego" } ``` -------------------------------- ### Configure Custom Remote Format Sources Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-formats.md Define custom indices or direct URLs for story formats via the CLI or configuration file to override default archive behavior. ```shell twee-ts --format-index https://example.com/index.json twee-ts --format-url https://example.com/my-format/format.js ``` ```json { "formatIndices": ["https://example.com/index.json"], "formatUrls": ["https://example.com/my-format/format.js"] } ``` -------------------------------- ### Configure package.json for Twine Story Format Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md Defines the package metadata, exports, and required keywords for a Twine story format package. ```json { "name": "@twine-formats/my-format", "version": "1.0.0", "type": "module", "exports": { ".": "./index.js" }, "keywords": ["twine-story-format"], "files": ["index.js", "format.js"] } ``` -------------------------------- ### Include Source Code in Package Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md Configures the package.json to include source files and adds JSDoc @see tags to link type declarations to implementation files. ```json { "files": ["index.js", "format.js", "types", "src"] } ``` ```typescript /** * Story format configuration. * @see {@link ../src/config.js} for the implementation. */ export interface FormatConfig { // ... } ``` -------------------------------- ### CompileOptions Reference Source: https://github.com/rohal12/twee-ts/blob/main/docs/plugins.md Details on the available options for `compileOptions` that can be passed to both Vite and Rollup plugins. ```APIDOC ## Using `compileOptions` ### Description Both the Vite and Rollup plugins accept a `compileOptions` object. This object's properties are spread into the main `compile()` function call, allowing fine-grained control over the compilation process. ### Method Passed as an option to `tweeTsPlugin` in `vite.config.ts` or `rollup.config.js`. ### Endpoint N/A (Build tool plugin configuration) ### Parameters #### `compileOptions` Fields - **startPassage** (string) - The name of the passage to start the story with. - **tagAliases** (object) - Aliases for specific tags (e.g., `{ library: 'script', theme: 'stylesheet' }`). - **modules** (string[]) - Paths to additional JavaScript modules to include. - **headFile** (string) - Path to an HTML file to include in the `` section. - **trim** (boolean) - If true, trims whitespace from passage content. - **twee2Compat** (boolean) - If true, enables compatibility mode for Twee 2 syntax. - **testMode** (boolean) - If true, enables test mode for the compiler. - **noRemote** (boolean) - If true, disables fetching remote resources. **Note**: The `sources` and `formatId` fields are controlled by the plugin's top-level options and should not be set within `compileOptions`. ### Request Example ```typescript compileOptions: { startPassage: 'Prologue', tagAliases: { library: 'script' }, modules: ['src/analytics.js'], headFile: 'src/head.html', trim: true, twee2Compat: false, testMode: false, noRemote: false, } ``` ### Response #### Success Response Compilation proceeds with the specified options. #### Response Example N/A (Build tool output) ``` -------------------------------- ### Compile Twee source to various output formats Source: https://context7.com/rohal12/twee-ts/llms.txt Demonstrates how to use the compile function to transform Twee source files into different formats such as HTML, Twee 3, Twee 1, Twine archives, or JSON. The outputMode parameter dictates the final structure, which is useful for both playable stories and data analysis. ```typescript import { compile } from '@rohal12/twee-ts'; const html = await compile({ sources: ['src/'], outputMode: 'html' }); const twee3 = await compile({ sources: ['src/'], outputMode: 'twee3' }); const twee1 = await compile({ sources: ['src/'], outputMode: 'twee1' }); const archive2 = await compile({ sources: ['src/'], outputMode: 'twine2-archive' }); const archive1 = await compile({ sources: ['src/'], outputMode: 'twine1-archive' }); const json = await compile({ sources: ['src/'], outputMode: 'json' }); console.log(JSON.parse(json.output)); ``` -------------------------------- ### Configure TypeScript for Story Authors Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md Shows how story authors enable global type declarations in their project by updating the tsconfig.json file. ```json { "compilerOptions": { "types": ["@twine-formats/my-format"] } } ``` -------------------------------- ### Minimal Twee-TS Configuration Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md The most basic twee-ts configuration file. It requires only the 'sources' and 'output' properties to specify input files and the output file name. ```json { "sources": ["src/"], "output": "story.html" } ``` -------------------------------- ### JSON Schema Integration Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Enable autocompletion and validation in editors by adding the `$schema` key to your config file, or rely on SchemaStore for automatic association. ```APIDOC ## JSON Schema The config file has a [JSON Schema](https://json-schema.org/) that provides autocompletion, validation, and inline documentation in editors like VS Code. Add a `$schema` key to enable it: ```json { "$schema": "https://unpkg.com/@rohal12/twee-ts/schemas/twee-ts.config.schema.json", "sources": ["src/"], "output": "story.html" } ``` The schema is also submitted to [SchemaStore](https://www.schemastore.org/), so editors that use SchemaStore will automatically associate `twee-ts.config.json` files with the schema — no `$schema` key needed. ``` -------------------------------- ### Define format.js Story Format Metadata Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md The standard Twine 2 format file containing the name, version, and HTML source template. ```javascript window.storyFormat({ name: 'My Format', version: '1.0.0', source: '...{{STORY_NAME}}...{{STORY_DATA}}...', }); ``` -------------------------------- ### Manage Remote Format Cache via CLI Source: https://context7.com/rohal12/twee-ts/llms.txt This section details the command-line interface (CLI) commands provided by Twee TS for managing the remote story format cache. It covers listing cached formats, checking cache size, clearing specific formats or the entire cache, and printing the cache directory path. These commands offer a convenient way to interact with the cache without writing code. ```bash # List cached formats with details npx @rohal12/twee-ts cache list # SugarCube 2.37.3 245K 2026-02-15 # Harlowe 3.3.9 512K 2026-01-20 # Show total cache size npx @rohal12/twee-ts cache size # Total: 757K (2 formats) # Clear specific format npx @rohal12/twee-ts cache clear Harlowe # Cleared 1 cached format. # Clear all cached formats npx @rohal12/twee-ts cache clear # Print cache directory path npx @rohal12/twee-ts cache path ``` -------------------------------- ### CLI Commands for Twee TS Source: https://context7.com/rohal12/twee-ts/llms.txt Common CLI operations including project initialization, compilation, watching for changes, linting, and decompilation. ```bash npx @rohal12/twee-ts --init npx @rohal12/twee-ts -o story.html src/ npx @rohal12/twee-ts -w -o story.html src/ npx @rohal12/twee-ts -o story.html -f harlowe-3 src/ npx @rohal12/twee-ts --lint src/ npx @rohal12/twee-ts -d -o story.twee story.html npx @rohal12/twee-ts --json -o story.json src/ npx @rohal12/twee-ts --list-formats ``` -------------------------------- ### Compile Twee Sources to File Source: https://context7.com/rohal12/twee-ts/llms.txt The compileToFile function simplifies the process of compiling Twee sources and writing the resulting output directly to a specified file path. ```typescript import { compileToFile } from '@rohal12/twee-ts'; const result = await compileToFile({ sources: ['src/'], outFile: 'dist/story.html', formatId: 'sugarcube-2', startPassage: 'Prologue', tagAliases: { macro: 'widget' }, }); console.log(`Compiled ${result.stats.passages} passages to ${result.stats.words} words`); ``` -------------------------------- ### Compilation and Decompilation API Source: https://github.com/rohal12/twee-ts/blob/main/docs/cli.md Core commands for compiling source directories to story files or decompiling story files back to Twee source. ```APIDOC ## CLI COMMAND: twee-ts compile/decompile ### Description Compiles Twee 3 source files into story formats or decompiles HTML story files back into Twee source. ### Method CLI Command ### Endpoint twee-ts [options] ### Parameters #### Options - **-o, --output** (string) - Output file path. - **-f, --format** (string) - Specify the story format. - **-d, --decompile** (boolean) - Enables decompile mode. - **-w, --watch** (boolean) - Enables watch mode for live updates. - **-c, --config** (string) - Path to custom configuration file. ### Request Example twee-ts -o story.html -f harlowe-3 src/ ### Response #### Success Response - **Status** (string) - Returns compilation status or file generation confirmation. ``` -------------------------------- ### Field Reference: Compilation Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Settings related to the compilation process. ```APIDOC ### Compilation | Key | Type | Default | Description | | ----------------- | --------- | ---------- | ---------------------------------------------------------------------------------------------- | | `startPassage` | `string` | `"Start"` | Name of the starting passage. | | `trim` | `boolean` | `true` | Trim leading and trailing whitespace from passage content. | | `twee2Compat` | `boolean` | `false` | Enable Twee2 syntax compatibility mode. | | `testMode` | `boolean` | `false` | Enable test/debug mode (sets the `debug` option in story data). | | `sourceInfo` | `boolean` | `false` | Embed source file/line as `data-` attributes on passage elements. | | `wordCountMethod` | `string` | `"tweego"` | Word counting: `"tweego"` (chars / 5, matches Tweego) or `"whitespace"` (standard word count). | ``` -------------------------------- ### Compile Twee Sources Programmatically Source: https://github.com/rohal12/twee-ts/blob/main/docs/api.md Demonstrates how to compile Twee sources into an HTML string using the compile function. It returns a result object containing the output, parsed story model, diagnostics, and compilation statistics. ```typescript import { compile } from '@rohal12/twee-ts'; const result = await compile({ sources: ['src/'], formatId: 'sugarcube-2', tagAliases: { library: 'script' }, }); console.log(result.output); console.log(result.story); console.log(result.diagnostics); ``` -------------------------------- ### Create index.js ESM Wrapper Source: https://github.com/rohal12/twee-ts/blob/main/docs/story-format-packages.md An ESM wrapper that reads the format.js file and exports its metadata for use by twee-ts. ```javascript import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { dirname, join } from 'node:path'; const __dirname = dirname(fileURLToPath(import.meta.url)); const raw = readFileSync(join(__dirname, 'format.js'), 'utf-8'); const json = JSON.parse(raw.slice(raw.indexOf('{'), raw.lastIndexOf('}') + 1)); export const name = json.name; export const version = json.version; export const source = json.source; export const proofing = json.proofing ?? false; ``` -------------------------------- ### Programmatic API Source: https://github.com/rohal12/twee-ts/blob/main/docs/index.md Demonstrates how to use the twee-ts compiler programmatically within your TypeScript or JavaScript projects. ```APIDOC ## Programmatic API ### Description This section details how to use the twee-ts compiler directly within your code using its programmatic API. ### Usage Import the necessary functions and use them to compile your Twee projects. ```typescript import { compile } from '@rohal12/twee-ts'; const result = await compile({ sources: ['src/'], tagAliases: { library: 'script' }, }); ``` ### Functions - **compile(options)**: Compiles Twee source files. - **compileToFile(options)**: Compiles Twee source files and writes to a file. - **watch(options)**: Watches source files for changes and recompiles. ### Options - **sources** (string[]): An array of paths to source files or directories. - **output** (string, optional): The output file path. Required for `compileToFile`. - **tagAliases** (object, optional): An object mapping custom tag names to built-in tags (e.g., `{ library: 'script' }`). - **distDir** (string, optional): The distribution directory for compiled files. - **watch** (boolean, optional): Enable watch mode (for `compile` function). - **clean** (boolean, optional): Clean the output directory before compilation. - **verbose** (boolean, optional): Enable verbose logging. - **force** (boolean, optional): Force compilation even if output is up to date. - **formats** (string[], optional): Specify which story formats to use. - **formatPaths** (string[], optional): Paths to local story format directories. - **formatArgs** (object, optional): Arguments to pass to story formats. - **macros** (object, optional): Custom macros to define. - **plugins** (object[], optional): Array of build tool plugins. ``` -------------------------------- ### Node.js Built-in Module Imports Source: https://github.com/rohal12/twee-ts/blob/main/CLAUDE.md Illustrates the preferred method for importing Node.js built-in modules in TypeScript projects. Using the 'node:' prefix improves clarity and avoids potential global namespace conflicts. ```typescript import fs from 'node:fs'; import path from 'node:path'; ``` -------------------------------- ### TypeScript Error Handling with Context Source: https://github.com/rohal12/twee-ts/blob/main/CLAUDE.md Demonstrates best practices for error handling in TypeScript, focusing on propagating errors with context and handling edge cases explicitly. It advises against using libraries like Zod for runtime validation to maintain zero dependencies. ```typescript // Example of propagating errors with context async function readFileContent(filePath: string): Promise { try { const content = await node:fs.promises.readFile(filePath, 'utf-8'); return content; } catch (error) { throw new Error(`Failed to read file ${filePath}: ${error.message}`); } } // Handling edge cases function processArray(arr: string[] | undefined) { if (!arr || arr.length === 0) { console.warn('Array is empty or undefined.'); return; } // process array elements } ``` -------------------------------- ### Field Reference: Head Injection Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Options for injecting custom scripts or HTML into the document head. ```APIDOC ### Head Injection | Key | Type | Default | Description | | ---------- | ---------- | ------- | ---------------------------------------------------------------- | | `modules` | `string[]` | `[]` | JS or CSS files to inject into the HTML ``. | | `headFile` | `string` | `""` | Path to a raw HTML file whose contents are appended to ``. | ``` -------------------------------- ### CLI Output Modes Source: https://github.com/rohal12/twee-ts/blob/main/docs/output-modes.md Details on how to control the output format of the twee-ts compiler using CLI flags or configuration files. ```APIDOC ## CLI Output Modes ### Description Controls the format of the compiled or decompiled story data produced by twee-ts. Modes can be set via CLI flags or the `outputMode` configuration key. ### Method CLI Execution ### Parameters #### Flags - **-o** (string) - Required - Output file path - **-d** (flag) - Optional - Decompile to Twee 3 - **--decompile-twee1** (flag) - Optional - Decompile to Twee 1 - **-a** (flag) - Optional - Output as Twine 2 Archive - **--archive-twine1** (flag) - Optional - Output as Twine 1 Archive - **--json** (flag) - Optional - Output as JSON ### Supported Modes - **html**: Compiles to a playable HTML file (default). - **twee3**: Decompiles to Twee 3 notation. - **twee1**: Decompiles to Twee 1 notation. - **twine2-archive**: Outputs raw XML ``. - **twine1-archive**: Outputs Twine 1 compatible archive. - **json**: Outputs story model as JSON. ### Configuration Example { "outputMode": "html" } ### Response Example (JSON Mode) { "name": "My Story", "ifid": "D674C58C-DEFA-4F70-B7A2-27742230C0FC", "format": "SugarCube", "passages": [ { "name": "Start", "tags": [], "text": "Hello, world!" } ] } ``` -------------------------------- ### Compile Twee to File Source: https://github.com/rohal12/twee-ts/blob/main/docs/api.md Compiles Twee source files directly to a specified output file path. ```typescript import { compileToFile } from '@rohal12/twee-ts'; const result = await compileToFile({ sources: ['src/'], outFile: 'story.html', }); ``` -------------------------------- ### Twine 2 Story Format Wrapper (JavaScript) Source: https://github.com/rohal12/twee-ts/blob/main/specs/twine2-storyformats-spec.md The standard structure for a Twine 2 story format is a single JavaScript file that immediately calls the `window.storyFormat` function. This function accepts an object containing the story format's metadata, such as its name and version. ```javascript window.storyFormat({ "name": "Snowman", "version": "1.3.0", ... }); ``` -------------------------------- ### Manage Remote Story Formats with Twee-ts Source: https://github.com/rohal12/twee-ts/blob/main/docs/api.md This snippet demonstrates how to interact with remote story formats using the '@rohal12/twee-ts' library. It covers resolving formats, discovering, listing, and clearing cached formats, as well as retrieving cache size and directory information. Dependencies include the '@rohal12/twee-ts' package. ```typescript import { resolveRemoteFormat, fetchAndCacheFormat, discoverCachedFormats, listCachedFormats, clearCachedFormats, getCacheSize, getCacheDir, } from '@rohal12/twee-ts'; // Auto-resolve from SFA indices const format = await resolveRemoteFormat('SugarCube', '2.37.3'); // List cached formats (Map) const cached = discoverCachedFormats(); // List cached formats with size and modification date const entries = listCachedFormats(); for (const e of entries) { console.log(`${e.name} ${e.version} — ${e.sizeBytes} bytes, modified ${e.modifiedAt.toISOString()}`); } // Clear all cached formats (returns count removed) clearCachedFormats(); // Clear cached formats by name clearCachedFormats('SugarCube'); // Get total cache size const { totalBytes, count } = getCacheSize(); // Get cache directory path const cacheDir = getCacheDir(); ``` -------------------------------- ### Export to Twine 1 Archive Source: https://github.com/rohal12/twee-ts/blob/main/docs/output-modes.md Generates a Twine 1-compatible archive containing tiddler elements. Supports optional ROT13 obfuscation for passage content. ```sh twee-ts --archive-twine1 -o archive.html src/ ``` -------------------------------- ### Define Compile Options Source: https://github.com/rohal12/twee-ts/blob/main/docs/plugins.md Defines the structure for advanced compilation settings available to both Vite and Rollup plugins. ```typescript compileOptions: { startPassage: 'Prologue', tagAliases: { library: 'script' }, modules: ['src/analytics.js'], headFile: 'src/head.html', trim: true, twee2Compat: false, testMode: false, noRemote: false, } ``` -------------------------------- ### Configuration Loading Source: https://github.com/rohal12/twee-ts/blob/main/docs/configuration.md Twee-ts automatically loads 'twee-ts.config.json'. You can specify a different file with '-c' or disable loading with '--no-config'. ```APIDOC ## Configuration Loading Twee-ts automatically loads `twee-ts.config.json` from the current working directory. Use `-c ` to specify a different path, or `--no-config` to skip loading entirely. ```