Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/36670-refusal-literal-close.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/spec': patch
---

fix(spec): a hook's or action's refusal code and reason are read as literal at save only when the quoted value closes the value

Clause-②: no
Metadata-protocol: none

The save doors of `HookSchema` and `ActionSchema` read the refusal codes and reasons a body throws literally (`hookRefusalCodesThrownIn`, `hookRefusalReasonsThrownIn`) and refuse one that `refusals` does not declare. The four readers stopped at the closing quote, so a value built from a literal — `throw { code: 'OVER' + suffix }`, `e.code = 'OVER' + suffix`, `reason: 'too' + suffix`, `e.reason = 'too' + suffix`, or a member access such as `'OVER'.concat(suffix)` — was read as the literal `OVER` or `too` and refused at save, though the body would run correctly once the built value is declared. The published reading already left a computed value to the run-time refusal; the save now agrees with it.

A property value is literal now only when its closing quote is followed by `,` or `}`, after optional whitespace. An assigned value is literal only when its closing quote is followed by `;`, `,`, `}` or `)`, by the end of the source, or by a line end whose next line does not continue the expression (a next line opening with an operator, a member access, a bracket or a template continues it). Every literal code or reason the save refused before is still refused, in the same words: `throw { code: 'X' }`, `throw Object.assign(new Error(), { code: 'X' })`, `e.code = 'X';`, `e.code = 'X'` at a line end, and the same for a reason, a listed reason included. A value built from a literal is refused when the hook or action runs, naming the code or reason, as any other computed value is. No author action is needed.
55 changes: 39 additions & 16 deletions packages/spec/src/data/hook-refusal-codes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,31 @@ export const HOOK_REFUSAL_PARAM_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** A string literal in any of the three quote forms, holding a refusal reason. */
const REASON_LITERAL = String.raw`(?<rquote>['"\x60])(?<reason>[a-z][a-z0-9]*(?:_[a-z0-9]+)*)\k<rquote>`;

/** `reason: 'x'` — the property in an object literal a `throw` builds. */
const REASON_PROPERTY = new RegExp(String.raw`(?<![\w$.])reason\s*:\s*` + REASON_LITERAL, 'g');
/**
* [#36670] What must follow a property's quoted value for the value to be that
* literal: `,` or `}`, after optional whitespace (a comment is blanked to
* whitespace first, {@link maskedSource}). Anything else — `'X' + suffix`, a
* member access such as `'X'.concat(suffix)` — builds a computed value, which
* the run-time refusal decides.
*/
const PROPERTY_VALUE_END = String.raw`(?=\s*[,}])`;

/** `e.reason = 'x'` — the reason assigned onto a name the body later throws. */
/**
* [#36670] What must follow an assignment's quoted value for the value to be
* that literal: `;`, `,`, `}` or `)` after optional whitespace, the source's
* end, or a line end whose next line does not continue the expression. A next
* line that opens with an operator, a member access, a call or index bracket
* or a template (`+ suffix`, `.concat(suffix)`) continues it, as JavaScript
* reads it, so the value is computed.
*/
const ASSIGNMENT_VALUE_END = String.raw`(?=\s*[;,})]|\s*$|[ \t]*\r?\n\s*[^\s+\-*/%.?[(&|^<>=,\x60])`;

/** `reason: 'x'` — the property in an object literal a `throw` builds, the literal closing the value. */
const REASON_PROPERTY = new RegExp(String.raw`(?<![\w$.])reason\s*:\s*` + REASON_LITERAL + PROPERTY_VALUE_END, 'g');

/** `e.reason = 'x'` — the reason assigned onto a name the body later throws, the literal closing the value. */
const REASON_ASSIGNMENT = new RegExp(
String.raw`(?<![\w$.])(?<binding>[A-Za-z_$][\w$]*)\s*\.\s*reason\s*=(?!=)\s*` + REASON_LITERAL,
String.raw`(?<![\w$.])(?<binding>[A-Za-z_$][\w$]*)\s*\.\s*reason\s*=(?!=)\s*` + REASON_LITERAL + ASSIGNMENT_VALUE_END,
'g',
);

