Skip to content

Commit 1ee2671

Browse files
committed
🐛 Keep GitHub search pages raw and validate admitted reads (#815)
1 parent f50ea18 commit 1ee2671

15 files changed

Lines changed: 212 additions & 224 deletions

‎packages/cli/src/repl/expansion.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,7 @@ export interface BoundaryPartition {
8383
* for a hold to be standing in. `hasCapture`, `hasContent` and `hasBinding`
8484
* answer a question about an invocation the walk has already reached; holding
8585
* one would stop the same walk the gate before it already stops, one question
86-
* later. `bindResult` reserves a name on an invocation the walk has already
87-
* reached. The engine publishes the value after teardown.
86+
* later.
8887
*
8988
* `expand` surrounds an element's whole expansion, which makes it a step in
9089
* the walk that reached it and not a walk of its own. Treating it as one would
@@ -115,7 +114,6 @@ export const COMPONENT_BOUNDARIES: BoundaryPartition = {
115114
"hasCapture",
116115
"hasContent",
117116
"hasBinding",
118-
"bindResult",
119117
],
120118
};
121119

‎packages/core/api.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ export type { JournalAdmission } from "./src/execute.ts";
7575
* boundary: a host that wants to watch an element expand needs the descriptor
7676
* and the shapes it will be handed, and nothing of the engine behind them.
7777
*/
78-
export { bindResult, Component } from "./src/component-api.ts";
78+
export { Component } from "./src/component-api.ts";
7979
export type {
8080
ComponentApi,
8181
ComponentExpansionPhase,

‎packages/core/mod.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@ export {
6565
tryContent,
6666
hasCapture,
6767
hasBinding,
68-
bindResult,
6968
capture,
7069
handleFailure,
7170
} from "./src/component-api.ts";

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

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ import type {
3131
ErrorSegment,
3232
EvalEnv,
3333
FunctionComponentDefinition,
34-
Json,
3534
Modifier,
3635
SourcePosition,
3736
} from "./types.ts";
@@ -209,12 +208,6 @@ export interface ComponentApi {
209208
* reading of the same prop.
210209
*/
211210
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>;
218211
/**
219212
* Create a resource owned by the scope that invoked this component
220213
* (spec §4.4).
@@ -396,10 +389,6 @@ const COMPONENT_DEFAULTS: Omit<ComponentApi, "registry"> = {
396389
*raise(error: ErrorSegment): Operation<ErrorSegment> {
397390
return yield* settle(error);
398391
},
399-
// deno-lint-ignore require-yield
400-
*bindResult(): Operation<(value: Json) => void> {
401-
throw new Error("Result bindings require a function component invocation.");
402-
},
403392
env: undefined,
404393
evalScope: undefined,
405394
// deno-lint-ignore require-yield
@@ -552,7 +541,6 @@ export const codeBlock: Operations<ComponentApi>["codeBlock"] = Component.operat
552541
export const persistent: Operations<ComponentApi>["persistent"] = Component.operations.persistent;
553542
export const content: Operations<ComponentApi>["content"] = Component.operations.content;
554543
export const hasContent: Operations<ComponentApi>["hasContent"] = Component.operations.hasContent;
555-
export const bindResult: Operations<ComponentApi>["bindResult"] = Component.operations.bindResult;
556544
export const hasBinding: Operations<ComponentApi>["hasBinding"] = Component.operations.hasBinding;
557545
export const retain: Operations<ComponentApi>["retain"] = Component.operations.retain;
558546
export const tryContent: Operations<ComponentApi>["tryContent"] = Component.operations.tryContent;

‎packages/core/src/expand.ts‎

Lines changed: 2 additions & 37 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, validateBindingName } from "./live-env.ts";
181+
import { liveEnvironment } from "./live-env.ts";
182182
import { TestHarnessComponentDefinition } from "./test-harness.ts";
183183
import type { TestHarnessBinding } from "./test-harness.ts";
184184

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

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

4406-
let resultBindings: Map<string, Json | undefined> | undefined;
44074406
let publishedBinding = false;
44084407
const binding: TestHarnessBinding = {
44094408
has(): boolean {
@@ -4554,28 +4553,6 @@ function* expandFunctionComponent(
45544553
return asBinding !== undefined;
45554554
},
45564555
// deno-lint-ignore require-yield
4557-
*bindResult([bindingName]) {
4558-
const checked = validateBindingName(bindingName);
4559-
if (!checked.ok) {
4560-
throw new Error(
4561-
`Additional result binding on <${name} /> ${checked.error.message}`,
4562-
);
4563-
}
4564-
if (asBinding === undefined || checked.value === undefined) {
4565-
throw new Error(
4566-
`An additional result binding on <${name} /> requires as and a binding name.`,
4567-
);
4568-
}
4569-
if (bindingName === asBinding || resultBindings?.has(bindingName)) {
4570-
throw new Error(`Duplicate result binding "${bindingName}" on <${name} />.`);
4571-
}
4572-
const staged = (resultBindings ??= new Map());
4573-
staged.set(bindingName, undefined);
4574-
return (value: Json) => {
4575-
staged.set(bindingName, parseJson(value));
4576-
};
4577-
},
4578-
// deno-lint-ignore require-yield
45794556
*hasCapture([captureName], _next) {
45804557
return captureName in literalCaptures || captureName in expressionCaptures;
45814558
},
@@ -4732,22 +4709,10 @@ function* expandFunctionComponent(
47324709
// By reference by default: the binding is the value the component
47334710
// returned. `returns` is the opt-in that says this one is a validated
47344711
// JSON record, and it is checked before binding.
4735-
const value =
4712+
parentEnv.values[asBinding] =
47364713
returns === undefined || invocationObservation !== undefined
47374714
? output
47384715
: yield* validateLiveReturnValue(name, output, returns);
4739-
parentEnv.values[asBinding] = value;
4740-
for (const [bindingName, bindingValue] of resultBindings ?? []) {
4741-
if (bindingValue === undefined) {
4742-
continue;
4743-
}
4744-
Object.defineProperty(parentEnv.values, bindingName, {
4745-
value: bindingValue,
4746-
writable: true,
4747-
enumerable: true,
4748-
configurable: true,
4749-
});
4750-
}
47514716
return [];
47524717
}
47534718
// Without `as` there is nowhere to bind, so only text can be observed:

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

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -305,26 +305,6 @@ 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-
328308
it("OBS16: an ambient throw error mode aborts at the first error on every path", function* () {
329309
const cases: Array<[string, ProbeOptions]> = [
330310
["<Broken /><Broken />", {}],

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

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -325,22 +325,11 @@ The `Query` projects URLs from that page. Pass a selected URL to
325325
`PullRequest.Reviews`, `PullRequest.Comments` or `PullRequest.Checks` to read
326326
its evidence.
327327

328-
Request a separate continuation binding with `nextAs`. It contains the
329-
complete next search arguments or `null` after the last accessible page.
328+
To read another page, repeat the search with an explicit `page` and the same
329+
`perPage`, query, and ordering.
330330

331331
```mdx
332-
<GitHub.Search query="is:pr is:open" sort="created" as="page" nextAs="next" />
333-
334-
<If condition={next !== null}>
335-
<GitHub.Search
336-
query={next.query}
337-
sort={next.sort}
338-
order={next.order}
339-
page={next.page}
340-
perPage={next.perPage}
341-
as="nextPage"
342-
/>
343-
</If>
332+
<GitHub.Search query="is:pr is:open label:bug" sort="created" page={2} perPage={20} as="pageTwo" />
344333
```
345334

346335
## IssueTracker

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

Lines changed: 47 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
import { documented, formDispatcher, isJsonObject } from "@executablemd/core";
2-
import { bindResult } from "@executablemd/core/api";
1+
import { documented, formDispatcher } from "@executablemd/core";
32
import type { ComponentRegistration, Json, JsonObject } from "@executablemd/core";
43
import { createApi } from "@effectionx/context-api";
54
import type { Operation } from "effection";
@@ -13,6 +12,7 @@ export const SEARCH_CEILING = 1000;
1312

1413
export type SearchRequest = JsonObject & {
1514
query: string;
15+
kind: "issue" | "pr";
1616
sort?: string;
1717
order?: string;
1818
page: number;
@@ -46,33 +46,64 @@ const sorts = [
4646
"updated",
4747
];
4848

49-
function admitQuery(query: string): void {
50-
// Keep quoted search terms intact while inspecting qualifier names and values.
51-
const tokens = query.match(/(?:[^\s"()]|"(?:\\.|[^"\\])*")+/gu) ?? [];
52-
const kinds = tokens.filter((token) => /^[+-]?(?:is|type):"?(?:issue|pr)"?$/i.test(token));
53-
if (
54-
tokens.some((token) => /^[+-]?(?:repo|org|user):/i.test(token)) ||
55-
query.replace(/"(?:\\.|[^"\\])*"/gu, "").includes('"')
56-
) {
49+
function admitQuery(query: string): SearchRequest["kind"] {
50+
const quoted = /"(?:\\.|[^"\\])*"/gu;
51+
const unquoted = query.replace(quoted, " ");
52+
if (/(?:^|[\s()])[+-]*(?:repo|org|user|owner):/iu.test(unquoted)) {
53+
throw new GitOperationAdmissionError(
54+
SEARCH_ELEMENT,
55+
"omit repository, organization, user and owner scope qualifiers.",
56+
);
57+
}
58+
if (/["()]/u.test(unquoted)) {
5759
throw new GitOperationAdmissionError(
5860
SEARCH_ELEMENT,
59-
"use a GitHub query without repository, organization or user scope qualifiers and with balanced quotes.",
61+
"balance quotes and place parentheses inside quoted text.",
6062
);
6163
}
62-
if (kinds.length !== 1 || !/^is:/i.test(kinds[0] ?? "")) {
64+
const matches = [...query.matchAll(/(?:[+-]*[\w-]+:)?"(?:\\.|[^"\\])*"|[^\s"]+/gu)];
65+
const kinds = matches.filter(([token]) =>
66+
/^[+-]*(?:is|type):(?:"(?:issue|pr|pull-request)"|(?:issue|pr|pull-request))$/i.test(token),
67+
);
68+
const kind = kinds[0];
69+
const token = kind?.[0] ?? "";
70+
const selected =
71+
kind !== undefined &&
72+
(kind.index === 0 || /\s/u.test(query[kind.index - 1] ?? "")) &&
73+
(kind.index + token.length === query.length ||
74+
/\s/u.test(query[kind.index + token.length] ?? ""))
75+
? token.toLowerCase()
76+
: undefined;
77+
if (kinds.length !== 1 || (selected !== "is:issue" && selected !== "is:pr")) {
6378
throw new GitOperationAdmissionError(
6479
SEARCH_ELEMENT,
6580
"select exactly one kind with is:issue or is:pr.",
6681
);
6782
}
83+
const operators = matches.map(([token]) => token);
84+
if (
85+
operators.some(
86+
(token, index) =>
87+
/^(?:AND|OR|NOT)$/u.test(token) &&
88+
[operators[index - 1], operators[index + 1]].some((operand) =>
89+
/^[+-]*[\w-]+:/u.test(operand ?? ""),
90+
),
91+
)
92+
) {
93+
throw new GitOperationAdmissionError(
94+
SEARCH_ELEMENT,
95+
"use Boolean operators with search terms instead of qualifiers.",
96+
);
97+
}
98+
return selected === "is:issue" ? "issue" : "pr";
6899
}
69100

70101
function* search(props: Record<string, Json>): Operation<JsonObject> {
71-
const { query, sort, order, page = 1, perPage = 20, nextAs } = props;
102+
const { query, sort, order, page = 1, perPage = 20 } = props;
72103
if (typeof query !== "string" || typeof page !== "number" || typeof perPage !== "number") {
73104
throw new GitOperationAdmissionError(SEARCH_ELEMENT, "the search arguments are invalid.");
74105
}
75-
admitQuery(query);
106+
const kind = admitQuery(query);
76107
if ((page - 1) * perPage >= SEARCH_CEILING) {
77108
throw new GitOperationAdmissionError(
78109
SEARCH_ELEMENT,
@@ -82,27 +113,19 @@ function* search(props: Record<string, Json>): Operation<JsonObject> {
82113
if (order !== undefined && sort === undefined) {
83114
throw new GitOperationAdmissionError(SEARCH_ELEMENT, "order requires sort.");
84115
}
85-
const publishNext = typeof nextAs === "string" ? yield* bindResult(nextAs) : undefined;
86116
const repository = yield* selectedRepository();
87117
if (repository === undefined) {
88118
throw new GitOperationAdmissionError(SEARCH_ELEMENT, "select a Repository before searching.");
89119
}
90-
const result = yield* GitHubSearch.operations.search(repository, {
120+
return yield* GitHubSearch.operations.search(repository, {
91121
query,
122+
kind,
92123
page,
93124
perPage,
94125
...(typeof sort === "string"
95126
? { sort, order: typeof order === "string" ? order : "desc" }
96127
: {}),
97128
});
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;
106129
}
107130

108131
export const githubSearchRegistration: ComponentRegistration = {
@@ -114,11 +137,6 @@ export const githubSearchRegistration: ComponentRegistration = {
114137
query: { type: "string", minLength: 1 },
115138
sort: { enum: sorts },
116139
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-
},
122140
page: { type: "integer", minimum: 1, maximum: SEARCH_CEILING },
123141
perPage: { type: "integer", minimum: 1, maximum: 100 },
124142
},

‎packages/git/src/composition/pull-request-read-execution.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export interface PullRequestReadExecutionApi {
5454
repository: string,
5555
request: SearchRequest,
5656
transport: () => Operation<JsonObject>,
57+
validate: (value: unknown) => JsonObject,
5758
): Operation<JsonObject>;
5859

5960
/**

0 commit comments

Comments
 (0)