|
| 1 | +/** |
| 2 | + * `<Answers>` and `<Answer>` — supplying elicitation answers from the document |
| 3 | + * (specs/executable-mdx-spec.md §6.16.2). |
| 4 | + * |
| 5 | + * ```md |
| 6 | + * <Answers> |
| 7 | + * <Answer template="Approve {?what}?" value={{ decision: "approve" }} /> |
| 8 | + * |
| 9 | + * <ReviewGate plan={plan} as="verdict" /> |
| 10 | + * </Answers> |
| 11 | + * ``` |
| 12 | + * |
| 13 | + * A component that elicits internally asks whoever the host's provider reaches. |
| 14 | + * Sometimes the surrounding document already knows the answer — a workflow |
| 15 | + * exercising somebody else's component non-interactively, a demo, a region of a |
| 16 | + * run that should not stop for a person. This is how a document says so without |
| 17 | + * writing TypeScript. |
| 18 | + * |
| 19 | + * `<Answers>` is elicitation middleware wearing a construct's clothes: it |
| 20 | + * installs a provider around its body's expansion and answers from its |
| 21 | + * matchers. It adds nothing to what the Elicitation Api already does — every |
| 22 | + * elicitation inside it is an ordinary one, judged by core against the *asking* |
| 23 | + * component's schema before it binds, so a supplied value that does not fit |
| 24 | + * fails exactly as a live provider's answer would. |
| 25 | + * |
| 26 | + * ## Why these are structural rather than registered |
| 27 | + * |
| 28 | + * A registered function component sees `content()` — rendered text. Matchers |
| 29 | + * are structure: `value` is an expression prop, `template` is a prop-or-children |
| 30 | + * pair, and each needs its own position for diagnostics. Only the expansion hook |
| 31 | + * hands over the element itself, which is why `<Test>` and `<WhenPrompt>` are |
| 32 | + * claimed the same way. Being claimed means being reserved: a repository file |
| 33 | + * named `Answers.md` never stands in, and it could not implement matcher |
| 34 | + * semantics if it did. |
| 35 | + * |
| 36 | + * Partitioning before expanding is what the hook buys. Matchers are collected |
| 37 | + * from the whole child list first, so where an `<Answer>` is written does not |
| 38 | + * decide what it can answer; and "an `<Answers>` with no body" is a structural |
| 39 | + * fact rather than a guess from empty rendered text. |
| 40 | + * |
| 41 | + * ## Selection |
| 42 | + * |
| 43 | + * First declared match wins, and a matcher is reusable — it answers every |
| 44 | + * elicitation it matches for as long as the region lasts. That pair is the whole |
| 45 | + * rule, and its consequence is deliberate: a broad template above a narrow one |
| 46 | + * shadows it permanently. An `<Answer>` that never fires is not an error. |
| 47 | + * |
| 48 | + * ## Templates and the `{binding}` asymmetry |
| 49 | + * |
| 50 | + * Templates match the whole rendered message: literal text constrains, |
| 51 | + * `{?name}` matches any text and binds nothing, `{binding}` interpolates an |
| 52 | + * existing binding and requires it at that position. |
| 53 | + * |
| 54 | + * The two spellings are not identical for `{binding}`, and the difference is |
| 55 | + * inherited from `<WhenPrompt>` rather than introduced here. In the `template` |
| 56 | + * prop the string is a literal, so `{binding}` reaches the engine intact and the |
| 57 | + * engine resolves it — an unbound name is a configuration error naming the |
| 58 | + * template. In the children form the text is interpolated during expansion, so |
| 59 | + * an in-scope binding is substituted before the engine sees it, and an |
| 60 | + * out-of-scope one survives to be reported by the engine. The matching |
| 61 | + * constraint is the same either way; only which layer reports an absent binding |
| 62 | + * differs. |
| 63 | + */ |
| 64 | + |
| 65 | +import { scoped } from "effection"; |
| 66 | +import type { Operation } from "effection"; |
| 67 | + |
| 68 | +import { Component, env, expandSegments, raise } from "./component-api.ts"; |
| 69 | +import { renderSegments } from "./render.ts"; |
| 70 | +import { evaluateExpression } from "./expand.ts"; |
| 71 | +import { Elicitation } from "./elicitation-api.ts"; |
| 72 | +import type { ElicitationRequest } from "./elicitation-api.ts"; |
| 73 | +import { JsonParseError, parseJson } from "./json.ts"; |
| 74 | +import { matchPrompt, parseTemplate } from "./template.ts"; |
| 75 | +import type { ParsedTemplate } from "./template.ts"; |
| 76 | +import type { ComponentElement, ComponentHandling, ErrorSegment, Json, Segment } from "./types.ts"; |
| 77 | + |
| 78 | +const ANSWERS = "Answers"; |
| 79 | +const ANSWER = "Answer"; |
| 80 | + |
| 81 | +/** One matcher, ready to be tried. `template` absent matches any message. */ |
| 82 | +interface Matcher { |
| 83 | + template?: ParsedTemplate; |
| 84 | + value: Json; |
| 85 | +} |
| 86 | + |
| 87 | +function positioned(message: string, element: ComponentElement): string { |
| 88 | + const { position } = element; |
| 89 | + if (!position) { |
| 90 | + return message; |
| 91 | + } |
| 92 | + const file = position.path === undefined ? "" : `${position.path}:`; |
| 93 | + return `${message} (${file}${position.line}:${position.column})`; |
| 94 | +} |
| 95 | + |
| 96 | +function configError(name: string, message: string, element: ComponentElement): ErrorSegment { |
| 97 | + return { type: "error", message: positioned(`<${name}> ${message}`, element), source: name }; |
| 98 | +} |
| 99 | + |
| 100 | +function isAnswer(segment: Segment): segment is ComponentElement { |
| 101 | + return segment.type === "component" && segment.name === ANSWER; |
| 102 | +} |
| 103 | + |
| 104 | +/** Markdown puts blank lines between block elements; they are not a body. */ |
| 105 | +function isBlankText(segment: Segment): boolean { |
| 106 | + return segment.type === "text" && segment.content.trim() === ""; |
| 107 | +} |
| 108 | + |
| 109 | +/** |
| 110 | + * Install the handler for both constructs. |
| 111 | + * |
| 112 | + * Offered every element, it claims only these two names and delegates the rest, |
| 113 | + * so it composes with any other expansion support a host has installed. |
| 114 | + */ |
| 115 | +export function installAnswers(): Operation<void> { |
| 116 | + return Component.around( |
| 117 | + { |
| 118 | + *expand([element], next) { |
| 119 | + if (element.name === ANSWERS) { |
| 120 | + return { segments: yield* expandAnswers(element) }; |
| 121 | + } |
| 122 | + if (element.name === ANSWER) { |
| 123 | + // Reaching here means no enclosing `<Answers>` consumed it: a |
| 124 | + // well-placed matcher is partitioned out and never expanded on its |
| 125 | + // own. Same shape as `<Else>` outside `<If>`. |
| 126 | + return { |
| 127 | + segments: [ |
| 128 | + yield* raise( |
| 129 | + configError( |
| 130 | + ANSWER, |
| 131 | + "must be a direct child of <Answers>. It is reserved: it never resolves a " + |
| 132 | + "component, and only the <Answers> it belongs to can read it.", |
| 133 | + element, |
| 134 | + ), |
| 135 | + ), |
| 136 | + ], |
| 137 | + }; |
| 138 | + } |
| 139 | + return yield* next(element); |
| 140 | + }, |
| 141 | + }, |
| 142 | + { at: "min" }, |
| 143 | + ); |
| 144 | +} |
| 145 | + |
| 146 | +function* expandAnswers(element: ComponentElement): Operation<Segment[]> { |
| 147 | + for (const name of Object.keys({ ...element.props, ...element.expressions })) { |
| 148 | + if (name !== "delegate") { |
| 149 | + return [ |
| 150 | + yield* raise( |
| 151 | + configError(ANSWERS, `does not accept a "${name}" prop (allowed: delegate).`, element), |
| 152 | + ), |
| 153 | + ]; |
| 154 | + } |
| 155 | + } |
| 156 | + const delegate = yield* readDelegate(element); |
| 157 | + if (delegate.error) { |
| 158 | + return [yield* raise(configError(ANSWERS, delegate.error, element))]; |
| 159 | + } |
| 160 | + |
| 161 | + const body: Segment[] = []; |
| 162 | + const matchers: Matcher[] = []; |
| 163 | + for (const child of element.children) { |
| 164 | + if (isAnswer(child)) { |
| 165 | + const parsed = yield* readAnswer(child); |
| 166 | + if (isErrorSegment(parsed)) { |
| 167 | + // The region cannot be trusted to answer anything, so it does not |
| 168 | + // expand a body that would ask. The diagnostic is returned rather than |
| 169 | + // only raised, so the caller settles it under its own policy. |
| 170 | + return [parsed]; |
| 171 | + } |
| 172 | + matchers.push(parsed); |
| 173 | + continue; |
| 174 | + } |
| 175 | + body.push(child); |
| 176 | + } |
| 177 | + |
| 178 | + if (element.selfClosing || body.every(isBlankText)) { |
| 179 | + return [ |
| 180 | + yield* raise( |
| 181 | + configError( |
| 182 | + ANSWERS, |
| 183 | + "has no body to answer for. It wraps the region whose elicitations it answers, so " + |
| 184 | + "an <Answers> containing only matchers can never do anything.", |
| 185 | + element, |
| 186 | + ), |
| 187 | + ), |
| 188 | + ]; |
| 189 | + } |
| 190 | + |
| 191 | + const bindings = (yield* env)?.values ?? {}; |
| 192 | + |
| 193 | + // Scoped, so the provider's lifetime is exactly the body's expansion. Without |
| 194 | + // this the install would land on the enclosing expansion's scope and the |
| 195 | + // region would go on answering elicitations written after its closing tag. |
| 196 | + return yield* scoped(function* () { |
| 197 | + yield* Elicitation.around( |
| 198 | + { |
| 199 | + *elicit([request], next) { |
| 200 | + // First declared match wins, and finding it does not remove it: a |
| 201 | + // matcher answers every elicitation it matches for as long as the |
| 202 | + // region lasts. |
| 203 | + const matched = matchers.find((matcher) => matches(matcher, request, bindings)); |
| 204 | + if (matched) { |
| 205 | + return matched.value; |
| 206 | + } |
| 207 | + if (delegate.value) { |
| 208 | + return yield* next(request); |
| 209 | + } |
| 210 | + throw new Error(unmatched(request, matchers)); |
| 211 | + }, |
| 212 | + }, |
| 213 | + { at: "min" }, |
| 214 | + ); |
| 215 | + |
| 216 | + return yield* expandSegments(body); |
| 217 | + }); |
| 218 | +} |
| 219 | + |
| 220 | +function matches( |
| 221 | + matcher: Matcher, |
| 222 | + request: ElicitationRequest, |
| 223 | + bindings: Record<string, unknown>, |
| 224 | +): boolean { |
| 225 | + if (!matcher.template) { |
| 226 | + return true; |
| 227 | + } |
| 228 | + return matchPrompt(matcher.template, request.message, bindings).ok; |
| 229 | +} |
| 230 | + |
| 231 | +/** |
| 232 | + * What an unmatched elicitation says. |
| 233 | + * |
| 234 | + * Both sides, in `PromptMismatchError`'s style: the message nobody answered and |
| 235 | + * every template that was tried, so the comparison does not have to be |
| 236 | + * reconstructed from the document. |
| 237 | + */ |
| 238 | +function unmatched(request: ElicitationRequest, matchers: Matcher[]): string { |
| 239 | + const tried = |
| 240 | + matchers.length === 0 |
| 241 | + ? " (no <Answer> matchers were declared)" |
| 242 | + : matchers |
| 243 | + .map( |
| 244 | + (matcher) => |
| 245 | + ` - ${matcher.template ? `"${matcher.template.source}"` : "(no template)"}`, |
| 246 | + ) |
| 247 | + .join("\n"); |
| 248 | + return ( |
| 249 | + "<Answers> has no matcher for this elicitation.\n" + |
| 250 | + ` actual: ${JSON.stringify(request.message)}\n` + |
| 251 | + ` tried:\n${tried}\n` + |
| 252 | + "Add an <Answer> whose template matches, or write delegate={true} to pass unmatched " + |
| 253 | + "elicitations outward." |
| 254 | + ); |
| 255 | +} |
| 256 | + |
| 257 | +function isErrorSegment(value: Matcher | ErrorSegment): value is ErrorSegment { |
| 258 | + return "type" in value && value.type === "error"; |
| 259 | +} |
| 260 | + |
| 261 | +/** One `<Answer>`, or the diagnostic that says why it is not one. */ |
| 262 | +function* readAnswer(element: ComponentElement): Operation<Matcher | ErrorSegment> { |
| 263 | + for (const name of Object.keys({ ...element.props, ...element.expressions })) { |
| 264 | + if (name !== "template" && name !== "value") { |
| 265 | + return yield* refuse(element, `does not accept a "${name}" prop (allowed: template, value).`); |
| 266 | + } |
| 267 | + } |
| 268 | + |
| 269 | + const templateProp = element.props.template; |
| 270 | + const hasChildren = !element.selfClosing && element.children.length > 0; |
| 271 | + if (typeof templateProp === "string" && hasChildren) { |
| 272 | + return yield* refuse(element, "accepts either a template prop or template children, not both."); |
| 273 | + } |
| 274 | + |
| 275 | + let template: ParsedTemplate | undefined; |
| 276 | + const source = |
| 277 | + typeof templateProp === "string" |
| 278 | + ? templateProp |
| 279 | + : hasChildren |
| 280 | + ? renderSegments(yield* expandSegments(element.children)).trim() |
| 281 | + : undefined; |
| 282 | + if (source !== undefined) { |
| 283 | + const parsed = parseTemplate(source); |
| 284 | + if (!parsed.ok) { |
| 285 | + return yield* refuse(element, parsed.error.message); |
| 286 | + } |
| 287 | + template = parsed.value; |
| 288 | + } |
| 289 | + |
| 290 | + if (!("value" in element.props) && !("value" in element.expressions)) { |
| 291 | + return yield* refuse(element, 'requires a "value" prop.'); |
| 292 | + } |
| 293 | + const value = yield* readValue(element); |
| 294 | + if (value.error) { |
| 295 | + return yield* refuse(element, value.error); |
| 296 | + } |
| 297 | + |
| 298 | + return template ? { template, value: value.parsed } : { value: value.parsed }; |
| 299 | +} |
| 300 | + |
| 301 | +function* refuse(element: ComponentElement, message: string): Operation<ErrorSegment> { |
| 302 | + return yield* raise(configError(ANSWER, message, element)); |
| 303 | +} |
| 304 | + |
| 305 | +/** |
| 306 | + * Read `value` in either accepted spelling. |
| 307 | + * |
| 308 | + * Read here rather than where it is consumed, so a malformed one is reported at |
| 309 | + * the matcher that wrote it instead of surfacing later as a provider failure. |
| 310 | + */ |
| 311 | +function* readValue(element: ComponentElement): Operation<{ parsed: Json; error?: string }> { |
| 312 | + const expression = element.expressions.value; |
| 313 | + if (expression !== undefined) { |
| 314 | + let evaluated: unknown; |
| 315 | + try { |
| 316 | + evaluated = yield* evaluateExpression(expression, ANSWER, "value", element.projectedEnv); |
| 317 | + } catch (error) { |
| 318 | + return { parsed: null, error: error instanceof Error ? error.message : String(error) }; |
| 319 | + } |
| 320 | + return read(evaluated); |
| 321 | + } |
| 322 | + const raw = element.props.value; |
| 323 | + if (typeof raw === "string") { |
| 324 | + let decoded: unknown; |
| 325 | + try { |
| 326 | + decoded = JSON.parse(raw); |
| 327 | + } catch (error) { |
| 328 | + return { |
| 329 | + parsed: null, |
| 330 | + error: `value text is not JSON: ${error instanceof Error ? error.message : String(error)}`, |
| 331 | + }; |
| 332 | + } |
| 333 | + return read(decoded); |
| 334 | + } |
| 335 | + return read(raw); |
| 336 | +} |
| 337 | + |
| 338 | +function read(value: unknown): { parsed: Json; error?: string } { |
| 339 | + try { |
| 340 | + return { parsed: parseJson(value) }; |
| 341 | + } catch (error) { |
| 342 | + if (error instanceof JsonParseError) { |
| 343 | + return { parsed: null, error: `value must be JSON: ${error.message}` }; |
| 344 | + } |
| 345 | + throw error; |
| 346 | + } |
| 347 | +} |
| 348 | + |
| 349 | +/** |
| 350 | + * `delegate` as a boolean. |
| 351 | + * |
| 352 | + * A literal `{true}` is resolved by the scanner and arrives already a boolean; |
| 353 | + * only an identifier or member expression reaches `expressions` and needs |
| 354 | + * evaluating here. |
| 355 | + */ |
| 356 | +function* readDelegate(element: ComponentElement): Operation<{ value: boolean; error?: string }> { |
| 357 | + const expression = element.expressions.delegate; |
| 358 | + if (expression !== undefined) { |
| 359 | + let evaluated: unknown; |
| 360 | + try { |
| 361 | + evaluated = yield* evaluateExpression(expression, ANSWERS, "delegate", element.projectedEnv); |
| 362 | + } catch (error) { |
| 363 | + return { value: false, error: error instanceof Error ? error.message : String(error) }; |
| 364 | + } |
| 365 | + if (typeof evaluated !== "boolean") { |
| 366 | + return { |
| 367 | + value: false, |
| 368 | + error: `delegate must be a boolean, and {${expression}} is ${typeof evaluated}.`, |
| 369 | + }; |
| 370 | + } |
| 371 | + return { value: evaluated }; |
| 372 | + } |
| 373 | + if (!("delegate" in element.props)) { |
| 374 | + return { value: false }; |
| 375 | + } |
| 376 | + const raw = element.props.delegate; |
| 377 | + if (typeof raw !== "boolean") { |
| 378 | + return { |
| 379 | + value: false, |
| 380 | + error: `delegate must be a boolean — write delegate={true}, not delegate=${JSON.stringify( |
| 381 | + raw, |
| 382 | + )}.`, |
| 383 | + }; |
| 384 | + } |
| 385 | + return { value: raw }; |
| 386 | +} |
0 commit comments