Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

model-apps 2.20.3: lookup, temp-folder and lexer fixes; lock and test fixes (#781)

Akshay Maloo0a7bf475552a
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.md
index 8f657ec27..823c0720a 100644
--- a/evals/model-apps/genpage/EVAL_GUIDE.md
+++ b/evals/model-apps/genpage/EVAL_GUIDE.md
@@ -117,7 +117,7 @@ Whether a page applies a style the maker asked for (a plan whose `Styling:` line
Plus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The column-name expectations (eval 1's Phase 5b, in both layers, and eval 7's) are graded by `lib/column-contract.js` against the RuntimeTypes.ts a fixture kept: every column a page names in its dataApi calls — a `select` list, an `orderBy` or `filter` expression, the keys of a `createRow`/`updateRow` payload, an options object or select list written as a name it declares, and each `<column>@OData.Community.Display.V1.FormattedValue` key it reads — must be one the schema declares on that table (or a system column every user-owned table has and the type generator does not write, such as `createdon`). A fixture that kept no RuntimeTypes.ts reports `column-name verification requires RuntimeTypes.ts fixture`. Lookup-identity use in page code is not graded yet: no check proves that a page reads, filters, retrieves, opens or writes a lookup only through its normalized table-and-id pair (`references/rules.md` Critical Rule 23) — eval 26 grades the question, the lookup metadata and the plan records behind its page, not the page's lookup code. Other unregistered expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.
-**Structural page checks:** several per-eval expectations are graded from how a page is BUILT rather than whether a word appears in it — eval 4's review step showing every entered field before the submit, and a label on every form field (its own `aria-label`/`aria-labelledby`, or a Fluent `<Field label>` around it); eval 5's components and utilities kept top level (a nested PascalCase component, or a nested function that reads nothing from the one around it, fails; a handler that closes over state does not); eval 12's search box beside a filter toolbar; eval 13's shown text through the `translate` (or `t`) helper; and eval 15's choice values named after the RuntimeTypes.ts member they are. `lib/tsx-structure.js` reads elements, attributes, JSX text and function scopes from the plugin's lexer view, where strings, comments and JSX text are blanked at their offsets, and `lib/page-checks.js` holds the checks; each states what it does not judge, which stays with the Layer 3 rubric. JSX text and a JSX attribute's string are read as the page renders them: `lib/jsx-references.js` decodes their character references with the page compiler the plugin vendors, so to eval 13's checks `<Text>&#72;&#105;</Text>` is the hardcoded text "Hi" and `<Text>&euro;{total}</Text>` a hardcoded currency symbol, exactly as when written plainly, while a JavaScript string (`{'&euro;'}`) shows its references as written. Eval 4's step navigation ("step state management … and Next/Back navigation") is deliberately not graded: whether Next and Back move the step is the value the step's setter receives — an updater can compute the next step and return the old one — which a scan of the page's text cannot prove; it needs data-flow analysis, and the coverage baseline records it as unscored with that reason.
+**Structural page checks:** several per-eval expectations are graded from how a page is BUILT rather than whether a word appears in it — eval 4's review step showing every entered field before the submit, and a label on every form field (its own `aria-label`/`aria-labelledby`, or a Fluent `<Field label>` around it); eval 5's components and utilities kept top level (a nested PascalCase component, or a nested function that reads nothing from the one around it, fails; a handler that closes over state does not); eval 12's search box beside a filter toolbar; eval 13's shown text through the `translate` (or `t`) helper; and eval 15's choice values named after the RuntimeTypes.ts member they are. `lib/tsx-structure.js` reads elements, attributes, JSX text and function scopes from the plugin's lexer view, where strings, comments and JSX text are blanked at their offsets, and `lib/page-checks.js` holds the checks; each states what it does not judge, which stays with the Layer 3 rubric. JSX text and a JSX attribute's string are read as the page renders them: `lib/jsx-references.js` decodes their character references with the page compiler the plugin vendors, so to eval 13's checks `<Text>&#72;&#105;</Text>` is the hardcoded text "Hi" and `<Text>&euro;{total}</Text>` a hardcoded currency symbol, exactly as when written plainly, while a JavaScript string (`{'&euro;'}`) shows its references as written. A component's type arguments are read when they are names only, so `<DataGridRow<Row> title="&euro;" />` is graded like any tag; a tag whose type arguments are anything else (a function, string, template, object or other type) cannot be read for certain, and every check that reads elements or JSX text fails its page with the tag's line and column rather than pass what it could not see. Eval 4's step navigation ("step state management … and Next/Back navigation") is deliberately not graded: whether Next and Back move the step is the value the step's setter receives — an updater can compute the next step and return the old one — which a scan of the page's text cannot prove; it needs data-flow analysis, and the coverage baseline records it as unscored with that reason.
**Bounded Custom API declaration tracking (Layers 1 and 2):** Potential-write checks
distinguish a definite plain arrow parameter declaration, including a default, from an
diff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.js
index da0a60f34..5995720c4 100644
--- a/evals/model-apps/genpage/lib/assertions-layer-2.js
+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js
@@ -30,7 +30,7 @@ const {
reviewSummaryProblems, formFieldLabelProblems, searchAndFilterProblems,
translateCoverageProblems, choiceEnumProblems,
} = require('./page-checks.js');
-const { nestedDefinitionProblems, renderedSource } = require('./tsx-structure.js');
+const { nestedDefinitionProblems, renderedSource, unreadableElementProblems } = require('./tsx-structure.js');
const { columnProblems } = require('./column-contract.js');
let _verifiedIcons = null;
@@ -758,7 +758,11 @@ function objectProperties(content, keep, isLiteral, name) {
return out;
}
+// A page with an element whose type arguments this reader cannot read (unreadableElementProblems) fails: its attribute
+// strings are not decoded, and which characters after it are text is the lexer's guess, so a symbol could hide there.
function hardcodedFormatProblem(content) {
+ const [unreadable] = unreadableElementProblems(content);
+ if (unreadable) return unreadable;
const keep = blankNonCodePreservingTemplateExpressions(content);
const comment = new Uint8Array(content.length);
for (const { start, end } of commentRanges(content)) comment.fill(1, start, end);
diff --git a/evals/model-apps/genpage/lib/page-checks.js b/evals/model-apps/genpage/lib/page-checks.js
index 864482f85..d654d4042 100644
--- a/evals/model-apps/genpage/lib/page-checks.js
+++ b/evals/model-apps/genpage/lib/page-checks.js
@@ -17,7 +17,7 @@
// label never counts as code, and code is never taken for text. What each one does NOT judge is said
// beside it; a person still judges the rest in the Layer 3 rubric.
-const { sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose, withoutComments } = require('./tsx-structure.js');
+const { sourceView, jsxElements, jsxTextRuns, declarationSource, matchingClose, withoutComments, unreadableElementProblems } = require('./tsx-structure.js');
const { renderedText } = require('./jsx-references.js');
const { runtimeEnums } = require('./expectation-evidence.js');
const { escapeRe } = require('./source-evidence.js');
@@ -326,8 +326,11 @@ function stepDomain(code, state, regions) {
// of the step (reachableSteps), so the summary is always seen first. A second, unconditional submit, or a
// boundary that lets the submit show on an earlier step (`step < 1 ? Next : Submit`), fails it. A condition
// the reader cannot tie to the step (`ready ? Submit : null`) proves nothing and fails it too. It does not
-// judge how the summary looks.
+// judge how the summary looks. A page with an element this reader cannot read (unreadableElementProblems) fails: the
+// field or submit it skips could be the one that decides.
function reviewSummaryProblems(content) {
+ const unreadable = unreadableElementProblems(content);
+ if (unreadable.length) return unreadable;
const { src, code } = sourceView(content);
const [state] = stepStates(content);
if (!state) return ['no step state, so there is no review step'];
@@ -409,7 +412,11 @@ function childrenShowText(content, element) {
return false;
}
+// A page with an element this reader cannot read (unreadableElementProblems) fails, even one with no form control in
+// sight: the skipped element may be a control, or a label, and the code after it is read by a guess.
function formFieldLabelProblems(content) {
+ const unreadable = unreadableElementProblems(content);
+ if (unreadable.length) return unreadable;
const controls = jsxElements(content, FORM_CONTROLS).filter((c) => c.attrs.get('type')?.value !== 'hidden');
if (!controls.length) return null;
const fields = jsxElements(content, /^Field$/).filter((f) => names(f.attrs.get('label')));
@@ -434,10 +441,13 @@ function formFieldLabelProblems(content) {
// search, wired to state by an onChange/onInput handler. A filter toolbar is a Fluent UI Toolbar (or an
// element with role="toolbar") holding at least one control — a Dropdown, Combobox, Select, toggle or
// radio, Checkbox, Switch, MenuButton or TabList — with a handler. Whether the two narrow the same rows
-// is not judged.
+// is not judged. A page with an element this reader cannot read (unreadableElementProblems) fails: what it skips, or a
+// tag read inside its type arguments, could make or break either.
const FILTER_CONTROLS = /^(?:Dropdown|Combobox|Select|ToggleButton|ToolbarToggleButton|ToolbarRadioButton|ToolbarRadioGroup|Checkbox|Switch|MenuButton|TabList|RadioGroup|select)$/;
const HANDLERS = ['onOptionSelect', 'onChange', 'onClick', 'onCheckedValueChange', 'onTabSelect', 'onSelectionChange', 'onInput'];
function searchAndFilterProblems(content) {
+ const unreadable = unreadableElementProblems(content);
+ if (unreadable.length) return unreadable;
const searchBoxes = jsxElements(content, /^(?:SearchBox|Input|input)$/).filter((el) => {
if (el.name !== 'SearchBox') {
const said = ['type', 'placeholder', 'aria-label'].map((name) => el.attrs.get(name)).filter((a) => a && a.kind === 'string').map((a) => a.value).join(' ');
@@ -445,7 +455,7 @@ function searchAndFilterProblems(content) {
}
return el.attrs.has('onChange') || el.attrs.has('onInput');
});
- const toolbars = jsxElements(content, /^[A-Za-z][\w.]*$/).filter((el) => el.name === 'Toolbar' || el.attrs.get('role')?.value === 'toolbar');
+ const toolbars = jsxElements(content).filter((el) => el.name === 'Toolbar' || el.attrs.get('role')?.value === 'toolbar');
const filtering = toolbars.filter((toolbar) => jsxElements(content, FILTER_CONTROLS).some((control) => control.start >= toolbar.childrenStart && control.start < toolbar.childrenEnd
&& HANDLERS.some((name) => control.attrs.has(name))));
const problems = [];
@@ -468,6 +478,8 @@ function searchAndFilterProblems(content) {
// `{'&#72;&#105;'}` shows those characters as written. A problem quotes the text as it renders, and as written too
// when references make the two differ.
// NOT read: a string a function returns to JSX (`renderHeaderCell: () => 'Name'`) or a variable holding one.
+// A page with an element this reader cannot read (unreadableElementProblems) fails: its attributes are not read, and the
+// JSX text after it is told from code by a guess.
const SHOWN_ATTRIBUTES = new Set(['label', 'placeholder', 'title', 'aria-label', 'aria-description', 'alt', 'header', 'description', 'content', 'hint', 'validationMessage', 'text']);
// The string and template literals an expression can evaluate to, as { quote, text }: the expression
@@ -522,6 +534,8 @@ const shownLetters = ({ quote, text }) => hasLetter(quote === '`' ? text.replace
const quoted = (quote, shown, written = shown) => `${quote}${shown.slice(0, 40)}${quote}${written === shown ? '' : ` (written ${quote}${written.slice(0, 40)}${quote})`}`;
function translateCoverageProblems(content) {
+ const unreadable = unreadableElementProblems(content);
+ if (unreadable.length) return unreadable;
const { src, code } = sourceView(content);
const helper = ['translate', 't'].find((name) => declarationSource(content, name) && new RegExp(`(?<![.\\w$])${name}\\s*\\(`).test(code.replace(new RegExp(`\\b(?:const|let|var|function)\\s+${name}\\b`, 'g'), '')));
if (!helper) return ['no translate() helper is declared and called'];
diff --git a/evals/model-apps/genpage/lib/source-evidence.js b/evals/model-apps/genpage/lib/source-evidence.js
index 479129091..6f6764bf9 100644
--- a/evals/model-apps/genpage/lib/source-evidence.js
+++ b/evals/model-apps/genpage/lib/source-evidence.js
@@ -1,7 +1,7 @@
'use strict';
const { blankNonCodePreservingTemplateExpressions } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
-const { jsxElements } = require('./tsx-structure.js');
+const { jsxElements, unreadableElements } = require('./tsx-structure.js');
const { transparentBoundary } = require('./page-error-canonical.js');
function groupEnd(mask, open) {
@@ -243,10 +243,13 @@ function componentNamed(mask, scopes, name) {
// Anything else returns null, and the default export stays the component exactly as before the wrapper existed. A
// failed proof is not evidence that a call is unrelated: what PageBody then receives is simply unproven. The proof reads
// the source text as well as its mask (the import's module name is a string the mask blanks): without `code` it fails.
+// Type arguments of names only (`<PageBody<Props> {...props} />`) are erased before React renders, so they are read like
+// any tag; a page with an element whose type arguments are anything else (unreadableElements) proves nothing.
const PAGE_BODY = 'PageBody';
const PAGE_ERROR_BOUNDARY = 'PageErrorBoundary';
function forwardedPageBody(mask, scopes, wrapper, code) {
if (typeof code !== 'string' || code.length !== mask.length) return null;
+ if (unreadableElements(mask).length) return null;
const propsName = wrapper?.propsName;
if (!propsName || reassigned(mask, propsName)) return null;
const { scope } = wrapper;
diff --git a/evals/model-apps/genpage/lib/tsx-structure.js b/evals/model-apps/genpage/lib/tsx-structure.js
index 09ba56f9f..c7bc4c710 100644
--- a/evals/model-apps/genpage/lib/tsx-structure.js
+++ b/evals/model-apps/genpage/lib/tsx-structure.js
@@ -16,19 +16,27 @@
// view: <Field label="··········"><Input aria-label="·····" value={form.x} /></Field>
// source: <Text>Hello {name} world</Text> view: <Text>······{name}······</Text>
// Limits, by design (each check that uses this says which it lives with):
-// - an element is found where a `<Name` stands at the start of an expression (after `(`, `=`, `,`,
-// `?`, `:`, `{`, `}`, `>`, `&&`, `return`, …); `useState<Row>(…)` and `a < b` are not elements;
-// - a closing tag is matched by name, counting nested same-name elements;
+// - an element is found where a `<Name` (its first character a letter, `_` or `$`) stands at the start of an
+// expression (after `(`, `=`, `,`, `?`, `:`, `{`, `}`, `>`, `&&`, `return`, …); `useState<Row>(…)` and `a < b`, `a <_b`
+// are not elements;
+// - an element's type arguments are read when they are names only (`<DataGridRow<Row> title="…">`);
+// any other (`<List<(r: Row) => string>>`) makes the element unreadable, and a check that reads
+// elements or JSX text fails closed on its page (unreadableElements);
+// - a closing tag is matched by name, counting the nested same-name openings of the one tag traversal,
+// so a name inside another tag's type arguments (`<B<of<A<T>>>`) is never an opening;
// - JSX text is a blanked run whose nearest code character before it is `>` or `}` (a string's run
// follows its quote, a template's its backtick, a regex body its `/`), comments excluded;
// - a function's scope is a body `{…}` (or an arrow's expression) found from `=>` and `function`;
// a declaration with no semicolon may run on into the next statement.
-const { blankLiterals, commentRanges } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
+const { blankLiterals, commentRanges, ofTakesOperand } = require('../../../../plugins/model-apps/scripts/lib/source-literals.js');
const { renderedText, characterReferences, hasReference } = require('./jsx-references.js');
const IDENT_CHAR = /[\w$]/;
-// Words after which an expression (so an element) may start, as in source-literals.js EXPR_START_WORDS.
+// Words after which an expression (so an element) may start, as in source-literals.js EXPR_START_WORDS. `of` is one wherever the lexer's
+// own rule (ofTakesOperand) cannot prove from its immediate context that it is no `for…of` keyword — a `(` right after `for` or `await`,
+// a word it cannot read whole, a bracket beyond its reach — and the page may then be misread as before; elsewhere it is a name
+// (`type of<T> = T`, `fn<of<Row>>()`).
const EXPR_WORDS = new Set(['return', 'yield', 'await', 'default', 'case', 'else', 'do', 'in', 'of', 'typeof', 'void', 'throw']);
const OPENERS = { '(': ')', '[': ']', '{': '}' };
@@ -53,7 +61,10 @@ function wordBefore(code, end) {
function elementMayStart(code, at) {
const k = prevSignificant(code, at);
if (k < 0) return true;
- if (IDENT_CHAR.test(code[k])) return EXPR_WORDS.has(wordBefore(code, k));
+ if (IDENT_CHAR.test(code[k])) {
+ const word = wordBefore(code, k);
+ return word === 'of' ? ofTakesOperand(code, k).operand : EXPR_WORDS.has(word);
+ }
return !/[)\]]/.test(code[k]);
}
@@ -73,7 +84,103 @@ function matchingClose(code, open) {
return -1;
}
-// The end of an opening tag whose name ends at `from`: the index of its `>`, and whether it is `/>`.
+// Words that start a type operator, a type predicate or a constructor type, never a type's name: `<A<keyof Row>>` is no
+// list of names.
+const TYPE_OPERATOR_WORDS = new Set(['keyof', 'typeof', 'infer', 'unique', 'readonly', 'asserts', 'new', 'abstract', 'is', 'extends']);
+const TYPE_NAME = /[A-Za-z_$][\w$]*/y;
+// A JSX tag's name: an identifier (a letter, `_` or `$`, then letters, digits, `_` or `$`), with `.` for a member
+// (`Toolbar.Item`). A hyphenated intrinsic name (`<my-element>`) is not read.
+const TAG_NAME = '[A-Za-z_$][\\w$.]*';
+// Deeper nesting than this is not read (a page never needs it); it is reported as unreadable rather than recursed into.
+const MAX_TYPE_ARGUMENT_DEPTH = 64;
+
+// The type arguments that open at `open` (a `<` in the code view, right after a tag's name and its trivia) when they are
+// made of names only, the form the plugin's lexer reads for certain (source-literals.js, its jsxTag mode: "for names and
+// their unions, arrays and nested arguments (`<DataGridRow<Account>`) this scan and TypeScript read the tag alike"):
+// arguments := `<` type (`,` type)* `>`
+// type := [`|` | `&`] operand ((`|` | `&`) operand)*
+// operand := name (`.` name)* [arguments] (`[` `]`)*
+// with white space between any two tokens; a comment there is white space in the code view already. Returns the index just
+// after the closing `>`, or -1 for anything else: a string, template, object, tuple, function, conditional, indexed,
+// keyof/typeof or literal type — where the lexer only guesses (its `jsx-type-arguments` ambiguity), since TypeScript
+// scans those by rules the lexer does not have:
+// <DataGridRow<Row> → read <Grid<Map<string, Row[]>>> → read <A.B<T | U, V & W> → read
+// <A<"a\"b"> <A<() => T> <A<{ x: T }> <A<[T, U]> <A<T["k"]> <A<keyof T> <A<1> → -1
+function namesOnlyTypeArguments(code, open) {
+ let i = open;
+ const skip = () => { while (i < code.length && /\s/.test(code[i])) i += 1; };
+ const name = () => {
+ TYPE_NAME.lastIndex = i;
+ const m = TYPE_NAME.exec(code);
+ if (!m) return null;
+ i += m[0].length;
+ return m[0];
+ };
+ const operand = (depth) => {
+ skip();
+ const first = name();
+ if (!first || TYPE_OPERATOR_WORDS.has(first)) return false;
+ skip();
+ while (code[i] === '.') {
+ i += 1;
+ skip();
+ if (!name()) return false;
+ skip();
+ }
+ if (code[i] === '<' && !list(depth + 1)) return false;
+ skip();
+ while (code[i] === '[') {
+ i += 1;
+ skip();
+ if (code[i] !== ']') return false;
+ i += 1;
+ skip();
+ }
+ return true;
+ };
+ const type = (depth) => {
+ skip();
+ if (code[i] === '|' || code[i] === '&') i += 1;
+ for (;;) {
+ if (!operand(depth)) return false;
+ if (code[i] !== '|' && code[i] !== '&') return true;
+ i += 1;
+ }
+ };
+ // At a `<`: the list, through its `>`.
+ const list = (depth) => {
+ if (depth > MAX_TYPE_ARGUMENT_DEPTH) return false;
+ i += 1;
+ for (;;) {
+ if (!type(depth)) return false;
+ if (code[i] !== ',') break;
+ i += 1;
+ }
+ if (code[i] !== '>') return false;
+ i += 1;
+ return true;
+ };
+ return list(0) ? i : -1;
+}
+
+// What follows a tag's name, which ends at `nameEnd` in the code view: where its attributes start, past the type arguments
+// TypeScript reads there — after white space, a line break or a comment too (parser.ts, tryParseTypeArguments,
+// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts) — or null when it has type arguments that are
+// not names only (namesOnlyTypeArguments), whose extent this reader does not know for certain:
+// <Input value={v} /> → { attrsFrom: after `Input` }
+// <DataGridRow<Row> key={id}> → { attrsFrom: after `<Row>`, typeArguments: true }
+// <List<(r: Row) => string> …> → null
+function openingTag(code, nameEnd) {
+ let i = nameEnd;
+ while (i < code.length && /\s/.test(code[i])) i += 1;
+ if (code[i] !== '<') return { attrsFrom: nameEnd, typeArguments: false };
+ const end = namesOnlyTypeArguments(code, i);
+ // After the arguments TypeScript reads attributes, a `/>` or a `>`; anything else is no tag this reader can bound.
+ if (end < 0 || !/[\s/>{A-Za-z_$]/.test(code[end] || '')) return null;
+ return { attrsFrom: end, typeArguments: true };
+}
+
+// The end of an opening tag whose attributes start at `from`: the index of its `>`, and whether it is `/>`.
function tagEnd(code, from) {
let depth = 0;
for (let i = from; i < code.length; i += 1) {
@@ -128,30 +235,52 @@ function readAttributes(src, code, from, end) {
return attrs;
}
+// The `<Name` of every tag that stands where an element may start, in source order: { name, start, open } where `open` is
+// its openingTag, or null when its type arguments are not names only. A `<` inside a tag's type arguments that were read
+// is part of them, never a tag of its own (`<A<B<C>>>` is one tag). A closing tag (`</Name>`) is no match here.
+function* openingTags(code) {
+ const re = new RegExp(`<(${TAG_NAME})(?=[\\s/><])`, 'g');
+ for (let m = re.exec(code); m; m = re.exec(code)) {
+ if (!elementMayStart(code, m.index)) continue;
+ const open = openingTag(code, m.index + m[0].length);
+ if (open && open.typeArguments) re.lastIndex = open.attrsFrom;
+ yield { name: m[1], start: m.index, open };
+ }
+}
+
// Every element of the page whose tag name `accept` allows (a Set, a RegExp, or nothing for all), in
// source order: { name, start, openEnd, selfClosing, attrs, childrenStart, childrenEnd, end }. The
-// children of a self-closing element, or of one whose closing tag cannot be found, are empty.
+// children of a self-closing element, or of one whose closing tag cannot be found, are empty. An element
+// with type arguments of names only (`<DataGridRow<Row> key={id}>`) is read like any other; one whose type
+// arguments are anything else is not read here, and unreadableElements reports it.
function jsxElements(content, accept = null) {
const { src, code } = sourceView(content);
const allowed = (name) => !accept || (accept instanceof Set ? accept.has(name) : accept.test(name));
const out = [];
- for (const m of code.matchAll(/<([A-Za-z][\w.]*)(?=[\s/>])/g)) {
- const name = m[1];
- if (!allowed(name) || !elementMayStart(code, m.index)) continue;
- const tag = tagEnd(code, m.index + m[0].length);
+ const tags = [...openingTags(code)].filter((tag) => tag.open);
+ // The readable openings of each name, for closingTag: found by the one traversal above, which steps over every tag's
+ // type arguments, so a name inside another tag's arguments (`<Box<of<Field<Row>>> />`) is never an opening.
+ const openings = new Map();
+ for (const tag of tags) {
+ if (!openings.has(tag.name)) openings.set(tag.name, []);
+ openings.get(tag.name).push(tag);
+ }
+ for (const { name, start, open } of tags) {
+ if (!allowed(name)) continue;
+ const tag = tagEnd(code, open.attrsFrom);
if (!tag) continue;
const element = {
name,
- start: m.index,
+ start,
openEnd: tag.end + 1,
selfClosing: tag.selfClosing,
- attrs: readAttributes(src, code, m.index + m[0].length, tag.end),
+ attrs: readAttributes(src, code, open.attrsFrom, tag.end),
childrenStart: tag.end + 1,
childrenEnd: tag.end + 1,
end: tag.end + 1,
};
if (!tag.selfClosing) {
- const close = closingTag(code, name, tag.end + 1);
+ const close = closingTag(code, name, tag.end + 1, openings.get(name));
if (close) Object.assign(element, { childrenEnd: close.start, end: close.end });
}
out.push(element);
@@ -159,23 +288,51 @@ function jsxElements(content, accept = null) {
return out;
}
-// The `</name>` that closes an element whose opening tag ends before `from`, counting nested
-// non-self-closing elements of the same name.
-function closingTag(code, name, from) {
- const re = new RegExp(`<(/?)${name.replace(/[.$]/g, '\\$&')}(?=[\\s/>])`, 'g');
+// Every tag in element position whose type arguments are not names only, as { name, start, line, column } (1-based, in
+// UTF-16 units, a line ending at LF, CR LF or a lone CR, as an editor counts). The plugin's lexer only guesses where such a
+// tag ends (its `jsx-type-arguments` ambiguity), so the code view from there on may hold strings as code or attributes as
+// text, and jsxElements skips the tag. A check that reads elements or JSX text fails closed on a page that has one
+// (unreadableElementProblems).
+function unreadableElements(content) {
+ const { src, code } = sourceView(content);
+ const out = [];
+ for (const { name, start, open } of openingTags(code)) {
+ if (open) continue;
+ const before = src.slice(0, start);
+ const breaks = [...before.matchAll(/\r\n|\r|\n/g)];
+ const lineStart = breaks.length ? breaks.at(-1).index + breaks.at(-1)[0].length : 0;
+ out.push({ name, start, line: breaks.length + 1, column: start - lineStart + 1 });
+ }
+ return out;
+}
+
+// The problem a check reports, as its first, for a page it cannot read for certain (unreadableElements): the first such tag,
+// where it is, and why. Empty when every element is read.
+function unreadableElementProblems(content) {
+ const [first] = unreadableElements(content);
+ if (!first) return [];
+ return [`<${first.name}> at line ${first.line}, column ${first.column} has type arguments that are not only names (a string, template, object, function or other type), which this check cannot read for certain`];
+}
+
+// The `</name>` that closes an element whose opening tag ends before `from`, counting the nested non-self-closing
+// elements of the same name among `openings` (that name's readable tags from openingTags, in source order). A closing
+// tag holds no type arguments, and names-only type arguments hold no `</`, so every `</name` match is a closing tag.
+function closingTag(code, name, from, openings = []) {
+ const re = new RegExp(`</${name.replace(/[.$]/g, '\\$&')}(?=[\\s/>])`, 'g');
re.lastIndex = from;
let depth = 1;
+ let next = openings.findIndex((tag) => tag.start >= from);
+ if (next < 0) next = openings.length;
for (let m = re.exec(code); m; m = re.exec(code)) {
- if (m[1]) {
- depth -= 1;
- if (depth === 0) {
- const gt = code.indexOf('>', m.index);
- return gt < 0 ? null : { start: m.index, end: gt + 1 };
- }
- } else if (elementMayStart(code, m.index)) {
- const tag = tagEnd(code, m.index + m[0].length);
+ for (; next < openings.length && openings[next].start < m.index; next += 1) {
+ const tag = tagEnd(code, openings[next].open.attrsFrom);
if (tag && !tag.selfClosing) depth += 1;
}
+ depth -= 1;
+ if (depth === 0) {
+ const gt = code.indexOf('>', m.index);
+ return gt < 0 ? null : { start: m.index, end: gt + 1 };
+ }
}
return null;
}
@@ -511,7 +668,8 @@ function nestedDefinitionProblems(content) {
}
module.exports = {
- sourceView, jsxElements, jsxTextRuns, renderedSource, declarationSource, matchingClose, patternNames,
+ sourceView, jsxElements, unreadableElements, unreadableElementProblems, jsxTextRuns, renderedSource, declarationSource,
+ matchingClose, patternNames,
namedFunctions, nestedDefinitionProblems, withoutComments,
// Exported so that a check needing a page's function scopes reads them through this reader instead of a second one.
functionScopes,
diff --git a/evals/model-apps/genpage/tests/page-expectations.test.js b/evals/model-apps/genpage/tests/page-expectations.test.js
index f9d8fab35..1a14b0abc 100644
--- a/evals/model-apps/genpage/tests/page-expectations.test.js
+++ b/evals/model-apps/genpage/tests/page-expectations.test.js
@@ -92,6 +92,97 @@ const n = useState<Row>(null);`;
assert.deepEqual(patternNames('{ item, dragging }: TaskCardProps'), ['item', 'dragging']);
});
+// A tag's type arguments (`<DataGridRow<Row> title="…">`) are erased before it renders: the tag is read like any other
+// when they are names only, the form the plugin's lexer reads for certain. Anything else in them (a function, string,
+// template, object or other type) leaves the tag unreadable: it is not read as an element, and unreadableElements reports
+// where it is, so a check can refuse the page rather than pass what it cannot see.
+test('tsx structure: a tag with type arguments of names only is read; any other is reported as unreadable', () => {
+ const { unreadableElements } = require('../lib/tsx-structure.js');
+ const read = (page) => jsxElements(page).map((e) => [e.name, e.start, e.openEnd, e.childrenEnd, e.end, Object.fromEntries([...e.attrs].map(([k, a]) => [k, a.value]))]);
+ for (const tag of ['<DataGridRow<Row>', '<A <Row>', '<A /* row */ <Row>', '<A\n<Row>', '<A\r\n<Row>', '<A // row\n<Row>', '<Grid<Map<string, Row[]>>', '<A.B<T | U, V & W>', '<A<| ns.T>', '<A<B>']) {
+ const page = `${tag} title="&euro;" />`;
+ const name = tag.match(/^<([\w.]+)/)[1];
+ assert.deepEqual(read(page), [[name, 0, page.length, page.length, page.length, { title: '&euro;' }]], tag);
+ assert.deepEqual(unreadableElements(page), [], tag);
+ }
+ // Nested elements of one name, with and without type arguments, close where they do; nothing inside the arguments is a tag.
+ const nested = '<L<Row>><L>a</L><L<Map<K, V>>>b</L></L>';
+ assert.deepEqual(read(nested).map(([name, start, openEnd, childrenEnd, end]) => [name, start, openEnd, childrenEnd, end]), [['L', 0, 8, 35, 39], ['L', 8, 11, 12, 16], ['L', 16, 30, 31, 35]]);
+ assert.deepEqual(jsxElements('<A<B<C>> />', /^[BC]$/), [], 'a type argument is no element');
+ // Not names only: not read, and reported at its line and column (a line ends at LF, CR LF or a lone CR).
+ const unreadable = [
+ '<A<() => () => "<B<() => string>>"> title="&euro;">Hello</A>',
+ '<DataGridRow<() => () => string /* <B<() => string>> */> title="&euro;" />',
+ '<A<() => "a\\\nb"> title="&euro;" />',
+ '<A<() => "a\\\r\nb"> title="&euro;" />',
+ '<A<() => `x${string /* the type\'s name */}y`> title={t("ok")} />',
+ '<A<"a\\"//"> title="&euro;" />',
+ '<A<"a\\"/*"> title="&euro;" />',
+ '<A<keyof Row> />', '<A<typeof row> />', '<A<Row["k"]> />', '<A<{ x: T }> />', '<A<[T, U]> />', '<A<1> />', '<A<(T)> />', '<A<T,> />', '<A<> />',
+ ];
+ for (const tag of unreadable) {
+ const page = `const a = 1;\r\nconst b = 2;\rconst P = () => ${tag};\nexport default P;`;
+ const name = tag.match(/^<([\w.]+)/)[1];
+ assert.deepEqual(unreadableElements(page)[0], { name, start: 43, line: 3, column: 17 }, tag);
+ assert.ok(!jsxElements(page).some((e) => e.start === 43), `${tag} is not read`);
+ }
+ // Type arguments of a call or a generic arrow, and a comparison, are no tags at all.
+ const code = 'const x = a < b;\nconst y = fn<T>(x);\nconst [r] = useState<Row>(null);\nconst f = <T,>(x: T) => x;\nconst m = useMemo<Record<string, Row[]>>(() => ({}), []);';
+ assert.deepEqual(jsxElements(code), []);
+ assert.deepEqual(unreadableElements(code), []);
+});
+
+// The closing tag of an element is found by counting the openings of its name that the one traversal of the page found,
+// which steps over every tag's type arguments: a type named `of` (an expression keyword's spelling) does not make
+// `<Field<Row>>` inside `<Box<of<Field<Row>>> />` an opening that would close the outer Field early.
+test('tsx structure: a name inside another tag\u2019s type arguments never counts toward a closing tag', () => {
+ const bounds = (page, name) => jsxElements(page, new RegExp(`^${name}$`)).map((e) => [e.start, e.openEnd, e.childrenEnd, e.end]);
+ assert.deepEqual(bounds('<A><B<of<A<T>>> /></A>', 'A'), [[0, 3, 18, 22]]);
+ const page = 'type of<T> = T;\nconst P = () => <Field label="Name"><Box<of<Field<Row>>> /><Input /></Field>;';
+ assert.deepEqual(bounds(page, 'Field'), [[32, 52, 84, 92]]);
+ assertPass(grade(LABELS, inline(page)));
+});
+
+// A tag's name may start with `_` or `$`, as any identifier may: such a tag is read, or reported, like any other.
+test('tsx structure: a tag whose name starts with _ or $ is read or reported like any other', () => {
+ const { unreadableElements } = require('../lib/tsx-structure.js');
+ const read = (page) => jsxElements(page).map((e) => [e.name, e.start, e.openEnd, e.childrenEnd, e.end, Object.fromEntries([...e.attrs].map(([k, a]) => [k, a.value]))]);
+ assert.deepEqual(read('<$Grid<Row> title="&euro;">x</$Grid>'), [['$Grid', 0, 27, 28, 36, { title: '&euro;' }]]);
+ assert.deepEqual(read('<_Grid title="a"><_Grid<Row> /></_Grid>'), [['_Grid', 0, 17, 31, 39, { title: 'a' }], ['_Grid', 17, 31, 31, 31, {}]]);
+ assert.deepEqual(unreadableElements('const P = () => <_Grid<keyof Row> title="&euro;" />;'), [{ name: '_Grid', start: 16, line: 1, column: 17 }]);
+ const code = 'const c = a <_b;\nconst d = x <$y> z;';
+ assert.deepEqual(jsxElements(code), []);
+ assert.deepEqual(unreadableElements(code), []);
+ const CURRENCY = 'Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats';
+ assertFail(grade(CURRENCY, inline('function t(k) { return k; }\nconst P = () => <$Grid<Row> title="&euro;">{t("ok")}</$Grid>;')), /hardcoded currency symbol "\u20ac"/);
+ assertFail(grade(CURRENCY, inline('function t(k) { return k; }\nconst P = () => <_Grid<keyof Row> title="&euro;">{t("ok")}</_Grid>;')), /<_Grid> at line 2, column 17 has type arguments that are not only names/);
+ assertPass(grade(CURRENCY, inline('function t(k) { return k; }\nconst P = () => <_Grid title={t("total")}>{t("ok")}</_Grid>;')));
+});
+
+// `of` is a keyword only inside a `for (… of …)` head, and a name outside every one (the lexer's ofTakesOperand), so
+// a `<` after a type or a value named `of` opens type arguments or compares; it never starts an element. Generic calls
+// and annotations through such a type are no tags, and the page's checks read only its real elements.
+test('tsx structure: a type or value named `of` starts no element; the `of` of a for head still does', () => {
+ const { unreadableElements } = require('../lib/tsx-structure.js');
+ const CURRENCY = 'Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats';
+ const body = 'function t(k) { return k; }\nexport default function P() { return <Field label={t("name")}><Input aria-label={t("name")} /><Text>{t("hi")}</Text></Field>; }\n';
+ const names = (page) => jsxElements(page).map((e) => e.name);
+ for (const head of [
+ 'type of<T> = T;\nconst x = fn<of<List<() => Row>>>();\n', 'import type { of } from "./t";\nconst x = fn<of<List<() => Row>>>();\n',
+ 'type of<T> = T;\nconst x = fn<of<List<Row>>>();\n', 'type of<T> = T;\nlet v: Map<string, of<List<() => Row>>>;\n',
+ 'const of = 1;\nconst y = of < 2;\nconst z = of / 2;\nconst w = x.of < y;\n',
+ ]) {
+ const page = head + body;
+ assert.deepEqual(unreadableElements(page), [], head);
+ assert.deepEqual(names(page), ['Field', 'Input', 'Text'], head);
+ for (const check of [LABELS, TRANSLATED, CURRENCY]) assertPass(grade(check, inline(page)));
+ }
+ for (const head of ['for (const x of <A title="&euro;" />.props.items) {}\n', 'async function f() { for await (const x of <A title="&euro;" />) {} }\n']) {
+ assert.deepEqual(names(head + body), ['A', 'Field', 'Input', 'Text'], head);
+ assertFail(grade(CURRENCY, inline(head + body)), /hardcoded currency symbol "\u20ac"/);
+ }
+});
+
// --- Eval 4: the wizard ----------------------------------------------------------------------------
const E4 = '4-case-wizard';
@@ -207,6 +298,31 @@ test('eval 13: shown text goes through the translate helper', () => {
assertPass(grade(TRANSLATED, inline("const translate = (k: string) => k;\nconst P = () => <Text>{translate('title')} ({count}) &nbsp;</Text>;")));
});
+// A generic component's attributes are read like any other's (tsx-structure.js), so an unlabelled control, a hardcoded
+// title or a submit written with type arguments of names only is graded. A page with a tag whose type arguments are
+// anything else fails every check that reads its elements or its JSX text: what that tag holds is not known for certain.
+test('evals 4, 12 and 13: a generic component is graded like any other, and a tag the reader cannot read fails the page', () => {
+ const UNREADABLE = /<List> at line 1, column \d+ has type arguments that are not only names/;
+ assertFail(grade(LABELS, inline('const P = () => <Input<Row> value={x} />;')), /<Input> has no aria-label, aria-labelledby or label/);
+ assertPass(grade(LABELS, inline('const P = () => <Input<Row> aria-label="Title" value={x} />;')));
+ assertFail(grade(LABELS, inline('const P = () => <div><Input aria-label="Title" value={x} /><List<() => Row> /></div>;')), UNREADABLE);
+ assertFail(grade(LABELS, inline('const P = () => <List<() => Row> />;')), UNREADABLE);
+ const translated = (jsx) => inline(`const t = (k: string) => k;\nconst P = () => <div>{t('title')}${jsx}</div>;`);
+ const UNREADABLE_2 = /<List> at line 2, column \d+ has type arguments that are not only names/;
+ assertFail(grade(TRANSLATED, translated('<DataGridRow<Row> title="Hello" />')), /hardcoded title "Hello" on <DataGridRow>/);
+ assertFail(grade(TRANSLATED, translated('<DataGridRow<Row> title="&#72;&#105;" />')), /hardcoded title "Hi" \(written "&#72;&#105;"\) on <DataGridRow>/);
+ assertPass(grade(TRANSLATED, translated("<DataGridRow<Row> title={t('row')} />")));
+ assertFail(grade(TRANSLATED, translated("<List<() => Row> title={t('row')} />")), UNREADABLE_2);
+ const gated = SUBMIT.replace('<Button ', '<Button disabled={step !== 2} ');
+ assertPass(grade(REVIEW, twoStepPage(gated)));
+ assertFail(grade(REVIEW, twoStepPage(SUBMIT.replace('<Button ', '<Button<Row> '))), /can be pressed when step is 1, not only on the review step/);
+ assertFail(grade(REVIEW, twoStepPage(`${gated}<List<() => Row> />`)), /<List> at line \d+, column \d+ has type arguments that are not only names/);
+ const revised = '<div><Input type="search" onChange={(_, d) => setQ(d.value)} /><div role="toolbar"><Dropdown onOptionSelect={pick} /></div></div>';
+ assertPass(grade(REVISED, inline(`const P = () => ${revised};`)));
+ assertPass(grade(REVISED, inline(`const P = () => ${revised.replace('<Dropdown ', '<Dropdown<Row> ')};`)));
+ assertFail(grade(REVISED, inline(`const P = () => <div>${revised}<List<() => Row> /></div>;`)), UNREADABLE);
+});
+
// --- Eval 15: choice names ------------------------------------------------------------------------------
const E15 = '15-support-tickets-real';
diff --git a/evals/model-apps/genpage/tests/phase-expectations.test.js b/evals/model-apps/genpage/tests/phase-expectations.test.js
index 957647727..324951a13 100644
--- a/evals/model-apps/genpage/tests/phase-expectations.test.js
+++ b/evals/model-apps/genpage/tests/phase-expectations.test.js
@@ -613,6 +613,33 @@ test('eval 13: a currency symbol or a date format spelled with character referen
assertPass(gradeCode(text, page("const label = '&#36;' + total; return null;")));
});
+// The page compiler erases a component's type arguments, so the string of a generic component's attribute renders like any
+// other: `<DataGridRow<Row> title="&euro;" />` shows "€". A tag whose type arguments are not names only (a function, string,
+// template or other type) is one the reader cannot bound for certain (lib/tsx-structure.js), so the check fails on it
+// rather than pass a symbol it could not see.
+test('eval 13: a currency symbol in a generic component\u2019s attribute is hardcoded too, and a tag the reader cannot read fails', () => {
+ const text = 'Phase 5 (Page Builder): Generated .tsx does NOT hardcode currency symbols or date formats';
+ const page = (body) => [{ name: 'page.tsx', content: `export default function GeneratedComponent() {\n ${body}\n}\n` }];
+ for (const tag of ['<DataGridRow<Row>', '<A <Row>', '<A /* row */ <Row>', '<A\n<Row>', '<A\r\n<Row>', '<Grid<Map<string, Row[]>>', '<A.B<T | U, V & W>', '<A<B>']) {
+ assertFail(gradeCode(text, page(`return ${tag} title="&euro;" />;`)), /hardcoded currency symbol "\u20ac"/);
+ }
+ assertFail(gradeCode(text, page('return <DataGridRow<Row> title="&#36;100" />;')), /hardcoded "\$" currency symbol/);
+ assertPass(gradeCode(text, page('return <DataGridRow<Row> title={t("total")} aria-label="&amp;" />;')));
+ const unreadable = [
+ '<A<() => () => "<B<() => string>>"> title="&euro;">Hello</A>',
+ '<DataGridRow<() => () => string /* <B<() => string>> */> title="&euro;" />',
+ '<A<() => "a\\\nb"> title="&euro;" />',
+ '<A<() => "a\\\r\nb"> title="&euro;" />',
+ '<A<() => `x${string /* the type\'s name */}y`> title={t("ok")} />',
+ '<A<"a\\"//"> title="&euro;" />',
+ '<A<"a\\"/*"> title="&euro;" />',
+ ];
+ for (const tag of unreadable) {
+ const name = tag.match(/^<(\w+)/)[1];
+ assertFail(gradeCode(text, page(`return ${tag};`)), new RegExp(`^page\\.tsx: <${name}> at line 2, column 10 has type arguments that are not only names`));
+ }
+});
+
// --- Eval 15 -----------------------------------------------------------------------------------
const E15 = '15-support-tickets-real';
diff --git a/evals/model-apps/genpage/tests/source-evidence.test.js b/evals/model-apps/genpage/tests/source-evidence.test.js
index f8b592968..17e6044ea 100644
--- a/evals/model-apps/genpage/tests/source-evidence.test.js
+++ b/evals/model-apps/genpage/tests/source-evidence.test.js
@@ -363,6 +363,17 @@ export default GeneratedComponent;
for (const [label, code] of Object.entries(refused)) assert.equal(receiverOk(code), false, label);
});
+// Type arguments are erased before React renders, so `<PageBody<GeneratedComponentProps> {...props} />` hands PageBody the
+// page props exactly as `<PageBody {...props} />` does, and the proof reads it alike. A tag whose type arguments are not
+// names only cannot be read for certain (lib/tsx-structure.js unreadableElements), so a page with one proves nothing.
+test('the boundary wrapper is read through type arguments of names only; a tag the reader cannot read proves nothing', () => {
+ const run = helper('client', 'client') + body(DESTRUCTURED);
+ assert.equal(receiverOk(run + wrapper('<PageErrorBoundary>\n <PageBody<GeneratedComponentProps> {...props} />\n </PageErrorBoundary>')), true, 'PageBody with a type argument');
+ assert.equal(receiverOk(run + wrapper('<PageErrorBoundary>\n <PageBody<keyof GeneratedComponentProps> {...props} />\n </PageErrorBoundary>')), false, 'PageBody with a type operator in its type argument');
+ assert.equal(receiverOk(run + wrapper(CANONICAL) + 'const Note = () => <Text<keyof Row>>x</Text>;\n'), false, 'an unreadable tag elsewhere in the page');
+ assert.equal(receiverOk(run + wrapper(CANONICAL) + 'const Note = () => <Text<Row>>x</Text>;\n'), true, 'a readable generic tag elsewhere in the page');
+});
+
// ---------- the boundary wrapper's proof on a whole page (fixture 27) ----------
// Only the documented boundary class lets PageBody's props be the page props: a PageErrorBoundary function, or a class of
// that name changed after it was copied, can hand PageBody another object — so neither proves a receiver, and the Custom API
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index e7f6a1142..829591486 100644
--- a/plugins/model-apps/.claude-plugin/plugin.json
+++ b/plugins/model-apps/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.20.2",
+ "version": "2.20.3",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index e7f6a1142..829591486 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.20.2",
+ "version": "2.20.3",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index c2d02f693..4ad9ff319 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -2822,7 +2822,7 @@ scripts/
web-resource-records.js ← `web-resource-unconfirmed.<hash>.json`, one file per environment in the build workspace: the web resources this workspace's builds wrote and could not confirm were published (`WEB_RESOURCE_UNVERIFIED`), by name and id. `openUnconfirmedWebResources` is a run's view of it (`idOf`, `note`, `clear`; it never throws: a record it cannot read is "nothing recorded", said once, and a run with no workspace records nothing). A name it holds is written again by id by the next run (sdk-build.js `writeOwnedWebResource`) instead of being reused untouched — the page manifest only where its published copy is not what that run wants, and kept where it is (`persistPageManifest`); the entry is cleared once the row is confirmed (that write verified, or the manifest's published copy found right) and is in the solution. Each change is made under the record's writer lease (`record-lease.js`) to the file as it is then, so builds sharing the workspace keep each other's entries: a note never replaces an entry with another row's id that another build recorded since this run read the file (said once; `note` answers false; a note of the same row is a later unconfirmed write of it and takes the entry's place with a revision of its own), and a clear removes only the entry its run knows — its id AND the revision of the note that made it (`revisions`, written beside the name-to-id map), so a later unconfirmed write of the same row that another build noted survives a clear by a build that verified an earlier one; an entry written without a revision is matched by its id, as before
dashboard-creation-records.js ← `dashboard-creation.<hash>.json`, one file per environment, app and solution in the build workspace: the dashboards this workspace's builds CREATED and have not yet seen join the solution, by name — the id the create was sent with (the SDK sends the workspace's own id as `systemform.formid`), noted before the push, and the id the push reported when that is another. `openDashboardCreations` is a run's view of it (`idsOf`, `note`, `observe`, `clear`, `path`; it never throws: a record it cannot read — an entry it does not write included — is "nothing recorded" and is never written over or removed, said once; a run with no workspace, environment or solution records nothing). Cleared once the row is in the solution or the build's own undo deleted it; the next run reads each recorded id in the saved layer before any name lookup and adds the row the create made to the solution — after a re-key only the reported one (sdk-build.js `recoverRecordedDashboard`) — never a namesake, never a delete, never teardown authority. Each change is made under the record's writer lease (`record-lease.js`) to the file as it is then, comparing the whole entry (both ids), so builds sharing the workspace keep each other's entries: `note` never replaces an entry another build recorded or changed since this run read the file (said once), and a note of the id the entry already holds keeps its reported id; `observe` adds only to the entry as its run noted it; `clear` removes only the entry as its run knows it, and answers null when another build has changed it since — when every id it recorded read as absent, `recoverRecordedDashboard` then stops instead of creating a dashboard on the word of the older entry (after the row joined the solution, a changed entry is left and the build goes on)
record-lease.js ← the writer lease of a workspace record (`withRecordLease(root, file, change)`): the change runs while `<record file>.lock` is held — the workspace lease protocol (`apply-snapshot-store.js acquireLease`: exclusive create, exclusive reclaim, owner-checked release), stamped and judged as the pages lock is (`process-owner.js`: taken over only from a build proven gone, never by age). A lock another build holds is tried `LEASE_ATTEMPTS` (10) times `LEASE_WAIT_MS` (100 ms) apart and then given up — the change is not made and its record says so once — so a build never hangs on it. Used by `web-resource-records.js` and `dashboard-creation-records.js`; reads take no lease
- app-operation-lease.js ← the local leases that keep two builds of ONE app in ONE workspace from writing at the same time: `withAppBuildLease({ workspaceDir, appUniqueName, buildLease, warn }, operation)` holds `app-build.<sha256 of the lower-cased app unique name>.lock` for one whole apply — the CLI takes it before its auth check, and `buildModelApp`, `runSdkBuild` and `runChangedOnlyApply` take it when called on their own or borrow the opaque capability their caller hands them (`opts.buildLease`; a string, a released capability or one for another app or folder is `build-lease-invalid`); a held lock is `build-locked` at once, with no wait. `acquireAppPagesLease(wsDir, appUnique)` (re-exported from `sdk-build.js`) takes `app-pages.<hash>.lock` and then the legacy `pages-<spelling>.lock` every earlier release takes, lets go of the first when the second refuses, and releases them in reverse order. Every file is taken through `apply-snapshot-store.js acquireLease` (exclusive create, exclusive reclaim, owner-checked release), stamped and judged by `process-owner.js` (taken over only from a build proven gone, never by age), checked with the `safe-fs.js` refusals first (a link or folder at a lock name is that error); a release that cannot confirm its own lock is gone says which file. `applyWorkspaceOf(opts)` is the one default workspace (`<app folder>/.maker-workspace`)
+ app-operation-lease.js ← the local leases that keep two builds of ONE app in ONE workspace from writing at the same time: `withAppBuildLease({ workspaceDir, appUniqueName, buildLease, warn }, operation)` holds `app-build.<sha256 of the lower-cased app unique name>.lock` for one whole apply — the CLI takes it before its auth check, and `buildModelApp`, `runSdkBuild` and `runChangedOnlyApply` take it when called on their own or borrow the opaque capability their caller hands them (`opts.buildLease`; a string, a released capability or one for another app or folder is `build-lease-invalid`); a held lock is `build-locked` at once, with no wait. `acquireAppPagesLease(wsDir, appUnique)` (re-exported from `sdk-build.js`) takes `app-pages.<hash>.lock` and then the legacy `pages-<spelling>.lock` every earlier release takes, lets go of the first when the second refuses, and releases them in reverse order. Every file is taken through `apply-snapshot-store.js acquireLease` (exclusive create, exclusive reclaim, owner-checked release), stamped and judged by `process-owner.js` (taken over only from a build proven gone, never by age), checked with the `safe-fs.js` refusals first (a link or folder at a lock name is that error); on Windows a lock or `.reclaim` name that answers EPERM — under Node 20 a name another build is deleting while a third has it open lingers and answers it, and so does a file this user may not read — is refused as held (`pages-locked` / `build-locked`), never as a planted link, and that refusal names the exact name that could not be inspected and adds that it may be being removed or be inaccessible, so a refusal that persists with no build running means checking that file's access (a create EPERM is that refusal only while the lock's name still answers EPERM; otherwise the take runs once more, and a second EPERM is the error it is); a release that cannot confirm its own lock is gone says which file. `applyWorkspaceOf(opts)` is the one default workspace (`<app folder>/.maker-workspace`)
source-literals.js ← TSX lexer (code/comment/string/template/regex/JSX) — see "Known limits" below
sdk-teardown.js ← app-builder teardown engine (planTeardown is pure)
sdk-http-client.js ← az-token HttpClient for the vendored SDK; a caller can name requests that are sent exactly once (`sendOnce(method, url)`: no retry on a transport failure, a 429 or 5xx, or a 401 refresh, and none of the replays special to a record delete and a `$batch` either) — `solution-settings.js` does for the three long solution actions; a caller can hand it the run's throttle budget (`deps.throttle`, lib/throttle-budget.js): every wait it takes before it sends a throttled request (HTTP 429, alone or as every operation of a `$batch`) again is then drawn from the budget — the answer's `Retry-After` whole, past the cap of a minute, or the schedule's wait when that is longer, placed on the clock so that requests throttled together are charged once — and a wait that does not fit is not taken: the 429 comes back as it came and the budget is told what the service asked (`decline`); every other wait (a 5xx, a reset connection, a deadlock victim's re-send) keeps its own schedule, and the budget is duck-typed and never loaded here, so the pcf copy, which has none, waits as it always did; an answer that is not a success comes back with the access token taken out of it (and a transport failure's text too, the error that carries Node's code included), a success untouched — the one `scrub` / `scrubAnswer` the Power Apps client uses as well; `needlesOf(token)` and `TOKEN_MARKER` are `lib/output-redaction.js`'s: the one list of texts a scrubber takes out of one token (the token and each of its parts of 24 characters or more) and the one marker, so the client's scrubber and what the process writes are kept free of a token by the same list, and each token the client sends is noted there (`noteToken`); `throttleBackoffMs(attempt, random)` is the capped, jittered schedule every throttled request waits on (1 s, 2 s, 4 s, 8 s, 8 s), exported because the page backend waits out a throttled page write on it (the client never re-sends a page's `$batch`: `lib/genpage-sdk.js` does, a push at a time); `retryAfterMs(headers, now, cap)` and `batchRetryAfterMs(res, now, cap)` cap what a response asks at a minute for the client's own retries, and a caller with a bound of its own passes `Infinity`: the page backend spends it inside the run's budget, the client itself does when it has that budget, and `solution-settings.js` inside the one budget of its import resend; `completeBatchStatus(res)` is the one status a COMPLETE multipart answer reports for every operation (the page backend reads a change set refused as a whole with it); the parser behind it, `isBatchThrottled` and `isBatchDeadlockVictim` is strict — an answer is read only when its outer boundary closes, every change set in it closes, and every part is a complete response whose first line is a status line; a part that declares a change set (`Content-Type: multipart/mixed; boundary=…`) must open and close exactly that boundary before the outer one goes on, a part with no response in it is an operation nobody answered, and a body is as long as the `Content-Length` its response gives, counted by the line breaks the answer has; a part that declares a `Transfer-Encoding` (chunked or any other) is not read at all, whole stream or not — the delimiters around it say nothing of whether its chunk stream is finished, so it never certifies a refusal or a deadlock victim; anything missing or malformed makes the WHOLE answer unproven (an answer that closes its outer boundary and is incomplete inside proves nothing); `isTransientTransportFailure(text, code)` says which failures of the transport are sent again — decided by Node's own error code when `makeRequest` reported one (`TRANSIENT_TRANSPORT_CODES`: `ECONNRESET`, `ETIMEDOUT`, `ESOCKETTIMEDOUT`, `ECONNABORTED`, `EPIPE`, `EAI_AGAIN`; any other code is final whatever the words say) and by the words only when it did not (a certificate's own phrases first): a reset, a timeout, an answer cut off, a temporary DNS failure, the same list `lib/retry-policy.js` calls a blip, and nothing else — a certificate that does not verify (whatever names it quotes), an unknown host and a message nobody recognises return at once; the error it throws carries the code beside the same message (this file is copied into the pcf plugin, so a test holds the two lists equal); a publish (`PublishXml`, `PublishAllXml`) is sent ONCE but for a 401 and a 429 of the service protection limits (`isServiceProtectionRefusal`, `SERVICE_PROTECTION_CODES`: the three codes the api-limits page documents) — never for the customization lock's 429, a 5xx or a failure of the transport — and its deadlock victim is the layer above's to re-send (`isSqlDeadlockVictim` and `DEADLOCK_RESENDS` are exported for `publish-xml.js`). Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`)
@@ -2833,11 +2833,11 @@ scripts/
throwaway-sdk.js ← `withThrowawaySdk({ env, prefix, httpClient? }, run)`: the bundled SDK, made through `maker-sdk.js`, over a throwaway workspace folder (made by `temp-workspace.js`) that is removed whichever way the run ends (a constructor, a storage or a module that throws included); `run(make)` gets a `make(extra)` for more instances over the same folder and the one client (`make({ languageCode })` is a writer). The one copy of what `apps.js`, `list-tables.js` and `list-languages.js` each wrote out
plan-sections.js ← the three Markdown primitives every genpage-plan reader shares (`planSection` — one `## ` section, any letter case; `findMarkdownTable`; `parseMarkdownRows`), moved unchanged from the eval harness, which re-exports them
genpage-plan-semantics.js ← the plan's semantic records, read with no I/O (references/plan-schema.md, "Assumptions, data semantics and lookup metadata"): the written plan (`## Assumptions` / `### A<n>`; per page `#### Data semantics` / `##### R<n>`, `F<n>` and `#### Lookup metadata`) and the approval preview at its own levels (`### Assumptions` first, `### Data Semantics` / `### Lookup Metadata` grouped by page file), every entry rule and cross-reference (an assumption that exists, a quote the requirements hold, the exact `Unattended default:` record), the field-by-field comparison `genpage-plan-provenance.js` gates on, and the check of observed lookups against `get-lookup-metadata.js` evidence. Proves structure and agreement, not entailment
- lookup-metadata.js ← `readLookupMetadata(sdk, tables)`: composes the SDK's `fetchEntityMetadata` (complete lookup targets) with `relationship-metadata.js` `readRelationshipsOf(…, 'ManyToOne', cache, { lookupDetails: true })` (every page; `ReferencedAttribute` and `ReferencingEntityNavigationPropertyName`, which the SDK projection drops) into concrete and shared paths; owns no HTTP. Every incomplete read fails the whole read. A table the environment does not have is `LOOKUP_TABLE_NOT_FOUND`, not the SDK's `CONNECTION_ERROR`: the SDK's own read of the table is the first request made for it, and only a 404 of that read (`genpage-sdk.js` `missingTableOf`, as for `genpage.js types`) or of the lookup-details read says so; any other failure keeps the SDK's code
+ lookup-metadata.js ← `readLookupMetadata(sdk, tables)`: composes the SDK's `fetchEntityMetadata` (complete lookup targets) with `relationship-metadata.js` `readRelationshipsOf(…, 'ManyToOne', cache, { lookupDetails: true })` (every page; `ReferencedAttribute` and `ReferencingEntityNavigationPropertyName`, which the SDK projection drops) into concrete and shared paths; owns no HTTP. Every incomplete read fails the whole read. The table name, primary-id name, lookup-column names and target names the reader takes from the metadata answer must be strings; a null, boolean or array is never coerced to one of them and fails the read as incomplete (the primary name column is passed through as the SDK states it). A table the environment does not have is `LOOKUP_TABLE_NOT_FOUND`, not the SDK's `CONNECTION_ERROR`: the SDK's own read of the table is the first request made for it, and only a 404 of that read (`genpage-sdk.js` `missingTableOf`, as for `genpage.js types`) or of the lookup-details read says so; any other failure keeps the SDK's code
collection-answers.js ← `requireCollectionAnswers(client, { reads, unreadable })`: the HttpClient the SDK is given, with one addition — a 2xx answer to a read `reads(url)` selects must be a collection (`{ value: [...] }`), or the read throws what `unreadable` says; `unreadableAnswer(error)` finds that error, itself or under the SDK's `ConnectionError`. `guardTableLists(client, makeError)` is its policy for the one read of the environment's table list (`/EntityDefinitions?…`, which only `findTables()` makes), and `maker-sdk.js` applies it to every SDK a script makes: the SDK's `findTables()` is `body.value ?? []`, and the bundle is not edited
- temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. On Windows a run HOLDS the folder while it judges it (three programs, about a second) — an empty file of its own, `.hold-<machine>-<pid>-<6 hex>`, put in once the access list of a folder it made is set and removed once its workspace is in it and recorded — because the end of every run that leaves nothing in the folder removes it (`rmdir`), and with several runs starting and ending at once the folder kept being removed and made again under each other's judgement until a run ran out of attempts and went to the plain temp folder; `rmdir` refuses a folder with a hold in it, and a sweep on Windows removes the hold of a run that is gone — only a hold carrying its own machine tag (`<machine>` is eight hex digits of a hash of the host name, as an owner record names its host), since a temp folder can be shared between machines and a pid says nothing on another (two host names can, rarely, share a tag; on a temp folder they share, the old fallback can then return); a POSIX sweep takes nothing for a hold. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entries
+ temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is not used and is removed by the run that made it, which waits up to 10 s for other runs' holds to leave it (a listing Windows refuses for a moment is waited out too), removes it only while it is still the folder it made, and stops waiting once a listing shows anything but holds — when the wait runs out, or the run is killed while it waits, the folder is left; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. On Windows a run HOLDS the folder while it judges it (three programs, about a second) — an empty file of its own, `.hold-<machine>-<pid>-<6 hex>`, put in once the access list of a folder it made is set and removed once its workspace is in it and recorded — because the end of every run that leaves nothing in the folder removes it (`rmdir`), and with several runs starting and ending at once the folder kept being removed and made again under each other's judgement until a run ran out of attempts and went to the plain temp folder; `rmdir` refuses a folder with a hold in it, and a sweep on Windows removes the hold of a run that is gone — only a hold carrying its own machine tag (`<machine>` is eight hex digits of a hash of the host name, as an owner record names its host), since a temp folder can be shared between machines and a pid says nothing on another (two host names can, rarely, share a tag; on a temp folder they share, the old fallback can then return); a POSIX sweep takes nothing for a hold. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entries
process-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the build lock and the pages lock (`app-operation-lease.js`), the recovery records' writer lease (`record-lease.js`), the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)
- windows-folder-acl.js ← who can change a folder on Windows, where Node reports no owner and no permissions, and the making of a folder that only this user can: `windowsFolderIsPrivate(folder)` saves the folder's access list with `icacls <folder> /save` (SDDL: SIDs, in every language, not names) and reads the user's SID with `whoami /user /fo csv /nh`, both started through `process-runner.js` with System32 first on PATH, and answers `{ ok, reason, owner? }` — private only when NO entry that grants a right to add to the folder, remove from it, delete it, write its attributes or extended attributes, change who may or take it over names anyone but this user, the system or the administrators (an INHERIT-ONLY entry counts too: it does not apply to the folder, but it is what every workspace and every owner record made in it is given; denials and audits grant nothing; SDDL writes the machine's own Administrator and Guest accounts as the aliases `LA` and `LG`, which are the user's own only for the user whose account that is, as a CI runner's renamed built-in Administrator is; an audit list after the access list, as Windows' own folders carry, is read and ignored) AND the folder is owned by this user or the administrators — whoever owns a folder can rewrite its list, so a list that names only the user does not make a foreign folder the user's. The owner is the one thing `icacls` cannot print (`/save` stores the list and nothing else), so it is read with PowerShell (`[IO.Directory]::GetAccessControl(folder, Owner)`, a SID; the folder goes in through the environment and the script is passed encoded) — half a second, which is why it is the last thing asked (a folder the list has refused never starts it), and PowerShell that cannot run is "not private". The administrators are accepted as owner because a process that runs elevated (a CI runner is one) owns what it makes through that group by default, and the list trusts them anyway. A list that icacls ran and could not save — Windows is removing the folder, which cannot be opened meanwhile — is `unreadable`, a "no" that `temp-workspace.js` does not keep: it asks again after a pause, and drops an answer about a folder that was replaced while it was being judged; whatever else cannot be read, run or understood is not private, and `temp-workspace.js` then makes its workspace in the plain temp folder as before. `makeWindowsFolderPrivate(folder)` is for a folder this process has just made: `icacls <folder> /inheritance:r /grant:r *<user>:(OI)(CI)F *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F` replaces its list, and the list is read back and must be exactly that — protected, nothing inherited, three grants, full control for the user
+ windows-folder-acl.js ← who can change a folder on Windows, where Node reports no owner and no permissions, and the making of a folder that only this user can: `windowsFolderIsPrivate(folder)` saves the folder's access list with `icacls <folder> /save` (SDDL: SIDs, in every language, not names) and reads the user's SID with `whoami /user /fo csv /nh`, both started through `process-runner.js` with System32 first on PATH, and answers `{ ok, reason, owner?, unreadable?, inherited? }` — private only when NO entry that grants a right to add to the folder, remove from it, delete it, write its attributes or extended attributes, change who may or take it over names anyone but this user, the system or the administrators (an INHERIT-ONLY entry counts too: it does not apply to the folder, but it is what every workspace and every owner record made in it is given; denials and audits grant nothing; SDDL writes the machine's own Administrator and Guest accounts as the aliases `LA` and `LG`, which are the user's own only for the user whose account that is, as a CI runner's renamed built-in Administrator is; an audit list after the access list, as Windows' own folders carry, is read and ignored) AND the folder is owned by this user or the administrators — whoever owns a folder can rewrite its list, so a list that names only the user does not make a foreign folder the user's. The owner is the one thing `icacls` cannot print (`/save` stores the list and nothing else), so it is read with PowerShell (`[IO.Directory]::GetAccessControl(folder, Owner)`, a SID; the folder goes in through the environment and the script is passed encoded) — half a second, which is why it is the last thing asked (a folder the list has refused never starts it), and PowerShell that cannot run is "not private". The administrators are accepted as owner because a process that runs elevated (a CI runner is one) owns what it makes through that group by default, and the list trusts them anyway. A list that icacls ran and could not save — Windows is removing the folder, which cannot be opened meanwhile — is `unreadable`, a "no" that `temp-workspace.js` does not keep: it asks again after a pause, and drops an answer about a folder that was replaced while it was being judged. A "no" about a list that is still only what the folder inherited (not protected, every entry `ID`) is `inherited`: that is also the list a folder another run made moments ago has until that run's icacls lands, and where the temp folder lets others write (`TEMP` on a data drive gives Authenticated Users "modify") a run that judged it then was refused the folder for the rest of its life; `temp-workspace.js` asks again about such a "no" after a pause while the folder is younger than `PROTECT_WINDOW_MS` (15 s), never remembers it meanwhile, and does not refuse the folder for good on it (the workspace goes to the plain temp folder only after the last attempt); whatever else cannot be read, run or understood is not private, and `temp-workspace.js` then makes its workspace in the plain temp folder as before. `makeWindowsFolderPrivate(folder)` is for a folder this process has just made: `icacls <folder> /inheritance:r /grant:r *<user>:(OI)(CI)F *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F` replaces its list, and the list is read back and must be exactly that — protected, nothing inherited, three grants, full control for the user
power-apps-service-client.js ← the HttpClient for the SDK's connection and connector reads: GET only, https only, a host allowlist that is exactly the hosts the SDK's connectivity code calls, redirects never followed, the Azure CLI token for the Power Apps service read only for a request that passed and never in a message, a body, a header or a key the service answers with (it is scrubbed, in whole and by part)
sdk-first.js ← the rule `list-connections.js`, `connector.js` and `solution-settings.js` share: read through the SDK, and through `pac` for the SDK's typed refusals (`sdkFirst`, `CONNECTIVITY_REFUSALS`) — an error counts only when it IS the bundle's `SdkError` (an HTTP body that carries a refusal's code does not); any other failure is thrown with the SDK's own code. An environment outside the Public cloud is judged from its host first (`connectivityCloudOf`, pinned to the bundle by a table of hosts) and answered by `pac` at once, with the code the SDK would give. What the SDK could not clean up before it refused (`readCleanupWarnings`: a staged copy of the package it could not delete, with its upload id) is carried across the fallback — as `warnings` on the answer, or attached to the error `pac` throws when it fails — so `solution-settings.js` shows it for `template` and `import` alike (an import's, sanitized once)
pac-fallback.js ← runs a `pac` fallback command through `process-runner.js` (`spawnResultTree`) within a fixed time limit (`PAC_READ_TIMEOUT_MS`, 3 minutes; `PAC_IMPORT_TIMEOUT_MS`, 60) — a call that runs out has its whole process tree ended before it is reported, and the message says what the runner confirmed — "`pac` and every process that held its output were stopped" — and, when the pipes did not close, that a process `pac` started may still be running — reads the JSON `pac` prints after its header, and keeps pac's sign-in banner and version lines out of every failure text (`pacErrorText`)
@@ -3643,7 +3643,7 @@ rejected a complete page saved with CRLF endings.
|---|---|---|
| `brace` | `}` ends a block (a `/` then starts a regex) or an object/function expression (it divides) | `{valueOf(){return 12;}}/2; … /x/` |
| `paren` | `)` ends an `if`/`for`/`while` head (a regex follows) or an operand, and its `(` is beyond the 2,000-character look-behind | `if (true /* …2,100 chars… */) /re/.test(x)` |
- | `keyword` | a word that is a keyword in some places and a name in others (`of` `await` `yield` `let` `async` `static` `get` `set` `as` `satisfies` `type` `from` `declare` `abstract` `readonly` `keyof` `infer` `is` `asserts` `override` `accessor` `using` `out` `module` `namespace` `global` `unique` `implements`) | `const of = 12; of/2; … /x/` |
+ | `keyword` | a word that is a keyword in some places and a name in others (`of` `await` `yield` `let` `async` `static` `get` `set` `as` `satisfies` `type` `from` `declare` `abstract` `readonly` `keyof` `infer` `is` `asserts` `override` `accessor` `using` `out` `module` `namespace` `global` `unique` `implements`); `of` only where its immediate context cannot prove it is no `for…of` keyword — its nearest open bracket is a `(` right after `for` or `await` (a loop head or not), the word before that `(` cannot be read whole, or the bracket lies beyond the scan's reach; anywhere else it is a name, for certain (`ofTakesOperand`), so `type of<T> = T` and `fn<of<Row>>()` open no element | `for (const x of of/2 + "") {} … /x/` |
| `angle` | a `>` closes type arguments, a JSX tag or a comparison; the `>` of `=>`, the closer of a cast the lexer proves is one (`castKeywordIsCertain`) and the end of an element or a regex it read are certain, and so is a `>` run after one of those — and any other `>` before a `/` or a `<` is reported | `total as Types . Alias<number> / 2`, `f<A> / x / 2` |
| `identifier` | an identifier written with a `\u` escape, or a word cut short by `#` or a non-ASCII letter; a `)` whose `(` follows a character beyond ASCII that is neither trivia nor part of a name (a token the lexer does not know, so "no head" would rest on nothing) | `Al\u0069as<number> / 2` |
| `operator` | a `/` after `...` or after a run of three signs; the second `<` of a shift, before a name; a `<` that opens a generic with a constraint right after `>=`, `>>=` or `>>>=` (the first `>` may end type arguments), after a `<`, after `in` or after `yield *`, where the text after it leaves both readings open — the element of a comparison, a test or a product, or the type parameters of an arrow: a parameter list that a `:` follows, or a head the reading cannot settle | `[.../a/.exec(s)]`, `a+++/x/`, `1<<n`, `a >= <T extends X>(y: T): T</T>`, `let x: A<number>= <T extends X>(y: T): T => y`, `a >>= <T extends X>(y: T): T => y`, `a < <T extends X>(y: T): T</T>`, `for (k in <T extends X>(y: T): T => y)`, `yield* <T extends X>(y: T): T => y` |
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 7a6b6ddf1..e92a4eb81 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,6 +5,23 @@ All notable changes to the **model-apps** plugin.
Entries are deliberately short: what changed and why it matters to you. The reasoning,
evidence and trade-offs behind a change live in its PR, in `docs/`, or in the linked issue.
+## [2.20.3]
+
+The bundled SDK is unchanged (power-platform-ux a3443479).
+
+### Fixed
+
+- **Lookup discovery takes only strings as table, column and id names.** A malformed metadata answer (a null, true/false or a
+ list) now fails the read instead of becoming a name such as "null".
+- **On Windows with Node 20, a build that meets an app lock being released or taken over reports another build**, naming the
+ file it could not inspect, instead of a file-safety or raw EPERM error.
+- **On Windows, a script that starts while another is still making the plugin's temp folder private asks again**, instead of
+ putting every workspace of its run in the plain temp folder. This happened where the temp folder lets other users write.
+- **On Windows, a script that cannot make its new plugin temp folder private retries removing it for up to ten seconds**; it
+ used to leave it, sending every later script to the plain temp folder. A timeout or killed script can still leave it.
+- **Pages that use `of` as a variable or type name are read correctly by the build's page checks** wherever its context rules
+ out a `for…of` keyword; where it could be one, the earlier cautious reading stays.
+
## [2.20.2]
The bundled SDK is unchanged (power-platform-ux a3443479).
diff --git a/plugins/model-apps/scripts/lib/app-operation-lease.js b/plugins/model-apps/scripts/lib/app-operation-lease.js
index 69d84658b..d06162c8d 100644
--- a/plugins/model-apps/scripts/lib/app-operation-lease.js
+++ b/plugins/model-apps/scripts/lib/app-operation-lease.js
@@ -56,6 +56,13 @@ const legacyPagesLockName = (rawApp) => `pages-${String(rawApp).replace(/[^A-Za-
// same moment, or died doing so).
const unreleasedNote = (lease) => (lease.stale ? ` The build that held it is no longer running, but its lock could not be released: ${lease.reason}.` : '');
+// What a refusal adds when Windows could not inspect a lock name (takeLockFile): the name it could not inspect, and why that may outlast every build.
+// EPERM is what a name being deleted answers, and also what a file this user may not read answers; only the second persists once no build runs,
+// and waiting or deleting the lock cannot cure it — so the refusal names THAT file, which may be the claim and not the lock, and says to check it.
+const uninspectableNote = (lease) => (lease.uninspectable ? ` Windows could not inspect ${lease.uninspectable} (EPERM): another build may be removing it, or this user may not have access to it. If this refusal persists while no build is running, check that file's access, or remove it.` : '');
+// The file a refusal names: the one Windows could not inspect, else the lock that refused.
+const blockingName = (lease, lockPath) => lease.uninspectable || lockPath;
+
// Takes ONE lock file `file` in the folder `dir`. Answers acquireLease's result: { ok: true, path, token, reclaimed?, previous? }, or
// { ok: false, reason, stale?, error? }.
//
@@ -63,19 +70,77 @@ const unreleasedNote = (lease) => (lease.stale ? ` The build that held it is no
// a hard link or a folder at either name is refused, not followed — a reclaim writes the lock and a release deletes it, and either would then land
// on whatever the link points at. A missing name is what a free lock is. These checks are of names, between operations; they are no defense
// against a hostile process that swaps a name for a link in between.
+//
+// A name that is being deleted is a lock in use, and is refused as one (Windows only; see beingDeleted below): another build is releasing the lock or
+// finishing a take-over at this very moment, which is a build that holds it or has just held it. The refusal carries the name (`uninspectable`), and
+// the callers name it and say it may be inaccessible instead (uninspectableNote). A create that fails with EPERM is that refusal only while the lock's
+// name still answers EPERM; otherwise the whole take — inspections and acquireLease — runs once more (the deletion may have finished in between), and
+// a second such failure is the error it is (a folder that cannot be written), as it always was.
function takeLockFile(dir, file, { owner = {}, now = Date.now, stamp }) {
const lockPath = path.join(dir, file);
- assertPlainFileTarget(lockPath);
- assertPlainFileTarget(`${lockPath}.reclaim`);
- return acquireLease(dir, {
- file,
- now,
- stamp: stamp || ownerStamp({ ...owner, now }),
- // Stale only when the process that took the lock is PROVEN gone (process-owner.js): a lock whose owner runs, or cannot be judged — another
- // machine, another pid namespace, a record that is missing or damaged, a lock of a release that recorded only { pid, at } — is never stale,
- // however old it is.
- isStale: (held) => ownerState(held, owner).state === 'gone',
- });
+ const beingRemoved = (name) => ({ ok: false, reason: `Windows could not inspect ${name} (EPERM)`, uninspectable: name });
+ for (let attempt = 1; ; attempt += 1) {
+ for (const name of [lockPath, `${lockPath}.reclaim`]) {
+ if (inspectLockName(name)) return beingRemoved(name);
+ }
+ const lease = acquireLease(dir, {
+ file,
+ now,
+ stamp: stamp || ownerStamp({ ...owner, now }),
+ // Stale only when the process that took the lock is PROVEN gone (process-owner.js): a lock whose owner runs, or cannot be judged — another
+ // machine, another pid namespace, a record that is missing or damaged, a lock of a release that recorded only { pid, at } — is never stale,
+ // however old it is.
+ isStale: (held) => ownerState(held, owner).state === 'gone',
+ });
+ if (process.platform !== 'win32' || lease.ok || !lease.error || lease.error.code !== 'EPERM') return lease;
+ if (beingDeleted(lockPath)) return beingRemoved(lockPath);
+ if (attempt >= 2) return lease;
+ }
+}
+
+// On Windows a file deleted while another process has it open — a build reading the lock to judge its owner, a scanner — keeps its name until that
+// handle closes ("delete pending"), unless the delete asks for POSIX semantics, which libuv does only from 1.48 (Node 22): https://github.com/libuv/libuv/issues/3839,
+// https://github.com/libuv/libuv/pull/4318. Under an older libuv (Node 20) every lstat and every create of that name meanwhile fails with EPERM
+// (STATUS_DELETE_PENDING reaches Node as ERROR_ACCESS_DENIED), and a build that lost a race for the lock used to stop with a file-safety error or a raw
+// EPERM instead of the refusal it is. EPERM cannot say WHY the name is refused: a file this user may not even look at answers it too. Either way the
+// name exists and cannot be used, so refusing changes nothing but the words; nothing is written or followed. Never true on Linux or macOS, where a
+// delete removes the name at once and these paths are as they were.
+function beingDeleted(name) {
+ if (process.platform !== 'win32') return false;
+ try {
+ fs.lstatSync(name);
+ return false;
+ } catch (e) {
+ return !!e && e.code === 'EPERM';
+ }
+}
+
+// The planted-link check of one lock name (assertPlainFileTarget), which answers true when the name could not be inspected because it is being
+// deleted (above), and throws what the check throws otherwise: a link, a junction, a hard link or a folder at the name is refused exactly as before.
+// The answer is read from the lstat the check itself made — through its `fs` seam — and not from a second look, which could find the deletion
+// finished and then let the check's error through after all.
+function inspectLockName(name) {
+ if (process.platform !== 'win32') {
+ assertPlainFileTarget(name);
+ return false;
+ }
+ let firstLook = null;
+ const watched = Object.create(fs);
+ watched.lstatSync = (...args) => {
+ try {
+ return fs.lstatSync(...args);
+ } catch (e) {
+ if (!firstLook) firstLook = e;
+ throw e;
+ }
+ };
+ try {
+ assertPlainFileTarget(name, { fs: watched });
+ return false;
+ } catch (e) {
+ if (e && e.code === 'UNSAFE_OUTPUT' && e.reason === 'uninspectable' && firstLook && firstLook.code === 'EPERM') return true;
+ throw e;
+ }
}
// Releases a lock this process holds, and says so when it cannot confirm that it did. Owner-checked: the file is removed only while it still holds
@@ -120,12 +185,13 @@ function sayAfterRelease(warn, message) {
const ownerKeyOf = (held) => JSON.stringify([held && held.pid, held && held.host, held && held.platform, held && held.ns, held && held.start]);
// The pages refusal, in the words it has always had (a person and the skills read them). `blocking` is the file that refused: the hashed one for two
-// builds of this release, the legacy one for a build of an earlier release that spells the app the same way. "Stale" in the sentence means what the
+// builds of this release, the legacy one for a build of an earlier release that spells the app the same way — or, on Windows, the lock name or claim
+// name that could not be inspected (uninspectableNote). "Stale" in the sentence means what the
// take-over means by it — the owner is proven gone — and never that the lock is old.
function pagesLocked(appUnique, blocking, lease) {
// `retry: NEVER`: the lock belongs to a build that is still running, or to one that is gone but whose lock could not be released — running the
// earlier phases again releases neither — and the message quotes the lock's path, which holds the maker's folder.
- return new BuildHalt(`another build is deploying pages for '${appUnique}' — refusing a second concurrent pages deploy (would risk duplicate page creation). Retry after it finishes, or delete ${blocking} if it is stale.${unreleasedNote(lease)}`, { phase: 'pages', code: 'pages-locked', recoverable: true, retry: RETRY.NEVER });
+ return new BuildHalt(`another build is deploying pages for '${appUnique}' — refusing a second concurrent pages deploy (would risk duplicate page creation). Retry after it finishes, or delete ${blockingName(lease, blocking)} if it is stale.${unreleasedNote(lease)}${uninspectableNote(lease)}`, { phase: 'pages', code: 'pages-locked', recoverable: true, retry: RETRY.NEVER });
}
// SINGLE-MACHINE advisory lock over the pages phase (design §9: a courtesy, not a cross-machine guarantee): it stops two LOCAL builds of the same app
@@ -211,7 +277,7 @@ const capabilities = new WeakMap();
// refusal quotes the lock's path, which holds the maker's folder — the retry rule must never read its words. `recoverable` is the operator's: a
// later run of the same command can proceed once the other build has finished. It never authorizes the build's own automatic re-run.
function buildLocked(appUnique, lockPath, lease) {
- return new BuildHalt(`another build may be applying '${appUnique}' in this workspace — refusing a second concurrent apply (would risk duplicate creation). Re-run the same command after it finishes. If no build using this workspace is running, inspect ${lockPath} and remove it only if it is abandoned; keep the workspace and its recovery records.${unreleasedNote(lease)}`, { phase: 'preflight', code: 'build-locked', recoverable: true, retry: RETRY.NEVER });
+ return new BuildHalt(`another build may be applying '${appUnique}' in this workspace — refusing a second concurrent apply (would risk duplicate creation). Re-run the same command after it finishes. If no build using this workspace is running, inspect ${blockingName(lease, lockPath)} and remove it only if it is abandoned; keep the workspace and its recovery records.${unreleasedNote(lease)}${uninspectableNote(lease)}`, { phase: 'preflight', code: 'build-locked', recoverable: true, retry: RETRY.NEVER });
}
function buildLeaseInvalid() {
return new BuildHalt('the supplied build lease is not active for this app and workspace — refusing to apply without its own lease', { phase: 'preflight', code: 'build-lease-invalid', recoverable: false, retry: RETRY.NEVER });
diff --git a/plugins/model-apps/scripts/lib/lookup-metadata.js b/plugins/model-apps/scripts/lib/lookup-metadata.js
index 6f2ba7213..4f73400e8 100644
--- a/plugins/model-apps/scripts/lib/lookup-metadata.js
+++ b/plugins/model-apps/scripts/lib/lookup-metadata.js
@@ -34,6 +34,12 @@ const ATTRIBUTE_TYPES = new Set(['BigInt', 'Boolean', 'CalendarRules', 'Customer
const TARGET_TYPES = new Set([...LOOKUP_TYPES, 'PartyList']);
const LOGICAL_NAME = /^[a-z_][a-z0-9_]*$/;
+// A name the metadata answer states, lower-cased. Only a string is a name: String(value) would turn a malformed answer's null, true or
+// ['customerid'] into the plausible names "null", "true" and "customerid", so anything else is '' and fails the checks below.
+function nameOf(value) {
+ return typeof value === 'string' ? value.toLowerCase() : '';
+}
+
function lookupError(code, message) {
const error = new Error(message);
error.code = code;
@@ -46,22 +52,23 @@ function lookupError(code, message) {
* @param {object[]} rows - readRelationshipsOf lookup-details rows: { schemaName, referencedEntity, referencingAttribute, referencedAttribute, navigationProperty }
*/
function tableLookups(metadata, rows) {
- const table = String(metadata.logicalName || '').toLowerCase();
+ const table = nameOf(metadata.logicalName);
+ if (!LOGICAL_NAME.test(table)) throw lookupError('LOOKUP_METADATA_INCOMPLETE', "the metadata read did not state the table's logical name");
const attributes = Array.isArray(metadata.attributes) ? metadata.attributes : [];
// The SDK cannot say its attribute inventory is complete: it maps an absent `Attributes` expansion to [] and a missing
// PrimaryIdAttribute to '', and it does not follow an `[email protected]` continuation. So completeness is
// established here from what must be in it — the table's primary id column, and the referencing column of every
// ManyToOne relationship the separately paged relationship read returned (every lookup has one) — and a gap fails
// the whole read rather than becoming a shorter list a planner reads as "no lookup".
- const inventory = new Set(attributes.filter(Boolean).map((attribute) => String(attribute.logicalName || '').toLowerCase()));
- const primaryId = String(metadata.primaryIdAttribute || '').toLowerCase();
+ const inventory = new Set(attributes.filter(Boolean).map((attribute) => nameOf(attribute.logicalName)));
+ const primaryId = nameOf(metadata.primaryIdAttribute);
if (!LOGICAL_NAME.test(primaryId) || !inventory.has(primaryId)) {
throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}: the metadata read did not state the table's primary id column among its attributes`);
}
// A relationship column is classified, too: an unknown or malformed type (the SDK's 'Unknown' for a missing AttributeType),
// or Targets on a type that cannot carry them, is an incomplete answer — never a column silently left out as "not a lookup".
// A known non-lookup type without Targets is kept out of the lookups as before.
- const byColumn = new Map(attributes.filter(Boolean).map((attribute) => [String(attribute.logicalName || '').toLowerCase(), attribute]));
+ const byColumn = new Map(attributes.filter(Boolean).map((attribute) => [nameOf(attribute.logicalName), attribute]));
for (const row of rows) {
const column = String(row.referencingAttribute || '').toLowerCase();
if (!inventory.has(column)) {
@@ -79,8 +86,8 @@ function tableLookups(metadata, rows) {
const lookups = [];
for (const attribute of attributes) {
if (!attribute || !LOOKUP_TYPES.has(attribute.attributeType)) continue;
- const column = String(attribute.logicalName || '').toLowerCase();
- const targets = Array.isArray(attribute.targets) ? attribute.targets.map((target) => String(target).toLowerCase()) : [];
+ const column = nameOf(attribute.logicalName);
+ const targets = Array.isArray(attribute.targets) ? attribute.targets.map(nameOf) : [];
// The SDK fills `targets` from a separate cast read and leaves them out when that read fails, so a lookup without them is an
// incomplete answer, never a lookup with no targets.
if (!LOGICAL_NAME.test(column) || !targets.length || targets.some((target) => !LOGICAL_NAME.test(target))) {
@@ -142,7 +149,7 @@ async function readLookupMetadata(sdk, tables) {
if (missingTableOf(err, [table]) === null) throw err;
throw lookupError('LOOKUP_TABLE_NOT_FOUND', `${table}: the environment has no table with this logical name — ${err.message}`);
}
- if (!metadata || String(metadata.logicalName || '').toLowerCase() !== table || !Array.isArray(metadata.attributes)) {
+ if (!metadata || nameOf(metadata.logicalName) !== table || !Array.isArray(metadata.attributes)) {
throw lookupError('LOOKUP_METADATA_INCOMPLETE', `${table}: the metadata read did not answer for this table`);
}
const relationships = await readRelationshipsOf(sdk.dataverse, table, 'ManyToOne', cache, { lookupDetails: true });
diff --git a/plugins/model-apps/scripts/lib/source-literals.js b/plugins/model-apps/scripts/lib/source-literals.js
index e159051b8..425f1281c 100644
--- a/plugins/model-apps/scripts/lib/source-literals.js
+++ b/plugins/model-apps/scripts/lib/source-literals.js
@@ -121,8 +121,8 @@ function prevSignificant(src, i) {
// const n = {valueOf(){return 12;}}/2; const re = /x/;
// paren `)` ends an if/for/while head (a regex follows) or an operand (a division), and its `(` is out of reach
// if (true /* …2,100 characters… */) /navigateTo({…})/.test(text);
-// keyword a word that is a keyword in some places and a name in others
-// const of = 12; const n = of/2; const re = /\/*$/;
+// keyword a word that is a keyword in some places and a name in others (`of` only in a `for` head: ofTakesOperand)
+// const of = 12; for (const x of of/2 + "") {} const re = /\/*$/;
// angle a `>` may close type arguments, a JSX tag or a comparison; the `>` of `=>`, the closer of a cast the lexer proves is one (castKeywordIsCertain) and the end of an element
// or a regex it read are certain
// const half = total as Types . Alias<number> / 2; const re = /x/;
@@ -331,6 +331,11 @@ function positionAfter(src, prev, ends = null, depth = 0) {
// short by an escape, `#` or a non-ASCII letter, which is not the word it spells (`identifier`), and `throw` before a line break — an
// error in JavaScript, `throw;` to TypeScript's `parseThrowStatement` — where what follows is unknowable (`newline`).
if (cutsWord(src, s)) return { expression, ambiguity: 'identifier' };
+ // `of` takes an operand only as the keyword of a `for (… of …)` head; anywhere else it is a name (ofTakesOperand).
+ if (keyword && word === 'of') {
+ const of = ofTakesOperand(src, index);
+ return { expression: of.operand, ambiguity: of.ambiguity };
+ }
if (keyword && word === 'throw' && prev.newline) return { expression, ambiguity: 'newline' };
return { expression, ambiguity: !property && CONTEXTUAL_WORDS.has(word) ? 'keyword' : null };
}
@@ -678,6 +683,46 @@ function wordBefore(src, j) {
return { word, start: s };
}
+// Whether the word `of` whose last character is at `index` takes an operand — a `/` after it starts a regex and a `<` an element — and whether
+// that answer is certain: { operand, ambiguity }. TypeScript's parser takes `of` as the keyword in one place only, right after what the head of a
+// `for (… of …)` or `for await (… of …)` statement binds (parseForOrForInOrForOfStatement,
+// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts); everywhere else `of` is an identifier, so a `/` after it divides
+// and a `<` compares or opens type arguments:
+// type of<T> = T; const x = fn<of<List<Row>>>(); a type's name, twice: no element
+// const half = of / 2; a division
+// for (const x of <A />.props.items) {} the keyword: an element
+// The word is a name for CERTAIN only where the scan PROVES that no for head can enclose it. The scan counts back over the lexer's output (where the
+// brackets of strings, comments, regexes and JSX text are blank) to the nearest bracket left open before the word, as statementHead does, and
+// a name is proven in three cases only, each the return of NAME below:
+// (a) that bracket is a `[` or a `{` — an array, a pattern, a block, an object, an attribute's or a child's braces: the keyword stands in the
+// parentheses of its head and nowhere deeper, so `for (const [a = of / 2] of xs)` holds a name;
+// (b) it is a `(` whose preceding token, read across white space and blanked comments, is read whole and is neither the word `for` nor the word
+// `await` — a punctuator, a quote, a regex's flag, any other ASCII word (`f(of / 2)`, `if (of / 2)`);
+// (c) the scan reaches the start of the source with no bracket left open.
+// Nothing else proves it, and no exception to a head may: a `(` after the word `for` or `await` is always a possible head, whatever stands before
+// that word — `a.for(…)` looks like a property, but the dot may be a decimal's that ends the statement before (`const n = 1.⏎for (…)`). Inside a
+// for head nothing is proven either, whatever stands before the `of`: a binding can end in a name the scan does not read (`π`), a non-null `!`, or
+// any type (`x as enum`). There, before a word cut by an escape, a `#` or a character beyond ASCII (which may be a `for` or an `await` spelled
+// otherwise), and where the bracket lies beyond LOOKAHEAD, the reading is the table's, as it always was: the keyword, and a GUESS (`keyword`).
+function ofTakesOperand(src, index) {
+ const keyword = { operand: true, ambiguity: 'keyword' };
+ const NAME = { operand: false, ambiguity: null };
+ let depth = 0;
+ for (let j = index - 2; j >= 0; j -= 1) {
+ if (index - 1 - j > LOOKAHEAD) return keyword;
+ const c = src[j];
+ if (c === ')' || c === ']' || c === '}') depth += 1;
+ else if (c === '(' || c === '[' || c === '{') {
+ if (depth > 0) { depth -= 1; continue; }
+ if (c !== '(') return NAME;
+ const head = wordBefore(src, j);
+ if (head.word === 'for' || head.word === 'await' || cutsWord(src, head.start)) return keyword;
+ return NAME;
+ }
+ }
+ return NAME;
+}
+
// The window for the scans that look back or ahead over a bounded stretch of source: the `(` of a statement head (statementHead), the `<` of
// a cast's type arguments (matchingTypeArgumentOpen) and the parameter list of a generic function type (genericFunctionTypeFollows). Past
// it the answer is a guess, and each says so (`paren`, `angle`, `generic`).
@@ -5091,4 +5136,4 @@ function ellipsisFollowedByStatement(mask, k) {
return STATEMENT_WORDS.has(word) || word === 'import' || word === 'export';
}
-module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING };
+module.exports = { blankLiterals, ofTakesOperand, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING };
diff --git a/plugins/model-apps/scripts/lib/temp-workspace.js b/plugins/model-apps/scripts/lib/temp-workspace.js
index eeb9e9fc4..1a7211593 100644
--- a/plugins/model-apps/scripts/lib/temp-workspace.js
+++ b/plugins/model-apps/scripts/lib/temp-workspace.js
@@ -26,9 +26,9 @@
//
// WHO IS TRUSTED TO HAVE MADE THE FOLDER. On POSIX the plugin's folder must be a plain folder this user owns and nobody else can write to (uid and mode). Windows gives Node
// no owner and no permissions, so an access list stands in (lib/windows-folder-acl.js): a folder this process MAKES is given an explicit, protected one before anything is put in it — only this
-// user, the system and the administrators, full control, inherited by every workspace and record made inside — and read back, and a folder that cannot be made so is removed and not used;
+// user, the system and the administrators, full control, inherited by every workspace and record made inside — and read back, and a folder that cannot be made so is removed (once other runs' holds have left it: removeUnprotectedParent) and not used;
// an EXISTING folder is used only if it is this user's (or the administrators') and NO entry of its list, an inherit-only one too, lets anyone else add to it, write to it, delete it
-// or take it over. The answer is asked once per folder and process. A folder that Windows is still removing — the last handle on it has not closed — refuses a new
+// or take it over. The answer is asked once per folder and process (but a "no" about a folder another run made moments ago, and has not yet given its own list, is asked again: checkParent). A folder that Windows is still removing — the last handle on it has not closed — refuses a new
// entry and cannot be read for a moment: the attempt is made again after short pauses, and one that is still refusing after the last is not used (WAITS_MS).
//
// A RUN HOLDS THE FOLDER WHILE IT JUDGES IT (Windows). Asking whether a folder that is there is private starts three programs (lib/windows-folder-acl.js) and takes about a second — more on a busy machine —
@@ -157,6 +157,18 @@ const pauseSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),
const windowsRefusesForAMoment = (e, deps) => uidOf(deps) === null && !!e && TRANSIENT_CODES.has(e.code);
// The code of the failure of a folder that this process made and could not make private (Windows): the folder is not used, and not tried again by this process (`refusing`, below).
const NOT_PRIVATE = 'ENOTPRIVATE';
+// The code of a "no" about a folder that may yet be made private by the run that made it (Windows: checkParent): the attempt is made again after a pause, and a folder that is still saying it after the last is not used for
+// this workspace — but it is not refused for the life of the process either, as a folder that is not private by anyone's choice is.
+const NOT_YET_PRIVATE = 'ENOTYETPRIVATE';
+// How long after it was made a folder whose access list is still all it took from the one above may be one that its maker has not yet given a list of its own: the maker's icacls is given 10 s
+// (lib/windows-folder-acl.js), and a maker whose icacls did not answer in that time removes the folder. Measured: about 200 ms on average, and up to about a second on a busy machine.
+const PROTECT_WINDOW_MS = 15000;
+// How long a maker whose folder could not be made private waits for other runs' holds to leave it before it leaves it (removeUnprotectedParent), and how often it looks. A hold is kept for one judgement
+// (three programs: about a second, a few on a busy machine) and let go before every pause, so ten seconds covers several judgements back to back by several runs; a look is an lstat, an rmdir and a listing,
+// so looking every 20 ms costs nothing worth counting, and lands in the shortest pause of a judge (WAITS_MS: 25 ms). The wait happens only after a failed protection — the rare path this is for — and the
+// run then works in the plain temp folder, as it did.
+const REMOVE_PATIENCE_MS = 10000;
+const REMOVE_PAUSE_MS = 20;
// The folder the plugin keeps its workspaces in, for the temp folder `deps.os` (the real one) names. Windows gives each user a temp folder of their
// own (GetTempPath reads TMP, TEMP, then the profile: https://learn.microsoft.com/windows/win32/api/fileapi/nf-fileapi-gettemppatha), and so does
@@ -173,6 +185,11 @@ function workspaceParent(deps = {}) {
//
// That is read once per folder and process, whatever the answer (the cache below): a run that makes a workspace for each of forty dashboards would otherwise start three programs
// forty times. The key names the folder itself — its place, device, file id and creation time — so a folder that is removed and made again by someone else is judged again.
+// The one "no" that is not remembered is one that may be about to change: a folder that another run made moments ago takes the access list of the temp folder it is in until that run's icacls
+// gives it one of its own (ensureParent), and where the temp folder lets others write — `TEMP` on a data drive gives Authenticated Users "modify" — a run that judges it in between is told
+// "not private" about a folder that is private a moment later, with the same identity. Remembered, that "no" sent every later workspace of the run to the plain temp folder, unrecorded, for the
+// rest of its life (measured: about one run in sixty, eight at a time, each making six). So a "no" about a list that is still only inherited (`inherited`, lib/windows-folder-acl.js), about a
+// folder made within PROTECT_WINDOW_MS, is not remembered: it is asked again after a pause (makeTempWorkspace). A "no" about a list somebody set, or about an older folder, is final, as before.
// `created`: this call made the folder, gave it an access list of its own and read it back (ensureParent): it is not asked about again.
// `deps.folderPrivacy` is a test seam for the Windows reader.
const privacyVerdicts = new Map();
@@ -199,6 +216,9 @@ function checkParent(parent, deps, { created = false } = {}) {
// A list that could not be got at all (the folder is being removed, most likely) is no answer either, and is not remembered: it is a refusal of the kind a folder being removed
// gives, and the caller asks again after a pause.
if (answer.unreadable) throw Object.assign(new Error(`${parent} could not be judged: ${answer.reason}`), { code: 'EBUSY' });
+ if (!answer.ok && answer.inherited === true && Math.abs(clockOf(deps)() - st.birthtimeMs) < PROTECT_WINDOW_MS) {
+ throw Object.assign(new Error(`${parent} can be changed by others, for now: ${answer.reason}`), { code: NOT_YET_PRIVATE });
+ }
privacyVerdicts.set(key, answer);
}
const verdict = privacyVerdicts.get(key);
@@ -279,14 +299,50 @@ function protectNewParent(parent, deps) {
let same = false;
try { same = identityOf(parent, fsx.lstatSync(parent)) === before; } catch { /* gone: another process that ended with nothing in it removed it */ }
if (answer.ok && same) return;
- if (same) {
- try { fsx.rmdirSync(parent); } catch { /* something is in it already, and it is not this call's to remove */ }
- }
+ if (same) removeUnprotectedParent(parent, before, deps);
// Gone, or replaced: ask again at once. A folder that icacls could not even open — Windows is removing it — asks again after a pause. Anything else is final for this process.
if (!same) throw Object.assign(new Error(`${parent} was replaced while it was being made private`), { code: 'ENOENT' });
throw Object.assign(new Error(`${parent} could not be made private: ${answer.reason}`), { code: answer.unreadable ? 'EBUSY' : NOT_PRIVATE });
}
+// THE FOLDER A FAILED MAKER LEAVES (Windows). Removing the folder this run made and could not make private is refused while another run's hold is in it (ENOTEMPTY) — a run that found the folder
+// moments after it was made and is judging it — and a single `rmdir` then left it for good: an empty folder whose list is still the temp folder's, which no later run could use (its "no" is final once
+// the folder is older than PROTECT_WINDOW_MS) and none removes (only a run that used it prunes it). So the maker waits for the holds to go: it removes the folder as soon as it is empty, asking again
+// every REMOVE_PAUSE_MS for up to REMOVE_PATIENCE_MS. A judge holds the folder only while it judges it — a "not yet" lets go before it pauses (makeTempWorkspace) — so
+// the holds of runs that are waiting for this folder to be made private come and go, and the maker's `rmdir` lands between them; the judge then finds the folder gone (ENOENT) and makes one of its own.
+// It removes only what it made: right before every `rmdir` the folder at the path must still be a plain folder with the identity it had right after this run's mkdir (`made`), and the waiting stops
+// at once when it is not. `rmdir` removes only an empty folder, in one step — never a file, never a hold — so the most a folder swapped in between that look and the `rmdir` could lose is itself,
+// empty: the same as the single `rmdir` that was here before, and as the end of every run (prune), which removes the folder by its path alone. A folder whose listing shows anything but files named
+// as holds — a workspace, a record, a file of anyone's — is not waited for: it is in use, or not this run's to empty. A listing Windows refuses for a moment (EPERM, EACCES, EBUSY) shows nothing,
+// and is waited out like a hold: `rmdir` still removes only an empty folder, so the wait can cost time, never content. When the wait runs out, or this run is killed while it waits, the folder is
+// left, as it was before (the caller throws NOT_PRIVATE either way).
+function removeUnprotectedParent(parent, made, deps) {
+ const fsx = deps.fs || fs;
+ const clock = clockOf(deps);
+ const until = clock() + REMOVE_PATIENCE_MS;
+ for (;;) {
+ try {
+ const now = fsx.lstatSync(parent);
+ if (!now.isDirectory() || identityOf(parent, now) !== made) return;
+ } catch {
+ return; // gone: what was wanted
+ }
+ let refusal;
+ try {
+ fsx.rmdirSync(parent);
+ return;
+ } catch (e) {
+ refusal = e;
+ }
+ // ENOTEMPTY: something is in it. EPERM, EACCES or EBUSY (Windows): a hold that is being made or removed at that moment — a file whose removal is pending keeps its folder from going, and is not listed.
+ if (!(refusal && (refusal.code === 'ENOTEMPTY' || windowsRefusesForAMoment(refusal, deps)))) return;
+ let onlyHolds = false;
+ try { onlyHolds = fsx.readdirSync(parent, { withFileTypes: true }).every((entry) => entry.isFile() && isHoldName(entry.name)); } catch (e) { onlyHolds = windowsRefusesForAMoment(e, deps); }
+ if (!onlyHolds || clock() >= until) return;
+ (deps.pause || pauseSync)(REMOVE_PAUSE_MS);
+ }
+}
+
// A file written WHOLE: to a file of its own name, then renamed over `file`, which is atomic — a reader (a sweep, which reads the record of a live run's folder on Linux) or a kill finds the file as it was or all of the
// new text, never half. Nothing in this module writes a file any other way, so there is no write that a full disk or a kill can cut off and leave a damaged file where a good one was needed. The temporary copy is
// created with `wx` — it is a name that did not exist — and removed if anything fails. True when `file` is written. A failure is never thrown: what is written here is a courtesy to the next run (the record of a folder,
@@ -711,6 +767,15 @@ function makeTempWorkspace(prefix, deps = {}) {
} catch (e) {
releaseHold(hold, deps);
if (e && e.code === 'ENOENT') continue;
+ if (e && e.code === NOT_YET_PRIVATE) {
+ // Its maker may not have given it its own list yet (checkParent): ask again after a pause. Still "no" after the last, it is not used for this workspace, and asked about again for the next.
+ // The hold is let go before the pause (ensureParent): a maker whose protection failed is waiting to remove the folder (removeUnprotectedParent), and must be able to.
+ if (attempt < MAKE_ATTEMPTS) {
+ (deps.pause || pauseSync)(WAITS_MS[attempt - 1]);
+ continue;
+ }
+ break;
+ }
if (windowsRefusesForAMoment(e, deps)) {
if (attempt < MAKE_ATTEMPTS) {
(deps.pause || pauseSync)(WAITS_MS[attempt - 1]);
diff --git a/plugins/model-apps/scripts/lib/windows-folder-acl.js b/plugins/model-apps/scripts/lib/windows-folder-acl.js
index 883359ea7..a29167ff4 100644
--- a/plugins/model-apps/scripts/lib/windows-folder-acl.js
+++ b/plugins/model-apps/scripts/lib/windows-folder-acl.js
@@ -261,7 +261,13 @@ function judge(folder, deps) {
const read = readDacl(folder, tool, deps);
if (read.verdict) return read.verdict;
const writers = foreignWriters(read.dacl.aces, sid);
- if (writers.length > 0) return { ok: false, reason: `${writers.join(', ')} can add to it, remove from it or take it over` };
+ if (writers.length > 0) {
+ // A list that is still all the folder took from the one above — not protected, and every entry marked `ID` (inherited) — is also the list a folder has between the `mkdir` of the run that
+ // made it and that run's icacls (makeWindowsFolderPrivate), when the temp folder it is in lets others write (`TEMP` on a data drive: `D:(A;OICIID;0x1301bf;;;AU)...`). The answer says so
+ // (`inherited`), so that a caller can tell that "no" from one about a list somebody set; it is a "no" all the same.
+ const inherited = !read.dacl.protected && read.dacl.aces.every((ace) => (ace.flags.match(/../g) || []).includes('ID'));
+ return { ok: false, reason: `${writers.join(', ')} can add to it, remove from it or take it over`, ...(inherited ? { inherited: true } : {}) };
+ }
// A list that names only the right principals does not make the folder theirs: its owner can rewrite the list whatever it says now. The owner is the user — or the administrators, whom the list
// trusts anyway, and who own what a process that runs elevated makes.
const owner = ownerSidOf(folder, tool);
@@ -309,10 +315,10 @@ function protect(folder, deps) {
/**
* Whether only this user, the system and the administrators can change `folder`, and it belongs to this user or the administrators. Never throws: whatever cannot be read, run or understood is
* `{ ok: false }`. `unreadable: true` marks the one kind of "no" that may not stay one: the list could not be got at all (the folder is being removed, most likely), which says nothing about
- * the folder.
+ * the folder. `inherited: true` marks a "no" about a list that is still only what the folder took from the one above — what a folder has until the run that made it gives it a list of its own.
* @param {string} folder
* @param {object} [deps] test seams: run (the process runner's spawnResultSync), env, saveIn (the folder the saved list goes in: the folder's own parent)
- * @returns {{ ok: boolean, reason: string, unreadable?: boolean, owner?: string }} `owner` is the SID of the folder's owner, when it was read
+ * @returns {{ ok: boolean, reason: string, unreadable?: boolean, inherited?: boolean, owner?: string }} `owner` is the SID of the folder's owner, when it was read
*/
function windowsFolderIsPrivate(folder, deps = {}) {
try {
diff --git a/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js b/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
index ab0460d03..216923ad2 100644
--- a/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
+++ b/plugins/model-apps/scripts/tests/ambiguity-sweep.test.js
@@ -58,7 +58,7 @@ const JS_CONSTRUCTS = [
{ name: 'a division after an object literal', kind: 'brace', code: 'const n1 = {valueOf(){return 12;}}/2; const r1 = /\\/*$/;' },
{ name: 'a regex after a block', kind: 'brace', code: 'if (true) { }\n/ab+c/.test("x");' },
{ name: 'a regex after a parenthesis out of reach', kind: 'paren', code: `if (true /*${'x'.repeat(2100)}*/) /x+/.test("y");` },
- { name: 'a division by a name that can be a keyword', kind: 'keyword', code: 'const of = 12; const n2 = of/2; const r2 = /\\/*$/;' },
+ { name: 'a division by a name that can be a keyword', kind: 'keyword', code: 'const yield = 12; const n2 = yield/2; const r2 = /\\/*$/;' },
{ name: 'an identifier written with an escape', kind: 'identifier', code: 'var a\\u0062 = 1; var n3 = a\\u0062/2; var r3 = /\\/*$/;' },
{ name: 'a regex after a spread', kind: 'operator', code: 'var s1 = [.../ab/.exec("ab")];' },
{ name: 'a regex after three signs', kind: 'operator', code: 'var i3 = 1; var n4 = i3+++/x/.test("x");' },
@@ -218,10 +218,10 @@ const TS_PAYLOADS = [
// a spread. The members after a guess are not read for certain, so the call is not trusted — its token is not rewritten, though it lies before
// the guess — and a page that is accepted must have its generative calls rewritten and every other call as it was. With the guess before the
// `pageId` the false comment it opens covers the `pageId` itself. Each page also holds a real call after the object.
-const NEST_PREAMBLE = 'const typeKey = "pageType"; const of = 12; const override = { pageType: "entityrecord" }; const flag = false;';
+const NEST_PREAMBLE = 'const typeKey = "pageType"; const yield = 12; const override = { pageType: "entityrecord" }; const flag = false;';
const NEST_GUESSES = [
{ name: 'a division after an object literal', kind: 'brace', code: 'data: {valueOf(){return 12;}}/2, r: /\\/*$/,' },
- { name: 'a division by a name that can be a keyword', kind: 'keyword', code: 'data: of/2, r: /\\/*$/,' },
+ { name: 'a division by a name that can be a keyword', kind: 'keyword', code: 'data: yield/2, r: /\\/*$/,' },
{ name: 'no guess', kind: null, code: 'data: 12 / 2, r: /\\/*$/,' },
];
const NEST_OVERRIDES = [
diff --git a/plugins/model-apps/scripts/tests/app-build-lease.test.js b/plugins/model-apps/scripts/tests/app-build-lease.test.js
index 5c57d9af1..2dd26b650 100644
--- a/plugins/model-apps/scripts/tests/app-build-lease.test.js
+++ b/plugins/model-apps/scripts/tests/app-build-lease.test.js
@@ -25,6 +25,7 @@ const { sha256 } = require('../lib/hash.js');
const { ownerStamp } = require('../lib/process-owner.js');
const { ConnectionError } = require('../lib/maker-sdk.js');
const { deadPid } = require('./helpers/kill-target-client.js');
+const { deletedWhileOpen, deletedNamesLinger } = require('./helpers/delete-pending.js');
// A valid spec, and not the point: one table the phases these tests run never reach.
const spec = (name = 'Lease Probe') => ({
@@ -384,3 +385,44 @@ test('a link or a folder at the lock\'s name is the file system problem it is, n
fs.writeFileSync(file, '');
await assert.rejects(engineBuild(spec(), file, { sdk: sdk.sdk }), (e) => e.code === 'UNSAFE_OUTPUT' && e.reason === 'not-directory');
});
+
+// A claim or a lock another build is deleting while a third still has it open lingers on Windows under Node 20, and every look at it fails with EPERM
+// (helpers/delete-pending.js): a lock in use, refused as one — never a file-safety error. Elsewhere the name is gone at once, and the same steps find
+// what a build then finds: the first build's lock, or a free one.
+const isUninspectable = (dir, name) => (e) => {
+ assert.strictEqual(e && e.code, 'build-locked', String(e && e.stack));
+ assert.strictEqual(e.phase, 'preflight');
+ assert.strictEqual(e.retry, 'never');
+ assert.strictEqual(e.message, `${REFUSAL(dir).replace(buildLock(dir), name)} Windows could not inspect ${name} (EPERM): another build may be removing it, or this user may not have access to it. If this refusal persists while no build is running, check that file's access, or remove it.`);
+ return true;
+};
+test('a lock or a claim another build is deleting while a third has it open is a lock in use: refused, never a file-safety error', async () => {
+ const dir = makeTempDir('build-lease-deleting-');
+ const lingers = deletedNamesLinger(dir);
+ const held = gate();
+ const inside = gate();
+ const running = engineBuild(spec(), dir, { sdk: solutionDouble(async () => { inside.open(); await held.opened; }).sdk });
+ await inside.opened;
+ const claimName = `${buildLock(dir)}.reclaim`;
+ const claim = deletedWhileOpen(claimName, JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'taking-over' }));
+ try {
+ const second = solutionDouble();
+ // Where it lingers, the refusal names the claim Windows could not inspect, and says it may be inaccessible; elsewhere the live lock refuses.
+ await assert.rejects(engineBuild(spec(), dir, { sdk: second.sdk }), lingers ? isUninspectable(dir, claimName) : isBuildLocked(dir), `the claim; names deleted while open linger here: ${lingers}`);
+ assert.deepStrictEqual(second.reads, []);
+ } finally {
+ claim.close();
+ }
+ held.open();
+ assert.strictEqual((await running).ok, true);
+
+ const lock = deletedWhileOpen(buildLock(dir), JSON.stringify({ ...ownerStamp(), rnd: 'letting-go' }));
+ try {
+ const next = engineBuild(spec(), dir, { sdk: solutionDouble().sdk });
+ if (lingers) await assert.rejects(next, isUninspectable(dir, buildLock(dir)), 'the lock');
+ else assert.strictEqual((await next).ok, true, 'the lock is gone: free');
+ } finally {
+ lock.close();
+ }
+ assert.deepStrictEqual(fs.readdirSync(dir).filter((n) => /\.lock|\.reclaim/.test(n)), [], 'nothing is left once the last handle is closed');
+});
diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.js
index 3f07427ee..ad6c33971 100644
--- a/plugins/model-apps/scripts/tests/download-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js
@@ -1371,7 +1371,7 @@ test('download leaves an id after a place the lexer reads by guess, and says whe
'export default function Overview() {',
` navigateTo({pageType:"generative",pageId:"${id}"});`,
' const of = 12;',
- ' const count = of/2; const re = /\\/*$/;',
+ ' for (const x of of/2 + "") {} const re = /\\/*$/;',
` const note = "*/ navigateTo({pageType:'generative', pageId:'${id}'}) /*";`,
` navigateTo({pageType:"generative",pageId:"${id}"});`,
' return null;',
diff --git a/plugins/model-apps/scripts/tests/helpers/delete-pending.js b/plugins/model-apps/scripts/tests/helpers/delete-pending.js
new file mode 100644
index 000000000..fa1615284
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/delete-pending.js
@@ -0,0 +1,40 @@
+'use strict';
+// A name in the state another build leaves it in when it deletes a lock file while a third process still has it open — reading it to judge the
+// lock's owner. On Windows under a libuv before 1.48 (Node 20) the name stays until that handle closes ("delete pending"), and every lstat and
+// create of it meanwhile fails with EPERM (https://github.com/libuv/libuv/issues/3839). From libuv 1.48 (Node 22), and on Linux and macOS, the
+// delete removes the name at once, and the same steps leave no name at all.
+const fs = require('node:fs');
+const path = require('node:path');
+
+// Writes `name`, opens it, and deletes it while it is open. `close()` lets go of the handle, and with it, the name.
+function deletedWhileOpen(name, content = '{}') {
+ fs.writeFileSync(name, content);
+ const fd = fs.openSync(name, 'r');
+ fs.rmSync(name);
+ let open = true;
+ return {
+ close() {
+ if (!open) return;
+ open = false;
+ fs.closeSync(fd);
+ },
+ };
+}
+
+// Whether a name deleted while open lingers here (the EPERM above), worked out in the folder `dir` and cleaned up again.
+function deletedNamesLinger(dir) {
+ const name = path.join(dir, 'delete-pending-probe');
+ const probe = deletedWhileOpen(name);
+ try {
+ fs.lstatSync(name);
+ return true;
+ } catch (e) {
+ if (e && e.code === 'ENOENT') return false;
+ if (e && e.code === 'EPERM') return true;
+ throw e;
+ } finally {
+ probe.close();
+ }
+}
+
+module.exports = { deletedWhileOpen, deletedNamesLinger };
diff --git a/plugins/model-apps/scripts/tests/helpers/misread-page.js b/plugins/model-apps/scripts/tests/helpers/misread-page.js
index 632011dbd..8e3043d52 100644
--- a/plugins/model-apps/scripts/tests/helpers/misread-page.js
+++ b/plugins/model-apps/scripts/tests/helpers/misread-page.js
@@ -55,15 +55,16 @@ const MISREAD_PAGES = {
'}',
),
},
- // `of` is a name here and the table takes it for the keyword before a regex. The false regex ends at the real one's `/`, the `/*` inside
- // it opens a comment that ends at the `*/` INSIDE a string, and the rest of that string is read as code.
+ // `of` is a name here — in the value a `for … of` head iterates — and the table takes it for the keyword before a regex: after what a head binds
+ // an `of` is the keyword, and a second one may be either (`for (let of of …)` binds a name `of`). The false regex ends at the real one's `/`,
+ // the `/*` inside it opens a comment that ends at the `*/` INSIDE a string, and the rest of that string is read as code.
keyword: {
kind: 'keyword',
frontier: (code) => code.indexOf('of/2') + 2,
code: page(
'export default function Page() {',
' const of = 12;',
- ' const count = of/2; const re = /\\/*$/;',
+ ' for (const x of of/2 + "") {} const re = /\\/*$/;',
` ${IN_A_STRING}`,
` ${CALL}`,
' return null;',
@@ -425,7 +426,7 @@ const HIDDEN_CALL_PAGE = {
code: page(
'export default function Page() {',
' const of = 12;',
- ' const count = of/2; const re = /\\/*$/;',
+ ' for (const x of of/2 + "") {} const re = /\\/*$/;',
` ${CALL}`,
' /* regular comment */',
' return null;',
diff --git a/plugins/model-apps/scripts/tests/iteration-emit.test.js b/plugins/model-apps/scripts/tests/iteration-emit.test.js
index ae42d41ee..918079030 100644
--- a/plugins/model-apps/scripts/tests/iteration-emit.test.js
+++ b/plugins/model-apps/scripts/tests/iteration-emit.test.js
@@ -11,8 +11,9 @@
// rest element throws. `transpileModule` reports syntax only, so the TS2802 error a type check would give never appears.
//
// Every case here is compiled by the vendored compiler with exactly those options and run in a fresh vm context; the
-// expected values are what that emit does, never what modern JavaScript would do. Results cross the context boundary as
-// JSON (undefined and thrown errors are compared separately), so nothing depends on another realm's prototypes. The host's
+// expected values are what that emit does, never what modern JavaScript would do. The last test holds those options to what
+// the real SDK bundle stores for a page, so an SDK that compiles pages another way fails here first. Results cross the context
+// boundary as JSON (undefined and thrown errors are compared separately), so nothing depends on another realm's prototypes. The host's
// own URLSearchParams, FormData and Headers are handed in for their cases: nothing is fetched and no DOM is used.
const { test } = require('node:test');
const assert = require('node:assert/strict');
@@ -270,3 +271,41 @@ test('Critical Rule 24 names the forms, the conversion and the section, after Ru
assert.match(rule[1], /See \*\*Common Errors > 5\. Iteration that compiles to nothing\*\*\.$/);
assert.equal(RULES.split(`\n${HEADING}\n`).length, 2, 'one canonical section');
});
+
+// ── The contract these proofs assume, read from the real SDK ──────────────────────────────────────────────────────────────────────
+
+// Everything above compiles with the options the SDK compiled pages with when it was written. This pushes a page through the REAL
+// vendored SDK bundle (over the stateful fake of the page tables, helpers/fake-genpage-server.js) and holds the compiled output it stores
+// to exactly what those options emit. When an SDK uptake compiles pages another way — with `downlevelIteration` (a spread then reads
+// `__read(…)`, a loop `__values(…)`) or an ES2015+ target (spreads and loops kept as written) — this fails first: then Critical Rule 24
+// and Common Errors §5 in references/rules.md, the skills that repeat the rule, and the expectations in this file are revised together,
+// once the maker portal is shown to compile pages the same way (the plugin keeps parity with it: lib/typescript-compiler.js).
+test('the real SDK stores a page compiled exactly as these proofs compile it: ES5, without iterator downleveling', async () => {
+ const { makeGenpageSdk } = require('../lib/genpage-sdk.js');
+ const { FakeGenPageServer, INSTANCE } = require('./helpers/fake-genpage-server.js');
+ const source = [
+ "import * as React from 'react';",
+ 'const seen = new Map<string, number>([["a", 1]]);',
+ 'const values = [...seen.values()];',
+ 'const pairs: Array<[string, number]> = [];',
+ 'for (const [k, v] of seen) pairs.push([k, v]);',
+ 'const [first] = new Set(["x"]);',
+ 'export default function Page() { return <div>{values.length}{pairs.length}{first}</div>; }',
+ '',
+ ].join('\n');
+ const server = new FakeGenPageServer();
+ const genpage = makeGenpageSdk(INSTANCE, { httpClient: server.http() });
+ let stored;
+ try {
+ const { pageId } = await genpage.create({ name: 'Emit', source, prompt: 'p', agentMessage: 'r' });
+ stored = server.rowText(pageId, 'src/pages/page.compiled');
+ } finally {
+ await genpage.dispose();
+ }
+ const changed = 'the vendored SDK no longer compiles pages as these proofs assume: revise Critical Rule 24, Common Errors §5 and this file';
+ assert.equal(stored, compile(source).outputText, `what the SDK stores is what the options these proofs use emit — ${changed}`);
+ assert.match(stored, /__spreadArray\(\[\], seen\.values\(\), true\)/, 'a spread reads the iterator by length and index');
+ assert.match(stored, /for \(var _i = 0, seen_1 = seen; _i < seen_1\.length; _i\+\+\)/, 'a loop walks it by index');
+ assert.match(stored, /var first = new Set\(\["x"\]\)\[0\];/, 'a destructure reads an index');
+ assert.doesNotMatch(stored, /__read|__values|\[\.\.\.seen|for \(const/, `no iterator downleveling, and no ES2015 form left as written — ${changed}`);
+});
diff --git a/plugins/model-apps/scripts/tests/lookup-metadata-real-bundle.test.js b/plugins/model-apps/scripts/tests/lookup-metadata-real-bundle.test.js
index 579402d4a..932d3d5e7 100644
--- a/plugins/model-apps/scripts/tests/lookup-metadata-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/lookup-metadata-real-bundle.test.js
@@ -93,6 +93,39 @@ test('REAL BUNDLE: an incomplete main metadata answer fails the whole discovery,
}
});
+for (const target of [null, true, false, ['contact']]) {
+ test(`REAL BUNDLE: non-string Targets entry ${JSON.stringify(target)} fails discovery`, async () => {
+ const lookupTargets = TARGETS.map((entry) => (
+ entry.LogicalName === 'customerid' ? { ...entry, Targets: ['account', target] } : entry));
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, transport({ lookupTargets })),
+ (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE' && /customerid/.test(err.message));
+ });
+}
+
+for (const name of [true, ['customerid']]) {
+ test(`REAL BUNDLE: a non-string column name ${JSON.stringify(name)} in the attribute inventory fails discovery`, async () => {
+ // The SDK reads the targets by the column's name, so a column named by a non-string has none; typed String it would, coerced,
+ // read as the listed non-lookup column `customerid` and the lookup would silently vanish.
+ const main = (body) => ({ ...body, Attributes: ATTRIBUTES.map((entry) => (
+ entry.LogicalName === 'customerid' ? { ...entry, LogicalName: name, AttributeType: 'String' } : entry)) });
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, transport({ main })), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE');
+ });
+}
+
+test('REAL BUNDLE: a lookup attribute whose name is not a string fails discovery; a non-lookup one is ignored as before', async () => {
+ const withExtra = (extra) => (body) => ({ ...body, Attributes: [...ATTRIBUTES, { ...ATTRIBUTES[1], ...extra }] });
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, transport({ main: withExtra({ LogicalName: true, AttributeType: 'Lookup', AttributeTypeName: { Value: 'LookupType' } }) })),
+ (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE');
+ const answer = await readLookups(ENV, { tables: ['opportunity'] }, transport({ main: withExtra({ LogicalName: true }) }));
+ assert.deepEqual(answer.tables[0].lookups.map((lookup) => lookup.column), ['customerid', 'ownerid']);
+});
+
+for (const [field, value] of [['PrimaryIdAttribute', ['opportunityid']], ['LogicalName', ['opportunity']], ['LogicalName', true]]) {
+ test(`REAL BUNDLE: the SDK passes a non-string ${field} ${JSON.stringify(value)} through and discovery rejects it`, async () => {
+ const main = (body) => ({ ...body, [field]: value });
+ await assert.rejects(readLookups(ENV, { tables: ['opportunity'] }, transport({ main })), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE');
+ });
+}
test('REAL BUNDLE: a relationship column the read does not classify, or classifies against its Targets, fails the whole discovery', async () => {
const retype = (change) => (body) => ({ ...body, Attributes: ATTRIBUTES.map((entry) => (entry.LogicalName === 'customerid' ? change({ ...entry }) : entry)) });
const untyped = retype((entry) => { delete entry.AttributeType; return entry; });
diff --git a/plugins/model-apps/scripts/tests/lookup-metadata.test.js b/plugins/model-apps/scripts/tests/lookup-metadata.test.js
index 3a750d4cb..563f28b47 100644
--- a/plugins/model-apps/scripts/tests/lookup-metadata.test.js
+++ b/plugins/model-apps/scripts/tests/lookup-metadata.test.js
@@ -81,6 +81,64 @@ test('a lookup whose targets the metadata did not state fails the read — it is
}
});
+for (const target of [null, true, false, ['contact']]) {
+ test(`a non-string lookup target ${JSON.stringify(target)} is not coerced to a table name`, () => {
+ const metadata = { ...OPPORTUNITY, attributes: OPPORTUNITY.attributes.map((entry) => (
+ entry.logicalName === 'customerid' ? { ...entry, targets: ['account', target] } : entry)) };
+ assert.throws(() => tableLookups(metadata, ROWS),
+ (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE' && /customerid/.test(err.message));
+ });
+}
+
+test('lookup target validation preserves case normalization and does not mutate SDK metadata', () => {
+ const targets = Object.freeze(['ACCOUNT', 'Contact']);
+ const metadata = { ...OPPORTUNITY, attributes: OPPORTUNITY.attributes.map((entry) => (
+ entry.logicalName === 'customerid' ? { ...entry, targets } : entry)) };
+ const customer = tableLookups(metadata, ROWS).lookups[0];
+ assert.deepEqual(customer.targets, ['account', 'contact']);
+ assert.deepEqual(customer.paths.map((entry) => entry.target), ['account', 'contact']);
+ assert.deepEqual(targets, ['ACCOUNT', 'Contact']);
+});
+
+for (const name of [true, false, null, 7, ['customerid']]) {
+ test(`a non-string lookup column name ${JSON.stringify(name)} is not coerced to a column`, () => {
+ // Listed in the inventory and named by a relationship, as the real column is: the coerced name must not satisfy either.
+ const renamed = { ...OPPORTUNITY, attributes: OPPORTUNITY.attributes.map((entry) => (
+ entry.logicalName === 'customerid' ? { ...entry, logicalName: name } : entry)) };
+ assert.throws(() => tableLookups(renamed, ROWS), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE', 'a relationship column the inventory does not list');
+ // A lookup no relationship names is caught only where the lookups are read.
+ const extra = { ...OPPORTUNITY, attributes: [...OPPORTUNITY.attributes, attribute(name, 'Lookup', ['account'])] };
+ assert.throws(() => tableLookups(extra, ROWS), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE' && /did not state the lookup's targets/.test(err.message));
+ });
+}
+
+for (const primaryIdAttribute of [['opportunityid'], true, 7]) {
+ test(`a non-string primary id ${JSON.stringify(primaryIdAttribute)} is not coerced to the id column`, () => {
+ const metadata = { ...OPPORTUNITY, primaryIdAttribute,
+ attributes: [...OPPORTUNITY.attributes, attribute(String(primaryIdAttribute), 'Uniqueidentifier')] };
+ assert.throws(() => tableLookups(metadata, ROWS), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE' && /primary id column/.test(err.message));
+ });
+}
+
+for (const logicalName of [['opportunity'], true, 7, null]) {
+ test(`a non-string table name ${JSON.stringify(logicalName)} is not coerced to the table`, async () => {
+ const metadata = { ...OPPORTUNITY, logicalName };
+ assert.throws(() => tableLookups(metadata, ROWS), (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE');
+ await assert.rejects(readLookupMetadata(fakeSdk({ metadata: { opportunity: metadata } }), ['opportunity']),
+ (err) => err.code === 'LOOKUP_METADATA_INCOMPLETE' && /did not answer for this table/.test(err.message));
+ });
+}
+
+test('names are lower-cased as before, and an attribute the reader never lists keeps whatever name it has', () => {
+ const upper = { ...OPPORTUNITY, logicalName: 'Opportunity', primaryIdAttribute: 'OpportunityId',
+ attributes: OPPORTUNITY.attributes.map((entry) => ({ ...entry, logicalName: entry.logicalName.toUpperCase() })) };
+ const rows = ROWS.map((row) => ({ ...row, referencingAttribute: row.referencingAttribute.toUpperCase() }));
+ assert.deepEqual(tableLookups(upper, rows), tableLookups(OPPORTUNITY, ROWS));
+ // A String column with no usable name, or a non-string one, is no lookup and no relationship column: ignored as before.
+ const odd = { ...OPPORTUNITY, attributes: [...OPPORTUNITY.attributes, { attributeType: 'String' }, attribute(7, 'String'), attribute(['x'], 'Memo'), null] };
+ assert.deepEqual(tableLookups(odd, ROWS), tableLookups(OPPORTUNITY, ROWS));
+});
+
test('an attribute inventory that cannot be complete fails the read: no primary id, or a relationship column it does not list', () => {
const without = (column) => ({ ...OPPORTUNITY, attributes: OPPORTUNITY.attributes.filter((entry) => entry.logicalName !== column) });
for (const [label, metadata] of [
diff --git a/plugins/model-apps/scripts/tests/pageref-resolver.test.js b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
index ad8103309..5176dc854 100644
--- a/plugins/model-apps/scripts/tests/pageref-resolver.test.js
+++ b/plugins/model-apps/scripts/tests/pageref-resolver.test.js
@@ -564,7 +564,7 @@ test('reverse resolution reports an id in a call that reaches a frontier, though
// comment that ends at the `*/` inside the string on the next line: the rest of that DOUBLE-quoted string is then read as code — a call, whose
// single-quoted id was rewritten as "PAGEREF_detail", quotes and all, inside a string that the new quotes then ended.
test('a single-quoted id inside a string the lexer read as code is not turned into a token', () => {
- const code = ['const of = 12;', 'const count = of/2; const re = /\\/*$/;', `const note = "*/ navigateTo({pageType:'generative', pageId:'${GUID}'}) /*";`, ''].join('\n');
+ const code = ['const of = 12;', 'for (const x of of/2 + "") {} const re = /\\/*$/;', `const note = "*/ navigateTo({pageType:'generative', pageId:'${GUID}'}) /*";`, ''].join('\n');
assert.deepStrictEqual(extractNavTargets(code).map((t) => [t.kind, t.quote, t.afterFrontier]), [['literal', "'", true]], 'the lexer does read the call out of the string');
const report = reverseResolveNavIdsReport(code, REVERSE_IDS);
assert.strictEqual(report.code, code, 'the string is intact');
@@ -1882,9 +1882,9 @@ test('only what lies at or after the earliest frontier is distrusted, and the ea
const twice = `${OBJECT_DIVISION}\n${DETAIL_CALL}\n${OBJECT_DIVISION}\n${DETAIL_CALL.replace('detail', 'other')}\n`;
assert.deepStrictEqual(strayPageRefs(twice).map((r) => [r.token, r.frontier.kind, r.frontier.line]), [['PAGEREF_detail', 'brace', 1], ['PAGEREF_other', 'brace', 1]]);
// The earliest by OFFSET, not the first kind found or the commonest one.
- const keywordFirst = `const of = 12; const count = of/2; const re = /x/;\n${OBJECT_DIVISION}\n${DETAIL_CALL}\n`;
+ const keywordFirst = `const yield = 12; const count = yield/2; const re = /x/;\n${OBJECT_DIVISION}\n${DETAIL_CALL}\n`;
assert.deepStrictEqual(strayPageRefs(keywordFirst).map((r) => [r.frontier.kind, r.frontier.line]), [['keyword', 1]]);
- const braceFirst = `${OBJECT_DIVISION}\nconst of = 12; const count = of/2; const re = /x/;\n${DETAIL_CALL}\n`;
+ const braceFirst = `${OBJECT_DIVISION}\nconst yield = 12; const count = yield/2; const re = /x/;\n${DETAIL_CALL}\n`;
assert.deepStrictEqual(strayPageRefs(braceFirst).map((r) => [r.frontier.kind, r.frontier.line]), [['brace', 1]]);
});
@@ -1893,7 +1893,7 @@ test('only what lies at or after the earliest frontier is distrusted, and the ea
const FRONTIER_SNIPPETS = {
brace: OBJECT_DIVISION,
paren: `if (true /*${'x'.repeat(2100)}*/) /abc/.test(text);`,
- keyword: 'const of = 12; const count = of/2; const re = /x/;',
+ keyword: 'const yield = 12; const count = yield/2; const re = /x/;',
angle: 'const half = total as Types . Alias<number> / 2; const re = /x/;',
identifier: 'var Al\\u0069as = 12;',
operator: 'const m = [.../a/.exec("a")]; const n = /b/;',
diff --git a/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.js b/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.js
index 0ae1a648d..2b2264131 100644
--- a/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.js
+++ b/plugins/model-apps/scripts/tests/pages-lock-dead-owner.test.js
@@ -9,9 +9,10 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { acquireAppPagesLease } = require('../lib/sdk-build.js');
-const { ownerStamp } = require('../lib/process-owner.js');
+const { ownerStamp, probeProcess } = require('../lib/process-owner.js');
const { sha256 } = require('../lib/hash.js');
const { startTarget, tempEnv, privateTempRoot, deadPid, removeWhenTestEnds } = require('./helpers/kill-target-client.js');
+const { deletedWhileOpen, deletedNamesLinger } = require('./helpers/delete-pending.js');
const APP = 'contoso_app';
const workspace = (t) => {
@@ -219,8 +220,217 @@ test('a workspace that cannot be written is that error, as it always was — not
assert.throws(() => acquireAppPagesLease(blocked, APP), (e) => !(e && e.code === 'pages-locked') && e.code === 'UNSAFE_OUTPUT' && e.reason === 'not-directory', 'the file system\'s own problem');
});
+// A name another build is deleting while a third process still has it open — a build reading the lock to judge its owner — lingers on Windows under
+// Node 20 until that handle closes, and every look at it and every create of it fails with EPERM meanwhile (helpers/delete-pending.js). That is the
+// moment a release or a take-over ends: another build holds the lock, or has just held it, and a build that finds the name so is refused as by a
+// held lock — not stopped with a file-safety error or a raw EPERM. Under Node 22, and on Linux and macOS, the delete removes the name at once: the same
+// steps leave no name, and each test says what a build then finds. A refusal for a name Windows could not inspect names THAT name — the claim, when it
+// is the claim — and adds why it may outlast every build: the same EPERM is what a file this user may not read answers.
+const UNINSPECTABLE = (name) => ` Windows could not inspect ${name} (EPERM): another build may be removing it, or this user may not have access to it. If this refusal persists while no build is running, check that file's access, or remove it.`;
+const refusedUninspectable = (name) => (e) => {
+ assert.strictEqual(e && e.code, 'pages-locked', String(e && e.stack));
+ assert.strictEqual(e.message, REFUSAL(name) + UNINSPECTABLE(name));
+ return true;
+};
+const refusedNotError = (lock) => (e) => {
+ assert.strictEqual(e && e.code, 'pages-locked', String(e && e.stack));
+ return refused(lock)(e);
+};
+
+test('a claim another build is deleting as its take-over ends, while a third still has it open, is a lock in use: refused, naming the claim where it lingers — the lock untouched', (t) => {
+ const dir = workspace(t);
+ const lingers = deletedNamesLinger(dir);
+ const mine = acquireAppPagesLease(dir, APP);
+ const held = fs.readFileSync(canonicalFile(dir), 'utf8');
+ const claimName = `${canonicalFile(dir)}.reclaim`;
+ const claim = deletedWhileOpen(claimName, JSON.stringify({ pid: process.pid, at: Date.now(), rnd: 'taking-over' }));
+ try {
+ // Where it lingers the claim is what could not be inspected; where it does not, the live lock refuses as it always has.
+ assert.throws(() => acquireAppPagesLease(dir, APP), lingers ? refusedUninspectable(claimName) : refusedNotError(canonicalFile(dir)), `names deleted while open linger here: ${lingers}`);
+ } finally {
+ claim.close();
+ }
+ assert.strictEqual(fs.readFileSync(canonicalFile(dir), 'utf8'), held, 'the lock is as it was');
+ mine.release();
+ assert.deepStrictEqual(fs.readdirSync(dir), [], 'released, and the claim is gone with its last handle');
+});
+
+test('a lock another build is deleting as it lets go, while a third still has it open, is refused where its name lingers, and free where it does not — never a file-safety error', (t) => {
+ const dir = workspace(t);
+ const lingers = deletedNamesLinger(dir);
+ const lock = deletedWhileOpen(canonicalFile(dir), JSON.stringify({ ...ownerStamp(), rnd: 'letting-go' }));
+ try {
+ if (lingers) assert.throws(() => acquireAppPagesLease(dir, APP), refusedUninspectable(canonicalFile(dir)));
+ else acquireAppPagesLease(dir, APP).release();
+ } finally {
+ lock.close();
+ }
+ assert.deepStrictEqual(fs.readdirSync(dir), [], 'nothing is left once the last handle is closed');
+ acquireAppPagesLease(dir, APP).release();
+});
+
+test('a lock that starts being deleted between a build\'s look and its create is refused where its name lingers, and taken where it does not — never the create\'s raw EPERM', (t) => {
+ const dir = workspace(t);
+ const lingers = deletedNamesLinger(dir);
+ const real = fs.writeFileSync;
+ let letGo = null;
+ // Another build lets go of the lock just after this one found the name free, while a third still reads it: the create meets the lingering name.
+ t.mock.method(fs, 'writeFileSync', function writeFileSync(file, data, opts) {
+ if (!letGo && file === canonicalFile(dir) && opts && opts.flag === 'wx') {
+ letGo = 'starting';
+ letGo = deletedWhileOpen(file, JSON.stringify({ ...ownerStamp(), rnd: 'letting-go' }));
+ }
+ return real.call(this, file, data, opts);
+ });
+ try {
+ if (lingers) assert.throws(() => acquireAppPagesLease(dir, APP), refusedUninspectable(canonicalFile(dir)));
+ else acquireAppPagesLease(dir, APP).release();
+ } finally {
+ if (letGo && letGo.close) letGo.close();
+ }
+ assert.ok(letGo, 'control: the create met the name being deleted');
+ t.mock.restoreAll();
+ assert.deepStrictEqual(fs.readdirSync(dir), []);
+});
+
+test('a create that fails with EPERM while nothing is at the lock\'s name is that error, as it always was — a folder this user cannot write in is not another build', (t) => {
+ const dir = workspace(t);
+ const real = fs.writeFileSync;
+ t.mock.method(fs, 'writeFileSync', function writeFileSync(file, data, opts) {
+ if (file === canonicalFile(dir) && opts && opts.flag === 'wx') throw Object.assign(new Error(`EPERM: operation not permitted, open '${file}'`), { code: 'EPERM' });
+ return real.call(this, file, data, opts);
+ });
+ assert.throws(() => acquireAppPagesLease(dir, APP), (e) => e && e.code === 'EPERM', 'the create\'s own error');
+ t.mock.restoreAll();
+ assert.deepStrictEqual(fs.readdirSync(dir), []);
+});
+
+test('on Windows a create that failed with EPERM while the name was being deleted, and finds it gone, is tried once more and takes the free lock; elsewhere it is that error', (t) => {
+ const dir = workspace(t);
+ const real = fs.writeFileSync;
+ let failed = 0;
+ // The deletion finished between the failed create and the look at the name: nothing lingers by the time the build looks.
+ t.mock.method(fs, 'writeFileSync', function writeFileSync(file, data, opts) {
+ if (file === canonicalFile(dir) && opts && opts.flag === 'wx' && failed === 0) {
+ failed += 1;
+ throw Object.assign(new Error(`EPERM: operation not permitted, open '${file}'`), { code: 'EPERM' });
+ }
+ return real.call(this, file, data, opts);
+ });
+ if (process.platform === 'win32') {
+ const lease = acquireAppPagesLease(dir, APP);
+ assert.strictEqual(JSON.parse(fs.readFileSync(canonicalFile(dir), 'utf8')).pid, process.pid, 'taken on the second try');
+ lease.release();
+ } else {
+ assert.throws(() => acquireAppPagesLease(dir, APP), (e) => e && e.code === 'EPERM', 'as it always was');
+ }
+ assert.strictEqual(failed, 1);
+ t.mock.restoreAll();
+ assert.deepStrictEqual(fs.readdirSync(dir), []);
+});
+
+test('a link or a junction at the lock\'s name or at its claim\'s is still refused as the file system problem it is, and nothing is written through it', (t) => {
+ for (const at of ['lock', 'claim']) {
+ const dir = workspace(t);
+ const elsewhere = path.join(dir, 'elsewhere');
+ fs.mkdirSync(elsewhere);
+ const name = at === 'lock' ? canonicalFile(dir) : `${canonicalFile(dir)}.reclaim`;
+ // A junction on Windows, which needs no privilege; the type is ignored elsewhere, where it is a symbolic link to the folder.
+ fs.symlinkSync(elsewhere, name, 'junction');
+ assert.throws(() => acquireAppPagesLease(dir, APP), (e) => {
+ assert.strictEqual(e && e.code, 'UNSAFE_OUTPUT', `${at}: ${String(e && e.stack)}`);
+ assert.strictEqual(e.reason, 'link', at);
+ return true;
+ });
+ assert.deepStrictEqual(fs.readdirSync(elsewhere), [], `${at}: nothing was written through it`);
+ assert.deepStrictEqual(fs.readdirSync(dir).sort(), ['elsewhere', path.basename(name)].sort(), `${at}: nothing was taken or left`);
+ }
+});
+
+// The access-denied side of the same EPERM: a claim this user may not read, while no build runs at all. Under Node 20 Windows cannot inspect it, and
+// the refusal must name the claim and say to check its access — waiting cannot cure it, and the lock it would otherwise name is not even there. Under
+// Node 22 lstat is allowed for this ACL (only reading is denied), so the claim is inspected, is a plain file, and the free lock is taken. The deny is a
+// real ACL on a file this test made, and is lifted again before the folder is removed.
+test('on Windows, a claim this user may not read is refused as pages-locked and build-locked naming that claim and its access, where it cannot be inspected', { skip: process.platform !== 'win32' && 'needs Windows ACLs' }, async (t) => {
+ const { execFileSync } = require('node:child_process');
+ const { withAppBuildLease } = require('../lib/app-operation-lease.js');
+ // Both tools by absolute path (helpers/windows-system-tools.js): by name alone, a machine with Git's tools on PATH — the GitHub-hosted
+ // Windows runners are one — runs Git's GNU `whoami`, which rejects `/user`.
+ const { systemTool } = require('./helpers/windows-system-tools.js');
+ // "<domain>\<user>","S-1-5-21-…": the SID is the last quoted field.
+ const sid = /"(S-[\d-]+)"\s*$/.exec(execFileSync(systemTool('whoami'), ['/user', '/fo', 'csv', '/nh'], { encoding: 'utf8' }).trim())[1];
+ const icacls = (...args) => execFileSync(systemTool('icacls'), args, { stdio: 'ignore' });
+ const buildFile = (dir) => path.join(dir, `app-build.${sha256(APP.toLowerCase())}.lock`);
+ const BUILD_REFUSAL = (name) => `another build may be applying '${APP}' in this workspace — refusing a second concurrent apply (would risk duplicate creation). Re-run the same command after it finishes. If no build using this workspace is running, inspect ${name} and remove it only if it is abandoned; keep the workspace and its recovery records.`;
+ for (const kind of ['pages', 'build']) {
+ const dir = workspace(t);
+ const lock = kind === 'pages' ? canonicalFile(dir) : buildFile(dir);
+ const claim = `${lock}.reclaim`;
+ fs.writeFileSync(claim, '{}');
+ icacls(claim, '/deny', `*${sid}:(R)`);
+ try {
+ let look = 'inspected';
+ try { fs.lstatSync(claim); } catch (e) { look = e.code; }
+ const take = kind === 'pages'
+ ? async () => acquireAppPagesLease(dir, APP).release()
+ : () => withAppBuildLease({ workspaceDir: dir, appUniqueName: APP }, async () => {});
+ if (look === 'EPERM') {
+ await assert.rejects(take(), (e) => {
+ assert.strictEqual(e && e.code, `${kind}-locked`, `${kind}: ${String(e && e.stack)}`);
+ assert.strictEqual(e.message, (kind === 'pages' ? REFUSAL(claim) : BUILD_REFUSAL(claim)) + UNINSPECTABLE(claim), kind);
+ return true;
+ });
+ assert.ok(!fs.existsSync(lock), `${kind}: no lock was taken`);
+ } else {
+ assert.strictEqual(look, 'inspected', `${kind}: an lstat that fails otherwise is not this case`);
+ await take();
+ assert.ok(!fs.existsSync(lock), `${kind}: taken and released`);
+ }
+ } finally {
+ icacls(claim, '/remove:d', `*${sid}`);
+ }
+ assert.strictEqual(fs.readFileSync(claim, 'utf8'), '{}', `${kind}: the claim is untouched`);
+ }
+});
+
+test('a lock or claim name that cannot be inspected for another reason than EPERM is the file-safety error it always was; EPERM is a refusal on Windows only', (t) => {
+ const real = fs.lstatSync;
+ for (const code of ['EACCES', 'EIO', 'EPERM']) {
+ for (const at of ['lock', 'claim']) {
+ const dir = workspace(t);
+ const name = at === 'lock' ? canonicalFile(dir) : `${canonicalFile(dir)}.reclaim`;
+ t.mock.method(fs, 'lstatSync', function lstatSync(p, ...rest) {
+ if (path.resolve(String(p)) === name) throw Object.assign(new Error(`${code}: lstat '${p}'`), { code });
+ return real.call(this, p, ...rest);
+ });
+ try {
+ if (code === 'EPERM' && process.platform === 'win32') {
+ assert.throws(() => acquireAppPagesLease(dir, APP), refusedUninspectable(name), `${code} at the ${at}`);
+ } else {
+ assert.throws(() => acquireAppPagesLease(dir, APP), (e) => {
+ assert.strictEqual(e && e.code, 'UNSAFE_OUTPUT', `${code} at the ${at}: ${String(e && e.stack)}`);
+ assert.strictEqual(e.reason, 'uninspectable');
+ assert.strictEqual(e.message, `refusing to write ${name}: it could not be inspected (${code})`);
+ return true;
+ });
+ }
+ } finally {
+ t.mock.restoreAll();
+ }
+ assert.deepStrictEqual(fs.readdirSync(dir), [], `${code} at the ${at}: nothing was taken or left`);
+ }
+ }
+});
+
// Several builds that start at once, and each finds the lock: not there at all, or left by a build that was killed. Exactly one of them takes it.
-for (const [what, killedFirst] of [['no lock at all', false], ['the lock of a killed build', true]]) {
+//
+// The build is killed only once every racer has started and loaded the module, and the gate opens at once after it. Windows hands a pid that is
+// free again to a new process after a while when the machine starts many processes (measured on a loaded machine: from about 8 s after the kill
+// at ~90 process starts a second), and then the killed build's lock names a pid that RUNS: process-owner.js cannot tell it from the build, so
+// every racer keeps the lock and is refused — the safe answer, pinned by the next test. Killed before the racers started, the build's
+// pid stayed free for as long as four processes took to start, which on a loaded machine is seconds: one whole-suite run saw all four refused.
+// Killed last, the pid is free only for the milliseconds the race takes, and no racer can be the process that gets it: each was running before.
+for (const [what, holderFate] of [['no lock at all', 'none'], ['the lock of a killed build', 'killed']]) {
test(`REAL PROCESSES racing for the lock — ${what}: exactly one takes it, the others are refused, and nothing is left but the lock`, async (t) => {
const RACERS = 4;
const ROUNDS = 3;
@@ -228,19 +438,24 @@ for (const [what, killedFirst] of [['no lock at all', false], ['the lock of a ki
for (let round = 1; round <= ROUNDS; round += 1) {
const dir = fs.mkdtempSync(path.join(root, 'ws-'));
const app = `race_${round}`;
- if (killedFirst) {
- const holder = startTarget(t, ['lock', dir, app], { env: tempEnv(root) });
+ let holder = null;
+ if (holderFate === 'killed') {
+ holder = startTarget(t, ['lock', dir, app], { env: tempEnv(root) });
await holder.waitFor(/^held$/);
- await holder.kill();
- assert.ok(fs.existsSync(lockFile(dir, app)));
}
const gate = path.join(root, `gate-${round}`);
const racers = Array.from({ length: RACERS }, () => startTarget(t, ['lock', dir, app, gate], { env: tempEnv(root) }));
await Promise.all(racers.map((racer) => racer.waitFor(/^ready$/)));
+ if (holder) {
+ await holder.kill();
+ assert.ok(fs.existsSync(lockFile(dir, app)));
+ }
fs.writeFileSync(gate, '');
const answers = await Promise.all(racers.map((racer) => racer.waitFor(/^(held|refused .*)$/)));
const winners = racers.filter((racer, i) => answers[i] === 'held');
- assert.strictEqual(winners.length, 1, `round ${round}: one winner, got ${JSON.stringify(answers)}`);
+ // Should the killed build's pid run again all the same, the failure says so: that refusal is the rule for a running pid, not a lost race.
+ const pidAgain = holder && probeProcess(holder.pid) !== 'gone' ? ` — the killed build's pid ${holder.pid} is a running process's again` : '';
+ assert.strictEqual(winners.length, 1, `round ${round}: one winner, got ${JSON.stringify(answers)}${pidAgain}`);
assert.ok(answers.filter((a) => a !== 'held').every((a) => a === 'refused pages-locked'), `round ${round}: the others are refused: ${JSON.stringify(answers)}`);
assert.strictEqual(JSON.parse(fs.readFileSync(lockFile(dir, app), 'utf8')).pid, winners[0].pid, `round ${round}: the lock names the winner`);
assert.strictEqual(JSON.parse(fs.readFileSync(canonicalFile(dir, app), 'utf8')).pid, winners[0].pid, `round ${round}: both of its files`);
@@ -249,3 +464,23 @@ for (const [what, killedFirst] of [['no lock at all', false], ['the lock of a ki
}
});
}
+
+// What every racer sees when a killed build's pid has been handed to another process: a lock whose pid runs. The build here is simply not killed.
+// None of them takes it — not one, however many race — and the lock is as it was: a pid that runs is never proven gone (process-owner.js).
+test('REAL PROCESSES racing for the lock of a build whose pid runs — what a killed build\'s lock is once its pid is another process\'s: every one is refused, and the lock is untouched', async (t) => {
+ const root = privateTempRoot(t);
+ const dir = fs.mkdtempSync(path.join(root, 'ws-'));
+ const app = 'race_running';
+ const holder = startTarget(t, ['lock', dir, app], { env: tempEnv(root) });
+ await holder.waitFor(/^held$/);
+ const held = [fs.readFileSync(lockFile(dir, app), 'utf8'), fs.readFileSync(canonicalFile(dir, app), 'utf8')];
+ const gate = path.join(root, 'gate');
+ const racers = Array.from({ length: 4 }, () => startTarget(t, ['lock', dir, app, gate], { env: tempEnv(root) }));
+ await Promise.all(racers.map((racer) => racer.waitFor(/^ready$/)));
+ fs.writeFileSync(gate, '');
+ const answers = await Promise.all(racers.map((racer) => racer.waitFor(/^(held|refused .*)$/)));
+ assert.deepStrictEqual(answers, Array(4).fill('refused pages-locked'), 'no winner: a pid that runs keeps its lock');
+ assert.deepStrictEqual([fs.readFileSync(lockFile(dir, app), 'utf8'), fs.readFileSync(canonicalFile(dir, app), 'utf8')], held, 'both files are as the build left them');
+ assert.deepStrictEqual(fs.readdirSync(dir).sort(), [path.basename(canonicalFile(dir, app)), `pages-${app}.lock`].sort(), 'no claim or other file is left');
+ await Promise.all([holder, ...racers].map((target) => target.kill()));
+});
diff --git a/plugins/model-apps/scripts/tests/parser-check.test.js b/plugins/model-apps/scripts/tests/parser-check.test.js
index 838546f56..8a3314e16 100644
--- a/plugins/model-apps/scripts/tests/parser-check.test.js
+++ b/plugins/model-apps/scripts/tests/parser-check.test.js
@@ -18,7 +18,7 @@ const { execFileSync } = require('node:child_process');
const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets } = require('../lib/source-literals.js');
const { typescriptViews, guessedPageViews, setParserCheck } = require('../lib/typescript-views.js');
const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');
-const { resolvePageRefs, strayPageRefs, navigationFrontier } = require('../lib/pageref-resolver.js');
+const { resolvePageRefs, strayPageRefs, navigationFrontier, navReferencedKeys } = require('../lib/pageref-resolver.js');
const { pageStructureProblems } = require('../lib/page-structure.js');
const { validPages, heldOpenLinePages, NAVIGATION_CALL } = require('./helpers/valid-pages.js');
const { loadBabelOracle } = require('./helpers/typescript-oracle.js');
@@ -361,6 +361,49 @@ test('parser check: a page the lexer misreads, resolved as TypeScript parses it,
}
});
+// `of` after a binding that ends where the lexer reads no word — a letter beyond ASCII, TypeScript's non-null `!`, any type after `as` or
+// `satisfies` — is the keyword of a for head, so what follows it is a regex. The lexer reads it so and says it guessed, and the parser check, asked there,
+// finds the regex too: the call written inside it is data, which no build may rewrite, and a real call after it still resolves where the parse vouches for the page.
+test('parser check: a regex after "of" in a for head whose binding the lexer cannot read to its end is data, and is never rewritten', () => {
+ const regex = '/navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})/';
+ const real = 'navigateTo({ pageType: "generative", pageId: "PAGEREF_detail" });';
+ for (const binding of ['const π', 'x!', 'x as Array<T>', 'x satisfies Array<T>', 'x as "a"', 'x as `a${string}`', 'x as void', 'x as enum', 'x satisfies enum']) {
+ for (const eol of ['\n', '\r\n']) {
+ const code = `export default function P() {${eol}let x; for (${binding} of ${regex}.source) {}${eol}return null;${eol}}${eol}`;
+ assert.equal(parses(code).parseDiagnostics.length, 0, `TypeScript parses ${binding}`);
+ assert.ok(guesses(code).has('keyword'), `${binding}: the lexer guesses`);
+ assert.deepEqual(navReferencedKeys(code), [], `${binding}: a regex is no navigation call`);
+ assert.equal(resolvePageRefs(new Map([['page', { code }]]), new Map([['detail', ID]])).deployment.get('page'), code, `${binding}: nothing is rewritten`);
+ const withCall = code.replace('return null;', `${real}${eol}return null;`);
+ const result = resolvePageRefs(new Map([['page', { code: withCall }]]), new Map([['detail', ID]]));
+ // `enum` is a reserved word used as a type's name, a page the parser check vouches for nothing in (typescript-views), so the lexer's guess
+ // stands: the build rewrites neither the call nor the regex, and reports both tokens as held.
+ if (binding.endsWith('enum')) {
+ assert.equal(result.deployment.get('page'), withCall, `${binding}: nothing is rewritten`);
+ assert.equal(result.residual.length, 2, `${binding}: both tokens are held`);
+ continue;
+ }
+ assert.equal(result.deployment.get('page'), withCall.replace(real, real.replace('PAGEREF_detail', ID)), `${binding}: the real call resolves, and the regex is kept`);
+ }
+ }
+});
+
+// A number that ends in a decimal point ends its statement at a line break, so a `for` on the next line heads a loop, though a dot stands before it:
+// the `of` in that head is the keyword, and what follows it is a regex. The lexer reads it so and says it guessed, and the call written inside the
+// regex is data, which no build may rewrite, whether the parser check is asked or not.
+test('parser check: a regex after "of" in a for head that follows a number ending in a decimal point is data, and is never rewritten', () => {
+ const regex = '/navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})/';
+ for (const head of ['for', 'for await']) {
+ for (const eol of ['\n', '\r\n']) {
+ const code = `export default async function P() {${eol}const n = 1.${eol}${head} (const x of ${regex}.source) {}${eol}return n;${eol}}${eol}`;
+ assert.equal(parses(code).parseDiagnostics.length, 0, `TypeScript parses ${head}`);
+ assert.ok(guesses(code).has('keyword'), `${head}: the lexer guesses`);
+ assert.deepEqual(navReferencedKeys(code), [], `${head}: a regex is no navigation call`);
+ assert.equal(resolvePageRefs(new Map([['page', { code }]]), new Map([['detail', ID]])).deployment.get('page'), code, `${head}: nothing is rewritten`);
+ }
+ }
+});
+
test('parser check: the views of a text are kept for the next check of the same text, and the lexer\'s own tests can turn the parser off', () => {
// The views are kept for the last few texts asked about: the oracle reads a page several times per build (resolve, stray, residual).
const code = WRAP('interface Api { <U>(x: U): U; }');
diff --git a/plugins/model-apps/scripts/tests/source-literals.test.js b/plugins/model-apps/scripts/tests/source-literals.test.js
index 260d252c9..0cab87e63 100644
--- a/plugins/model-apps/scripts/tests/source-literals.test.js
+++ b/plugins/model-apps/scripts/tests/source-literals.test.js
@@ -9,7 +9,7 @@ const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
-const { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, scanTemplateExpressionEnd, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS } = require('../lib/source-literals.js');
+const { blankLiterals, ofTakesOperand, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, scanTemplateExpressionEnd, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS } = require('../lib/source-literals.js');
const { navReferencedKeys, strayPageRefs, resolvePageRefs } = require('../lib/pageref-resolver.js');
const { pageStructureProblems } = require('../lib/page-structure.js');
// These tests hold the lexer to its own rules — what it reads for certain, what it reports as a guess, and what a guess costs a page — so they read pages with
@@ -1920,24 +1920,170 @@ test('ambiguity paren: a "/" or "<" after a ")" whose "(" is out of reach is hea
]);
});
-// `of`, `await` and `yield` are keywords where a regex may follow and names where a division does; `type`, `get`, `async`, `as` … are keywords
+// `await` and `yield` are keywords where a regex may follow and names where a division does; `type`, `get`, `async`, `as` … are keywords
// in a declaration or an assertion and names anywhere else. Which one it is depends on the grammar around it.
-// const of = 12; const count = of/2; const re = /\/*$/;
+// const yield = 12; const count = yield/2; const re = /\/*$/;
+// `of` is one too, but only in a `for` head, which the lexer finds: anywhere else it is a name for certain (the test after this one).
const CONTEXTUAL_WORDS = ['of', 'await', 'yield', 'let', 'async', 'static', 'get', 'set', 'as', 'satisfies', 'type', 'from', 'declare', 'abstract', 'readonly',
'keyof', 'infer', 'is', 'asserts', 'override', 'accessor', 'using', 'out', 'module', 'namespace', 'global', 'unique', 'implements'];
test('ambiguity keyword: a "/" or "<" after a word that is a keyword in some places and a name in others', () => {
- for (const word of CONTEXTUAL_WORDS) {
+ for (const word of CONTEXTUAL_WORDS.filter((w) => w !== 'of')) {
assertAmbiguous('keyword', [[`var ${word} = 12; var count = ${word}/2; var re = /x/;`, '/2; var re']]);
}
// A `<` after `async` on its line is code, whatever follows it (the next test). After a line break `async` is a name, and what follows is a guess unless it cannot be an element:
// `<T,>(x: T) => x` cannot, and is code there as everywhere.
- assertAmbiguous('keyword', [['const f = async\n<T extends X>text</T>;', '<T extends X>'], ['const f = async\n<div>x</div>;', '<div>'], ['const c = of/2; const re = /\\/*$/;', '/2; const re']]);
+ assertAmbiguous('keyword', [['const f = async\n<T extends X>text</T>;', '<T extends X>'], ['const f = async\n<div>x</div>;', '<div>'], ['const c = yield/2; const re = /\\/*$/;', '/2; const re']]);
assertCertain([
'a.of / 2 / 3', 'obj?.get / 2 / 3', 'a.type / 2 / 3', 'ofx / 2 / 3', 'typeofx / 2 / 3', 'return /x/.test(s)', 'typeof /x/.test(s)', 'x = new /x/', 'a = await_ / 2 / 3',
'const f = (x) => x < 3;',
]);
});
+// `of` is the keyword in one place only: right after what the head of a `for (… of …)` or `for await (… of …)` binds (TypeScript's
+// parseForOrForInOrForOfStatement, https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts). Outside every for head it is a name,
+// for certain, so a `/` after it divides and a `<` compares or opens type arguments. Read as the keyword, `type of<T> = T;` opened an element
+// at `<T>` whose text ran on over the next statement, and `fn<of<List<() => Row>>>()` one at `<of` whose type arguments the lexer could only guess.
+// The word is outside every for head when the nearest bracket left open before it is a `[` or a `{`, a `(` that neither `for` nor `await` stands before, or none.
+test('"of" is a name outside a for head, for certain, and the keyword after what a for head binds', () => {
+ const names = [
+ 'type of<T> = T;\nconst x = fn<of<List<() => Row>>>();\n', 'import type { of } from "./t";\nconst x = fn<of<List<() => Row>>>();\n',
+ 'type of<T> = T;\nconst x = fn<of<List<Row>>>();\n', 'let v: Map<string, of<List<() => Row>>>;\n', 'const c = of < 2 && of / 2;',
+ 'for (const [a = of / 2] of xs) {}', 'for (const {a = of / 2 / 3} of xs) {}', 'for (const x of xs) of / 2 / 3;', 'for (const x of xs) { of / 2 / 3; }',
+ 'for (const x of xs.map(() => of / 2 / 3)) {}', 'for (const x of [of / 2 / 3]) {}', 'for (;;) of / 2 / 3;', 'if (of / 2 / 3) {}', 'x = {a: of / 2 / 3};', 'const e = <A x={of / 2 / 3}>{of / 2 / 3}</A>;', 'const y = x.of < y; const w = 1;',
+ ];
+ for (const code of names) assert.strictEqual(blankLiterals(code), code.replace('"./t"', '" "'), `nothing but the string is blanked: ${JSON.stringify(code)}`);
+ assertCertain([...names, 'const of = 12; const count = of/2; const re = /\\/*$/;', 'f(of / 2, /x/)', 'const t = `${of / 2 / 3}`; const r = /x/;',
+ 'const o = { of }; class C { of() { return /x/; } }']);
+ assert.ok(blankLiterals('const of = 12; const count = of/2; const re = /navigateTo/;').includes('count = of/2; const re = / /'), 'a division, then the regex');
+ // After what the head binds — a name, a member, a pattern — the keyword, as it always was: a regex or an element follows. A guess (`keyword`).
+ for (const code of [
+ 'for (const x of /navigateTo/.exec(s)) {}', 'for (x.y of /navigateTo/.exec(s)) {}', 'for (const [a, b] of /navigateTo/.exec(s)) {}',
+ 'async function f() { for await (const x of /navigateTo/.exec(s)) {} }', 'for (const x of <A>navigateTo</A>.props.items) {}',
+ ]) {
+ assert.ok(!blankLiterals(code).includes('navigateTo'), `read as a regex or an element: ${JSON.stringify(code)}`);
+ assertAmbiguous('keyword', [[code, code.includes('/navigateTo') ? '/navigateTo' : '<A>']]);
+ }
+});
+
+// Inside a for head nothing proves the word a name, whatever stands before it: a binding can end in a name the lexer reads no word of (a letter
+// beyond ASCII, a combining mark), in TypeScript's non-null `!`, or in any type after `as` or `satisfies` — `x as enum` included, which TypeScript
+// and Babel parse and a JSDoc typedef can even make check — and in each the `of` is the keyword. Read as a name there, the regex after it was code,
+// with no guess to say so, and the navigation oracle rewrote the call written inside it. So there, and where the scan cannot reach the bracket, the
+// lexer reads exactly as it did before it told a name from the keyword: the keyword, and a guess.
+test('"of" inside a for head, or past the reach of the scan, reads exactly as it did before the lexer told a name from the keyword', () => {
+ const regex = '/navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})/';
+ const bindings = ['const π', 'const café', 'let x\u0301', 'x!', 'obj.x!', 'obj[0]!', '(x)!', 'x as Array<T>', 'x as ns.Box<T>', 'x satisfies Array<T>',
+ 'x as "a"', 'x as `a${string}`', 'x as const', 'x as void', 'x satisfies void', 'x as enum', 'x satisfies enum', 'x as keyof enum', 'ąconst', `const x /*${'y'.repeat(2100)}*/`];
+ for (const binding of bindings) {
+ for (const eol of [' ', '\n', '\r\n']) {
+ for (const code of [`let x; for (${binding}${eol}of ${regex}.source) {}`, `async function f() { let x; for await (${binding}${eol}of <A>navigateTo</A>) {} }`]) {
+ assert.ok(!blankLiterals(code).includes('navigateTo'), `read as a regex or an element: ${JSON.stringify(code)}`);
+ assertAmbiguous('keyword', [[code, code.includes(regex) ? regex : '<A>']]);
+ }
+ }
+ }
+ // The reading of the lexer that took `of` for the keyword everywhere, recorded: the view and every guess, whatever stands before the word in the
+ // head — the `(`, `const`, an operator, a `;`, `in`, another `of` — and a head written with an escape.
+ const before = [
+ ['for (of of /navigateTo/.source) {}', 'for (of of / /.source) {}', [[11, 'keyword']]],
+ ['for (const of of /navigateTo/.source) {}', 'for (const of of / /.source) {}', [[17, 'keyword']]],
+ ['for (const x of of / 2 / 3) {}', 'for (const x of of / / 3) {}', [[19, 'keyword']]],
+ ['for (x as enum of /navigateTo/.source) {}', 'for (x as enum of / /.source) {}', [[18, 'keyword']]],
+ ['for (of = 1; of < 2; of++) {}', 'for (of = 1; of < 2; of++) {}', [[16, 'jsx-open']]],
+ ['for (a = of / 2 / 3;;) {}', 'for (a = of / / 3;;) {}', [[12, 'keyword']]],
+ ['for (;of / 2 / 3;) {}', 'for (;of / / 3;) {}', [[9, 'keyword']]],
+ ['for (const x in of / 2 / 3) {}', 'for (const x in of / / 3) {}', [[19, 'keyword']]],
+ ['for (x in of) /navigateTo/.test(k);', 'for (x in of) / /.test(k);', []],
+ ['for (const x of fn<of<T>>()) {}', 'for (const x of fn<of<T> {}', [[21, 'keyword']]],
+ ['f\\u006fr (x of /navigateTo/.source) {}', 'f\\u006fr (x of / /.source) {}', [[1, 'identifier'], [15, 'keyword']]],
+ ];
+ for (const [code, view, found] of before) {
+ assert.strictEqual(blankNonCodePreservingTemplateExpressions(code), view, JSON.stringify(code));
+ assert.deepStrictEqual(ambiguities(code), found, JSON.stringify(code));
+ }
+ // Past the reach of the scan the bracket is unknown, so a name outside every head is read so too.
+ const far = `/*${'y'.repeat(2100)}*/`;
+ for (const [code, end] of [[`const a = 1; ${far} of / 2 / 3; const r = /x/;`, ' of / / 3; const r = / /;'], [`f(${far} of / 2 / 3);`, ' of / / 3);']]) {
+ assert.ok(blankNonCodePreservingTemplateExpressions(code).endsWith(end), JSON.stringify(code.slice(-30)));
+ assertAmbiguous('keyword', [[code, '/ 2 / 3']]);
+ }
+});
+// A `(` after the word `for` or `await` is always a possible head, whatever stands before the word: a dot before it looks like a property
+// (`a.for(…)`), but it may be the decimal point of a number that ends the statement before, and a line break, a comment or a line separator between
+// them leaves the next statement a loop — `const n = 1.⏎for (const x of /re/.source)` is valid TypeScript, and its `of` is the keyword. Read
+// as a property there, the `of` was a name for certain, the regex after it code, and the navigation oracle rewrote the call written inside it.
+// So no exception to a head proves a name: such an `of` reads as it did before the lexer told a name from the keyword — the keyword, and a guess.
+test('"of" after a "(" that the word "for" or "await" stands before is the keyword and a guess, even where the word looks like a property', () => {
+ const regex = '/navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})/';
+ for (const number of ['1.', '0.', '1_000.', '1..x', '.5', '1e3', '0x1', '1n']) {
+ for (const sep of ['\n', '\r\n', '\u2028', '\u2029', '/*\n*/', '// c.\n']) {
+ for (const code of [`const n = ${number}${sep}for (const x of ${regex}.source) {}`,
+ `async function f() { const n = ${number}${sep}for await (const x of <A>navigateTo</A>) {} }`]) {
+ assert.ok(!blankLiterals(code).includes('navigateTo'), `read as a regex or an element: ${JSON.stringify(code)}`);
+ assertAmbiguous('keyword', [[code, code.includes(regex) ? regex : '<A>']]);
+ }
+ }
+ }
+ assertAmbiguous('keyword', ['a.for(of / 2 / 3);', 'a?.for(of / 2 / 3);', 'a . for (of / 2 / 3);', 'a.\nfor(of / 2 / 3);', 'x.await(of / 2 / 3);',
+ '({ for(a = of / 2 / 3) {} });', 'class C { for(a = of / 2 / 3) {} }', 'f(πfor(of / 2 / 3));'].map((code) => [code, '/ 2 / 3']));
+ // A `(` after any other word read whole, or after no word, is no head: a name, for certain.
+ assertCertain(['xfor(of / 2 / 3);', 'forx(of / 2 / 3);', '$for(of / 2 / 3);', 'awaitx(of / 2 / 3);', 'f(of / 2 / 3);', 'f()(of / 2 / 3);',
+ 'const n = 1.\nf(of / 2 / 3);', 'const n = 1.\n[of / 2 / 3];']);
+});
+
+// With the TypeScript parser oracle set: pages that put `of` before a regex, an element, a division or type arguments in and out of for and for-await heads, nested in brackets,
+// after tokens of every kind before the `for` or the `(` (numbers that end in a decimal point, strings, templates, a regex, a member dot, a
+// non-ASCII or escaped name, comments, line breaks and line separators, a label), at the top and in an async generator. Wherever the lexer's rule
+// says an `of` is a name for certain, TypeScript does not read it as the keyword of a for-of statement, and every for-of keyword before a `/` or a
+// `<` is read with a guess at it or before it.
+test('oracle: an "of" that the lexer calls a name for certain is never the keyword of a for-of statement, wherever it stands', (t) => {
+ const ts = loadTypescriptOracle();
+ if (!ts) { t.skip('TYPESCRIPT_ORACLE_PATH is not set'); return; }
+ const contexts = ['for (const x @) {}', 'for (x! @) {}', 'for (x as enum @) {}', 'for (const π @) {}', 'for /* c */ (const x @) {}', 'for await (const x @) {}',
+ 'for (const [a = @] of xs) {}', 'for (a = @;;) {}', 'for (const x of f(@)) {}', 'for(@);', 'f(@);', '[@];', 'x = {a: @};', 'a.for(@);', 'x.await(@);',
+ 'const v = @;'];
+ const prefixes = ['1.', '1..x', '.5', '0x1', '1n', '"s."', '`${a}`', '/a./g', 'a', 'π', 'a\\u0062', 'a.', 'a?.', '<B/>'];
+ const seps = ['', ' ', '\n', '\r\n', '\u2028', '/*\n*/', ';'];
+ let pages = 0;
+ let keywords = 0;
+ let names = 0;
+ for (const wrap of ['@@', 'async function* f() { L: { @@ } }']) {
+ for (const context of contexts) {
+ for (const prefix of prefixes) {
+ for (const sep of seps) {
+ for (const tail of ['/navigateTo/.source', '<A>navigateTo</A>', '/ 2', '<T>(x)']) {
+ const code = wrap.replace('@@', () => `const n = ${prefix}${sep}${context.replace('@', () => `of ${tail}`)}`);
+ const sf = ts.createSourceFile('page.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ if (sf.parseDiagnostics.length) continue;
+ pages += 1;
+ const forOf = new Set();
+ (function visit(node) {
+ if (ts.isForOfStatement(node)) forOf.add(ts.skipTrivia(code, node.initializer.end));
+ ts.forEachChild(node, visit);
+ })(sf);
+ const view = blankLiterals(code);
+ const found = ambiguities(code);
+ for (const word of code.matchAll(/(?<![\w$.\\])of(?![\w$])/g)) {
+ const at = word.index;
+ if (view.slice(at, at + 2) !== 'of' || ofTakesOperand(view, at + 1).operand) continue;
+ names += 1;
+ assert.ok(!forOf.has(at), `a name for certain where TypeScript reads the for-of keyword: ${JSON.stringify(code)} at ${at}`);
+ }
+ for (const at of forOf) {
+ const next = at + 2 + /^\s*/.exec(code.slice(at + 2))[0].length;
+ if (code[next] !== '/' && code[next] !== '<') continue;
+ keywords += 1;
+ assert.ok(found.some(([offset]) => offset <= next), `a for-of keyword read with no guess: ${JSON.stringify(code)} at ${at}`);
+ }
+ }
+ }
+ }
+ }
+ }
+ // The sweep reaches what it is for: pages TypeScript parses, for-of keywords before a regex or an element, and names the rule proves.
+ assert.ok(pages > 1000 && keywords > 500 && names > 500, JSON.stringify({ pages, keywords, names }));
+});
+
// `async` and a `<` on its line. TypeScript's rule for `.tsx` steps over `async` (parser.ts, isParenthesizedArrowFunctionExpressionWorker,
// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts): with no line break before the `<`, the next tokens decide — a comma, `=` or `extends` and a token that is not
// `=`, `>` or `/` — as they do for any `<`, and a generic shape is the head of an async generic arrow. Every other is no arrow, and `async` is then an ordinary token: a method named `async`
@@ -3044,7 +3190,7 @@ test('AMBIGUITY_KINDS names every kind the lexer reports, each with an example t
const examples = {
brace: 'const count = {valueOf(){return 12;}}/2; const half = total / 2;',
paren: `if (true /*${'x'.repeat(2100)}*/) /abc/.test(text);`,
- keyword: 'const of = 12; const count = of/2; const re = /x/;',
+ keyword: 'const yield = 12; const count = yield/2; const re = /x/;',
angle: 'const half = total as Types . Alias<number> / 2; const re = /x/;',
identifier: 'var Al\\u0069as = 12;',
operator: 'const m = [.../a/.exec("a")]; const n = /b/;',
@@ -3538,10 +3684,15 @@ test('every scan of the lexer reads U+0085 and the zero-width space as white spa
assert.ok(!maskOf(code).includes('navigateTo'), `the regex is data: ${visible(code)}`);
}
// A keyword before a `/` or a `<`: an expression starts. A name before one: it divides or compares.
- for (const word of ['return', 'typeof', 'throw', 'delete', 'void', 'in', 'of']) {
+ for (const word of ['return', 'typeof', 'throw', 'delete', 'void', 'in']) {
const code = `function f(x) { ${word}${c}/navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})/.test(s); }\n`;
assert.ok(!maskOf(code).includes('navigateTo'), `${word}: the regex is data: ${visible(code)}`);
}
+ // `of` is the keyword, and a guess, in a `for` head, and a name outside every one: it divides there, for certain.
+ const forOf = `for${c}(const${c}y${c}of${c}/navigateTo({pageType:"generative",pageId:"PAGEREF_detail"})/.exec(s)) {}\n`;
+ assert.ok(!maskOf(forOf).includes('navigateTo'), `of: the regex is data: ${visible(forOf)}`);
+ assertCertain([`function f(x) { const k = of${c}/ 2 / 3; }`, `f${c}(${c}of${c}/ 2 / 3);`]);
+ assertAmbiguous('keyword', [[`for${c}(;${c}of${c}/ 2 / 3;) {}`, '/ 2 / 3'], [`a${c}.${c}for${c}(${c}of${c}/ 2 / 3);`, '/ 2 / 3']]);
// A property named like a keyword is no keyword, with the `.` and the word apart: `obj.${c}return / 2 / 3` divides, with no regex.
assertCertain([`const k = obj.${c}return / 2 / 3;`, `const k = obj${c}.${c}new / 2 / 3;`, `const k = obj?.${c}delete / 2 / 3;`, `const k = a${c}+${c}b / 2 / 3;`]);
// `type`, `export` and `declare` before a type alias head, and a name with the white space between them.
diff --git a/plugins/model-apps/scripts/tests/temp-workspace.test.js b/plugins/model-apps/scripts/tests/temp-workspace.test.js
index 33c966571..82b19a63b 100644
--- a/plugins/model-apps/scripts/tests/temp-workspace.test.js
+++ b/plugins/model-apps/scripts/tests/temp-workspace.test.js
@@ -1312,6 +1312,60 @@ test('the answer about a folder is the answer about THAT folder: one that is rem
assert.strictEqual(asked.length, 2);
});
+// A folder another run has just made has the access list of the temp folder it is in until that run's icacls gives it one of its own (makeWindowsFolderPrivate). Where the temp folder lets others write —
+// `TEMP` on a data drive gives Authenticated Users "modify" — a run that judges the folder in between is told "no" about a folder that is private a moment later, with the same identity.
+const inheritedNo = { ok: false, inherited: true, reason: 'S-1-5-11 can add to it, remove from it or take it over' };
+
+test('(Windows) a run that judges the plugin\'s folder while the run that made it is still giving it its own access list is not refused the folder for good: that "no" is asked again, and every workspace of the run is made in the folder', (t) => {
+ const { deps } = tempRoot(t);
+ const parent = workspaceParent({ ...deps, uid: null });
+ // Run A makes the folder just before this run does (this run's mkdir answers EEXIST), and gives it its own list a moment later: during this run's first pause, or — if this run does not pause — before its next workspace.
+ let madeByA = false;
+ let protectedByA = false;
+ const racing = { ...fs, mkdirSync: (target, ...rest) => {
+ if (target === parent && !madeByA) { madeByA = true; fs.mkdirSync(parent); }
+ return fs.mkdirSync(target, ...rest);
+ } };
+ const asked = [];
+ const slept = [];
+ // The clock reads a moment after the folder was made (the file system's own creation time: a POSIX one may have none to give).
+ const runB = { ...deps, uid: null, fs: racing, owner: { now: () => (fs.existsSync(parent) ? fs.lstatSync(parent).birthtimeMs + 100 : Date.now()) },
+ folderPrivacy: () => { asked.push(protectedByA ? 'its own list' : 'inherited'); return protectedByA ? { ok: true, reason: 'private' } : inheritedNo; },
+ folderProtect: () => assert.fail('run B did not make the folder, and does not set its list'),
+ pause: (ms) => { slept.push(ms); protectedByA = true; } };
+ const made = [];
+ for (let i = 0; i < 6; i += 1) {
+ made.push(makeTempWorkspace('genpage-', runB));
+ protectedByA = true;
+ }
+ assert.deepStrictEqual(made.map((dir) => path.dirname(dir)), Array(6).fill(parent), 'every workspace of run B is made in the plugin\'s folder — none in the plain temp folder, unrecorded');
+ assert.ok(made.every((dir) => recordOfFolder(dir)), 'and recorded');
+ assert.deepStrictEqual([asked, slept], [['inherited', 'its own list'], [25]], 'the "no" about the inherited list was asked again after a pause; the "yes" is remembered');
+});
+
+test('(Windows) a "no" about a list that is still only inherited is asked again only while the folder is young: one its maker never made private is not used — every try is bounded — and once it is older than its maker could take, the "no" is final and remembered', (t) => {
+ const { root, deps } = tempRoot(t);
+ const parent = workspaceParent({ ...deps, uid: null });
+ fs.mkdirSync(parent); // made, and never given a list of its own: its maker was killed before its icacls ran
+ let now = fs.lstatSync(parent).birthtimeMs + 100; // a moment after it was made, by the file system's own clock
+ let asked = 0;
+ const slept = [];
+ const stuck = { ...deps, uid: null, owner: { now: () => now }, folderPrivacy: () => { asked += 1; return inheritedNo; }, pause: (ms) => slept.push(ms) };
+ const first = makeTempWorkspace('genpage-', stuck);
+ assert.strictEqual(path.dirname(first), root, 'not used: the plain temp folder');
+ assert.deepStrictEqual(fs.readdirSync(first), [], 'unrecorded, as before');
+ assert.deepStrictEqual([asked, slept], [6, [25, 50, 100, 200, 400]], 'asked MAKE_ATTEMPTS times, with the waits of a refusal of the moment');
+ assert.strictEqual(path.dirname(makeTempWorkspace('genpage-', stuck)), root);
+ assert.strictEqual(asked, 12, 'not refused for the life of the process: the next workspace asks again while the folder is young');
+ // Older than any maker's icacls could take (PROTECT_WINDOW_MS): the "no" is what it says.
+ now += 60000;
+ slept.length = 0;
+ assert.strictEqual(path.dirname(makeTempWorkspace('genpage-', stuck)), root);
+ assert.strictEqual(path.dirname(makeTempWorkspace('genpage-', stuck)), root);
+ assert.deepStrictEqual([asked, slept], [13, []], 'asked once, at once, and remembered: the forty-workspace run starts no more programs');
+ assert.deepStrictEqual(fs.readdirSync(parent), [], 'and nothing was made in it');
+});
+
// ---------------------------------------------------------------------------------------------------------------------
// A folder this process makes on Windows takes the access list of the temp folder it is in, and `mode` means nothing there — so it is given a list of its own before anything is put in it
// ---------------------------------------------------------------------------------------------------------------------
@@ -1371,6 +1425,117 @@ test('(Windows) a folder that cannot be made private is not used and not left: i
assert.deepStrictEqual(asked, [parent], 'a folder that was refused is not made, and set, again by this process: it costs programs, and the answer will not change');
});
+// A run, as another process has it: what a process remembers (its verdicts, the folders it refuses) is its own.
+function anotherRun() {
+ const file = require.resolve('../lib/temp-workspace.js');
+ const mine = require.cache[file];
+ delete require.cache[file];
+ try {
+ return require('../lib/temp-workspace.js');
+ } finally {
+ require.cache[file] = mine;
+ }
+}
+
+// THE FOLDER A FAILED MAKER LEAVES. Run A makes the plugin's folder and its icacls fails; run B, which found the folder a moment after A made it, is judging it — its hold is in it — so A's `rmdir`
+// is refused. A single `rmdir` left the folder for good: empty, with the temp folder's list, and every later run was told "no" about it once it was older than a maker could take. The maker waits
+// for the holds to go, and removes the folder it made; whatever it did not make, or anything but holds in it, it leaves.
+const holdOfB = `${HOLD_PREFIX}0a1b2c3d-4242-abcdef`;
+function failingMaker(deps, parent, { onProtect = () => fs.writeFileSync(path.join(parent, holdOfB), ''), onPause = () => {} } = {}) {
+ let now = 1000000;
+ const paused = [];
+ const run = { ...deps, uid: null, owner: { now: () => now },
+ folderProtect: () => { onProtect(); return { ok: false, reason: 'its access list could not be set (icacls could not be run)' }; },
+ pause: (ms) => { paused.push(ms); now += ms; onPause(paused.length); } };
+ return { run, paused };
+}
+
+test('(Windows) a folder its maker could not make private, while another run held it, is removed by the maker once that run lets go — and a later run makes, protects and uses a folder of its own instead of working outside it for good', (t) => {
+ const { root, deps } = tempRoot(t);
+ const parent = workspaceParent({ ...deps, uid: null });
+ // B judges the folder (holding it), is told "not yet", lets go and pauses: here, during A's third look.
+ const a = failingMaker(deps, parent, { onPause: (n) => { if (n === 3) fs.unlinkSync(path.join(parent, holdOfB)); } });
+ assert.strictEqual(path.dirname(anotherRun().makeTempWorkspace('genpage-', a.run)), root, 'run A, whose folder could not be made private, works in the plain temp folder, as before');
+ assert.ok(!fs.existsSync(parent), 'and the folder it made is not left behind: removed once B let go');
+ assert.deepStrictEqual(a.paused, [20, 20, 20], 'it looked again every REMOVE_PAUSE_MS until it could');
+ const asked = [];
+ const later = { ...deps, uid: null, owner: { now: () => (fs.existsSync(parent) ? fs.lstatSync(parent).birthtimeMs + 60000 : Date.now()) },
+ folderPrivacy: () => { asked.push('privacy'); return inheritedNo; },
+ folderProtect: (folder) => { asked.push('protect'); assert.deepStrictEqual(fs.readdirSync(folder), []); return { ok: true, reason: 'set, and read back' }; } };
+ const runC = anotherRun();
+ const made = [runC.makeTempWorkspace('genpage-', later), runC.makeTempWorkspace('genpage-', later)];
+ assert.deepStrictEqual(made.map((dir) => path.dirname(dir)), [parent, parent], 'a later run works in the plugin\'s folder — not in the plain temp folder, unrecorded');
+ assert.ok(made.every((dir) => recordOfFolder(dir)), 'and recorded');
+ assert.deepStrictEqual(asked, ['protect'], 'it made the folder, and gave it its own list');
+ // Windows refuses an rmdir with EPERM, not ENOTEMPTY, while a hold in the folder is being deleted: that is a moment, too.
+ const { root: root2, deps: deps2 } = tempRoot(t);
+ const parent2 = workspaceParent({ ...deps2, uid: null });
+ let refused = 0;
+ const b = failingMaker(deps2, parent2, { onProtect: () => {} });
+ b.run.fs = { ...fs, rmdirSync: (target, ...rest) => {
+ if (target === parent2 && refused < 2) { refused += 1; throw Object.assign(new Error(`EPERM: operation not permitted, rmdir '${target}'`), { code: 'EPERM' }); }
+ return fs.rmdirSync(target, ...rest);
+ } };
+ assert.strictEqual(path.dirname(anotherRun().makeTempWorkspace('genpage-', b.run)), root2);
+ assert.deepStrictEqual([fs.existsSync(parent2), b.paused], [false, [20, 20]], 'EPERM while a hold goes: looked again, and removed');
+});
+
+test('(Windows) a maker waiting to remove the folder it could not make private removes only that folder: one put in its place is left untouched, and so is a folder with anything but holds in it', (t) => {
+ // Renamed away during the wait, and an empty folder of someone else's put at the path: removing it would remove what this run did not make.
+ {
+ const { root, deps } = tempRoot(t);
+ const parent = workspaceParent({ ...deps, uid: null });
+ const away = path.join(root, 'moved-away');
+ let replacement = null;
+ const a = failingMaker(deps, parent, { onPause: (n) => { if (n === 2) { fs.renameSync(parent, away); fs.mkdirSync(parent); replacement = fs.lstatSync(parent); } } });
+ assert.strictEqual(path.dirname(anotherRun().makeTempWorkspace('genpage-', a.run)), root);
+ assert.deepStrictEqual(a.paused, [20, 20], 'it stopped at the first look after the swap');
+ const now = fs.lstatSync(parent);
+ assert.deepStrictEqual([now.isDirectory(), now.ino, now.birthtimeMs, fs.readdirSync(parent)], [true, replacement.ino, replacement.birthtimeMs, []], 'the replacement is there, untouched');
+ assert.deepStrictEqual(fs.readdirSync(away), [holdOfB], 'and the folder it made is where it was moved, as it was');
+ }
+ // Anything that is not a hold: it is in use, or not this run's to empty — not waited for, not touched.
+ for (const [what, put] of [
+ ['a workspace', (parent) => fs.mkdirSync(path.join(parent, `genpage-${deadPid()}-AbC123`))],
+ ['a file', (parent) => fs.writeFileSync(path.join(parent, 'notes.txt'), 'theirs')],
+ ['a folder named as a hold', (parent) => fs.mkdirSync(path.join(parent, `${HOLD_PREFIX}0a1b2c3d-4243-abcdef`))],
+ ['a hold, and a workspace', (parent) => { fs.writeFileSync(path.join(parent, holdOfB), ''); fs.mkdirSync(path.join(parent, `genpage-${deadPid()}-AbC123`)); }],
+ ]) {
+ const { root, deps } = tempRoot(t);
+ const parent = workspaceParent({ ...deps, uid: null });
+ const a = failingMaker(deps, parent, { onProtect: () => put(parent) });
+ assert.strictEqual(path.dirname(anotherRun().makeTempWorkspace('genpage-', a.run)), root, what);
+ const left = entriesOf(parent);
+ assert.deepStrictEqual([what, a.paused], [what, []], `${what}: not waited for`);
+ assert.ok(left.length > 0 && left.every((name) => fs.existsSync(path.join(parent, name))), `${what}: left as it was`);
+ }
+});
+
+test('(Windows) a maker waits for a hold that never goes for REMOVE_PATIENCE_MS at most: then the folder is left, as before, and the run works in the plain temp folder and does not try again', (t) => {
+ const { root, deps } = tempRoot(t);
+ const parent = workspaceParent({ ...deps, uid: null });
+ const a = failingMaker(deps, parent);
+ const runA = anotherRun();
+ assert.strictEqual(path.dirname(runA.makeTempWorkspace('genpage-', a.run)), root);
+ assert.deepStrictEqual([a.paused.length, a.paused.reduce((s, ms) => s + ms, 0)], [500, 10000], 'ten seconds of looks, twenty milliseconds apart');
+ assert.deepStrictEqual(fs.readdirSync(parent), [holdOfB], 'the folder is left, with the other run\'s hold in it, untouched');
+ assert.strictEqual(path.dirname(runA.makeTempWorkspace('genpage-', a.run)), root);
+ assert.strictEqual(a.paused.length, 500, 'refused for the rest of the process (NOT_PRIVATE), as before: it does not wait again');
+});
+
+test('(Windows) a run told "not yet" about a folder that another run is making private does not hold it while it pauses — so the maker, if its protection failed, can remove it meanwhile', (t) => {
+ const { deps } = tempRoot(t);
+ const parent = workspaceParent({ ...deps, uid: null });
+ fs.mkdirSync(parent);
+ const whileJudged = [];
+ const whilePaused = [];
+ const judge = { ...deps, uid: null, owner: { now: () => fs.lstatSync(parent).birthtimeMs + 100 },
+ folderPrivacy: () => { whileJudged.push(entriesOf(parent).length); return inheritedNo; },
+ pause: () => whilePaused.push(entriesOf(parent)) };
+ makeTempWorkspace('genpage-', judge);
+ assert.deepStrictEqual([whileJudged, whilePaused], [[1, 1, 1, 1, 1, 1], [[], [], [], [], []]], 'held while it is judged, and let go before every pause');
+});
+
test('(Windows) an access list that cannot be set for a moment — icacls cannot open a folder that Windows is removing — is asked again after a short wait, and the folder made again; one that keeps failing ends as a refusal', (t) => {
const unreadable = { ok: false, unreadable: true, reason: 'its access list could not be set (icacls /inheritance:r /grant:r)' };
const a = tempRoot(t);
diff --git a/plugins/model-apps/scripts/tests/verify-spec.test.js b/plugins/model-apps/scripts/tests/verify-spec.test.js
index 21679b6ab..f0aa3b668 100644
--- a/plugins/model-apps/scripts/tests/verify-spec.test.js
+++ b/plugins/model-apps/scripts/tests/verify-spec.test.js
@@ -484,7 +484,7 @@ test('verifySpec pages: a residual PAGEREF_ in deployed nav code FAILS the no-pa
// the lexer read only by guess proves no edge: after `of/2` it reads a regex up to the next `/`, and the `/*` inside it opens a comment that
// ends inside a string, so the string's text — here a navigation call to the target — is read as code.
test('verifySpec pages: an id in a call the lexer reads only by guess does not prove the nav edge', async () => {
- const forgery = ['const of = 12;', 'const count = of/2; const re = /\\/*$/;', `const note = "*/ navigateTo({pageType:'generative', pageId:'${GP_DETAIL}'}) /*";`, ''].join('\n');
+ const forgery = ['const of = 12;', 'for (const x of of/2 + "") {} const re = /\\/*$/;', `const note = "*/ navigateTo({pageType:'generative', pageId:'${GP_DETAIL}'}) /*";`, ''].join('\n');
const verify = async (code) => verifySpec(pageSpec(), pageRead({ sitemapIds: [GP_OVERVIEW, GP_DETAIL], existenceIds: [GP_OVERVIEW, GP_DETAIL], manifest: BOTH_MANIFEST, sitemap: SITEMAP_OK, code: { [GP_OVERVIEW]: code } }));
const forged = await verify(forgery);
assert.ok(forged.checks.some((c) => c.kind === 'page-nav' && c.name === 'Overview -> detail' && !c.present), 'the string is not a navigation');
diff --git a/plugins/model-apps/scripts/tests/windows-folder-acl.test.js b/plugins/model-apps/scripts/tests/windows-folder-acl.test.js
index 0d281abb4..3c263c116 100644
--- a/plugins/model-apps/scripts/tests/windows-folder-acl.test.js
+++ b/plugins/model-apps/scripts/tests/windows-folder-acl.test.js
@@ -193,6 +193,27 @@ test('windowsFolderIsPrivate: not private when anyone else can change the folder
assert.deepStrictEqual(fs.readdirSync(tmp), []);
});
+// A folder made in a temp folder that lets others write takes their entries until its maker gives it its own list (makeWindowsFolderPrivate): a caller may ask again about that "no" (lib/temp-workspace.js).
+test('windowsFolderIsPrivate: a "no" about a list that is still only what the folder took from the one above — not protected, every entry inherited — says so (`inherited`); a "no" about a list anyone set does not', (t) => {
+ const tmp = scratchTemp(t);
+ const verdictFor = (sddl) => windowsFolderIsPrivate('C:\\Temp\\p', { run: fakeWindows({ sddl }).run, saveIn: tmp });
+ // What a folder made in a temp folder on a data drive has until its maker gives it its own list: Authenticated Users may modify it, by inheritance.
+ const asMade = verdictFor(`D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;ID;0x1301bf;;;AU)(A;OICIIOID;SDGXGWGR;;;AU)(A;OICIID;FA;;;${USER})`);
+ assert.deepStrictEqual([asMade.ok, asMade.inherited], [false, true], asMade.reason);
+ assert.match(asMade.reason, /S-1-5-11/);
+ for (const [sddl, why] of [
+ [`D:AI(A;OICI;0x1301bf;;;AU)(A;OICIID;FA;;;${USER})`, 'a grant somebody set, beside inherited entries'],
+ [`D:(A;OICI;0x1301bf;;;WD)(A;OICI;FA;;;${USER})`, 'a list of explicit entries'],
+ [`D:PAI(A;OICIID;0x1301bf;;;WD)(A;OICI;FA;;;${USER})`, 'a protected list: it takes nothing from above any more'],
+ ]) {
+ const verdict = verdictFor(sddl);
+ assert.deepStrictEqual([verdict.ok, verdict.inherited], [false, undefined], why);
+ }
+ const fine = verdictFor(`D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;${USER})`);
+ assert.deepStrictEqual([fine.ok, fine.inherited], [true, undefined], 'an inherited list that is private is a "yes", and says nothing more');
+ assert.deepStrictEqual(fs.readdirSync(tmp), []);
+});
+
// Whoever owns a folder can rewrite its list, whatever it says now: a list that names only the right principals does not make the folder theirs.
test('windowsFolderIsPrivate: the folder must be the user\'s (or the administrators\', which the list trusts anyway) — a list that names only the user is not enough if somebody else owns the folder', (t) => {
const tmp = scratchTemp(t);
@@ -451,7 +472,8 @@ test('REAL ICACLS (Windows): a folder made in a temp folder that EVERYONE can wr
const handmade = path.join(root, 'handmade');
fs.mkdirSync(handmade);
assert.match(savedList(handmade, root), /;;;WD\)/, 'control: a folder made here the ordinary way has Everyone on it');
- assert.strictEqual(windowsFolderIsPrivate(handmade).ok, false, 'and is not private');
+ const asMade = windowsFolderIsPrivate(handmade);
+ assert.deepStrictEqual([asMade.ok, asMade.inherited], [false, true], `and is not private — by what it inherited, as a folder is until its maker gives it its own list: ${asMade.reason}`);
const folder = path.join(root, 'power-platform-skills-model-apps');
fs.mkdirSync(folder);
const verdict = makeWindowsFolderPrivate(folder);
diff --git a/plugins/pcf/scripts/lib/source-literals.js b/plugins/pcf/scripts/lib/source-literals.js
index e159051b8..425f1281c 100644
--- a/plugins/pcf/scripts/lib/source-literals.js
+++ b/plugins/pcf/scripts/lib/source-literals.js
@@ -121,8 +121,8 @@ function prevSignificant(src, i) {
// const n = {valueOf(){return 12;}}/2; const re = /x/;
// paren `)` ends an if/for/while head (a regex follows) or an operand (a division), and its `(` is out of reach
// if (true /* …2,100 characters… */) /navigateTo({…})/.test(text);
-// keyword a word that is a keyword in some places and a name in others
-// const of = 12; const n = of/2; const re = /\/*$/;
+// keyword a word that is a keyword in some places and a name in others (`of` only in a `for` head: ofTakesOperand)
+// const of = 12; for (const x of of/2 + "") {} const re = /\/*$/;
// angle a `>` may close type arguments, a JSX tag or a comparison; the `>` of `=>`, the closer of a cast the lexer proves is one (castKeywordIsCertain) and the end of an element
// or a regex it read are certain
// const half = total as Types . Alias<number> / 2; const re = /x/;
@@ -331,6 +331,11 @@ function positionAfter(src, prev, ends = null, depth = 0) {
// short by an escape, `#` or a non-ASCII letter, which is not the word it spells (`identifier`), and `throw` before a line break — an
// error in JavaScript, `throw;` to TypeScript's `parseThrowStatement` — where what follows is unknowable (`newline`).
if (cutsWord(src, s)) return { expression, ambiguity: 'identifier' };
+ // `of` takes an operand only as the keyword of a `for (… of …)` head; anywhere else it is a name (ofTakesOperand).
+ if (keyword && word === 'of') {
+ const of = ofTakesOperand(src, index);
+ return { expression: of.operand, ambiguity: of.ambiguity };
+ }
if (keyword && word === 'throw' && prev.newline) return { expression, ambiguity: 'newline' };
return { expression, ambiguity: !property && CONTEXTUAL_WORDS.has(word) ? 'keyword' : null };
}
@@ -678,6 +683,46 @@ function wordBefore(src, j) {
return { word, start: s };
}
+// Whether the word `of` whose last character is at `index` takes an operand — a `/` after it starts a regex and a `<` an element — and whether
+// that answer is certain: { operand, ambiguity }. TypeScript's parser takes `of` as the keyword in one place only, right after what the head of a
+// `for (… of …)` or `for await (… of …)` statement binds (parseForOrForInOrForOfStatement,
+// https://github.com/microsoft/TypeScript/blob/v5.8.3/src/compiler/parser.ts); everywhere else `of` is an identifier, so a `/` after it divides
+// and a `<` compares or opens type arguments:
+// type of<T> = T; const x = fn<of<List<Row>>>(); a type's name, twice: no element
+// const half = of / 2; a division
+// for (const x of <A />.props.items) {} the keyword: an element
+// The word is a name for CERTAIN only where the scan PROVES that no for head can enclose it. The scan counts back over the lexer's output (where the
+// brackets of strings, comments, regexes and JSX text are blank) to the nearest bracket left open before the word, as statementHead does, and
+// a name is proven in three cases only, each the return of NAME below:
+// (a) that bracket is a `[` or a `{` — an array, a pattern, a block, an object, an attribute's or a child's braces: the keyword stands in the
+// parentheses of its head and nowhere deeper, so `for (const [a = of / 2] of xs)` holds a name;
+// (b) it is a `(` whose preceding token, read across white space and blanked comments, is read whole and is neither the word `for` nor the word
+// `await` — a punctuator, a quote, a regex's flag, any other ASCII word (`f(of / 2)`, `if (of / 2)`);
+// (c) the scan reaches the start of the source with no bracket left open.
+// Nothing else proves it, and no exception to a head may: a `(` after the word `for` or `await` is always a possible head, whatever stands before
+// that word — `a.for(…)` looks like a property, but the dot may be a decimal's that ends the statement before (`const n = 1.⏎for (…)`). Inside a
+// for head nothing is proven either, whatever stands before the `of`: a binding can end in a name the scan does not read (`π`), a non-null `!`, or
+// any type (`x as enum`). There, before a word cut by an escape, a `#` or a character beyond ASCII (which may be a `for` or an `await` spelled
+// otherwise), and where the bracket lies beyond LOOKAHEAD, the reading is the table's, as it always was: the keyword, and a GUESS (`keyword`).
+function ofTakesOperand(src, index) {
+ const keyword = { operand: true, ambiguity: 'keyword' };
+ const NAME = { operand: false, ambiguity: null };
+ let depth = 0;
+ for (let j = index - 2; j >= 0; j -= 1) {
+ if (index - 1 - j > LOOKAHEAD) return keyword;
+ const c = src[j];
+ if (c === ')' || c === ']' || c === '}') depth += 1;
+ else if (c === '(' || c === '[' || c === '{') {
+ if (depth > 0) { depth -= 1; continue; }
+ if (c !== '(') return NAME;
+ const head = wordBefore(src, j);
+ if (head.word === 'for' || head.word === 'await' || cutsWord(src, head.start)) return keyword;
+ return NAME;
+ }
+ }
+ return NAME;
+}
+
// The window for the scans that look back or ahead over a bounded stretch of source: the `(` of a statement head (statementHead), the `<` of
// a cast's type arguments (matchingTypeArgumentOpen) and the parameter list of a generic function type (genericFunctionTypeFollows). Past
// it the answer is a guess, and each says so (`paren`, `angle`, `generic`).
@@ -5091,4 +5136,4 @@ function ellipsisFollowedByStatement(mask, k) {
return STATEMENT_WORDS.has(word) || word === 'import' || word === 'export';
}
-module.exports = { blankLiterals, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING };
+module.exports = { blankLiterals, ofTakesOperand, blankNonCodePreservingTemplateExpressions, commentRanges, endsMidStatement, findElisionMarker, hasDefaultExport, hasUnbalancedBrackets, expressionPosition, opensTypeParameters, elementFailsAt, elementChildren, scanTemplateExpressionEnd, isLineTerminator, isTrivia, isSingleLineTrivia, trimTrivia, TRIVIA_CLASS, WS, AMBIGUITY_KINDS, ANGLE_AFTER, ANGLE_AFTER_LINE_BREAK, NO_MEMBER_BEFORE, RESERVED_WORDS, TYPE_PARAMETER_MODIFIERS, MEMBER_NAME_OPERATORS, MEMBER_PREFIX_WORDS, OPERATOR_WORD_ENDS_MEMBER_AFTER, OPERATOR_WORDS_THAT_ARE_NAMES, HEAD_NESTING };