Skip to content

Commit b9645df

Browse files
committed
🐛 Bind the original GitHub search page directly (#815)
1 parent dba0fe2 commit b9645df

8 files changed

Lines changed: 152 additions & 41 deletions

File tree

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import type {
3131
ErrorSegment,
3232
EvalEnv,
3333
FunctionComponentDefinition,
34+
Json,
3435
Modifier,
3536
SourcePosition,
3637
} from "./types.ts";
@@ -208,6 +209,12 @@ export interface ComponentApi {
208209
* reading of the same prop.
209210
*/
210211
hasBinding(): Operation<boolean>;
212+
/**
213+
* Reserve another JSON result binding in this invocation's caller scope.
214+
* The engine publishes its value together with `as` after successful return
215+
* validation and teardown.
216+
*/
217+
bindResult(name: string): Operation<(value: Json) => void>;
211218
/**
212219
* Create a resource owned by the scope that invoked this component
213220
* (spec §4.4).
@@ -389,6 +396,10 @@ const COMPONENT_DEFAULTS: Omit<ComponentApi, "registry"> = {
389396
*raise(error: ErrorSegment): Operation<ErrorSegment> {
390397
return yield* settle(error);
391398
},
399+
// deno-lint-ignore require-yield
400+
*bindResult(): Operation<(value: Json) => void> {
401+
throw new Error("Result bindings require a function component invocation.");
402+
},
392403
env: undefined,
393404
evalScope: undefined,
394405
// deno-lint-ignore require-yield

‎packages/core/src/expand.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ import {
178178
import { remark } from "remark";
179179
import { select as cssSelect } from "unist-util-select";
180180
import { toString as mdastToString } from "mdast-util-to-string";
181-
import { liveEnvironment } from "./live-env.ts";
181+
import { liveEnvironment, validateBindingName } from "./live-env.ts";
182182
import { TestHarnessComponentDefinition } from "./test-harness.ts";
183183
import type { TestHarnessBinding } from "./test-harness.ts";
184184

@@ -4403,6 +4403,7 @@ function* expandFunctionComponent(
44034403

44044404
const expansion = snapshot(path, name, position);
44054405

4406+
let resultBindings: Map<string, Json | undefined> | undefined;
44064407
let publishedBinding = false;
44074408
const binding: TestHarnessBinding = {
44084409
has(): boolean {
@@ -4553,6 +4554,26 @@ function* expandFunctionComponent(
45534554
return asBinding !== undefined;
45544555
},
45554556
// deno-lint-ignore require-yield
4557+
*bindResult([bindingName]) {
4558+
const checked = validateBindingName(bindingName);
4559+
if (!checked.ok) {
4560+
throw checked.error;
4561+
}
4562+
if (asBinding === undefined || checked.value === undefined) {
4563+
throw new Error(
4564+
`An additional result binding on <${name} /> requires as and a binding name.`,
4565+
);
4566+
}
4567+
if (bindingName === asBinding || resultBindings?.has(bindingName)) {
4568+
throw new Error(`Duplicate result binding "${bindingName}" on <${name} />.`);
4569+
}
4570+
const staged = (resultBindings ??= new Map());
4571+
staged.set(bindingName, undefined);
4572+
return (value: Json) => {
4573+
staged.set(bindingName, parseJson(value));
4574+
};
4575+
},
4576+
// deno-lint-ignore require-yield
45564577
*hasCapture([captureName], _next) {
45574578
return captureName in literalCaptures || captureName in expressionCaptures;
45584579
},
@@ -4709,10 +4730,22 @@ function* expandFunctionComponent(
47094730
// By reference by default: the binding is the value the component
47104731
// returned. `returns` is the opt-in that says this one is a validated
47114732
// JSON record, and it is checked before binding.
4712-
parentEnv.values[asBinding] =
4733+
const value =
47134734
returns === undefined || invocationObservation !== undefined
47144735
? output
47154736
: yield* validateLiveReturnValue(name, output, returns);
4737+
parentEnv.values[asBinding] = value;
4738+
for (const [bindingName, bindingValue] of resultBindings ?? []) {
4739+
if (bindingValue === undefined) {
4740+
continue;
4741+
}
4742+
Object.defineProperty(parentEnv.values, bindingName, {
4743+
value: bindingValue,
4744+
writable: true,
4745+
enumerable: true,
4746+
configurable: true,
4747+
});
4748+
}
47164749
return [];
47174750
}
47184751
// Without `as` there is nowhere to bind, so only text can be observed:

‎packages/core/tests/construct-error-observation.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,26 @@ describe("Tier OBS — construct error observation", () => {
305305
expect(fn.output).toContain(broke());
306306
});
307307

308+
it("publishes additional result bindings only with an accepted primary result", function* () {
309+
const component: FunctionComponentDefinition = {
310+
kind: "function",
311+
name: "Page",
312+
props: OPEN_SCHEMA,
313+
returns: { type: "object" },
314+
*fn(props) {
315+
const bind = yield* Component.operations.bindResult("next");
316+
bind({ page: 2 });
317+
return props.invalid ? "invalid" : { items: [] };
318+
},
319+
};
320+
const options = { functions: { Page: component } };
321+
const accepted = yield* runProbe('<Page as="page" />', options);
322+
expect(accepted.values).toEqual({ page: { items: [] }, next: { page: 2 } });
323+
const refused = yield* runProbe('<Page as="page" invalid />', options);
324+
expect(refused.values).toEqual({});
325+
expect(refused.observed).toHaveLength(1);
326+
});
327+
308328
it("OBS16: an ambient throw error mode aborts at the first error on every path", function* () {
309329
const cases: Array<[string, ProbeOptions]> = [
310330
["<Broken /><Broken />", {}],

‎packages/git/src/composition/components.md‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -317,24 +317,30 @@ The host supplies the repository scope and authorizes the read.
317317

318318
```mdx
319319
<GitHub.Search query="is:pr is:open label:bug" sort="created" perPage={20} as="page" />
320-
<Query value={page.value} yq="[.items[].html_url]" as="pullRequestUrls" />
320+
<Query value={page} yq="[.items[].html_url]" as="pullRequestUrls" />
321321
```
322322

323-
`page.value` holds the original GitHub response, including `incomplete_results`.
323+
`page` holds the original GitHub response, including `incomplete_results`.
324324
The `Query` projects URLs from that page. Pass a selected URL to
325325
`PullRequest.Reviews`, `PullRequest.Comments` or `PullRequest.Checks` to read
326-
its evidence. When `page.next` is present, pass its fields to another search
327-
within the same repository. It is `null` after the last accessible page.
326+
its evidence.
327+
328+
Request a separate continuation binding with `nextAs`. It contains the
329+
complete next search arguments or `null` after the last accessible page.
328330

329331
```mdx
332+
<GitHub.Search query="is:pr is:open" sort="created" as="page" nextAs="next" />
333+
334+
<If condition={next !== null}>
330335
<GitHub.Search
331-
query={page.next.query}
332-
sort={page.next.sort}
333-
order={page.next.order}
334-
page={page.next.page}
335-
perPage={page.next.perPage}
336+
query={next.query}
337+
sort={next.sort}
338+
order={next.order}
339+
page={next.page}
340+
perPage={next.perPage}
336341
as="nextPage"
337342
/>
343+
</If>
338344
```
339345

340346
## IssueTracker

‎packages/git/src/composition/components/GitHubSearch.ts‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { documented, formDispatcher } from "@executablemd/core";
1+
import { Component, documented, formDispatcher, isJsonObject } from "@executablemd/core";
22
import type { ComponentRegistration, Json, JsonObject } from "@executablemd/core";
33
import { createApi } from "@effectionx/context-api";
44
import type { Operation } from "effection";
@@ -67,7 +67,7 @@ function admitQuery(query: string): void {
6767
}
6868

6969
function* search(props: Record<string, Json>): Operation<JsonObject> {
70-
const { query, sort, order, page = 1, perPage = 20 } = props;
70+
const { query, sort, order, page = 1, perPage = 20, nextAs } = props;
7171
if (typeof query !== "string" || typeof page !== "number" || typeof perPage !== "number") {
7272
throw new GitOperationAdmissionError(SEARCH_ELEMENT, "the search arguments are invalid.");
7373
}
@@ -81,18 +81,28 @@ function* search(props: Record<string, Json>): Operation<JsonObject> {
8181
if (order !== undefined && sort === undefined) {
8282
throw new GitOperationAdmissionError(SEARCH_ELEMENT, "order requires sort.");
8383
}
84+
const publishNext =
85+
typeof nextAs === "string" ? yield* Component.operations.bindResult(nextAs) : undefined;
8486
const repository = yield* selectedRepository();
8587
if (repository === undefined) {
8688
throw new GitOperationAdmissionError(SEARCH_ELEMENT, "select a Repository before searching.");
8789
}
88-
return yield* GitHubSearch.operations.search(repository, {
90+
const result = yield* GitHubSearch.operations.search(repository, {
8991
query,
9092
page,
9193
perPage,
9294
...(typeof sort === "string"
9395
? { sort, order: typeof order === "string" ? order : "desc" }
9496
: {}),
9597
});
98+
if (!isJsonObject(result.value) || (result.next !== null && !isJsonObject(result.next))) {
99+
throw new GitOperationAdmissionError(
100+
SEARCH_ELEMENT,
101+
"the search provider returned an invalid page.",
102+
);
103+
}
104+
publishNext?.(result.next);
105+
return result.value;
96106
}
97107

98108
export const githubSearchRegistration: ComponentRegistration = {
@@ -104,18 +114,18 @@ export const githubSearchRegistration: ComponentRegistration = {
104114
query: { type: "string", minLength: 1 },
105115
sort: { enum: sorts },
106116
order: { enum: ["asc", "desc"] },
117+
nextAs: {
118+
type: "string",
119+
minLength: 1,
120+
description: "Bind the next request arguments or null to this name.",
121+
},
107122
page: { type: "integer", minimum: 1, maximum: SEARCH_CEILING },
108123
perPage: { type: "integer", minimum: 1, maximum: 100 },
109124
},
110125
required: ["query"],
111126
additionalProperties: false,
112127
},
113-
returns: {
114-
type: "object",
115-
properties: { value: { type: "object" }, next: { type: ["object", "null"] } },
116-
required: ["value", "next"],
117-
additionalProperties: false,
118-
},
128+
returns: { type: "object" },
119129
fn: formDispatcher({
120130
forms: "self-closing",
121131
fn: search,
@@ -125,7 +135,7 @@ export const githubSearchRegistration: ComponentRegistration = {
125135
...documented({
126136
description:
127137
"Search the selected GitHub repository with GitHub's issue and pull-request query syntax.",
128-
as: "Required. Binds the original GitHub JSON under value and the next request arguments or null under next.",
138+
as: "Required. Binds the original GitHub response JSON.",
129139
context: null,
130140
}),
131141
};

‎packages/git/tests/github-workflow-activation.test.ts‎

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -232,20 +232,41 @@ function searchProvider(
232232
describe("GitHub repository search", () => {
233233
beforeEach(journalBeforeEach(OWNER));
234234

235+
it("runs the search and Query example with the original page as its input", function* () {
236+
const remote = yield* useBareRemote(REMOTE);
237+
const checkout = yield* useNamedOriginCheckout(remote, REPOSITORY);
238+
const root = yield* useTempDirectory("github-search");
239+
const page = { ...FIRST_PAGE, total_count: 1 };
240+
const provider = searchProvider([REPOSITORY], () => ({
241+
status: 200,
242+
body: JSON.stringify(page),
243+
}));
244+
const output = yield* runOrdinaryDocument(
245+
[
246+
'<GitHub.Search query="is:pr is:open label:bug" sort="created" perPage={20} as="page" />',
247+
'<Query value={page} yq="[.items[].html_url]" as="pullRequestUrls" />',
248+
"<Json value={{ page, pullRequestUrls }} />",
249+
].join("\n"),
250+
{ cwd: checkout.root, root, gitHubPullRequests: provider.options },
251+
);
252+
expect(JSON.parse(String(output))).toEqual({ page, pullRequestUrls: [ITEM.html_url] });
253+
expect(provider.requests).toHaveLength(1);
254+
});
255+
235256
it("binds original pages, projects URLs and exposes only reusable continuation arguments", function* () {
236257
const remote = yield* useBareRemote(REMOTE);
237258
const checkout = yield* useNamedOriginCheckout(remote, REPOSITORY);
238259
const root = yield* useTempDirectory("github-search");
239260
const provider = searchProvider();
240261
const output = yield* runOrdinaryDocument(
241262
[
242-
`<GitHub.Search query={${JSON.stringify(QUERY)}} sort="created" perPage={1} as="first" />`,
243-
'<Query value={first.value} yq="[.items[].html_url]" as="urls" />',
263+
`<GitHub.Search query={${JSON.stringify(QUERY)}} sort="created" perPage={1} as="first" nextAs="next" />`,
264+
'<Query value={first} yq="[.items[].html_url]" as="urls" />',
244265
'<PullRequest.Reviews url={urls[0]} as="reviews" />',
245-
'<GitHub.Search query={first.next.query} sort={first.next.sort} order={first.next.order} page={first.next.page} perPage={first.next.perPage} as="second" />',
246-
'<GitHub.Search query="is:issue" page={10} perPage={100} as="ceiling" />',
266+
'<GitHub.Search query={next.query} sort={next.sort} order={next.order} page={next.page} perPage={next.perPage} as="second" nextAs="after" />',
267+
'<GitHub.Search query="is:issue" page={10} perPage={100} as="ceiling" nextAs="beyond" />',
247268
"",
248-
"<Json value={{ first, second, ceiling, urls, reviews }} />",
269+
"<Json value={{ first, next, second, after, ceiling, beyond, urls, reviews }} />",
249270
].join("\n"),
250271
{
251272
cwd: checkout.root,
@@ -254,12 +275,12 @@ describe("GitHub repository search", () => {
254275
},
255276
);
256277
expect(JSON.parse(String(output))).toEqual({
257-
first: {
258-
value: FIRST_PAGE,
259-
next: { query: QUERY, sort: "created", order: "desc", page: 2, perPage: 1 },
260-
},
261-
second: { value: { total_count: 2, incomplete_results: true, items: [] }, next: null },
262-
ceiling: { value: { total_count: 1500, incomplete_results: true, items: [] }, next: null },
278+
first: FIRST_PAGE,
279+
next: { query: QUERY, sort: "created", order: "desc", page: 2, perPage: 1 },
280+
second: { total_count: 2, incomplete_results: true, items: [] },
281+
after: null,
282+
ceiling: { total_count: 1500, incomplete_results: true, items: [] },
283+
beyond: null,
263284
urls: [ITEM.html_url],
264285
reviews: [],
265286
});
@@ -294,6 +315,8 @@ describe("GitHub repository search", () => {
294315
[checkout.root, 'query="is:issue is:pr"', "exactly one kind"],
295316
[checkout.root, 'query="is:open"', "exactly one kind"],
296317
[checkout.root, 'query="is:pr" page={11} perPage={100}', "first 1,000"],
318+
[checkout.root, 'query="is:pr" nextAs="page"', "Duplicate result binding"],
319+
[checkout.root, 'query="is:pr" nextAs="class"', "valid JavaScript binding name"],
297320
[checkout.root, 'query="is:pr"', "has not authorized"],
298321
[local.root, 'query="is:pr"', "does not name a GitHub repository"],
299322
[outside, 'query="is:pr"', "repository"],
@@ -390,9 +413,9 @@ describe("GitHub repository search", () => {
390413
const provider = searchProvider();
391414
const source = [
392415
`<Repository name="search" url="${REPOSITORY}">`,
393-
'<GitHub.Search query="is:pr" perPage={1} as="page" />',
416+
'<GitHub.Search query="is:pr" perPage={1} as="page" nextAs="next" />',
394417
"",
395-
"<Json value={page.value} />",
418+
"<Json value={{ page, next }} />",
396419
"</Repository>",
397420
].join("\n");
398421
yield* withStorage(root, function* () {

‎specs/executable-mdx-spec.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5964,6 +5964,13 @@ would be a second, disagreeing reading of the same source. Each invocation
59645964
answers for itself: a nested invocation is not told about its caller's binding,
59655965
and two invocations that are live at once do not see each other's.
59665966

5967+
A value component with an additional JSON result can reserve its authored name
5968+
with `Component.operations.bindResult(name)`. It uses the same binding-name
5969+
rules and caller scope as `as`. Reserving requires `as` and a distinct name.
5970+
The returned setter stages the value. The engine publishes staged values after
5971+
the invocation finishes, its resources close, and its primary return passes
5972+
validation.
5973+
59675974
**Providers are scope-local middleware.** Behavior is installed with
59685975
`Component.around(middlewares, { at })` and lasts until the installing
59695976
scope exits. Runtime implementations — the document's import and

‎specs/workflow-workspace-spec.md‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2361,20 +2361,21 @@ Each invocation fetches one page. `page` defaults to 1 and `perPage` defaults
23612361
to 20. Page size is an integer from 1 through 100. A page whose first result
23622362
would be beyond GitHub's 1,000 accessible results is refused before transport.
23632363

2364-
The binding has two members. `value` is the GitHub search response JSON
2365-
unchanged, including `total_count`, `incomplete_results`, nullable fields and
2366-
unfamiliar members. `next` is the complete search arguments for the next page,
2367-
with the same query, ordering and page size, or `null` when the pagination
2368-
header offers no next page within the accessible results. The transport
2364+
The name supplied by `as` binds the original GitHub search response JSON,
2365+
including `total_count`, `incomplete_results`, nullable fields and unfamiliar
2366+
members. Optional `nextAs` names a separate binding in the same scope. It
2367+
receives the complete search arguments for the next page, with the same query,
2368+
ordering and page size, or `null` when the pagination header offers no next
2369+
page within the accessible results. The two binding names must differ. The transport
23692370
headers and credentials stay with the adapter. An authentication or transport
23702371
failure, a malformed response, or an item from a different repository refuses
23712372
the read. A valid incomplete response
23722373
binds its original page and incompleteness indicator.
23732374

23742375
An ordinary run reads afresh. A workflow retains the admitted repository, full
23752376
request and result as one `github_search` read. Replay restores the retained
2376-
answer without opening a GitHub session. `Query` can project fields from
2377-
`value` within the fetched page.
2377+
answer without opening a GitHub session. `Query` can project fields directly from the
2378+
bound page.
23782379

23792380
### 7.8 Local repository reads
23802381

0 commit comments

Comments
 (0)