Skip to content

Commit 32ed872

Browse files
authored
Merge pull request #285 from taras/feat/retire-expand-hook-b
💥 Retire the expansion hook (#202, part B of two)
2 parents 3c4e6c0 + 7f5a999 commit 32ed872

18 files changed

Lines changed: 348 additions & 997 deletions

‎packages/core/mod.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ export type {
3636
Json,
3737
JsonObject,
3838
SourcePosition,
39-
ComponentHandling,
4039
} from "./src/types.ts";
4140

4241
export type { Workflow } from "@executablemd/durable-streams";
@@ -58,8 +57,6 @@ export {
5857
raise,
5958
env,
6059
evalScope,
61-
expand,
62-
expandSegments,
6360
codeBlock,
6461
persistent,
6562
content,

‎packages/core/src/answers.ts‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464
import { scoped } from "effection";
6565
import type { Operation } from "effection";
6666

67-
import { env, expandSegments, raise } from "./component-api.ts";
67+
import { env, raise } from "./component-api.ts";
6868
import { renderSegments } from "./render.ts";
6969
import { evaluateExpression } from "./expand.ts";
7070
import { Elicitation } from "./elicitation-api.ts";
@@ -74,6 +74,18 @@ import { matchPrompt, parseTemplate } from "./template.ts";
7474
import type { ParsedTemplate } from "./template.ts";
7575
import type { ComponentElement, ErrorSegment, Json, Segment } from "./types.ts";
7676

77+
/**
78+
* The enclosing expansion's recursion, handed in by the arm that dispatched the
79+
* region.
80+
*
81+
* A region renders segments of its own — its body, and each matcher's template
82+
* children — and those have to expand with the interpolation inputs, hide set
83+
* and block counter of the expansion they were written in. Only the dispatching
84+
* arm holds that state, so it binds the recursion and passes it down; nothing
85+
* here could reconstruct which expansion a region belongs to.
86+
*/
87+
type ExpandSegments = (segments: Segment[]) => Operation<Segment[]>;
88+
7789
const ANSWERS = "Answers";
7890
const ANSWER = "Answer";
7991

@@ -115,7 +127,10 @@ export function strayAnswerError(element: ComponentElement): ErrorSegment {
115127
);
116128
}
117129

118-
export function* expandAnswers(element: ComponentElement): Operation<Segment[]> {
130+
export function* expandAnswers(
131+
element: ComponentElement,
132+
expand: ExpandSegments,
133+
): Operation<Segment[]> {
119134
for (const name of Object.keys({ ...element.props, ...element.expressions })) {
120135
if (name !== "delegate") {
121136
return [
@@ -134,7 +149,7 @@ export function* expandAnswers(element: ComponentElement): Operation<Segment[]>
134149
const matchers: Matcher[] = [];
135150
for (const child of element.children) {
136151
if (isAnswer(child)) {
137-
const parsed = yield* readAnswer(child);
152+
const parsed = yield* readAnswer(child, expand);
138153
if (isErrorSegment(parsed)) {
139154
// The region cannot be trusted to answer anything, so it does not
140155
// expand a body that would ask. The diagnostic is returned rather than
@@ -185,7 +200,7 @@ export function* expandAnswers(element: ComponentElement): Operation<Segment[]>
185200
{ at: "min" },
186201
);
187202

188-
return yield* expandSegments(body);
203+
return yield* expand(body);
189204
});
190205
}
191206

@@ -231,7 +246,10 @@ function isErrorSegment(value: Matcher | ErrorSegment): value is ErrorSegment {
231246
}
232247

233248
/** One `<Answer>`, or the diagnostic that says why it is not one. */
234-
function* readAnswer(element: ComponentElement): Operation<Matcher | ErrorSegment> {
249+
function* readAnswer(
250+
element: ComponentElement,
251+
expand: ExpandSegments,
252+
): Operation<Matcher | ErrorSegment> {
235253
for (const name of Object.keys({ ...element.props, ...element.expressions })) {
236254
if (name !== "template" && name !== "value") {
237255
return yield* refuse(element, `does not accept a "${name}" prop (allowed: template, value).`);
@@ -261,7 +279,7 @@ function* readAnswer(element: ComponentElement): Operation<Matcher | ErrorSegmen
261279
typeof templateProp === "string"
262280
? templateProp
263281
: hasChildren
264-
? renderSegments(yield* expandSegments(element.children)).trim()
282+
? renderSegments(yield* expand(element.children)).trim()
265283
: undefined;
266284
if (source !== undefined) {
267285
const parsed = parseTemplate(source);

‎packages/core/src/component-api.ts‎

Lines changed: 2 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import type {
2323
CodeBlockResult,
2424
ComponentDefinition,
2525
ComponentElement,
26-
ComponentHandling,
2726
ComponentFailure,
2827
ComponentInvocationMetadata,
2928
ComponentRegistry,
@@ -35,20 +34,6 @@ import type {
3534
Segment,
3635
} from "./types.ts";
3736

38-
/**
39-
* The engine's segment expansion, already bound to one expansion's
40-
* interpolation inputs, cycle-detection hide set, and block counter. The
41-
* expansion loop sets it around each element it offers to extensions and
42-
* restores the enclosing one afterwards, so a claiming handler recurses with
43-
* that expansion's state and nothing else in the run sees one at all.
44-
* Internal: extensions reach it through `Component.expandSegments`.
45-
*/
46-
export const ExpansionFrame: Context<((segments: Segment[]) => Operation<Segment[]>) | undefined> =
47-
createContext<((segments: Segment[]) => Operation<Segment[]>) | undefined>(
48-
"component.expansionFrame",
49-
undefined,
50-
);
51-
5237
export interface ComponentApi {
5338
/** `"__root__"` imports the root document. */
5439
importComponent(name: string): Operation<ComponentDefinition | FunctionComponentDefinition>;
@@ -61,46 +46,13 @@ export interface ComponentApi {
6146
* `AmbientErrorPolicy`: collected for rendering, or thrown inside
6247
* suppressed documentation.
6348
*
64-
* Whoever creates an ErrorSegment calls this, including an `expand` handler.
65-
* A segment that reaches the document without it never passes the chain, so
49+
* Whoever creates an ErrorSegment calls this. A segment that reaches the
50+
* document without it never passes the chain, so
6651
* middleware that counts, logs, or forwards failures never sees it.
6752
*/
6853
raise(error: ErrorSegment): Operation<ErrorSegment>;
6954
env: EvalEnv | undefined;
7055
evalScope: EvalScope | undefined;
71-
/**
72-
* Offer a component element to extensions before built-in expansion.
73-
* Extensions install middleware that returns `{ segments }` for the names
74-
* they claim and delegates to `next` for everything else. The default
75-
* answers `undefined` — unhandled — so expansion proceeds normally.
76-
*
77-
* A handler owns the observation of every ErrorSegment it creates: it calls
78-
* `raise` for its own diagnostics — an invalid prop, a structural violation —
79-
* and returns errors that came back from `expandSegments` untouched, because
80-
* those were already reported where they were produced. The engine settles
81-
* whatever is returned under the caller's ambient policy, so a collecting
82-
* caller keeps the error and a throwing one aborts, either way without a
83-
* second observation. Returning a diagnostic the handler created but never
84-
* raised bypasses the observation chain and breaks this contract.
85-
*/
86-
expand(element: ComponentElement): Operation<ComponentHandling | undefined>;
87-
/**
88-
* Expand segments within the expansion that offered the current element:
89-
* the engine's own recursion, already bound to that expansion's
90-
* interpolation inputs, cycle-detection state, and block-ID counter. A
91-
* handler uses it for an element's children or for segments it generates.
92-
*
93-
* Live for exactly one `expand` offer, so it answers only inside the handler
94-
* that received the element. Ordinary expansion work — a code block, a
95-
* modifier chain, a task that outlives the offer — finds no active expansion
96-
* and gets an error.
97-
*
98-
* Every ErrorSegment among the returned segments has already been reported
99-
* through `raise`, at the point inside the expansion that produced it. A
100-
* handler passes them on as they are; raising one again would report the same
101-
* failure twice.
102-
*/
103-
expandSegments(segments: Segment[]): Operation<Segment[]>;
10456
/** Whether the invocation wrote this capture prop at all. */
10557
hasCapture(name: string): Operation<boolean>;
10658
/**
@@ -220,10 +172,6 @@ export const Component: Api<ComponentApi> = createApi<ComponentApi>("Component",
220172
env: undefined,
221173
evalScope: undefined,
222174
// deno-lint-ignore require-yield
223-
*expand(): Operation<ComponentHandling | undefined> {
224-
return undefined;
225-
},
226-
// deno-lint-ignore require-yield
227175
*hasCapture(_name: string): Operation<boolean> {
228176
return false;
229177
},
@@ -233,16 +181,6 @@ export const Component: Api<ComponentApi> = createApi<ComponentApi>("Component",
233181
`Component.capture("${name}") has no provider: not inside a function component invocation.`,
234182
);
235183
},
236-
*expandSegments(segments: Segment[]): Operation<Segment[]> {
237-
const frame = yield* ExpansionFrame.get();
238-
if (!frame) {
239-
throw new Error(
240-
"Component.expandSegments() has no active expansion in this scope. It is available " +
241-
"to a Component.around({ expand }) handler, for the element it was offered.",
242-
);
243-
}
244-
return yield* frame(segments);
245-
},
246184
// deno-lint-ignore require-yield
247185
*codeBlock(): Operation<CodeBlockContext> {
248186
throw new Error(
@@ -297,9 +235,6 @@ export const applyModifiers: Operations<ComponentApi>["applyModifiers"] =
297235
export const raise: Operations<ComponentApi>["raise"] = Component.operations.raise;
298236
export const env: Operations<ComponentApi>["env"] = Component.operations.env;
299237
export const evalScope: Operations<ComponentApi>["evalScope"] = Component.operations.evalScope;
300-
export const expand: Operations<ComponentApi>["expand"] = Component.operations.expand;
301-
export const expandSegments: Operations<ComponentApi>["expandSegments"] =
302-
Component.operations.expandSegments;
303238
export const codeBlock: Operations<ComponentApi>["codeBlock"] = Component.operations.codeBlock;
304239
export const persistent: Operations<ComponentApi>["persistent"] = Component.operations.persistent;
305240
export const content: Operations<ComponentApi>["content"] = Component.operations.content;

‎packages/core/src/expand.ts‎

Lines changed: 7 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import type {
2121
TextSegment,
2222
ErrorSegment,
2323
ComponentElement,
24-
ComponentHandling,
2524
ComponentDefinition,
2625
ComponentFailure,
2726
ComponentInvocationMetadata,
@@ -36,7 +35,6 @@ import { interpolate } from "./interpolate.ts";
3635
import { interpolateEvalBindings } from "./eval-interpolate.ts";
3736
import {
3837
Component,
39-
ExpansionFrame,
4038
applyModifiers,
4139
env,
4240
evalScope,
@@ -145,53 +143,6 @@ function* rejectRetain(): Operation<never> {
145143
);
146144
}
147145

148-
/**
149-
* Offer an element to extensions, with this expansion's recursion — its
150-
* interpolation inputs, hide set, and block counter — bound for exactly the
151-
* length of the offer. A claiming handler reaches it through
152-
* `Component.expandSegments`; a nested claim replaces the binding for its own
153-
* offer and restores this one.
154-
*/
155-
function offerElement(
156-
element: ComponentElement,
157-
parentMeta: Record<string, unknown>,
158-
parentProps: Record<string, Json>,
159-
hideSet: Set<string>,
160-
counter: BlockCounter,
161-
): Operation<ComponentHandling | undefined> {
162-
return withExpansionFrame(parentMeta, parentProps, hideSet, counter, () =>
163-
Component.operations.expand(element),
164-
);
165-
}
166-
167-
/**
168-
* Bind this expansion's recursion for the length of `body`.
169-
*
170-
* Two callers need it. An offer publishes it for a claiming handler, and a
171-
* structural construct that renders segments of its own — `<Answers>` — reaches
172-
* them through the Api form of `expandSegments` rather than this module's
173-
* function. Nothing else in expansion binds one, so a code block or modifier
174-
* running between elements finds none active.
175-
*/
176-
function* withExpansionFrame<T>(
177-
parentMeta: Record<string, unknown>,
178-
parentProps: Record<string, Json>,
179-
hideSet: Set<string>,
180-
counter: BlockCounter,
181-
body: () => Operation<T>,
182-
): Operation<T> {
183-
const scope = yield* useScope();
184-
const enclosing = scope.get(ExpansionFrame);
185-
scope.set(ExpansionFrame, (inner: Segment[]) =>
186-
expandSegments(inner, parentMeta, parentProps, hideSet, counter),
187-
);
188-
try {
189-
return yield* body();
190-
} finally {
191-
scope.set(ExpansionFrame, enclosing);
192-
}
193-
}
194-
195146
/**
196147
* Expand segments in a fresh scope whose eval env is the caller's values
197148
* plus an optional per-render override. The override is a shallow layer —
@@ -548,22 +499,6 @@ export function* expandSegments(
548499
}
549500

550501
case "component": {
551-
// Extension hook: installed component support may claim this element
552-
// before built-in expansion. A handler reports the errors it creates
553-
// (§6.9), so returned segments are settled here rather than reported
554-
// again: a collecting policy keeps them, a throwing one aborts.
555-
const handling = yield* offerElement(segment, parentMeta, parentProps, hideSet, counter);
556-
if (handling) {
557-
for (const handled of handling.segments) {
558-
if (handled.type === "error") {
559-
result.push(yield* settle(handled));
560-
} else {
561-
result.push(handled);
562-
}
563-
}
564-
break;
565-
}
566-
567502
if (segment.name === "Content") {
568503
// A `<Content />` the invocation claimed carries its resolved
569504
// projection; expanding it here runs that content in the
@@ -648,12 +583,12 @@ export function* expandSegments(
648583
if (segment.name === "Answers") {
649584
// No raise() here, like the branches above: expandAnswers reports the
650585
// errors it creates, and the selected answer settled its own (§6.9).
651-
// It renders the answer it chose through the Api form of
652-
// `expandSegments`, so it needs this frame — the same one the
653-
// retired claim hook used to publish for a handler.
586+
// The region renders segments of its own — its body, and each
587+
// matcher's template children — so it is handed this expansion's
588+
// recursion to render them with.
654589
result.push(
655-
...(yield* withExpansionFrame(parentMeta, parentProps, hideSet, counter, () =>
656-
expandAnswers(segment),
590+
...(yield* expandAnswers(segment, (inner) =>
591+
expandSegments(inner, parentMeta, parentProps, hideSet, counter),
657592
)),
658593
);
659594
break;
@@ -2132,9 +2067,8 @@ function* expandFunctionComponent(
21322067
// component installed for it — see ProjectionState.callerEnv.
21332068
callerEnv: undefined,
21342069
// ...but the content itself is the CALLER's markdown, so `{meta.x}`
2135-
// and `{props.x}` in it resolve against the frame that wrote it. The
2136-
// Api form of `expandSegments` carries this through ExpansionFrame;
2137-
// projection has to be handed it.
2070+
// and `{props.x}` in it resolve against the expansion that wrote it,
2071+
// which projection has to be handed.
21382072
meta: callerMeta,
21392073
props: callerProps,
21402074
hideSet,

‎packages/core/src/types.ts‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -100,14 +100,6 @@ export interface EvalEnv {
100100
values: Record<string, unknown>;
101101
}
102102

103-
/**
104-
* A claimed element's replacement segments. `{ segments: [] }` means
105-
* handled-with-no-output — distinct from `undefined` (unhandled).
106-
*/
107-
export interface ComponentHandling {
108-
segments: Segment[];
109-
}
110-
111103
export interface ParsedInfoString {
112104
language: string;
113105
modifiers: Modifier[];

0 commit comments

Comments
 (0)