Table of Contents

smudgy:core — Automations

Generated from smudgy v0.5.6 (smudgy-core.d.ts @ a6d8757f1b33). Index: scriptref.

Aliases, triggers, timers, and hotkeys created from scripts: the create* functions, the handles they return, and the registries. These are cleared and recreated on every script reload. For the saved automations shown in the automations window, see saved-automations.

For examples that combine trigger text with foreground, background, text attributes, or color ranges, see Match colors in scripted triggers.

createAlias

export function createAlias(
  patterns: Pattern | Pattern[] | Command,
  script: AutomationScript,
  options?: AliasOptions,
): Alias;

Create an alias: a shortcut that watches what you type and runs a script instead of sending it. patterns is one regex or several — or a command value for word-and-arguments matching; when your input matches, script runs: a command template string, or a function that receives the Matches.

import { command, createAlias } from "smudgy:core";
// Typing "gt any message here" sends "guildtell any message here".
createAlias("^gt (.+)$", "guildtell $1");
// The same shortcut as a command, with tab completion and a usage line.
createAlias(command`gt [words...]`, "guildtell $words");

The typed command is consumed by default (see capture). Aliases created this way last until the next script reload, and show up in the automations window named after their pattern (pass options.name to label one yourself). Returns an Alias handle.

createTrigger

export function createTrigger(
  patterns: TriggerPattern | TriggerPatterns,
  script: AutomationScript,
  options?: TriggerOptions,
): Trigger;

Create a trigger: it watches every line arriving from the MUD and runs a script on a match. patterns is one TriggerPattern, or a TriggerPatterns object for alternatives/raw/veto patterns; script is a command template string, or a function that receives the Matches. A style chain can qualify one regex occurrence, or stand alone to match any incoming run with that terminal style.

import { createTrigger, send, style } from "smudgy:core";
 
createTrigger(style.red(/^Danger:/), () => send("flee"));
createTrigger({
  patterns: [style.yellow(/^Warning:/), style.red(/^Danger:/)],
  antiPatterns: [style.faint(/harmless/)],
}, ({ 0: warning }) => {
  send(`say I saw: ${warning}`);
});

Triggers created this way last until the next script reload, and show up in the automations window named after their patterns (pass options.name to label one yourself); see TriggerOptions for prompt matching, fire limits, and more. Returns a Trigger handle.

createTriggers

export function createTriggers(triggers: Record<string, TriggerDef>): Record<string, Trigger>;

Create several triggers in one call: pass an object mapping each name to its TriggerDef; get back the same names mapped to their Trigger handles. The keys make this the natural form for a staged chain (chain.row.enabled = true) and give multi-pattern triggers a readable name in the automations window.

import { createTriggers, style } from "smudgy:core";
 
createTriggers({
  warning: {
    patterns: [style.yellow(/^Warning:/), style.red(/^Danger:/)],
    script: "look",
  },
  recovery: {
    patterns: [style.green(/^You recover/)],
    script: "score",
  },
});

createTimer

export function createTimer(options: TimerOptions, callback: () => void): Timer;

Create a timer that runs callback after intervalMs milliseconds: once by default, or repeatedly with repeat: true.

import { createTimer, send } from "smudgy:core";
// Keep sipping, every 30 seconds until deleted:
const sip = createTimer({ intervalMs: 30000, repeat: true },
  () => send("drink potion"));
// later: sip.delete();

Timers are cleared on script reload. Returns a Timer handle; set enabled = false to pause it, or delete() to stop it.

createHotkey

export function createHotkey(keySpec: KeySpec, handler: () => void, options?: HotkeyOptions): Hotkey;

Bind a keyboard shortcut: handler runs whenever the KeySpec combination is pressed in this session.

import { createHotkey, send } from "smudgy:core";
createHotkey({ key: "F1" }, () => send("flee"));
createHotkey({ key: "h", modifiers: ["ctrl"] }, () => send("cast 'heal' self"));

Hotkeys are cleared on script reload. Returns a Hotkey handle.

fallthrough

export function fallthrough(value: boolean): void;

