Skip to content
Prompting Press v0.2

TypeScript API reference

class Prompt

An immutable, fully-validated prompt. Wraps a NapiPrompt handle; all construction invariants (shape-valid, template-parseable, agreement-sound, reserved-name clean) are enforced by the Rust consumer at construction time There are no setters; the sole mutator is Prompt.derive. ## Construction — four entry points, all throwing on invalid input ts const p = new Prompt(shape, validators?); const p = Prompt.fromYaml(text, validators?); const p = Prompt.fromJson(text, validators?); const p = Prompt.fromToml(text, validators?); // TOML routed to Rust, no smol-toml dep ## validators? — validation_required coverage check When supplied, any variable with validation_required: true must appear in validators.shape. Construction throws a PromptValidationError if a required variable is uncovered. When validators.shape is absent (non-ZodObject schema), the check is skipped. ## render — validate-then-render ts p.render(schema, data, opts?); // schema form: safeParse before templating p.render(data, opts?); // static form (or uses bound validators when present) ## derive(overlay, validators?) — sole mutator Shallow-replaces top-level fields; re-validates the merged whole. Validators carry forward from the source by default; pass validators to override.

get body(): string

The root body template source (the default arm’s unrendered template text).

get metadata(): Record<string, unknown>

The metadata opaque map (library-defined top-level annotations, if any).

get name(): string

The prompt’s name (the name field of the underlying definition).

get outputModel(): string | undefined

The output_model reference, if declared. Carried as metadata only — the library never parses against it.

get role(): string

The conversational role ("system" / "user" / "assistant").

get variables(): object | undefined