Expand All @@ -79,12 +98,12 @@ const REASONS_LIST_PROPERTY = /(?<![\w$.])reasons\s*:\s*\[/g;
/** [#36877] `e.reasons = [` — the list assigned onto a name the body later throws. */
const REASONS_LIST_ASSIGNMENT = /(?<![\w$.])(?<binding>[A-Za-z_$][\w$]*)\s*\.\s*reasons\s*=(?!=)\s*\[/g;

/** `code: 'X'` — the property in an object literal a `throw` builds. */
const CODE_PROPERTY = new RegExp(String.raw`(?<![\w$.])code\s*:\s*` + CODE_LITERAL, 'g');
/** `code: 'X'` — the property in an object literal a `throw` builds, the literal closing the value. */
const CODE_PROPERTY = new RegExp(String.raw`(?<![\w$.])code\s*:\s*` + CODE_LITERAL + PROPERTY_VALUE_END, 'g');

/** `e.code = 'X'` — the code assigned onto a name the body later throws. */
/** `e.code = 'X'` — the code assigned onto a name the body later throws, the literal closing the value. */
const CODE_ASSIGNMENT = new RegExp(
String.raw`(?<![\w$.])(?<binding>[A-Za-z_$][\w$]*)\s*\.\s*code\s*=(?!=)\s*` + CODE_LITERAL,
String.raw`(?<![\w$.])(?<binding>[A-Za-z_$][\w$]*)\s*\.\s*code\s*=(?!=)\s*` + CODE_LITERAL + ASSIGNMENT_VALUE_END,
'g',
);

Expand Down Expand Up @@ -253,11 +272,14 @@ function thrownBinding(statement: string): string | undefined {
* `throw Object.assign(new Error(), { code: 'X' })`, `throw { code: 'X' }`;
* - `e.code = 'X'` on a name some `throw` statement throws bare: `throw e`.
*
* A code that arrives any other way — a helper's parameter
* (`refuse('…', code)`), a variable, a computed value — is left to the run-time
* refusal, which judges the code the body actually threw. Only SCREAMING_SNAKE
* literals are read ({@link HOOK_REFUSAL_CODE_PATTERN}), so a record field
* named `code` written with a lower-case value is never mistaken for one.
* Each literal closes its value ({@link PROPERTY_VALUE_END},
* {@link ASSIGNMENT_VALUE_END}). A code that arrives any other way — a
* helper's parameter (`refuse('…', code)`), a variable, a computed value, a
* literal joined to something (`'OVER' + suffix`) included — is left to the
* run-time refusal, which judges the code the body actually threw. Only
* SCREAMING_SNAKE literals are read ({@link HOOK_REFUSAL_CODE_PATTERN}), so a
* record field named `code` written with a lower-case value is never mistaken
* for one.
*/
export function hookRefusalCodesThrownIn(source: string): string[] {
const codes = new Set<string>();
Expand Down Expand Up @@ -299,9 +321,10 @@ export interface HookRefusalThrownReason {
* with that name's literal `e.code = 'X'` — and, marked `listed`, each
* `reason: 'x'` inside `e.reasons = [ … ]` on such a name.
*
* A reason with no literal code beside it, or one that arrives any other way
* (a list built in a variable, a computed reason), is left to the run-time
* refusal.
* Each literal closes its value, as for a code. A reason with no literal code
* beside it, or one that arrives any other way (a list built in a variable, a
* computed reason, a literal joined to something such as `'too' + suffix`), is
* left to the run-time refusal.
*/
export function hookRefusalReasonsThrownIn(source: string): HookRefusalThrownReason[] {
const found: HookRefusalThrownReason[] = [];
Expand Down
100 changes: 100 additions & 0 deletions packages/spec/src/data/hook-refusals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,3 +592,103 @@ describe('Hook.refusals — a listed reason is refused at save where the body na
expect(r.success).toBe(true);
});
});

// A code or reason is literal only when its quoted value closes the value: a
// property's quote is followed by `,` or `}`; an assignment's by `;`, `,`, `}`,
// `)`, the source's end, or a line end whose next line does not continue the
// expression. A value built from a literal (`'OVER' + suffix`, a member access,
// a template hole) is computed, and the run-time refusal decides it, as the
// `hookRefusalCodesThrownIn` docblock says.
describe('Hook.refusals — a literal code or reason closes its value; one built from a literal is computed', () => {
const refusals = {
OVER_LIMIT: { message: 'Over the limit.', reasons: { too_high: { message: 'The amount is too high.' } } },
};
const codeSuffix = "const suffix = '_LIMIT';\n";
const reasonSuffix = "const suffix = '_high';\n";

const LITERAL_CODE = [
['a property closed by `}`', "throw { code: 'OVER' };"],
['a property closed by `,`', "throw { code: 'OVER', reason: 'too_high' };"],
['a property with a line break before the close', "throw {\n code: 'OVER'\n};"],
['a property with a comment before the close', "throw { code: 'OVER' /* the cap */ };"],
['a property in a backtick with no hole', 'throw { code: `OVER` };'],
['a property in Object.assign', "throw Object.assign(new Error('x'), { code: 'OVER' });"],
['an assignment closed by `;`', "const e = new Error('x'); e.code = 'OVER'; throw e;"],
['an assignment closed by a line end', "const e = new Error('x')\ne.code = 'OVER'\nthrow e"],
['an assignment closed by a comment and a line end', "const e = new Error('x');\ne.code = 'OVER' // the cap\nthrow e;"],
['an assignment closed by `,`', "const e = new Error('x'); e.code = 'OVER', e.reason = 'too_high'; throw e;"],
['an assignment closed by `}`', "const e = new Error('x'); if (ctx.input.x) { e.code = 'OVER' } throw e;"],
['an assignment closed by `)`', "const e = new Error('x'); (e.code = 'OVER'); throw e;"],
['an assignment at the source end', "const e = new Error('x'); if (ctx.input.x) throw e; e.code = 'OVER'"],
] as const;

it.each(LITERAL_CODE)('lit: refuses an undeclared literal code written as %s, at body.source', (_shape, source) => {
expect(hookRefusalCodesThrownIn(source)).toEqual(['OVER']);
const r = HookSchema.safeParse({ ...base, refusals, body: body(source) });
expect(r.success).toBe(false);
const issue = r.error!.issues.find((i) => i.path.join('.') === 'body.source')!;
expect(issue.message).toBe(undeclaredHookRefusalCodeAtSave('OVER', ['OVER_LIMIT']));
});

const COMPUTED_CODE = [
['a property concatenation', "throw { code: 'OVER' + suffix };"],
['a property concatenation on the next line', "throw { code: 'OVER'\n + suffix };"],
['a property backtick concatenation', 'throw { code: `OVER` + suffix };'],
['a property member access', "throw { code: 'OVER'.concat(suffix) };"],
['a property template hole', 'throw { code: `OVER${suffix}` };'],
['an assignment concatenation', "const e = new Error('x'); e.code = 'OVER' + suffix; throw e;"],
['an assignment concatenation on the next line', "const e = new Error('x');\ne.code = 'OVER'\n + suffix\nthrow e;"],
['an assignment member access on the next line', "const e = new Error('x');\ne.code = 'OVER'\n .concat(suffix)\nthrow e;"],
['an assignment backtick concatenation', "const e = new Error('x'); e.code = `OVER` + suffix; throw e;"],
] as const;

it.each(COMPUTED_CODE)('dark: passes the save for a code built from a literal by %s (the run-time refusal decides it)', (_shape, source) => {
expect(hookRefusalCodesThrownIn(source)).toEqual([]);
expect(HookSchema.safeParse({ ...base, refusals, body: body(codeSuffix + source) }).success).toBe(true);
});

const LITERAL_REASON = [
['a property closed by `}`', "throw { code: 'OVER_LIMIT', reason: 'too' };"],
['a property closed by `,`', "throw { code: 'OVER_LIMIT', reason: 'too', params: {} };"],
['a property in a listed reason', "throw { code: 'OVER_LIMIT', reasons: [{ reason: 'too' }] };"],
['an assignment closed by `;`', "const e = new Error('x'); e.code = 'OVER_LIMIT'; e.reason = 'too'; throw e;"],
['an assignment closed by a line end', "const e = new Error('x')\ne.code = 'OVER_LIMIT'\ne.reason = 'too'\nthrow e"],
] as const;

it.each(LITERAL_REASON)('lit: refuses an undeclared literal reason written as %s, at body.source', (_shape, source) => {
expect(hookRefusalReasonsThrownIn(source).map((p) => p.reason)).toEqual(['too']);
const r = HookSchema.safeParse({ ...base, refusals, body: body(source) });
expect(r.success).toBe(false);
const issue = r.error!.issues.find((i) => i.path.join('.') === 'body.source')!;
expect(issue.message).toBe(undeclaredHookRefusalReasonAtSave('OVER_LIMIT', 'too', ['too_high'], 'body.source'));
});

const COMPUTED_REASON = [
['a property concatenation', "throw { code: 'OVER_LIMIT', reason: 'too' + suffix };"],
['a property member access', "throw { code: 'OVER_LIMIT', reason: 'too'.concat(suffix) };"],
['a listed property concatenation', "throw { code: 'OVER_LIMIT', reasons: [{ reason: 'too' + suffix }] };"],
['an assignment concatenation', "const e = new Error('x'); e.code = 'OVER_LIMIT'; e.reason = 'too' + suffix; throw e;"],
['an assignment concatenation on the next line', "const e = new Error('x');\ne.code = 'OVER_LIMIT';\ne.reason = 'too'\n + suffix\nthrow e;"],
] as const;

it.each(COMPUTED_REASON)('dark: passes the save for a reason built from a literal by %s (the run-time refusal decides it)', (_shape, source) => {
expect(hookRefusalReasonsThrownIn(source)).toEqual([]);
expect(HookSchema.safeParse({ ...base, refusals, body: body(reasonSuffix + source) }).success).toBe(true);
});

it('dark: an inline handler building its code by concatenation passes the save, at handler', () => {
const handler = async () => {
const suffix = '_LIMIT';
throw Object.assign(new Error('x'), { code: 'OVER' + suffix });
};
expect(HookSchema.safeParse({ ...base, handler, refusals }).success).toBe(true);
});

it('CONTROL: a literal code beside a computed one in the same body is still refused, once', () => {
const source = `${codeSuffix}if (ctx.input.x) throw { code: 'OVER' + suffix };\nthrow { code: 'OVER' };`;
expect(hookRefusalCodesThrownIn(source)).toEqual(['OVER']);
const r = HookSchema.safeParse({ ...base, refusals, body: body(source) });
expect(r.success).toBe(false);
expect(r.error!.issues.filter((i) => i.path.join('.') === 'body.source')).toHaveLength(1);
});
});
59 changes: 59 additions & 0 deletions packages/spec/src/ui/action-refusals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,3 +320,62 @@ describe('Action.refusals — a listed reason is refused at save where the body
);
});
});