Inside an alias or trigger function handler, decide whether later matching automations from the same script/package may run for this dispatch. This overrides the automation's fallthrough option for this invocation only. Nested send() calls begin a fresh alias dispatch.

Alias

export interface Alias {
  readonly name: string;
  readonly created?: boolean;
  enabled: boolean;
  readonly pattern: string;
  readonly priority: number;
  readonly fallthrough: boolean;
  delete(): void;
}

A handle to a script-created alias: enable/disable it with enabled, remove it with delete(). Returned by createAlias.

Trigger

export interface Trigger {
  readonly name: string;
  readonly created?: boolean;
  enabled: boolean;
  readonly pattern: string;
  readonly priority: number;
  readonly fallthrough: boolean;
  delete(): void;
}

A handle to a script-created trigger; the same shape as Alias. Returned by createTrigger.

Timer

export interface Timer {
  readonly name: string;
  enabled: boolean;
  delete(): void;
}

A handle to a script-created timer. Returned by createTimer; timers are cleared on script reload.

Hotkey

export interface Hotkey {
  readonly name: string;
  enabled: boolean;
  delete(): void;
}

A handle to a script-created hotkey. Returned by createHotkey; hotkeys are cleared on script reload.

aliases

export const aliases: AutomationRegistry<Alias>;

The registry of aliases your scripts created.

triggers

export const triggers: AutomationRegistry<Trigger>;

The registry of triggers your scripts created.

timers

export const timers: AutomationRegistry<Timer>;

The registry of timers your scripts created.

hotkeys

export const hotkeys: AutomationRegistry<Hotkey>;

The registry of hotkeys your scripts created.

AutomationRegistry

export interface AutomationRegistry<H> {
  get(name: string): H | undefined;
  list(): string[];
  exists(name: string): boolean;
}

Look up the automations of one kind that your own scripts created. Each script sees only its own; two scripts can both own a "heal" trigger without colliding.

Matches

export type Matches = {
  readonly [group: number]: string;
  readonly [name: string]: string;
};

The captures handed to a trigger or alias handler. matches[0] is the whole matched text; matches[1], matches[2], and so on are the capture groups in order. A named group like (?<who>...) can also be read by name, as matches.who, and handlers often destructure it: ({ who }) => .... Every group of the pattern that fired is present: one that matched nothing (an optional group, say) is the empty string, not undefined as in standard JavaScript regex matches.

When a trigger has several patterns, only the fired pattern's groups are present; the other patterns' groups are absent and read as undefined. "who" in matches tells you which pattern fired.

InlineTemplate

export type InlineTemplate = string;

A trigger/alias body written as a plain string instead of a function: a command template sent to the MUD after substitution.

Unknown or non-matching groups become the empty string.

Pattern

Support type used by signatures on this page.

type Pattern = string | RegExp;

A match pattern: a regular expression, written either as a RegExp (/^You follow/) or as a string of regex source ("^You follow"). Strings are compiled as regexes, not matched literally.

A RegExp's flags are honored: i and s carry their usual meaning. The rest are dropped. m would promise interior line boundaries, but only a single line is ever matched; g, y, and d have nothing to change in a pattern matched once per line; and u/v are unnecessary — matching is Unicode-aware by default (a v-mode pattern using set notation may be rejected when the automation is created).

pattern

export const pattern: PatternTag;

The pattern tagged template: friendly pattern syntax that evaluates to a RegExp, so it slots anywhere a Pattern goes. Four forms — one per anchor combination:

import { pattern } from "smudgy:core";
 
pattern`You are {state}.`            // the whole line
pattern.startsWith`You are`          // anchored at the front
pattern.endsWith`is hungry.`         // anchored at the end
pattern.contains`is hun`             // anywhere in the line

Syntax, matching the editor's Simple patterns exactly: plain text matches itself, case-sensitively, with any run of spaces matching any run of spaces. {name} is a wildcard hole (lazy; greedy when it ends the pattern), so You are {state}. matches You are very hungry. whole. {name...} takes the rest of the line, {name?} is an optional word, {name:word} exactly one word, {name:number} a number. {} (and {...}, {?}) are the same, anonymous — every hole takes the next group number in the order written; there are no {1}-style numbered holes. * matches anything without capturing, and /…/ is a raw regex island inserted verbatim. Backslashes reach the pattern uncooked, so /\d+/ in an island means the regex digit class.