The declared variables map (&#123; [name]: PromptVariable &#125;). Read-only metadata. Each entry carries the variable’s type, trusted flag, and optional validation_required.

get variants(): object | undefined

The named variants map (&#123; [name]: PromptVariant &#125;). Empty object when the prompt has no named variants (only the implicit default arm).

new Prompt(shape: PromptDefinition, validators?: ValidatorMap): Prompt

Primary public constructor — constructs a Prompt from a PromptDefinition-shaped object. The optional third parameter _internal is a module-private token (type InternalCtorArg) that can only be formed by code within this module. External callers cannot construct a valid InternalCtorArg value (its type uses a unique symbol brand), so new Prompt(shape, v?) is effectively the only publicly-callable form. The static factories (fromYaml, fromJson, fromToml) and with use the internal path to avoid re-running the Rust validator on an already-validated handle.

check(): CheckReport

Pure advisory lint: returns a CheckReport containing only the trusted/guard finding class ("untrusted_without_guard"). Construction already enforces agreement, parse, and reserved-name invariants; those are structurally unreachable here. Pure: never renders, never mutates.

derive(overlay: Partial<PromptDefinition>, validators?: ValidatorMap): Prompt

The sole mutator: shallow-replace top-level fields from overlay onto a clone of this prompt’s definition, then re-validate the merged whole via the Rust consumer. The original Prompt is untouched (immutability guaranteed). Validators carry forward from the source by default; pass validators to override/augment. Coverage is re-checked against the merged definition.

static fromJson(text: string, validators?: ValidatorMap): Prompt

Construct a Prompt from already-read JSON text.

static fromToml(text: string, validators?: ValidatorMap): Prompt

Construct a Prompt from already-read TOML text. TOML parsing is done by the Rust consumer (toml@1.1.2 via Prompt::from_toml). Raw text is routed to the addon — no smol-toml or other JS TOML library needed.

static fromYaml(text: string, validators?: ValidatorMap): Prompt

Construct a Prompt from already-read YAML text. The text is routed to the Rust consumer’s Prompt::from_yaml — no JS YAML parsing. Error semantics mirror new Prompt.

getSource(opts?: { variant: string } | null): string

Return a variant’s unrendered template source (the exact string the kernel hashes into templateHash). Pure: no vars, no validation. opts.variant selects an arm (absent ⇒ the reserved default).

render(data: unknown, opts?: RenderOptions | null): RenderResult

Render this prompt’s resolved variant with typed inputs, validating first. Three call forms, selected at runtime: - Schema form: render(schema, data, opts?)schema.safeParse(data) runs here, before any templating; on failure a PromptValidationError is thrown and the kernel is never reached. - Static form: render(data, opts?) — already-typed plain data, marshaled directly (no Zod check at render time). - Bound-validator form: render(data, opts?) when the prompt was constructed with validators — the bound schema’s safeParse(data) runs automatically. opts carries &#123; variant?, guard? &#125; as named fields.

class RenderResult

A rendered prompt + its content-addressed provenance, read-only from JS. The Node mirror of the kernel’s RenderResult. Surfaced 1:1 — the binding adds nothing and interprets nothing. Read-only class with camelCase JS accessors (template_hashtemplateHash). A result is produced by renderPrompt, never constructed from JS.

get guard(): string | null

The opt-in guard instruction text (present iff a guard was enabled and the prompt declares a trusted: false field); null for a plain render. Never part of text.

get name(): string

The prompt name.

get renderHash(): string

Lowercase-hex SHA256(rendered text). Surfaces as renderHash.

get templateHash(): string

Lowercase-hex SHA256(resolved variant source). Surfaces as templateHash.

get text(): string

The rendered body text. The guard text is NEVER concatenated here.

get variant(): string

The resolved variant name (the reserved default, or the named arm).

interface GuardConfig

The opt-in guard-expansion config, accepted from JS as a plain object and plumbed through to the kernel. A 1:1 mirror of the kernel’s GuardConfig. This is config only; it carries no logic. The kernel owns guard expansion; the binding only marshals fields across the boundary and surfaces whatever [RenderResult::guard] the kernel populates. Accepted from JS as a plain TS object &#123; enabled, advisory? &#125;. ## Advisory override When advisory is supplied it replaces the fixed default wording returned in RenderResult.guard. The override MUST reference the <untrusted> opening tag, the </untrusted> closing tag, AND an escape indication (&amp;/&lt;/&gt; or the word “escap”) — otherwise the kernel rejects it and a [PromptRenderError] is thrown with errors[0].code === "render" and errors[0].field === "guard".

advisory?: string

Optional override for the advisory sentence returned in RenderResult.guard. null / absent ⇒ the fixed default advisory. When provided, must reference <untrusted>, </untrusted>, and an escape indication; otherwise the kernel rejects it with a structured PromptRenderError.

enabled: boolean

When false, the render is plain and [RenderResult::guard] is None.

interface RenderOptions

Options for Prompt.render.

guard?: GuardConfig | null

Opt-in guard config; absent / &#123; enabled: false &#125; ⇒ a plain render (RenderResult.guard === null).

unsafeRevealRenderDetail?: boolean

Off by default. When true, the full underlying render-error detail is surfaced in the thrown PromptRenderError“.errors[0].messageinstead of the fixed scrubbed string. **Risk:** enabling this may place **bound-value content** — untrusted input, PII, secrets — into the thrown error and into any log line or stack trace derived from it. Use only in a controlled debug context with a trusted log destination, and only after deliberately accepting that exposure. Never settrue` by default or via ambient configuration.

variant?: string

Select a named variant arm; absent ⇒ the reserved default arm.

class CheckReport

The output of a lint check: an ordered, read-only list of [Finding]s. Empty ⇒ the lint passed. The Node mirror of the consumer’s CheckReport. Surfaced 1:1 — the binding adds nothing and interprets nothing. Read-only class with read-only accessors; a report is produced by prompt.check, never constructed from JS.

get findings(): Finding[]

Every lint failure found, in the consumer’s deterministic order. Empty ⇒ pass.

isEmpty(): boolean

report.isEmpty — alias for passed: true iff there are no findings.

passed(): boolean

report.passedtrue iff there are no findings (the lint passed). Reads clearly at a CI gate (if (!prompt.check.passed) process.exit(1)).

interface Finding

One actionable lint finding, read-only from JS. Names the prompt, the variant where applicable (null for a prompt-level finding), the failure kind (a stable snake_case discriminant string — see the module docs), and a human-readable detail. The detail carries no bound-value content (it is built by the consumer from prompt/field names only). Surfaced as a plain JS object with all four fields (the natural shape for the findings array the TS facade iterates / matches on).

detail: string

A human-readable, actionable description. Carries no bound-value content.

kind: string

The failure kind as a stable snake_case discriminant string — the value JS matches on. Currently always "untrusted_without_guard". The kind’s inner datum is echoed in detail.

prompt: string

The prompt’s name.

variant?: string

The variant the finding pertains to; None (undefined in JS) for a prompt-level provenance finding.

class Composition

An explicit, ordered composition of (Prompt, vars, variant?) entries that resolves to an ordered Message[]. Built with new Composition + append or Composition.fromMessages([...]). No fluent .chain. No Registry: each entry holds an owned Prompt object. resolve takes no arguments — it renders using each entry’s stored Prompt handle directly. No-partial guarantee: if any entry fails validation at append/fromMessages, the whole call throws and nothing is stored. If an entry fails at resolve (unknown variant, undefined variable, parse/render), resolve throws and the partial result is discarded.

get length(): number

The number of appended entries (== the resolved-message count on success).

append(entry: CompositionEntry): void

Marshal + store one CompositionEntry. When entry.schema is present, validation runs here (schema.safeParse(entry.data)); on failure a PromptValidationError is thrown and nothing is stored. Returns void (not this): intentionally not fluent.

static fromMessages(entries: readonly CompositionEntry[]): Composition

Build a composition from an ordered array of CompositionEntry objects, validating each in order. The first entry whose schema.safeParse(data) fails throws a PromptValidationError and no Composition is returned (no partial state —).

resolve(): Message[]

Resolve the composition to an ordered Message[], rendering each entry in append order through the kernel (via NapiPrompt.renderPrompt on each stored handle). No Registry — each entry holds its own NapiPrompt handle. One entry’s failure (unknown variant, undefined variable, parse/render error) throws the mapped PromptingPressError subclass and the partial result is discarded — never returned as success. An empty composition resolves to [].

interface CompositionEntry

One composition entry, as a named-field options object. - prompt — the Prompt object to render. - schema — optional Zod-like schema. Present ⇒ schema.safeParse(data) runs at append. - data — the vars value (validated against schema when present). - variant — the selected variant arm (absent ⇒ the reserved default).

data: unknown

The vars value passed to the prompt renderer (validated against schema when present).

prompt: Prompt

The Prompt object to render.

schema?: ZodLikeSchema<unknown>

Optional Zod-like schema. When present, schema.safeParse(data) runs at append time.

variant?: string

The selected variant arm. Absent means the reserved default variant.

interface Message

One resolved message in a composition’s output: a role-tagged rendered string. role is the prompt definition’s role stringified ("system" / "user" / "assistant"); text is that prompt rendered with the entry’s own validated value. Surfaced as a plain JS object &#123; role, text &#125;; a message is produced by [Composition::resolve], never constructed from JS.

role: string

The conversational role, taken from the prompt definition’s role.

text: string

The rendered body text for this entry. The guard text is never concatenated here.

class LoadError

Raised when a document fails to load: malformed YAML/JSON/TOML, or a prompt-definition shape violation. Nothing is partially loaded. Top-level code "load".

class PromptingPressError

The base class for every failure the library raises. Carries the normalized, already-scrubbed errors rows. Every thrown error is an instanceof PromptingPressError; callers branch on the concrete subclass (or on err.errors[*].code) and never see a ZodError or a native napi error.

readonly errors: readonly FieldError[]

The structured failure rows (the cross-language contract).

class PromptRenderError

Raised when the kernel rejects a render: an unknown variant, a referenced-but-undefined root variable (the loud three-sets gap — never a silent empty render), a parse/render failure, or an excluded template feature. Maps the kernel codes unknown_variant / undefined_variable / parse / render / excluded_feature. parse/render/excluded_feature detail is scrubbed.

class PromptValidationError

Raised when typed input fails validation — either the facade’s Zod safeParse (before any templating) or a garde-class validation surfaced by the consumer. Top-level code "validation". It is not a ZodError: the facade copies only the value-free issue message + path.

interface FieldError

One normalized failure row. The TS mirror of the Rust consumer’s FieldError and the cross-language error contract. Reconstructed by the facade from the addon’s JSON payload (or, for a Zod validation failure, built locally from issue.message + issue.path).

readonly code: string

A stable code from the consumer’s closed vocabulary (e.g. "validation", "render").

readonly field: string

The offending field or dotted path; "" when no single field applies.

readonly message: string

A human-readable message safe to log (never the rejected value).

interface ZodLikeSchema

The minimal structural contract this facade needs from a Zod schema: a safeParse returning a tagged result. Typing it structurally (rather than importing Zod’s concrete ZodType) keeps the facade decoupled from a specific Zod minor and lets a caller pass any object exposing the same shape — the library never depends on Zod’s identity, only on safeParse. The optional shape field supports the validation_required coverage check at construction: if present (it is on a ZodObject), field in schema.shape proves that a validation_required variable is covered. If absent, the coverage check is skipped with a documented “cannot assert coverage” limitation.

shape?: Record<string, unknown>

Optional: ZodObject.shape — a record of field name → ZodType. Present on a ZodObject; absent on other schema types. When absent, validation_required coverage cannot be introspected and the check is skipped (documented limitation).

safeParse(data: unknown): ZodSafeParseResult<T>

Validate data and return a tagged success/failure result without throwing.

coreVersion(): string

Returns the version string of the underlying rendering kernel. Surfaces as coreVersion in JS (napi renames snake_case → camelCase).

type ValidatorMap = ZodLikeSchema

A validator bound at Prompt construction. In practice this is a Zod schema (a ZodObject) whose shape property the construction-time validation_required coverage check introspects. Typed as ZodLikeSchema so callers aren’t forced to import Zod types.

docs current as of 0.2.0