// The hook door's reading, at the action door: a code or reason is literal only
// when its quoted value closes the value (a property's by `,` or `}`, an
// assignment's by `;`, `,`, `}`, `)`, the source's end or a line end that does
// not continue the expression); one built from a literal is computed, the
// run-time refusal's.
describe('Action.refusals — a literal code or reason closes its value; one built from a literal is computed', () => {
const refusals = {
OVER_LIMIT: { message: 'Over the limit.', reasons: { too_high: { message: 'The amount is too high.' } } },
};
const DECLARED = ['OVER_LIMIT'];

const LITERAL_CODE = [
['a property closed by `}`', "throw { code: 'OVER' };"],
['a property closed by `,`', "throw { code: 'OVER', reason: 'too_high' };"],
['a property in Object.assign', "throw Object.assign(new Error('x'), { code: 'OVER' });"],
['an assignment closed by `;`', "const e = new Error('x'); e.code = 'OVER'; throw e;"],
['an assignment closed by a line end', "const e = new Error('x')\ne.code = 'OVER'\nthrow e"],
] as const;

it.each(LITERAL_CODE)('lit: refuses an undeclared literal code written as %s, at body.source', (_shape, source) => {
const r = ActionSchema.safeParse({ ...base, body: body(source), refusals });
expect(r.success).toBe(false);
const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source');
expect(issue?.message).toBe(undeclaredActionRefusalCodeAtSave('OVER', DECLARED));
});

const COMPUTED_CODE = [
['a property concatenation', "throw { code: 'OVER' + suffix };"],
['a property member access', "throw { code: 'OVER'.concat(suffix) };"],
['an assignment concatenation', "const e = new Error('x'); e.code = 'OVER' + suffix; throw e;"],
['an assignment concatenation on the next line', "const e = new Error('x');\ne.code = 'OVER'\n + suffix\nthrow e;"],
] as const;

it.each(COMPUTED_CODE)('dark: passes the save for a code built from a literal by %s (the run-time refusal decides it)', (_shape, source) => {
expect(ActionSchema.safeParse({ ...base, body: body(`const suffix = '_LIMIT';\n${source}`), refusals }).success).toBe(true);
});

const LITERAL_REASON = [
['a property closed by `}`', "throw { code: 'OVER_LIMIT', reason: 'too' };"],
['an assignment closed by `;`', "const e = new Error('x'); e.code = 'OVER_LIMIT'; e.reason = 'too'; throw e;"],
] as const;

it.each(LITERAL_REASON)('lit: refuses an undeclared literal reason written as %s, at body.source', (_shape, source) => {
const r = ActionSchema.safeParse({ ...base, body: body(source), refusals });
expect(r.success).toBe(false);
const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source');
expect(issue?.message).toBe(undeclaredActionRefusalReasonAtSave('OVER_LIMIT', 'too', ['too_high']));
});

const COMPUTED_REASON = [
['a property concatenation', "throw { code: 'OVER_LIMIT', reason: 'too' + suffix };"],
['an assignment concatenation', "const e = new Error('x'); e.code = 'OVER_LIMIT'; e.reason = 'too' + suffix; throw e;"],
] as const;

it.each(COMPUTED_REASON)('dark: passes the save for a reason built from a literal by %s (the run-time refusal decides it)', (_shape, source) => {
expect(ActionSchema.safeParse({ ...base, body: body(`const suffix = '_high';\n${source}`), refusals }).success).toBe(true);
});
});
Loading