Interpolated ${values} are always literal text, never syntax — the reason to prefer the tag over string concatenation, and what makes it safe to build patterns from game data. A body that fails to compile throws at evaluation time.

What was written rides along for display on two non-enumerable properties: patternSource (the tag body) and patternAnchors ("both" | "start" | "end" | "none").

PatternTag

Support type used by signatures on this page.

interface PatternTag {
  (strings: TemplateStringsArray, ...values: unknown[]): RegExp;
  startsWith(strings: TemplateStringsArray, ...values: unknown[]): RegExp;
  endsWith(strings: TemplateStringsArray, ...values: unknown[]): RegExp;
  contains(strings: TemplateStringsArray, ...values: unknown[]): RegExp;
}

The four anchor forms of the pattern tag.

StyleMatch

export interface StyleMatch {
  readonly __smudgyStyleMatch: true;
}

Qualifies a trigger Pattern using the terminal colors and attributes at the pattern's first displayed character. A style chain creates this immutable value; regex occurrences are tried from left to right, and captures come from the first occurrence whose style qualifies.

Strings are regex source, just as they are elsewhere in the trigger API:

import { style } from "smudgy:core";
 
style.red`Danger`    // StyledText for output
style.red(/Danger/)  // StyleMatch for an incoming trigger
style.red("Danger")  // also StyleMatch; the string is regex source
style.red("")        // style-only StyleMatch
style.red(new RegExp("")) // ordinary zero-width StyleMatch
style.red``          // empty StyledText, still output

A parenthesized empty string on a constrained chain is the explicit style-only sentinel. style.red("") scans nonempty style runs, or the final cursor style on an empty line, just like passing bare style.red to createTrigger. The handler's matches[0] is ""; $0 in a plaintext body also expands to the empty string. By contrast, new RegExp("").source is "(?:)", so style.red(new RegExp("")) retains ordinary zero-width regex behavior and can qualify only at a position with a displayed character. With no surviving color or positive attribute, style("") remains an inert empty pattern rather than becoming match-all.

StyleMatchBuilder

export interface StyleMatchBuilder {
  (pattern: Pattern): StyleMatch;
  (options: LineColorOptions): StyleMatchBuilder;
  readonly fg: {
    (color: Color): StyleMatchBuilder;
    range(from: RgbColor, to: RgbColor): StyleMatchBuilder;
  };
  readonly bg: {
    (color: Color): StyleMatchBuilder;
    range(from: RgbColor, to: RgbColor): StyleMatchBuilder;
  };
  readonly black: StyleMatchBuilder;
  readonly red: StyleMatchBuilder;
  readonly green: StyleMatchBuilder;
  readonly yellow: StyleMatchBuilder;
  readonly blue: StyleMatchBuilder;
  readonly magenta: StyleMatchBuilder;
  readonly cyan: StyleMatchBuilder;
  readonly white: StyleMatchBuilder;
  readonly default: StyleMatchBuilder;
  readonly echo: StyleMatchBuilder;
  readonly output: StyleMatchBuilder;
  readonly warn: StyleMatchBuilder;
  readonly bgBlack: StyleMatchBuilder;
  readonly bgRed: StyleMatchBuilder;
  readonly bgGreen: StyleMatchBuilder;
  readonly bgYellow: StyleMatchBuilder;
  readonly bgBlue: StyleMatchBuilder;
  readonly bgMagenta: StyleMatchBuilder;
  readonly bgCyan: StyleMatchBuilder;
  readonly bgWhite: StyleMatchBuilder;
  readonly bold: StyleMatchBuilder;
  readonly faint: StyleMatchBuilder;
  readonly italic: StyleMatchBuilder;
  readonly underline: StyleMatchBuilder;
  readonly doubleUnderline: StyleMatchBuilder;
  readonly crossedOut: StyleMatchBuilder;
  readonly reverse: StyleMatchBuilder;
}

A trigger-only style chain. Calling style.fg.range(...) or style.bg.range(...) creates this builder. It can keep composing exact colors, ranges, and positive attributes, then qualify one Pattern; passed bare to createTrigger, it means “any run with this style.” Foreground, background, and attributes are ANDed.

A chain stays trigger-only after it has used a range, even if a later exact setter replaces that range. Start a new exact StyleBuilder for output. Final theme roles (default, echo, output, warn) and negative attribute requirements are rejected when converted to a trigger.

TriggerPattern

export type TriggerPattern = Pattern | StyleMatch | StyleBuilder | StyleMatchBuilder;

One displayed-text condition accepted by a trigger: a regex source, RegExp, immutable StyleMatch, or a constrained style chain used bare as a color/attribute-only condition. A decorated "" is the same style-only sentinel; a decorated new RegExp("") remains an ordinary zero-width regex. Separate leaves are alternatives.

TriggerPatterns

export type TriggerPatterns = {
  patterns?: readonly TriggerPattern[];
  rawPatterns?: readonly Pattern[];
  antiPatterns?: readonly TriggerPattern[];
};

The three pattern lists a trigger can match with. Most triggers set only patterns. Displayed patterns and rawPatterns are alternatives; the raw pass runs first and a trigger fires at most once per line.

CommandArg

export type CommandArg = {
  readonly name: string;
  readonly kind: "required" | "optional" | "rest";
};

One argument of a command value, in declaration order.

Command

export interface Command {
  readonly word: string;
  readonly args: readonly CommandArg[];
  readonly usage: string;
}

A parsed command... value: the command word plus its argument spec. Hand it to createAlias in the pattern position; the tag is the only way to make one.

command

export const command: CommandTag;

The command tagged template: a command-style alias matcher, written in the editor's Usage-line notation.

import { command, createAlias, send } from "smudgy:core";
createAlias(command`greet <person> [greeting] [words...]`, (m) => {
  send(`say ${m.greeting || "Hello"}, ${m.person}! ${m.words}`);
});

The first token is the command word; <name> is a required argument, [name] optional, and [name...] takes the rest of the line (last position only) — exactly what the editor's Usage row prints, so a Usage line copies straight into a script. Arguments arrive as named entries on the Matches object (an absent optional reads ""); m[0] is the line as typed, and in a string body $name substitutes each argument.

The behavior matches an editor-made Command alias: typing the word with a missing required argument echoes the usage line and consumes the input without running the body; extra words nothing claims fall through to the game; words split on spaces, with quotes or braces grouping a multi-word argument; and the command word tab-completes in the input.

Interpolated ${values} are always literal word text, never syntax, so the word can come from data. A body that fails to parse throws. The alias is named after its word (pass options.name to label it yourself).

CommandTag

Support type used by signatures on this page.

interface CommandTag {
  (strings: TemplateStringsArray, ...values: unknown[]): Command;
}

The command tag's call shape.

TriggerDef

export type TriggerDef = TriggerPatterns & {
  script: InlineTemplate | ((matches: Matches) => string | void);
  prompt?: boolean;
  enabled?: boolean;
  singleton?: boolean;
  fireLimit?: number;
  lineLimit?: number;
  priority?: number;
  fallthrough?: boolean;
};

One trigger in a createTriggers batch: its patterns, its body, and the same options as TriggerOptions (except name — the batch's key is the name).

AliasOptions

export type AliasOptions = {
  name?: string;
  singleton?: boolean;
  fireLimit?: number;
  priority?: number;
  fallthrough?: boolean;
};

Options for createAlias.

TriggerOptions

export type TriggerOptions = {
  name?: string;
  prompt?: boolean;
  enabled?: boolean;
  singleton?: boolean;
  fireLimit?: number;
  lineLimit?: number;
  priority?: number;
  fallthrough?: boolean;
};

Options for createTrigger.

TimerOptions

export type TimerOptions = {
  name?: string;
  intervalMs: number;
  repeat?: boolean;
  fireLimit?: number;
};

Options for createTimer.

HotkeyOptions

export type HotkeyOptions = {
  name?: string;
};

Options for createHotkey.

KeySpec

export type KeySpec = {
  key: HotkeyKey;
  modifiers?: HotkeyModifier[];
};

The key combination for createHotkey.

HotkeyKey

export type HotkeyKey = HotkeyCharacterKey | HotkeyNamedKey | HotkeyPhysicalKey;

A logical character, named logical key, or layout-independent physical key.

HotkeyModifier

export type HotkeyModifier = "ctrl" | "alt" | "shift" | "super";

A modifier accepted by createHotkey.

HotkeyCharacterKey

export type HotkeyCharacterKey =
| HotkeyDigitKey | HotkeyLetterKey | Uppercase<HotkeyLetterKey>
| " " | "!" | "\"" | "#" | "$" | "%" | "&" | "'" | "(" | ")" | "*" | "+" | "," | "-" | "." | "/"
| ":" | ";" | "<" | "=" | ">" | "?" | "@" | "[" | "\\" | "]" | "^" | "_" | "`" | "{" | "|" | "}" | "~"
| `Character(${string})`;

A logical character key. Common keyboard characters can be written directly; use Character(...) for any other Unicode character or grapheme.

HotkeyDigitKey

export type HotkeyDigitKey = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";

A decimal digit used as a logical character key.

HotkeyLetterKey

export type HotkeyLetterKey =
| "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m"
| "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z";

A Latin letter used as a logical character key.

HotkeyNamedKey

export type HotkeyNamedKey =
| "Alt" | "AltGraph" | "CapsLock" | "Control" | "Fn" | "FnLock" | "NumLock" | "ScrollLock"
| "Shift" | "Symbol" | "SymbolLock" | "Meta" | "Hyper" | "Super" | "Enter" | "Tab"
| "Space" | "ArrowDown" | "ArrowLeft" | "ArrowRight" | "ArrowUp" | "End" | "Home" | "PageDown"
| "PageUp" | "Backspace" | "Clear" | "Copy" | "CrSel" | "Cut" | "Delete" | "EraseEof"
| "ExSel" | "Insert" | "Paste" | "Redo" | "Undo" | "Accept" | "Again" | "Attn"
| "Cancel" | "ContextMenu" | "Escape" | "Execute" | "Find" | "Help" | "Pause" | "Play"
| "Props" | "Select" | "ZoomIn" | "ZoomOut" | "BrightnessDown" | "BrightnessUp" | "Eject" | "LogOff"
| "Power" | "PowerOff" | "PrintScreen" | "Hibernate" | "Standby" | "WakeUp" | "AllCandidates" | "Alphanumeric"
| "CodeInput" | "Compose" | "Convert" | "FinalMode" | "GroupFirst" | "GroupLast" | "GroupNext" | "GroupPrevious"
| "ModeChange" | "NextCandidate" | "NonConvert" | "PreviousCandidate" | "Process" | "SingleCandidate" | "HangulMode" | "HanjaMode"
| "JunjaMode" | "Eisu" | "Hankaku" | "Hiragana" | "HiraganaKatakana" | "KanaMode" | "KanjiMode" | "Katakana"
| "Romaji" | "Zenkaku" | "ZenkakuHankaku" | "Soft1" | "Soft2" | "Soft3" | "Soft4" | "ChannelDown"
| "ChannelUp" | "Close" | "MailForward" | "MailReply" | "MailSend" | "MediaClose" | "MediaFastForward" | "MediaPause"
| "MediaPlay" | "MediaPlayPause" | "MediaRecord" | "MediaRewind" | "MediaStop" | "MediaTrackNext" | "MediaTrackPrevious" | "New"
| "Open" | "Print" | "Save" | "SpellCheck" | "Key11" | "Key12" | "AudioBalanceLeft" | "AudioBalanceRight"
| "AudioBassBoostDown" | "AudioBassBoostToggle" | "AudioBassBoostUp" | "AudioFaderFront" | "AudioFaderRear" | "AudioSurroundModeNext" | "AudioTrebleDown" | "AudioTrebleUp"
| "AudioVolumeDown" | "AudioVolumeUp" | "AudioVolumeMute" | "MicrophoneToggle" | "MicrophoneVolumeDown" | "MicrophoneVolumeUp" | "MicrophoneVolumeMute" | "SpeechCorrectionList"
| "SpeechInputToggle" | "LaunchApplication1" | "LaunchApplication2" | "LaunchCalendar" | "LaunchContacts" | "LaunchMail" | "LaunchMediaPlayer" | "LaunchMusicPlayer"
| "LaunchPhone" | "LaunchScreenSaver" | "LaunchSpreadsheet" | "LaunchWebBrowser" | "LaunchWebCam" | "LaunchWordProcessor" | "BrowserBack" | "BrowserFavorites"
| "BrowserForward" | "BrowserHome" | "BrowserRefresh" | "BrowserSearch" | "BrowserStop" | "AppSwitch" | "Call" | "Camera"
| "CameraFocus" | "EndCall" | "GoBack" | "GoHome" | "HeadsetHook" | "LastNumberRedial" | "Notification" | "MannerMode"
| "VoiceDial" | "TV" | "TV3DMode" | "TVAntennaCable" | "TVAudioDescription" | "TVAudioDescriptionMixDown" | "TVAudioDescriptionMixUp" | "TVContentsMenu"
| "TVDataService" | "TVInput" | "TVInputComponent1" | "TVInputComponent2" | "TVInputComposite1" | "TVInputComposite2" | "TVInputHDMI1" | "TVInputHDMI2"
| "TVInputHDMI3" | "TVInputHDMI4" | "TVInputVGA1" | "TVMediaContext" | "TVNetwork" | "TVNumberEntry" | "TVPower" | "TVRadioService"
| "TVSatellite" | "TVSatelliteBS" | "TVSatelliteCS" | "TVSatelliteToggle" | "TVTerrestrialAnalog" | "TVTerrestrialDigital" | "TVTimer" | "AVRInput"
| "AVRPower" | "ColorF0Red" | "ColorF1Green" | "ColorF2Yellow" | "ColorF3Blue" | "ColorF4Grey" | "ColorF5Brown" | "ClosedCaptionToggle"
| "Dimmer" | "DisplaySwap" | "DVR" | "Exit" | "FavoriteClear0" | "FavoriteClear1" | "FavoriteClear2" | "FavoriteClear3"
| "FavoriteRecall0" | "FavoriteRecall1" | "FavoriteRecall2" | "FavoriteRecall3" | "FavoriteStore0" | "FavoriteStore1" | "FavoriteStore2" | "FavoriteStore3"
| "Guide" | "GuideNextDay" | "GuidePreviousDay" | "Info" | "InstantReplay" | "Link" | "ListProgram" | "LiveContent"
| "Lock" | "MediaApps" | "MediaAudioTrack" | "MediaLast" | "MediaSkipBackward" | "MediaSkipForward" | "MediaStepBackward" | "MediaStepForward"
| "MediaTopMenu" | "NavigateIn" | "NavigateNext" | "NavigateOut" | "NavigatePrevious" | "NextFavoriteChannel" | "NextUserProfile" | "OnDemand"
| "Pairing" | "PinPDown" | "PinPMove" | "PinPToggle" | "PinPUp" | "PlaySpeedDown" | "PlaySpeedReset" | "PlaySpeedUp"
| "RandomToggle" | "RcLowBattery" | "RecordSpeedNext" | "RfBypass" | "ScanChannelsToggle" | "ScreenModeNext" | "Settings" | "SplitScreenToggle"
| "STBInput" | "STBPower" | "Subtitle" | "Teletext" | "VideoModeNext" | "Wink" | "ZoomToggle"
| "F1" | "F2" | "F3" | "F4" | "F5" | "F6" | "F7" | "F8" | "F9" | "F10"
| "F11" | "F12" | "F13" | "F14" | "F15" | "F16" | "F17" | "F18" | "F19" | "F20"
| "F21" | "F22" | "F23" | "F24" | "F25" | "F26" | "F27" | "F28" | "F29" | "F30"
| "F31" | "F32" | "F33" | "F34" | "F35";

Every named logical key understood by Smudgy/iced 0.14.

<