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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
model-apps 2.25.0: page scroll check, failure-safe page downloads, adopt configuration created before opting in (#839)
Akshay Maloo7322abba73b4
diff --git a/evals/model-apps/app-builder/EVAL_GUIDE.md b/evals/model-apps/app-builder/EVAL_GUIDE.mdindex 2e0be9d4c..9dab8731c 100644--- a/evals/model-apps/app-builder/EVAL_GUIDE.md+++ b/evals/model-apps/app-builder/EVAL_GUIDE.md@@ -53,14 +53,23 @@ grade is the **spec**, in both directions, on every fixture:states a count. Removing the only declared artifact of an asked kind on a table, dropping its `reconcile: "declared"`,putting it on another table, or adding an artifact of a kind or table nobody asked for fails; when a table carries severaldeclared artifacts of one kind, only the count the prompt states is checked. Names, stage labels, tile order and scope are- never compared here.+ never compared by this check; the shape assertions below grade what the prompt says about them.- What grades a declared artifact's shape, and what does not. On every fixture the common assertions check that eachbusiness rule binds only columns the spec creates and compiles at least one condition and one action, that eachprocess-flow step binds a field on the flow's table and each stage is scoped to that table, and that each declared- dashboard, rule and flow has a teardown step. Beyond that, among the fixtures 21-24 only fixture 21 has its own shape assertions (the authored- tab, form-column and section topology, and column and row spans). The shape of the declared dashboard (tiles) in- fixture 22, of the declared rules in fixture 23 (scope, conditions) and of the declared flow (stages) in fixture 24 is- **not graded yet**: removing a tile or a stage still passes. Grading those shapes is a follow-up.+ dashboard, rule and flow has a teardown step. Beyond that, fixtures 21-24 each have their own shape assertions. Fixture 21+ grades the authored tab, form-column and section topology, and column and row spans. Fixtures 22-24 grade what the plugin+ compiles for the artifact (`facts.declaredShapes`) against `expect.declaredDashboards`, `expect.declaredRules` and+ `expect.declaredFlows`, each written from the prompt:+ - 22, dashboard: exactly the asked tiles, each bound to the view, chart or iframe address it names (the tile kind and the+ table are part of that identity) and at least as wide or as tall as the prompt says. Tile names and order are not compared.+ - 23, rules: each asked rule is Active (a Draft rule never runs, so it is not the operating rule the prompt asks for), fires on+ exactly the asked conditions (column, operator and, for a choice, the option label), has+ the asked logic and scope where the prompt states them, and carries exactly the asked actions (kind, column, lock, required,+ visible, a non-empty message). Rule names, the order of rules, conditions and actions, and any scope the prompt leaves+ unsaid are not compared.+ - 24, flow: exactly the asked stages in order, each matched by a pattern for the word the prompt uses. Stage wording beyond+ that word, step names and the flow name are not compared.- A prompt that declines rules and flows (`expect.noBusinessLogic: true`) fails on any rule or flow, declared or not.Whether the agent makes the offer is **not** graded. That is a property of a conversation, and no offline harness records@@ -98,9 +107,9 @@ confined to the fixture directory, including when the fixtures root is a junctio| 19 | `19-modern-branding` | An explicit branding ask declares `app.theme` (Preview): a base colour, header colours and a logo that is a declared SVG web resource, never a URL. The spec asks for 2.21.0. An ordinary app ask must not get a theme; `--verify` reports API state, and the header is checked in a browser. || 20 | `20-stable-identities` | A new-app ask writes `createIdentity: "stable-v1"` with `minimumPluginVersion` `2.21.0` and declares its view and chart, the only creates that get stable ids. A download prompt must not gain the field (negative unit probe). The `/app-builder` skill's `createIdentity` guidance must tell the maker that an unsent local edit stops the build (`create-completion-required`) and that running again does not merge it. || 21 | `21-declared-form-layout` | A "lay out this form myself and keep it" ask declares the Main form with `reconcile: "declared"`: a full-width name (`colspan`), a two-row address (`rowspan`), field flags set both true and false, two sub-grids to different child tables, and an `onload` handler from a declared web resource. The runner checks the compiled topology and spans; the declared-form unit tests check that content the spec omits is kept and that a rebuild finds the same form and sends no form write. |-| 22 | `22-declared-dashboard` | A "keep this dashboard's tiles the way the spec says" ask declares a global Standard dashboard with `reconcile: "declared"`, a `key` on it and on each tile (a two-column list, a chart, a tall iframe), and the app shell places it. The runner checks the plan, the sitemap target and its teardown; the declared-dashboard unit tests check that a keyed tile edit writes only that tile, an added tile goes after the last row, a tile made in Maker is kept, and a rebuild sends no write. |-| 23 | `23-declared-business-rule` | A "keep these business rules the way the spec says" ask declares two business rules with `reconcile: "declared"`, a `key` on each rule, condition and action: one on the table (a required resolution and a locked field when closed), one on every form (`scope: "AllForms"`, an error message from a two-condition test). The runner checks that each compiles and binds only the spec's columns, and its teardown; the declared-rule unit tests check the Draft-first create, the conditional activation, that a rebuild sends no write, the typed adoption, verify and the managed download. |-| 24 | `24-declared-bpf` | A "keep this process flow the way the spec says" ask declares one linear business process flow with `reconcile: "declared"`, a `key` on each stage and step (three stages, required and optional steps), a description, an order and an Active status. The runner checks that it compiles on its own table and binds only the spec's columns, and its teardown; the declared-flow unit tests check that every stage and step id is fixed before the Draft-first create, the conditional activation, that a rebuild sends no write, that an edit, omission or reorder is refused with no write, the typed adoption, verify and the managed download.+| 22 | `22-declared-dashboard` | A "keep this dashboard's tiles the way the spec says" ask declares a global Standard dashboard with `reconcile: "declared"`, a `key` on it and on each tile (a two-column list, a chart, a tall iframe), and the app shell places it. The runner checks the plan, the sitemap target and its teardown, and that it holds exactly the asked tiles (a wide list of the open view, the status chart, a tall iframe of the named address); the declared-dashboard unit tests check that a keyed tile edit writes only that tile, an added tile goes after the last row, a tile made in Maker is kept, and a rebuild sends no write. |+| 23 | `23-declared-business-rule` | A "keep these business rules the way the spec says" ask declares two business rules with `reconcile: "declared"`, a `key` on each rule, condition and action: one on the table (a required resolution and a locked field when closed), one on every form (`scope: "AllForms"`, an error message from a two-condition test). The runner checks that each compiles and binds only the spec's columns, that each is Active and fires on the asked condition with the asked scope and actions, and its teardown; the declared-rule unit tests check the Draft-first create, the conditional activation, that a rebuild sends no write, the typed adoption, verify and the managed download. |+| 24 | `24-declared-bpf` | A "keep this process flow the way the spec says" ask declares one linear business process flow with `reconcile: "declared"`, a `key` on each stage and step (three stages, required and optional steps), a description, an order and an Active status. The runner checks that it compiles on its own table and binds only the spec's columns, that its stages are the three the prompt names in order, and its teardown; the declared-flow unit tests check that every stage and step id is fixed before the Draft-first create, the conditional activation, that a rebuild sends no write, that an edit, omission or reorder is refused with no write, the typed adoption, verify and the managed download.| 25 | `25-no-optional-extras` | A new-app ask that says no to branding, outside services, per-environment settings, business rules, process flows and fixed layouts gets none of them: no `app.theme`, no configuration item, no declared form, dashboard, rule or flow, and no plain business rule or process flow either (`expect.noBusinessLogic`). |> **Fixture 2 note:** `appShell.subAreas[].page` references use the page's **key** (e.g. `"overview"`), not its display name (`"Overview"`). The v2 validator requires keys, and the linter accepts valid key references; `key === name` is neither required nor used by this fixture.diff --git a/evals/model-apps/app-builder/evals.json b/evals/model-apps/app-builder/evals.jsonindex 194f87a51..07591fbbb 100644--- a/evals/model-apps/app-builder/evals.json+++ b/evals/model-apps/app-builder/evals.json@@ -552,9 +552,20 @@"pages": [],"declared": {"dashboards": { "minCount": 1 }- }+ },+ "declaredDashboards": [+ {+ "tiles": [+ { "type": "list", "entity": "cnt_workorder", "view": "Open Work Orders", "minColspan": 2 },+ { "type": "chart", "entity": "cnt_workorder", "chart": "Work Orders by Status" },+ { "type": "iframe", "url": "https://contoso.example/field-map", "minRowspan": 13 }+ ]+ }+ ]},- "expectations": []+ "expectations": [+ "process: a declared dashboard holds exactly the tiles the prompt describes, each bound to the view, chart or address it names and sized as asked"+ ]},{"id": 23,@@ -573,9 +584,29 @@"pages": [],"declared": {"businessRules": { "tables": ["cnt_request"], "minCount": 2 }- }+ },+ "declaredRules": [+ {+ "when": [{ "field": "cnt_status", "operator": "Equals", "option": "Closed" }],+ "do": [+ { "type": "SetBusinessRequired", "field": "cnt_resolution", "required": true },+ { "type": "LockUnlock", "field": "cnt_notes", "lock": true }+ ]+ },+ {+ "when": [+ { "field": "cnt_status", "operator": "Equals", "option": "In Progress" },+ { "field": "cnt_assignee", "operator": "DoesNotContainData" }+ ],+ "logic": "AND",+ "scope": "AllForms",+ "do": [{ "type": "ShowErrorMessage", "hasMessage": true }]+ }+ ]},- "expectations": []+ "expectations": [+ "process: each declared business rule has the condition, scope and actions the prompt describes"+ ]},{"id": 24,@@ -594,9 +625,14 @@"pages": [],"declared": {"businessProcessFlows": { "tables": ["cnt_claim"] }- }+ },+ "declaredFlows": [+ { "stages": [{ "pattern": "intake" }, { "pattern": "assess" }, { "pattern": "decision|decide" }] }+ ]},- "expectations": []+ "expectations": [+ "process: a declared process flow has exactly the stages the prompt names, in order"+ ]},{"id": 25,diff --git a/evals/model-apps/app-builder/lib/assertions.js b/evals/model-apps/app-builder/lib/assertions.jsindex 2550d1d8e..1b2e11e90 100644--- a/evals/model-apps/app-builder/lib/assertions.js+++ b/evals/model-apps/app-builder/lib/assertions.js@@ -1176,9 +1176,9 @@ ASSERTIONS.set('author: the skill tells the maker that an unsent local edit stop// only when the prompt asks for it (no expectation = none is allowed). Whether the offer itself is made needs a transcript of a// conversation (EVAL_GUIDE.md, "Optional capabilities").// It grades presence and absence by capability kind and table, and nothing else: a name, a stage label, a tile order or a scope is the-// maker's to choose, so none of them is compared here, and this check grades no shape at all. Shape is graded elsewhere only in part:-// the common process assertions check well-formedness, fixture 21 has its own layout assertions, and the declared dashboard,-// rules and flow of fixtures 22-24 have no shape assertion yet (EVAL_GUIDE.md, "Optional capabilities").+// maker's to choose, so none of them is compared here, and this check grades no shape at all. Shape is graded elsewhere: the common+// process assertions check well-formedness, fixture 21 has its own layout assertions, and the declared dashboard, rules and flow of+// fixtures 22-24 each have a shape assertion of their own (the "declared shapes" block below; EVAL_GUIDE.md, "Optional capabilities").// expect.appTheme as the theme assertion reads it (set = a theme is asked for)// expect.configuration as the configuration assertion reads it (a non-empty list, or solutionVersion, is an ask)// expect.declared { forms|dashboards|businessRules|businessProcessFlows: { tables: [table...], minCount: n } }@@ -1235,4 +1235,126 @@ ASSERTIONS.set('author: a maker who declines business rules and process flows gereturn PASS;});+// --- BEGIN declared shapes (fixtures 22-24; EVAL_GUIDE.md, "Optional capabilities") ---+// What the capability check above leaves out: the shape of what a declared dashboard, business rule or process flow holds. Each is+// graded from facts.declaredShapes (what the plugin compiles for it) against expectations written from the PROMPT, never from the+// spec or from what was compiled: expect.declaredDashboards, expect.declaredRules and expect.declaredFlows. A name, a tile's order,+// a stage's exact label, the steps of a stage and any property the prompt leaves unsaid are the maker's to choose, so none is+// compared. An artifact the plugin could not compile (an `error` shape) fails with the reason.+const describeCondition = (c) => `${c.field} ${c.operator}${c.option !== undefined ? ` "${c.option}"` : c.value !== undefined ? ` ${c.value}` : ''}`;+const describeAction = (a) => (a.field ? `${a.type} ${a.field}` : a.type);++// Pairs each wanted item with a distinct actual one (a greedy, order-free match; the wanted items of one set differ in what they+// name, so the first fit is the only fit) and returns what is wanted but unmatched and what is left over.+function pairOff(wanted, actual, fits) {+ const free = [...actual];+ const missing = [];+ for (const w of wanted) {+ const at = free.findIndex((a) => fits(a, w));+ if (at < 0) missing.push(w); else free.splice(at, 1);+ }+ return { missing, extra: free };+}++const tileIdentity = (want) => (tile) => {+ if (tile.type !== want.type) return false;+ if (want.type === 'iframe') return tile.url === want.url;+ if (lc(tile.entity) !== lc(want.entity)) return false;+ if (want.type === 'list') return tile.viewId === `view:${lc(want.entity)}|${want.view}`;+ if (want.type === 'chart') return tile.chartId === `chart:${lc(want.entity)}|${want.chart}` && (want.view === undefined || tile.viewId === `view:${lc(want.entity)}|${want.view}`);+ return false;+};+const describeTile = (want) => (want.type === 'iframe' ? `iframe of ${want.url}` : want.type === 'list' ? `list of view "${want.view}" on ${want.entity}` : `chart "${want.chart}" on ${want.entity}`);++function dashboardProblems(dashboard, want) {+ const broken = dashboard.tiles.find((t) => t.error);+ if (broken) return [`the ${broken.type || 'unknown'} tile "${broken.name || ''}" does not compile: ${broken.error}`];+ if (dashboard.tiles.length !== want.tiles.length) return [`${dashboard.tiles.length} tile(s) [${dashboard.tiles.map((t) => t.type)}], the prompt asks for ${want.tiles.length} [${want.tiles.map((t) => t.type)}]`];+ const free = [...dashboard.tiles];+ const problems = [];+ for (const t of want.tiles) {+ const at = free.findIndex(tileIdentity(t));+ if (at < 0) { problems.push(`no tile is the ${describeTile(t)} the prompt asks for`); continue; }+ const [tile] = free.splice(at, 1);+ if (t.minColspan !== undefined && tile.colspan < t.minColspan) problems.push(`the ${describeTile(t)} is ${tile.colspan} column(s) wide, the prompt asks for at least ${t.minColspan}`);+ if (t.minRowspan !== undefined && tile.rowspan < t.minRowspan) problems.push(`the ${describeTile(t)} is ${tile.rowspan} row(s) tall, the prompt asks for more than ${t.minRowspan - 1}`);+ }+ return problems;+}++ASSERTIONS.set('process: a declared dashboard holds exactly the tiles the prompt describes, each bound to the view, chart or address it names and sized as asked', ({ facts, eval: ev }) => {+ const want = ev && ev.expect && ev.expect.declaredDashboards;+ if (!Array.isArray(want) || !want.length) return fail('no independent expectation of the declared dashboards (expect.declaredDashboards)');+ const got = facts.declaredShapes.dashboards;+ if (got.length !== want.length) return fail(`${got.length} declared dashboard(s) [${got.map((d) => d.name)}], the prompt asks for ${want.length}`);+ const free = [...got];+ for (const [i, w] of want.entries()) {+ const verdicts = free.map((d) => dashboardProblems(d, w));+ const at = verdicts.findIndex((p) => p.length === 0);+ if (at < 0) return fail(`dashboard ${i + 1}: ${verdicts[0].join('; ')}`);+ free.splice(at, 1);+ }+ return PASS;+});++const conditionFits = (actual, want) => lc(actual.field) === lc(want.field) && actual.operator === want.operator+ && (want.option !== undefined ? (actual.options || []).some((o) => lc(o) === lc(want.option)) : want.value === undefined || String(actual.value) === String(want.value));+const actionFits = (actual, want) => actual.type === want.type && (want.field === undefined || lc(actual.field) === lc(want.field))+ && (want.lock === undefined || actual.lock === want.lock) && (want.required === undefined || actual.required === want.required)+ && (want.visible === undefined || actual.visible === want.visible) && (want.hasMessage !== true || actual.hasMessage === true);++function ruleProblems(rule, want) {+ const problems = [];+ // A Draft rule is inert (it never runs for the user), and the prompt asks for rules that operate.+ if (String(rule.status === undefined || rule.status === null ? 'Active' : rule.status).toLowerCase() !== 'active') problems.push(`its status is ${rule.status}, the prompt asks for a rule that is Active`);+ if (want.scope !== undefined && lc(rule.scope) !== lc(want.scope)) problems.push(`its scope is ${rule.scope}, the prompt asks for ${want.scope}`);+ if (want.logic !== undefined && String(rule.logic).toUpperCase() !== String(want.logic).toUpperCase()) problems.push(`its conditions combine with ${rule.logic}, the prompt asks for ${want.logic}`);+ const { missing, extra } = pairOff(want.do || [], rule.actions, actionFits);+ if (missing.length) problems.push(`it lacks the action(s) [${missing.map(describeAction)}] the prompt asks for`);+ if (extra.length) problems.push(`it carries the action(s) [${extra.map(describeAction)}] the prompt does not ask for`);+ return problems;+}++ASSERTIONS.set('process: each declared business rule has the condition, scope and actions the prompt describes', ({ facts, eval: ev }) => {+ const want = ev && ev.expect && ev.expect.declaredRules;+ if (!Array.isArray(want) || !want.length) return fail('no independent expectation of the declared rules (expect.declaredRules)');+ const got = facts.declaredShapes.rules;+ const broken = got.find((r) => r.error);+ if (broken) return fail(`the rule "${broken.name || ''}" does not compile: ${broken.error}`);+ if (got.length !== want.length) return fail(`${got.length} declared rule(s) [${got.map((r) => r.name)}], the prompt asks for ${want.length}`);+ const free = [...got];+ for (const w of want) {+ const at = free.findIndex((r) => {+ const { missing, extra } = pairOff(w.when || [], r.conditions, conditionFits);+ return !missing.length && !extra.length;+ });+ if (at < 0) return fail(`no declared rule fires on exactly [${(w.when || []).map(describeCondition)}]; the declared rules fire on ${got.map((r) => `[${r.conditions.map(describeCondition)}]`).join(', ')}`);+ const [rule] = free.splice(at, 1);+ const problems = ruleProblems(rule, w);+ if (problems.length) return fail(`the rule that fires on [${(w.when || []).map(describeCondition)}]: ${problems.join('; ')}`);+ }+ return PASS;+});++ASSERTIONS.set('process: a declared process flow has exactly the stages the prompt names, in order', ({ facts, eval: ev }) => {+ const want = ev && ev.expect && ev.expect.declaredFlows;+ if (!Array.isArray(want) || !want.length) return fail('no independent expectation of the declared flows (expect.declaredFlows)');+ const got = facts.declaredShapes.flows;+ const broken = got.find((f) => f.error);+ if (broken) return fail(`the flow "${broken.name || ''}" does not compile: ${broken.error}`);+ if (got.length !== want.length) return fail(`${got.length} declared flow(s) [${got.map((f) => f.name)}], the prompt asks for ${want.length}`);+ const free = [...got];+ for (const [i, w] of want.entries()) {+ const patterns = (w.stages || []).map((s) => new RegExp(s.pattern, 'i'));+ const verdicts = free.map((f) => (f.stages.length !== patterns.length+ ? `${f.stages.length} stage(s) [${f.stages}], the prompt names ${patterns.length}`+ : patterns.map((re, k) => (re.test(f.stages[k]) ? null : `stage ${k + 1} is "${f.stages[k]}", which is not /${re.source}/i`)).filter(Boolean).join('; ')));+ const at = verdicts.findIndex((v) => v === '');+ if (at < 0) return fail(`flow ${i + 1}: ${verdicts[0]}`);+ free.splice(at, 1);+ }+ return PASS;+});+// --- END declared shapes ---+module.exports = { ASSERTIONS };\ No newline at end of filediff --git a/evals/model-apps/app-builder/lib/facts.js b/evals/model-apps/app-builder/lib/facts.jsindex e3ccbe650..ae06beaa1 100644--- a/evals/model-apps/app-builder/lib/facts.js+++ b/evals/model-apps/app-builder/lib/facts.js@@ -10,10 +10,11 @@ function pluginLib(name) { return require(path.join(__dirname, '..', '..', '..',// helpers and performs no I/O at require time, so it is safe to load from the offline harness.function pluginLib2(name) { return require(path.join(__dirname, '..', '..', '..', '..', 'plugins', 'model-apps', 'scripts', name)); }-const { migrateAppSpec, validateAppSpec, lookupColumnsFor, normalizePageSource, SDK_ROLE_MARKER, FORM_TYPE_CODE, formLayoutNames, subgridRelationshipName } = pluginLib('app-spec.js');+const { migrateAppSpec, validateAppSpec, lookupColumnsFor, normalizePageSource, SDK_ROLE_MARKER, FORM_TYPE_CODE, formLayoutNames, subgridRelationshipName, choiceValueMap } = pluginLib('app-spec.js');const { lintAppSpec } = pluginLib('spec-lint.js');const { isDeclaredView, compileViewIntent } = pluginLib('view-reconcile.js');-const { planFor, PHASES, appDef, viewDef, chartDef, compileFormIntent, formFieldLogicals, defaultViewColumns, enrichesDefaultViews, subgridLabel, personaRoleSpecFor, businessRuleDef, bpfDef } = pluginLib('sdk-build.js');+const { planFor, PHASES, appDef, viewDef, chartDef, compileFormIntent, formFieldLogicals, defaultViewColumns, enrichesDefaultViews, subgridLabel, personaRoleSpecFor, businessRuleDef, bpfDef, dashboardTileOpts, dashboardComponent } = pluginLib('sdk-build.js');+const { compileRuleIntent, isDeclaredRule } = pluginLib('rule-settlement.js');const { subgridSectionIntent, isNonFieldControl } = pluginLib('artifact-intent.js');const { SUBGRID_CLASS_ID, splitSubgrids, columnItems } = pluginLib('form-subgrid-placement.js');const { TIMELINE_CLASS_ID, wantsTimeline } = pluginLib('form-timeline.js');@@ -925,6 +926,88 @@ function processFacts(spec) {return { rules, flows };}+// The shapes of the DECLARED dashboards, business rules and process flows, read from what the plugin compiles for them (the+// tile component, the rule intent and the flow definition the build writes) rather than from the spec's own words, so a mapping+// that drops a size, a binding, a condition or a stage shows up here. Only `reconcile: "declared"` artifacts are read: a plain+// one is not the maker's to keep. Names are carried for the report and are never compared with the prompt.+//+// A tile's view and chart are resolved through synthetic ids shaped `view:<table>|<name>` and `chart:<table>|<name>` (the build's own+// `<table>|<name>` key), so "this tile is bound to that view" is a string comparison and no environment is involved.+function declaredShapeFacts(spec) {+ const declared = (list) => (Array.isArray(list) ? list : []).filter((x) => x && typeof x === 'object' && x.reconcile === 'declared');+ const created = { views: {}, charts: {} };+ for (const v of spec.views || []) created.views[`${lc(v.entity)}|${v.name}`] = `view:${lc(v.entity)}|${v.name}`;+ for (const c of spec.charts || []) created.charts[`${lc(c.entity)}|${c.name}`] = `chart:${lc(c.entity)}|${c.name}`;++ const dashboards = declared(spec.dashboards).map((d) => ({+ name: d.name,+ tiles: (d.tiles || []).map((tile, index) => {+ try {+ const c = dashboardComponent(dashboardTileOpts(spec, tile, { created }), index);+ const p = c.parameters || {};+ return {+ type: c.type,+ name: c.name,+ colspan: c.colspan,+ rowspan: c.rowspan,+ entity: p.TargetEntityType ? lc(p.TargetEntityType) : undefined,+ viewId: p.ViewId,+ chartId: p.VisualizationId,+ url: p.Url,+ };+ } catch (e) {+ return { type: tile && tile.type, name: tile && tile.name, error: String((e && e.message) || e) };+ }+ }),+ }));++ // A declared artifact the plugin cannot compile is reported as an `error` shape, so one malformed rule fails its own assertion+ // with the reason instead of stopping every other fact of the fixture.+ const shaped = (artifact, read) => {+ try { return read(artifact); } catch (e) { return { name: artifact && artifact.name, error: String((e && e.message) || e) }; }+ };++ const rules = declared(spec.businessRules).map((r) => shaped(r, () => {+ // The same compile the declared-rule build uses; a rule that is not declared never reaches it.+ const def = isDeclaredRule(r) ? compileRuleIntent(r) : businessRuleDef(r);+ const root = def.rootCondition || {};+ const entity = (spec.entities || []).find((e) => lc(e.schemaName) === lc(def.entityLogicalName));+ const options = entity ? choiceValueMap(entity, spec) : {};+ return {+ name: def.name,+ entity: lc(def.entityLogicalName),+ scope: def.scope,+ status: def.status,+ logic: root.logic,+ conditions: (root.clauses || []).map((c) => {+ const byLabel = options[lc(c.field)] || {};+ return {+ field: lc(c.field),+ operator: c.operator,+ value: c.value,+ // Every label the compiled value stands for, so "Closed" can be asked of a stored 100000002.+ options: Object.keys(byLabel).filter((label) => String(byLabel[label]) === String(c.value)),+ };+ }),+ actions: (root.trueBranch || []).map((a) => ({+ type: a.type,+ field: lc(a.field),+ lock: a.lock,+ required: a.required,+ visible: a.visible,+ hasMessage: typeof a.errorMessage === 'string' && a.errorMessage.trim().length > 0,+ })),+ };+ }));++ const flows = declared(spec.businessProcessFlows).map((f) => shaped(f, () => {+ const def = bpfDef(f);+ return { name: def.name, entity: lc(def.entityLogicalName), stages: (def.stages || []).map((st) => st.name) };+ }));++ return { dashboards, rules, flows };+}+// A synthetic "deployed app" reader built from the spec, so hydrateSpec (the pure download primitive)// round-trips offline: the spec is projected into the deployed shapes hydrate consumes (sitemap JSON,// pages with a GenPageId, entities, dashboards keyed by id), then hydrated back. Synthetic ids are@@ -1096,6 +1179,7 @@ async function stageFacts(rawSpec, options = {}) {changedOnly: await changedOnlyFacts(spec, options.fixture),page: pageFacts(spec),process: processFacts(spec),+ declaredShapes: declaredShapeFacts(spec),teardown: teardownFacts(spec),download: downloadFacts(spec),roundTrip: await roundTripFacts(spec, options),diff --git a/evals/model-apps/app-builder/tests/facts.test.js b/evals/model-apps/app-builder/tests/facts.test.jsindex 27d4796d6..3ce784f26 100644--- a/evals/model-apps/app-builder/tests/facts.test.js+++ b/evals/model-apps/app-builder/tests/facts.test.js@@ -1235,8 +1235,8 @@ test('a capability the prompt asks for must be authored: deleting it, or droppin// A kind the prompt did not ask for fails even on a positive fixture.assert.strictEqual(gradeOptional(23, (s) => { s.businessProcessFlows = [{ entity: 'cnt_request', name: 'Extra', reconcile: 'declared', stages: [] }]; }).status, 'fail', 'a flow nobody asked for beside the rules');assert.strictEqual(gradeOptional(21, (s) => { s.dashboards = [{ name: 'Board', key: 'board', reconcile: 'declared', tiles: [] }]; }).status, 'fail', 'a dashboard nobody asked for beside the form');- // Shape and wording are not this check's business, and fixtures 22-24 have no shape assertion of their own yet: another stage- // word, a reversed tile order, a rule scope swapped between two rules, or a changed tile kind still pass here.+ // Shape and wording are not THIS check's business, and the shapes of fixtures 22-24 are graded by their own assertions (below): another+ // stage word, a reversed tile order, a rule scope swapped between two rules, or a changed tile kind still pass here.assert.strictEqual(gradeOptional(24, (s) => { const st = s.businessProcessFlows[0].stages; st[1].name = 'Appraisal'; st[2].name = 'Outcome'; }).status, 'pass', 'other stage labels');assert.strictEqual(gradeOptional(22, (s) => { s.dashboards[0].tiles.reverse(); }).status, 'pass', 'tiles in another order');assert.strictEqual(gradeOptional(23, (s) => { const [r1, r2] = s.businessRules; [r1.scope, r2.scope] = [r2.scope, r1.scope]; }).status, 'pass', 'swapped scopes');@@ -1261,6 +1261,136 @@ test('what must NOT change: plain forms, dashboards, rules and flows are not optassert.ok(![...ASSERTIONS.keys()].some((t) => /^offers:/.test(t)));});+// The shape of a declared dashboard, business rule and process flow (fixtures 22-24). Each expectation is written from the prompt, and+// each assertion reads what the plugin compiles for the artifact, so a mapping that drops a size, a binding, a condition or a stage fails.+const DASHBOARD_SHAPE = 'process: a declared dashboard holds exactly the tiles the prompt describes, each bound to the view, chart or address it names and sized as asked';+const RULE_SHAPE = 'process: each declared business rule has the condition, scope and actions the prompt describes';+const FLOW_SHAPE = 'process: a declared process flow has exactly the stages the prompt names, in order';+async function gradeShape(id, text, mutate, mutateEval) {+ const fixture = fixtureFor(id);+ const spec = structuredClone(fixture.spec);+ if (mutate) mutate(spec);+ const ev = structuredClone(evalsManifest.evals.find((e) => e.id === id));+ if (mutateEval) mutateEval(ev);+ const facts = await stageFacts(spec, { fixture });+ return ASSERTIONS.get(text)({ facts, spec, eval: ev });+}+async function assertShape(id, text, mutate, reason, what) {+ const result = await gradeShape(id, text, mutate);+ assert.strictEqual(result.status, 'fail', `${what}: expected a failure, got ${result.status}`);+ assert.match(reasonOf(result), reason, what);+}+const tilesOf = (s) => s.dashboards[0].tiles;+const closeOutRule = (s) => s.businessRules.find((r) => r.key === 'close-out');+const askRule = (s) => s.businessRules.find((r) => r.key === 'ask-assignee');++test('the shape assertions of fixtures 22-24 are listed by their evals, and the expectations come from the prompts', () => {+ for (const [id, text, key] of [[22, DASHBOARD_SHAPE, 'declaredDashboards'], [23, RULE_SHAPE, 'declaredRules'], [24, FLOW_SHAPE, 'declaredFlows']]) {+ const ev = evalsManifest.evals.find((e) => e.id === id);+ assert.ok(ev.expectations.includes(text), `eval ${id} lists its shape assertion`);+ assert.ok(Array.isArray(ev.expect[key]) && ev.expect[key].length, `eval ${id} states ${key}`);+ }+ const prompt = (id) => evalsManifest.evals.find((e) => e.id === id).prompt;+ assert.match(prompt(22), /wide list of open work orders, a chart of work orders by status and a tall crew map from https:\/\/contoso\.example\/field-map/);+ assert.match(prompt(23), /closed request needs a resolution and its notes lock, and a request in progress with no assignee shows an error on every form/);+ assert.match(prompt(24), /intake, assessment and a decision/);+});++test('the shipped fixtures 22-24 pass their shape assertions, and an eval that states no expectation cannot use one', async () => {+ for (const [id, text, key] of [[22, DASHBOARD_SHAPE, 'declaredDashboards'], [23, RULE_SHAPE, 'declaredRules'], [24, FLOW_SHAPE, 'declaredFlows']]) {+ assert.deepStrictEqual(await gradeShape(id, text), { status: 'pass' }, `fixture ${id}`);+ const result = await gradeShape(id, text, null, (ev) => { delete ev.expect[key]; });+ assert.strictEqual(result.status, 'fail', `fixture ${id} without ${key}`);+ assert.match(reasonOf(result), /no independent expectation/);+ }+});++test('declared dashboard shape: a missing, extra, unbound, re-addressed or undersized tile fails; names, order and extra size do not', async () => {+ await assertShape(22, DASHBOARD_SHAPE, (s) => { tilesOf(s).pop(); }, /2 tile\(s\) \[list,chart\], the prompt asks for 3/, 'the map is missing');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { tilesOf(s).push({ key: 'more', type: 'iframe', url: 'https://contoso.example/more', name: 'More' }); }, /4 tile\(s\)/, 'a tile nobody asked for');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { delete tilesOf(s).find((t) => t.type === 'iframe').rowspan; }, /iframe of https:\/\/contoso\.example\/field-map is 12 row\(s\) tall, the prompt asks for more than 12/, 'the map is not tall');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { tilesOf(s).find((t) => t.type === 'iframe').rowspan = 12; }, /row\(s\) tall/, 'the map is as tall as an unsized tile');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { delete tilesOf(s).find((t) => t.type === 'list').colspan; }, /list of view "Open Work Orders" on cnt_workorder is 1 column\(s\) wide, the prompt asks for at least 2/, 'the list is not wide');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { tilesOf(s).find((t) => t.type === 'iframe').url = 'https://contoso.example/other-map'; }, /no tile is the iframe of https:\/\/contoso\.example\/field-map/, 'the map address changed');+ await assertShape(22, DASHBOARD_SHAPE, (s) => {+ s.views.push({ entity: 'cnt_workorder', name: 'All Work Orders', columns: ['cnt_name'] });+ tilesOf(s).find((t) => t.type === 'list').view = 'All Work Orders';+ }, /no tile is the list of view "Open Work Orders"/, 'the list shows another view');+ await assertShape(22, DASHBOARD_SHAPE, (s) => {+ s.charts.push({ entity: 'cnt_workorder', name: 'Work Orders by Due', groupBy: 'cnt_dueon', measure: 'count', chartType: 'Column' });+ tilesOf(s).find((t) => t.type === 'chart').chart = 'Work Orders by Due';+ }, /no tile is the chart "Work Orders by Status"/, 'the chart tile shows another chart');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { tilesOf(s).find((t) => t.type === 'chart').type = 'list'; }, /no tile is the chart "Work Orders by Status"/, 'the chart became a list');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { delete s.dashboards[0].reconcile; }, /0 declared dashboard\(s\) \[\], the prompt asks for 1/, 'the dashboard is not declared');+ await assertShape(22, DASHBOARD_SHAPE, (s) => { s.dashboards.push({ name: 'Second', key: 'second', reconcile: 'declared', tiles: [] }); }, /2 declared dashboard\(s\)/, 'a second declared dashboard');+ // What the prompt leaves to the maker keeps its verdict.+ const keeps = [+ ['tiles in another order', (s) => { tilesOf(s).reverse(); }],+ ['other tile names', (s) => { tilesOf(s).forEach((t, i) => { t.name = `Tile ${i}`; }); }],+ ['a wider list and a taller map', (s) => { tilesOf(s).find((t) => t.type === 'list').colspan = 4; tilesOf(s).find((t) => t.type === 'iframe').rowspan = 30; }],+ ];+ for (const [what, mutate] of keeps) assert.deepStrictEqual(await gradeShape(22, DASHBOARD_SHAPE, mutate), { status: 'pass' }, what);+});++test('declared business rule shape: a changed condition, option, scope, logic or action fails; names, order and the unstated scope do not', async () => {+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).conditions[0].value = '100000000'; }, /no declared rule fires on exactly \[cnt_status Equals "Closed"\]/, 'closed became New');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).conditions[0].operator = 'NotEqual'; }, /no declared rule fires on exactly/, 'another operator');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).conditions[0].field = 'cnt_assignee'; }, /no declared rule fires on exactly/, 'another column');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).actions = closeOutRule(s).actions.filter((a) => a.type !== 'LockUnlock'); }, /lacks the action\(s\) \[LockUnlock cnt_notes\]/, 'the lock is missing');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).actions.find((a) => a.type === 'LockUnlock').lock = false; }, /lacks the action\(s\) \[LockUnlock cnt_notes\]/, 'the notes unlock');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).actions.find((a) => a.type === 'SetBusinessRequired').required = false; }, /lacks the action\(s\) \[SetBusinessRequired cnt_resolution\]/, 'the resolution is not required');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).actions.find((a) => a.type === 'SetBusinessRequired').field = 'cnt_notes'; }, /lacks the action\(s\) \[SetBusinessRequired cnt_resolution\]/, 'another required column');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).actions.push({ key: 'hide', type: 'SetVisibility', field: 'cnt_notes', visible: false }); }, /carries the action\(s\) \[SetVisibility cnt_notes\] the prompt does not ask for/, 'an extra action');+ await assertShape(23, RULE_SHAPE, (s) => { askRule(s).scope = 'Entity'; }, /its scope is Entity, the prompt asks for AllForms/, 'not every form');+ await assertShape(23, RULE_SHAPE, (s) => { delete askRule(s).scope; }, /its scope is Entity, the prompt asks for AllForms/, 'the default scope');+ await assertShape(23, RULE_SHAPE, (s) => { askRule(s).conditionLogic = 'OR'; }, /combine with OR, the prompt asks for AND/, 'either condition');+ await assertShape(23, RULE_SHAPE, (s) => { askRule(s).conditions.pop(); }, /no declared rule fires on exactly \[cnt_status Equals "In Progress",cnt_assignee DoesNotContainData\]/, 'the assignee test is missing');+ await assertShape(23, RULE_SHAPE, (s) => { askRule(s).conditions[1].operator = 'ContainsData'; }, /no declared rule fires on exactly/, 'an assignee is required rather than missing');+ await assertShape(23, RULE_SHAPE, (s) => { askRule(s).actions[0].errorMessage = ' '; }, /lacks the action\(s\) \[ShowErrorMessage\]/, 'an empty message');+ await assertShape(23, RULE_SHAPE, (s) => { askRule(s).actions[0].type = 'LockUnlock'; askRule(s).actions[0].lock = true; delete askRule(s).actions[0].errorMessage; }, /lacks the action\(s\) \[ShowErrorMessage\]/, 'a lock instead of an error');+ await assertShape(23, RULE_SHAPE, (s) => { s.businessRules.pop(); }, /1 declared rule\(s\) \[Close out a request\], the prompt asks for 2/, 'one rule is missing');+ await assertShape(23, RULE_SHAPE, (s) => { const [r1, r2] = s.businessRules; [r1.scope, r2.scope] = [r2.scope, r1.scope]; }, /its scope is Entity, the prompt asks for AllForms/, 'scopes swapped between the rules');+ await assertShape(23, RULE_SHAPE, (s) => { closeOutRule(s).status = 'Draft'; }, /its status is Draft, the prompt asks for a rule that is Active/, 'a rule left as a draft');+ await assertShape(23, RULE_SHAPE, (s) => { askRule(s).status = 'Inactive'; }, /its status is Inactive, the prompt asks for a rule that is Active/, 'an inactive rule');+ const keeps = [+ ['another rule name', (s) => { closeOutRule(s).name = 'Closing'; askRule(s).name = 'Assignee'; }],+ ['rules in another order', (s) => { s.businessRules.reverse(); }],+ ['conditions and actions in another order', (s) => { askRule(s).conditions.reverse(); closeOutRule(s).actions.reverse(); }],+ ['the unstated scope of the closed rule', (s) => { closeOutRule(s).scope = 'AllForms'; }],+ ['a rule that states it is Active', (s) => { closeOutRule(s).status = 'Active'; }],+ ['another error message', (s) => { askRule(s).actions[0].errorMessage = 'Name an assignee.'; }],+ ];+ for (const [what, mutate] of keeps) assert.deepStrictEqual(await gradeShape(23, RULE_SHAPE, mutate), { status: 'pass' }, what);+});++test('declared process flow shape: a missing, extra, reordered or renamed stage fails; wording within the stage and its steps do not', async () => {+ const flow = (s) => s.businessProcessFlows[0];+ await assertShape(24, FLOW_SHAPE, (s) => { flow(s).stages.pop(); }, /2 stage\(s\) \[Intake,Assess\], the prompt names 3/, 'the decision is missing');+ await assertShape(24, FLOW_SHAPE, (s) => { flow(s).stages.splice(1, 1); }, /2 stage\(s\)/, 'the assessment is missing');+ await assertShape(24, FLOW_SHAPE, (s) => { flow(s).stages.push({ key: 'close', name: 'Close', steps: [{ key: 'x', name: 'X', field: 'cnt_decision' }] }); }, /4 stage\(s\)/, 'a stage nobody asked for');+ await assertShape(24, FLOW_SHAPE, (s) => { flow(s).stages.reverse(); }, /stage 1 is "Decide", which is not \/intake\/i/, 'reversed');+ await assertShape(24, FLOW_SHAPE, (s) => { const st = flow(s).stages; [st[0], st[1]] = [st[1], st[0]]; }, /stage 1 is "Assess"/, 'two swapped');+ await assertShape(24, FLOW_SHAPE, (s) => { flow(s).stages[1].name = 'Appraisal'; }, /stage 2 is "Appraisal", which is not \/assess\/i/, 'the assessment renamed');+ await assertShape(24, FLOW_SHAPE, (s) => { delete flow(s).reconcile; }, /0 declared flow\(s\) \[\], the prompt asks for 1/, 'the flow is not declared');+ await assertShape(24, FLOW_SHAPE, (s) => { s.businessProcessFlows.push({ ...structuredClone(flow(s)), name: 'Another flow' }); }, /2 declared flow\(s\)/, 'a second flow');+ const keeps = [+ ['other wording for the same stages', (s) => { const st = flow(s).stages; st[0].name = 'Intake review'; st[1].name = 'Assessment'; st[2].name = 'Decision'; }],+ ['another flow name', (s) => { flow(s).name = 'Handling'; }],+ ['other steps', (s) => { flow(s).stages.forEach((st) => { st.steps = st.steps.slice(0, 1); }); }],+ ['a stage key rename', (s) => { flow(s).stages[1].key = 'appraise'; }],+ ];+ for (const [what, mutate] of keeps) assert.deepStrictEqual(await gradeShape(24, FLOW_SHAPE, mutate), { status: 'pass' }, what);+});++test('the shape assertions read a declared artifact only: a plain dashboard, rule or flow never satisfies or spoils them', async () => {+ const plainRule = { entity: 'cnt_request', name: 'Plain', conditions: [{ field: 'cnt_status', operator: 'Equals', value: '100000002', dataType: 'Picklist' }], actions: [{ type: 'LockUnlock', field: 'cnt_notes', lock: true }] };+ assert.deepStrictEqual(await gradeShape(23, RULE_SHAPE, (s) => { s.businessRules.push(plainRule); }), { status: 'pass' }, 'a plain rule beside the declared ones');+ await assertShape(23, RULE_SHAPE, (s) => { s.businessRules.forEach((r) => { delete r.reconcile; }); }, /0 declared rule\(s\) \[\], the prompt asks for 2/, 'no rule is declared');+ const facts = await stageFacts(structuredClone(fixtureFor(22).spec), { fixture: fixtureFor(22) });+ assert.deepStrictEqual(facts.declaredShapes.dashboards[0].tiles.map((t) => [t.type, t.colspan, t.rowspan]), [['list', 2, 12], ['chart', 1, 12], ['iframe', 1, 16]],+ 'an unsized tile is one column wide and the common 12 rows tall');+});+test('a maker who declines business rules and process flows gets none of ANY kind, graded independently of the declared-capability check', async () => {const { gradeFixture } = require('../run-app-builder.js');assert.ok(evalsManifest.evals.find((e) => e.id === 25).expectations.includes(NO_LOGIC));diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.mdindex 11ab5475b..07e730f23 100644--- a/evals/model-apps/genpage/EVAL_GUIDE.md+++ b/evals/model-apps/genpage/EVAL_GUIDE.md@@ -111,6 +111,7 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua- `<DataGrid>` usage imports `createTableColumn` + configures `columnSizingOptions` or `resizableColumns`- Every effective navigation target is checked with the production resolver; current before/after snapshots must differ by exact substitutions only, and only affected pages reupload- The production `pageStructureProblems` gate rejects truncated modules, including unfinished statements after valid exports+- A scroll context, with the plugin's own rule (`scripts/lib/page-scroll.js`, the one `check-griffel-styles.js` runs at the /genpage gate): the page's top element is bounded by the host's fixed-height container and scrolls, or holds a bounded scrolling body, with no padded content-box box overhanging the host. The pages captured before the rule (`lib/scroll-context.js`) report a skip that names the verdict the rule gives them, so the report still shows which captures clip (AB#6793599)- The Custom API lifecycle grades actual saved TSX, method/parameter/bound-record parity, sanitized result handling and preservation versus explicit clear. For a clear of a page that binds `WhoAmI` or `RetrieveVersion`, the grader reads the maker's `Clear choice:` line recorded right before each upload the clear covers; it does not check that the choice was made before the edit plan was approved, which the skill requires (`edit-flow.md`, Edit Phase 3).Whether a page applies a style the maker asked for (a plan whose `Styling:` line starts with `Maker-requested:`) is not graded yet.@@ -154,7 +155,7 @@ still refuse lookup provenance.All eval definitions live in `evals.json` alongside this file. The file contains:- `common_workflow_assertions`: **18** registered workflow checks, each passed or explicitly skipped when inapplicable.-- `common_code_assertions`: **21** registered code checks.+- `common_code_assertions`: **22** registered code checks.- `evals`: **27** prompt definitions, each with `id`, `tier`, `prompt`, `data`, and per-eval `expectations`.The `data` field specifies scenario assumptions for a manual capture or constructed fixture. The offline harness does not provide responses to `AskUserQuestion` or verify every recorded answer. The corpus contains **35 fixture directories / 39 top-level TSX files**, representing 27 prompt IDs. IDs **none** have no fixture — every registered prompt is executed.diff --git a/evals/model-apps/genpage/evals.json b/evals/model-apps/genpage/evals.jsonindex 3c0c52601..9530927c3 100644--- a/evals/model-apps/genpage/evals.json+++ b/evals/model-apps/genpage/evals.json@@ -42,7 +42,8 @@"For Dataverse list/detail pages, the inline IIFE + window cache + cache-guard pattern from references/data-caching.md is used (Rule 15); no useCallback for data-fetching functions","For multi-page builds, cross-page navigation uses quoted `\"PAGEREF_<filename>\"` placeholders that the orchestrator's Phase 6.5 resolves to real GUIDs","For Dataverse pages that call dataApi.queryTable, the result is accessed via .rows (DataTable<T> = { rows: T[], hasMoreRows, loadMoreRows() }) — never used directly as an array (Rule 11)",- "Generated .tsx passes the production completeness gate (complete module, JSX, brackets, strings, comments and no prose fences)"+ "Generated .tsx passes the production completeness gate (complete module, JSX, brackets, strings, comments and no prose fences)",+ "Generated .tsx establishes a scroll context: its top element is bounded by the host (height 100%) and scrolls, or holds a bounded scrolling body, so content below the fold is reachable"],"evals": [{diff --git a/evals/model-apps/genpage/lib/assertions-layer-2.js b/evals/model-apps/genpage/lib/assertions-layer-2.jsindex 5995720c4..a2dda76ed 100644--- a/evals/model-apps/genpage/lib/assertions-layer-2.js+++ b/evals/model-apps/genpage/lib/assertions-layer-2.js@@ -32,6 +32,7 @@ const {} = require('./page-checks.js');const { nestedDefinitionProblems, renderedSource, unreadableElementProblems } = require('./tsx-structure.js');const { columnProblems } = require('./column-contract.js');+const { SCROLL_CONTEXT_ASSERTION, gradeScrollContext } = require('./scroll-context.js');let _verifiedIcons = null;function getVerifiedIcons() {@@ -528,6 +529,12 @@ ASSERTIONS.set(});+// ── scroll context (AB#6793599) ──+// Graded by the plugin's own rule (lib/scroll-context.js), with the pages captured before the rule+// reported as skips that name their verdict.+ASSERTIONS.set(SCROLL_CONTEXT_ASSERTION, gradeScrollContext);+// ── end scroll context ──+const PHASE5_EXPECTATIONS = new Map();PHASE5_EXPECTATIONS.set(diff --git a/evals/model-apps/genpage/lib/scroll-context.js b/evals/model-apps/genpage/lib/scroll-context.jsnew file mode 100644index 000000000..1ca3a5da6--- /dev/null+++ b/evals/model-apps/genpage/lib/scroll-context.js@@ -0,0 +1,99 @@+// The Layer 2 grade for "the page establishes a scroll context" (AB#6793599): a generated page renders+// inside a host container of fixed height that never scrolls, so a page whose top element is not bounded+// by that container and made to scroll clips everything below the fold, with no error anywhere.+//+// It grades with the plugin's own rule (plugins/model-apps/scripts/lib/page-scroll.js), the one the+// /genpage gate runs through check-griffel-styles.js, so the eval and the gate cannot drift apart.+//+// The pages captured before the rule existed are real outputs and are not rewritten, so they are listed+// below with the verdict the rule gives them today and report SKIP with that verdict as the reason: the+// report still shows which captures clip. A page that is not listed (a new capture) is graded.+// scripts/tests/page-scroll.test.js pins this list against the files, so a parser change that flips a+// verdict, or a new capture that does not pass, fails the plugin suite rather than drifting silently.++'use strict';++const path = require('node:path');+const { analyzePageScroll } = require('../../../../plugins/model-apps/scripts/lib/page-scroll.js');++const SCROLL_CONTEXT_ASSERTION = 'Generated .tsx establishes a scroll context: its top element is bounded by the host (height 100%) and scrolls, or holds a bounded scrolling body, so content below the fold is reachable';++// Keyed by the page's path below evals/model-apps/genpage/fixtures/, with forward slashes. The verdict+// words are the ones verdictOf returns: fail, padding, unproven:<reason>.+const CAPTURED_BEFORE_THE_RULE = Object.freeze({+ '11-recruitment-multi-page/candidate-list.tsx': 'padding',+ '11-recruitment-multi-page/hiring-metrics.tsx': 'fail',+ '11-recruitment-multi-page/interview-schedule.tsx': 'padding',+ '11-recruitment-pages-real/candidate-list.tsx': 'fail',+ '11-recruitment-pages-real/hiring-metrics-dashboard.tsx': 'fail',+ '15-support-tickets-real/support-tickets.tsx': 'fail',+ '17-weather-mock-data/weather-dashboard.tsx': 'fail',+ '18-sharepoint-connectors/sharepoint-docs.tsx': 'fail',+ '19-add-weather-connector/weather-panel.tsx': 'fail',+ '2-mock-dashboard-real/sales-dashboard.tsx': 'unproven:style-expression',+ '2-mock-dashboard/dashboard.tsx': 'fail',+ '20-upload-preservation/revenue.tsx': 'fail',+ '22-navigation-contract/before/overview.tsx': 'fail',+ '22-navigation-contract/before/pet-gallery.tsx': 'fail',+ '22-navigation-contract/before/pet.tsx': 'fail',+ '22-navigation-contract/overview.tsx': 'fail',+ '22-navigation-contract/pet-gallery.tsx': 'fail',+ '22-navigation-contract/pet.tsx': 'fail',+ '23-worker-completeness/page.tsx': 'fail',+ '24-custom-api-lifecycle/page.tsx': 'fail',+ '24-custom-api-lifecycle/stages/with-api.tsx': 'fail',+ '25-solution-package/list.tsx': 'fail',+ '25-solution-package/metrics.tsx': 'fail',+ '25-solution-package/schedule.tsx': 'fail',+ '26-customer-lookup/customer-lookup.tsx': 'fail',+ '27-page-error-helper/order-approvals.tsx': 'fail',+ '4-case-wizard/page.tsx': 'fail',+ '5-kanban-task-board/task-board.tsx': 'fail',+ '6-traffic-analytics-mock/traffic-dashboard.tsx': 'fail',+ '8-account-metrics-new-app/account-metrics.tsx': 'fail',+ '9-project-tracker-new-entities/project-tracker.tsx': 'fail',+ 'stable-turn-retry/ordinary/revenue.tsx': 'fail',+ 'stable-turn-retry/revenue.tsx': 'fail',+});++// One word for what the rule says about a page: pass, fail (no scroll context), unproven:<reason> (the+// rule cannot read the top element), padding (it scrolls, but a padded box overhangs the host), or+// "not judged: <why>" (no default export the rule can find, or it renders nothing).+function verdictOf(source) {+ const r = analyzePageScroll(source);+ if (!r.judged) return { verdict: `not judged: ${r.why}`, problem: null };+ const fail = r.problems.find((p) => p.code === 'no-scroll-context');+ if (fail) return { verdict: 'fail', problem: fail };+ const unproven = r.problems.find((p) => p.code === 'scroll-context-unproven');+ if (unproven) return { verdict: `unproven:${unproven.reason}`, problem: unproven };+ const padded = r.problems.find((p) => p.code === 'scroll-context-padding');+ if (padded) return { verdict: 'padding', problem: padded };+ return { verdict: 'pass', problem: null };+}++// `fixture.dir` is the fixture's own folder (fixtures/<dirName>); a page's key is its path below the+// fixtures root, so a page in a subfolder of the fixture keeps that subfolder.+function capturedKey(fixture, file) {+ const rel = fixture && fixture.dir ? path.relative(fixture.dir, file.path) : file.name;+ return `${fixture && fixture.dirName ? fixture.dirName : ''}/${rel}`.replace(/\\/g, '/').replace(/^\//, '');+}++function gradeScrollContext({ files, fixture }) {+ const skipped = [];+ let graded = 0;+ for (const file of files) {+ const key = capturedKey(fixture, file);+ const { verdict, problem } = verdictOf(file.content);+ if (Object.prototype.hasOwnProperty.call(CAPTURED_BEFORE_THE_RULE, key)) {+ skipped.push(`${file.name}: captured before the rule (${verdict})`);+ continue;+ }+ if (verdict.startsWith('not judged')) continue;+ graded += 1;+ if (problem) return { status: 'fail', reason: `${file.name}:${problem.line}:${problem.column}: ${problem.code}: ${problem.message}` };+ }+ if (graded) return { status: 'pass', reason: '' };+ return { status: 'skip', reason: skipped.length ? skipped.join('; ') : 'no page the rule judges' };+}++module.exports = { SCROLL_CONTEXT_ASSERTION, CAPTURED_BEFORE_THE_RULE, gradeScrollContext, verdictOf };diff --git a/evals/model-apps/genpage/tests/run-layer-2.test.js b/evals/model-apps/genpage/tests/run-layer-2.test.jsindex e1851aa76..b405e1501 100644--- a/evals/model-apps/genpage/tests/run-layer-2.test.js+++ b/evals/model-apps/genpage/tests/run-layer-2.test.js@@ -33,7 +33,7 @@ test('runner: exits 0 when fixture passes all assertions', () => {// Minimal v2.1-compliant single-file mock page.writeFixture(root, '2-mock-clean', {'page.tsx': `import { makeStyles, tokens } from '@fluentui/react-components';-const useStyles = makeStyles({ root: { padding: tokens.spacingHorizontalM } });+const useStyles = makeStyles({ root: { height: '100%', overflowY: 'auto', boxSizing: 'border-box', padding: tokens.spacingHorizontalM } });const data = [{ a: 1, b: 'x' }, { a: 2, b: 'y' }];const GeneratedComponent = (props) => {const { pageInput } = props;@@ -99,14 +99,14 @@ test('runner: --tier smoke filters to smoke evals only', () => {'page.tsx': `import { makeStyles } from '@fluentui/react-components';const useStyles = makeStyles({ r: {} });const data = [{ a: 1 }, { a: 2 }];-const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div style={{ height: '100%', overflowY: 'auto' }} />; };export default GeneratedComponent;`,});writeFixture(root, '4-full', {'page.tsx': `import { makeStyles } from '@fluentui/react-components';const useStyles = makeStyles({ r: {} });const data = [{ a: 1 }, { a: 2 }];-const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div style={{ height: '100%', overflowY: 'auto' }} />; };export default GeneratedComponent;`,});const { code, stdout } = runRunner(['--fixtures', root, '--tier', 'smoke']);@@ -127,7 +127,7 @@ test('runner: --eval <id> runs only that eval id', () => {'page.tsx': `import { makeStyles } from '@fluentui/react-components';const useStyles = makeStyles({ r: {} });const data = [{ a: 1 }, { a: 2 }];-const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div style={{ height: '100%', overflowY: 'auto' }} />; };export default GeneratedComponent;`,});writeFixture(root, '4-y', {@@ -160,7 +160,7 @@ test('runner: skips folders without numeric prefix', () => {'page.tsx': `import { makeStyles } from '@fluentui/react-components';const useStyles = makeStyles({ r: {} });const data = [{ a: 1 }, { a: 2 }];-const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div style={{ height: '100%', overflowY: 'auto' }} />; };export default GeneratedComponent;`,});const { code, stdout } = runRunner(['--fixtures', root]);@@ -181,7 +181,7 @@ test('runner: emits TAP version 13 header and aggregate counts', () => {'page.tsx': `import { makeStyles } from '@fluentui/react-components';const useStyles = makeStyles({ r: {} });const data = [{ a: 1 }, { a: 2 }];-const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div style={{ height: '100%', overflowY: 'auto' }} />; };export default GeneratedComponent;`,});const { stdout } = runRunner(['--fixtures', root]);@@ -205,7 +205,7 @@ test('fixture-loader: excludes RuntimeTypes.ts from check', () => {'page.tsx': `import { makeStyles } from '@fluentui/react-components';const useStyles = makeStyles({ r: {} });const data = [{ a: 1 }, { a: 2 }];-const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div/>; };+const GeneratedComponent = (props) => { const { pageInput } = props; void pageInput; return <div style={{ height: '100%', overflowY: 'auto' }} />; };export default GeneratedComponent;`,'RuntimeTypes.tsx': `// This file should be excluded from checks - it has TODO`,});@@ -223,7 +223,7 @@ test('runner: the registered Phase-5b column checker executes and can fail the rt.after(() => fs.rmSync(root, { recursive: true, force: true }));writeFixture(root, '1-phase-5b', {'page.tsx': `import { makeStyles } from '@fluentui/react-components';-const useStyles = makeStyles({ root: {} });+const useStyles = makeStyles({ root: { height: '100%', overflowY: 'auto' } });const data = [{ name: 'First' }, { name: 'Second' }];const GeneratedComponent = (props) => {const { pageInput } = props;diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.jsonindex 9a839a8dc..eb0daba19 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.24.0",+ "version": "2.25.0","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.jsonindex 9a839a8dc..eb0daba19 100644--- a/plugins/model-apps/.plugin/plugin.json+++ b/plugins/model-apps/.plugin/plugin.json@@ -1,6 +1,6 @@{"name": "model-apps",- "version": "2.24.0",+ "version": "2.25.0","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.mdindex 6ea6eef07..b74fccece 100644--- a/plugins/model-apps/AGENTS.md+++ b/plugins/model-apps/AGENTS.md@@ -1679,6 +1679,41 @@ the pipeline and delegates each script's **behavioral spec** to the entries belodashboards, solution). It reads through a throwaway SDK workspace, never the folder's`.maker-workspace` — a copy an interrupted build left there made the download fail, or describe editsthat were never saved to Dataverse — and writes only the baseline (`last-applied.json`) into it.+ **The page tree is swapped in whole, never written over the old one** (`writePageTree`, #814): the new tree is+ written to a hidden swap folder `<out>/.pages-replace.<pid>.<random>.tmp`, `pages/` is checked again and moved+ into it, the new tree is moved to `pages/`, and only then is the swap folder (the previous tree) removed. A+ failure part-way (a full disk, a lock) leaves `pages/` as it was — the maker's unsaved page edits are never+ lost; a refused move-in puts the previous tree back, and if that fails too nothing is deleted and the error+ names both folders; a swap folder that cannot be removed at the end is a warning. A stopped run's swap folder+ is never reused, moved or deleted; one that holds a `previous` tree (the maker's pages from before that run,+ the only copy when it stopped between the two moves) is named in one warning by the next download, which goes+ on. Every fs operation on a path in a folder the download made (the swap folder, its `new` and `previous`+ trees, the managed download's `.download-pages.*` staging folder) goes through one guarded fs+ (`generatedFolders`): each mkdir, each file write (the temp file, its rename into place, and the real-path+ lookup that aims it), each rename attempt (every retry of the move-in and of the move-back included),+ each removal, and each read (a listing, a stat, a file's bytes) is preceded by its own check that the folder+ made, and every folder between it and the path, is still the plain folder made at its own path+ (`ownedDir`), and that the path is not a link. Reads count because the managed download reads its staged+ tree back (the page metadata the spec states, each page file whose page ids it rewrites, and every file it+ publishes), so a staging folder replaced by a junction would otherwise hand on page sources from wherever+ the junction points. One replaced by a link or junction (or moved away with one put at its name) is refused+ (`UNSAFE_OUTPUT`) and marked: nothing more is read, written, moved or removed under it, no clean-up descends+ through it (a warning names it), and the previous pages are moved back only while `previous` still passes+ the check — otherwise the error names where they had been moved. A staging folder found replaced at any+ check — its removal after the last read included — refuses the download (`runDownload`): nothing read from+ it is published, and `pages/` is not written. A test holds `writePageTree`, the staged readback and their+ helpers to that fs (no raw read, write, mkdir, rename or removal). What a check cannot close is the interval+ between it and the one syscall it guards, a read or a write; no wait sits there, since a retry's wait comes+ before the next attempt's own check. Before the maker's `pages/` is moved aside, `new`, each page folder in+ it and each file written there are checked once more and must still be there (a folder as a folder, a+ file as a file), so a page folder replaced by a junction after its files were written is refused+ (`UNSAFE_OUTPUT`) and a page folder or file removed from `new` fails the download (`IO_ERROR`) rather than+ an incomplete tree being moved into `pages/`. **Every CLI download stages its page tree**:+ `main` passes `runDownload` `stagePages`, so the tree is written to a `.download-pages.*` staging folder,+ read back and rewritten there, and `stagedPages.check`/`publish` (the same swap) run only after the+ lossy-download gate, the App Spec validation and, for `--include-managed`, the fragments file — a refusal+ or a failed write before then leaves `pages/`, `app-spec.json` and the baseline as they were. A library+ caller that omits `stagePages` still has `runDownload` write `pages/` itself.**The navigation titles are read in the language a rebuild of the spec resolves, and only in a language thedownload knows**: `--language-code` (read as the build and verify read it), else the `languageCode` the specalready on disk pins, else the environment's base language (one read through the download's own client,@@ -2942,10 +2977,11 @@ charts phases. A spec that uses none of them takes the legacy paths unchanged. Wand another name tried. Files from earlier downloads stay. With nothing due nothing is written or removed. Alink, junction or file at `.maker-workspace`, or no name free after 8 tries, is `managed-fragments-unwritable`.It is settled after the restore and the validation and before anything is published: `main` passes- `runDownload` `stagePages`, which writes the page tree to a hidden staging folder inside `<out>`, reads it- back and answers `stagedPages` (`check`, `publish`); the tree, the spec and the baseline are written only- after the fragments file, so a failure there leaves every output as it was. The restored form is the group's- `consumerState.declaration` (`DECLARATION_KEYS`, `autoSubgrids` included). A plain download reads no form.+ `runDownload` `stagePages` (as it does for every download), which writes the page tree to a hidden staging+ folder inside `<out>`, reads it back and answers `stagedPages` (`check`, `publish`); the tree, the spec and+ the baseline are written only after the fragments file, so a failure there leaves every output as it was. The+ restored form is the group's `consumerState.declaration` (`DECLARATION_KEYS`, `autoSubgrids` included). A+ plain download reads no form.The download writes no store and transfers no binding authority: the first binding of a form from thedownloaded folder needs `adopt:form:<key>`, and an identical unbound no-op may leave it unbound.**A removed form deleted in Maker** (`retireAbsentRemovedForms` in `sdk-build.js`, before the store's tables@@ -3338,7 +3374,36 @@ retry runs the same command again over the same store, so it finds the rows at tbound (a lost or uncertain create stops as `create-outcome-unknown`, never retried). The `adopt:` approvals astop prints are read by `configurationAuthorizationKeys` (`adopt:<kind>:<port key>`,`adopt:<child kind>:<encoded port key>/<encoded slot>`; only under the opt-in, the root and child declared) into-`opts.configurationApprovals`; a root's approval never covers its children. The build's configuration items+`opts.configurationApprovals`; a root's approval never covers its children. A single namesake at another id (a row+a maker made before the opt-in) of an environment variable, a connection reference or a Custom API (`ADOPTABLE`) is+adopted at its own id only through `adoptionOf`/`adoptNamesake` (`configuration-protected.js`). A duplicate rule's+namesake is never adopted and keeps the plain `create-identity-conflict` stop after the same reads: an adopted rule+would be reconciled by the rule path, which neither holds the edit to the printed list nor keeps from publishing a rule+edited after the acceptance (`planOf` refuses an as-is rule plan too). For the adoptable kinds: the row read exactly, every row under it listed completely and paired with the+declaration (`planOf` `childIdOf`; an undeclared row is a removal and refuses), the fixed fields (`IMMUTABLE`) and+the name's case equal, the change the build would then make judged with the bound-edit verdicts, a first value, a+clear or a private value or connection other than the settings' refused, and every member in the solution+(`asIsReason`). The preflight stop (`adoptionHalt`) keeps the+`create-identity-conflict` sentence byte for byte and appends either why it cannot be adopted or the field pointers+(names only) and one token per row, `adopt:<kind>:<port key>@<row id>[+<digest>]` /+`adopt:<child kind>:<encoded port key>/<encoded slot>@<row id>` (the digest is the first 16 hex of SHA-256 over the+sorted pointer list). `configurationAuthorizationKeys` types the two meanings apart: a plain approval stays `adopt:...`, an`+`@<row id>` one becomes `adopt-row:...` (which no plain approval reads as), and a token whose two readings both name+declared items is refused (`CONFIGURATION_ADOPT_AMBIGUOUS`); `adoptionOf` reads its printed tokens back the same way and+refuses to offer a namesake whose approval would be ambiguous. Rule and condition tokens keep only their plain reading,+as in 2.24.0 (a rule or condition key is free text, so `odd@<id>` is just that key). The build error (`configuration-build.js`) prints each+adoptable item's tokens beside its own id and pointer list, so no token is printed without its details. Data-source+variables are planned after their declared parent (`parentsFirst`), and a child is located against its parent's+protected binding, committed or adopted in this build (`parentIdOf`), never its derived id. In `resolve`, under every token: `ctx.begin` the as-is plan (`planOf` `asIs`: update rows only, the row's own+values as expected, no publish effect), `captureReadOnly`, `adoptionOf` again (the same id, rows, pointers and+tokens), then `acceptReadOnly` with the adoption's token function; a refusal or an unreadable read releases+the attempt and commits nothing, and nothing is sent. Records carry `origin: 'adopted'`, and `locateItem` takes the+child ids from them. An item adopted in this build keeps its as-is rows and pointer list (`adoptedHere`): `update()` observes the row again+and sends only if it is still as accepted and the change is exactly that list, else stops with nothing sent (a later+build plans it as an ordinary bound item). A pending adoption attempt is retired only when proven unsent (`retireAdoption`) and never sent+as a create (`run()` refuses it). Older plugins: the `@` token is an unknown item; an adopted group with no children+is bound; one with children is `create-identity-unverified`; a cut-off adoption attempt is+`managed-pending-intent-changed`. The build's configuration itemswork in a throwaway SDK workspace per command run (`makeSdk`), so a kept local copy lasts until that run ends.Edits: a duplicate rule is created with its conditions, completes its initialpublication/state, and is then only verified (any later field, condition or state change, the@@ -3816,7 +3881,7 @@ scripts/genpage-plan-provenance.js ← /genpage: quarantine a stale plan before the planner writes, then verify the written plan targets the pages the approval named and, for an edit, carries the exact approved change list; for a create, also that its assumptions, data-semantics decisions and lookup records are the approved ones, field by field (`lib/genpage-plan-semantics.js`) — `--require-assumptions` (a newly authored plan carries them all), `--lookup-metadata <file>` (every observed lookup matches the saved metadata read; a planned one may then be promoted), `--require-observed-lookups` (none still planned before generation); an unknown flag is a usage error (exit 1)check-page-files.js ← /genpage: pre-dispatch gate — the page file names of the plan's one ## Pages table are safe write targets (lib/page-file-targets.js)genpage-worker-output.js ← /genpage: accept a parallel worker's page only if complete (default export, balanced, no elided code)- check-griffel-styles.js ← /genpage and /app-builder: a page's `makeStyles` calls hold none of the ten shorthands Griffel's runtime drops (lib/griffel-styles.js; see "Griffel shorthands" below)+ check-griffel-styles.js ← /genpage and /app-builder: a page's `makeStyles` calls hold none of the ten shorthands Griffel's runtime drops (lib/griffel-styles.js; see "Griffel shorthands" below, and the page establishes its own scroll context (lib/page-scroll.js; `--existing` makes that a note; see "Page scroll context" below)capture-fixture.js ← Copies /genpage working dir into an eval fixture and runs both runnerslib/entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column (unless the run's throttle budget refused to wait for the change set: the phase then stops, `stop`); a column create or status-reason insert for a table this attempt just created that is refused with that table's lag (HTTP 400 `0x80040216`/`0x80090457`) is read, and sent again only when a read proves it absent, within the table's budget (`createInLagWindow`, `recoverRefusedBatch`, `drainLagStatuses`; a spent check is the original refusal, its halt saying the build may be run again); the primary name column's length is always sent (100 unless the spec gives one), its required level is asked in the create when the spec states one (and said applied only when the SDK confirms it) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; `makeRunner`, whose runner stops the phase at the next step once the run's throttle budget has refused a wait (`stopIfRefused`: `run` and each item of its `mapLimit`; a step that pays the name column length a table the run created is owed is let through; a step taken up again later in its phase — a status reason its table's lag deferred — keeps its number and names the outcome it replaces, so every step stays within the plan's total and the summary counts it once); and `mapLimit`, the bounded fan-out every parallel path reuses@@ -3866,6 +3931,7 @@ scripts/page-plan.js ← pure App Spec → plan-document projection used by write-page-plan.jspage-structure.js ← the one structural gate a generated page must pass (empty, truncated, prose, elided), shared by genpage-worker-output.js and promote-intent-pages.jsgriffel-styles.js ← the ten shorthands Griffel's runtime drops, found as keys of a `makeStyles` style object (any depth, code only — the plugin's own lexer), with their longhands and where each sits (`within`: its slot, selectors and at-rules; `owner`: the `makeStyles` hook, by the name it is bound to at the top of the page — through a type annotation, or as a property — and null for a call the page does not prove a name for; `branch` and `arms`: which style object of that call, and which object of each value below it, where a condition chooses between two); shared by check-griffel-styles.js, `genpage-upload.js` (refuses a create, and an update's NEW keys — `griffelProblemsNotIn` tells them from the deployed page's) and the build's pages-phase scan (halts a new or changed page, warns for one it sends as it is), whose texts (`describeGriffelRefusal` / `describeGriffelWarning`) say what each way out does to the page; and the tests+ page-scroll.js ← does a page establish its own scroll context: follows the default export to the page's top element (TypeScript parser) and proves an element from there down is bounded and scrolls; `no-scroll-context`, `scroll-context-unproven` (with `reason`) or `scroll-context-padding`, each with a remedy the check always accepts (see "Page scroll context" below)page-file-targets.js ← the one page-filename rule (absolute/backslash/traversal/.tsx only/links/case collision, incl. with files already there), shared with check-page-files.js and the evalsapp-source-path.js ← shared lexical + realpath confinement for app source reads/uploads and hashespage-ownership-records.js ← local CREATE receipts and pre-delete ownership records, scoped to app/key/id; and the `pending` records of a page create that was started and not acknowledged (written before the create is sent, under the id it will use, with the name and the SHA-256 of the source it sends — one per create sent under the id; intent, never ownership: `readPageOwnership` does not see it, `readPendingCreations` / `completePendingCreations` settle it, and only evidence settles it — an acknowledged create, a page proven to be the one sent, a teardown that deleted the page — never an absence from a listing)@@ -3913,7 +3979,7 @@ scripts/app-component-scope.js ← what an edit of an app that is not about its components may ADD to them, held at the SDK's transport (`makeAppComponentScope()`: `wrap(httpClient)`, `limit(appId, { views }, work)`). Every `pushArtifact('app', …)` of an existing app (the bundle's `appApi.update`) PATCHes the sitemap and then posts ONE AddAppComponents whose list it DERIVES: for each Entity sub-area the table, EVERY active Main form, EVERY active public view and EVERY chart, for each DashBoard sub-area the dashboard — whether or not the app has them, and `components.mainFormsByTable` narrows the Main forms alone. AddAppComponents only adds, so a page edit that went through it put back what the app's maker had taken out, and its publish made it live. The bundle is never patched and cannot be told to skip the derivation, so the page backend (`placeInApp`, `removeFromApp`) keeps the SDK's sitemap write and has the post limited where it leaves the process: to the views the edit pins, and — when none is left — not sent at all (the SDK is answered with the service's 204). The action is found by the PATH of the address, percent-decoded as a whole before its trailing slashes are dropped and its last segment is read (a query string or fragment that mentions the name is not it; `AddAppComponents%2F` and `%41ddAppComponents` are it, in another spelling), and every POST is read ONCE while an edit is open — its address as text, its body as the plugin's transport takes it (text as it is, bytes copied, an object serialized as the transport serializes it and read back as plain data) — decided on in that CANONICAL form and sent in that form in every branch (the action it cuts, another app's request, a request to another address, a batch), never the object, bytes or address the caller holds, which the transport would read again: a `toJSON`, a getter or an address that answers differently the second time cannot undo the limit, and JSON text and the UTF-8 bytes of it are parsed for the action. While an edit is open, a request that IS the action in a shape the limit does not read — another spelling of the name, an address or path that cannot be decoded, a body that is JSON text (for a `post`), is not JSON or cannot be serialized, or has no list — or that does not carry every view the edit pins (a view named as a reference, or left out), or a `$batch` that may carry the action, through `post` and `postRaw` alike (a part of a batch cannot be limited: one classifier reads a multipart batch request line by line and a JSON batch entry by entry, each address as any address is read, and a JSON batch after its JSON is), is REFUSED with the bundle's `SdkError` `APP_COMPONENTS_NOT_LIMITED`: not sent whole and not answered as done. The one change set read whole is the bundle's guarded pin (since model-apps 2.20.6: an unpublished default-mode push that holds the app token and reads a derived component missing from the current layer sends `PATCH {}` under that token, the action and an echoed `PATCH {}` as ONE change set): for an app with an edit open, exactly that change set is not sent, and the SDK is answered with a refused guard, so it sends its plain action once, limited as above — no app-row write, the writes of earlier releases; any other change set that names the action is refused. The bundle of 2.21.0 says so in a note of the push, `APP_PIN_TOKEN_UNCONFIRMED (guardRefused)` (the app token it holds may be stale): `limit` takes out that one note for that app when the limit itself answered the guard — nothing reached the service, and the page backend fetches the app with overwrite before each push it makes, so no edit is made under that token — and keeps every other (`APP_PIN_REBASE_REQUIRED`, a guard the service refused). `placeInApp` reports in `pinnedViews` only the views the app's current layer is read back holding after the push, and warns of the rest. A raw POST (`postRaw`: a real POST whose body the transport does not touch, which the bundle uses for `$batch` only) is told by its address exactly as a `post` is, so the action cannot escape the limit by the method that carries it: one to the action's address is limited as the object form is when its body is JSON text of the same object, the UTF-8 bytes of it or an object, and what goes on is a form the transport sends as it is — JSON text for text and for bytes (the transport would send a Buffer as `{"type":"Buffer",…}`), the plain object for an object — with any `Content-Length` the caller declared, in whatever spelling, rewritten to one header with the exact length of what is written; it is refused when its body cannot be read that way. The SDK reports that as a warning of the push ("one or more components were not pinned"), so the sitemap the edit saved stays saved and nothing unlimited reaches the app. A page is a GenPage sub-area, which needs nothing from the app's components, and everything the SDK derives belongs to a sub-area that was there before the edit. The build owns the whole app and never opens an edit; an SDK lent to the backend keeps its owner's transport, and is not limited. Pinned against the real bundle by `genpage-app-edit-real-bundle.test.js` — the re-vendor tripwire for the request's shape, which also pushes the app through the limit — over the plugin's own transport, under a fake service that reads the wire (the body as JSON, a `Content-Length` that must be its length) — with that request changed, or sent through the raw method, to see the limit and the refusal as the user doesgenpage-base.js ← base-marker hash, compare, and read/write (sibling dotfile of the code file; no environment URL; `appId` is optional — a page created before any app held it is recorded with the page alone, and the first update that names the app it was then placed in goes ahead on that marker and records the app; `unfinished` (`publish` or `place`) is set only by an upload that CREATED the page and did not finish it, and is what lets `genpage-upload.js --page-id` finish exactly that page — it is cleared when the page is finished, and `genpage-base.js record` never writes it)safe-fs.js ← confined output writes and deletes: the named directory's final component must not be a link or junction (readlink, not a path-text compare, so an 8.3 name and a share root stay usable); write via exclusive temp + rename, or — with `exclusive: true` — never replace a name: the content goes to a sibling file this process created exclusively and is published with a hard link to the target name (which fails if the name exists, so the file system decides and a file that appeared meanwhile is never overwritten: `IO_ERROR` with `reason: 'exists'`; where hard links do not exist the write fails closed, `reason: 'no-hard-links'`), and only that sibling is ever removed — retried, and reported (a warning after a publish, the error after a failure) when it cannot be — and a later write of a file that still has its second name is refused naming it. Everything it writes or appends has the access tokens the process obtained taken out first (`lib/output-redaction.js` `redactFileData`: a text as a text; bytes — any ArrayBuffer view, or a string given with a `hex`, `base64` or `base64url` encoding — masked with as many `*`, and data it cannot read refused before anything is written): it is the one writer of the build's journal and status file, of a download's files and of a page's file and its deployed copy. Shared by genpage markers and later callers- rename-retry.js ← the one rename that outlasts a brief Windows file lock (EPERM, EACCES or EBUSY while a scanner or a second process holds the file): on win32 only, the same rename is repeated after growing pauses (25 ms doubling to 1 s), at most 5 s for one rename and 30 s for the whole process (the wait blocks the event loop, so it must stay well inside the teardown heartbeat and the transport's timeouts; once the 30 s are spent every later refused rename is ONE attempt), then the ORIGINAL error is thrown untouched, so every caller keeps its message and code; any other platform or code is one attempt. Used ONLY by `apply-snapshot-store.js` for files the plugin owns: those it serialises with a lease and compare-and-set (`writeFileAtomic` — which the managed binding store, the snapshot and the page, dashboard and web-resource records write through) and the distrust markers, which take no lease (they must be recordable while another writer holds it) but are each created under a name unique to the call; each site has a note why repeating is safe there; a target that an unleased writer can also write passes `{ retryLock: false }` and renames once (the deployed baseline, which the download writes without the build lease). NOT used by `safe-fs.js` (a maker's files and the diagnostic status file keep their own 25-400 ms waits), by the folder move-aside of `clearWorkspace` (one attempt: the approval was for the folder as it is now) or by `temp-workspace.js` (its own shorter waits). A test that keeps a rename failing for good calls `tests/helpers/short-rename-wait.js`, which also restores the process total+ rename-retry.js ← the one rename that outlasts a brief Windows file lock (EPERM, EACCES or EBUSY while a scanner or a second process holds the file): on win32 only, the same rename is repeated after growing pauses (25 ms doubling to 1 s), at most 5 s for one rename and 30 s for the whole process (the wait blocks the event loop, so it must stay well inside the teardown heartbeat and the transport's timeouts; once the 30 s are spent every later refused rename is ONE attempt), then the ORIGINAL error is thrown untouched, so every caller keeps its message and code; any other platform or code is one attempt. Used by `apply-snapshot-store.js` for files the plugin owns: those it serialises with a lease and compare-and-set (`writeFileAtomic` — which the managed binding store, the snapshot and the page, dashboard and web-resource records write through) and the distrust markers, which take no lease (they must be recordable while another writer holds it) but are each created under a name unique to the call; each site has a note why repeating is safe there; a target that an unleased writer can also write passes `{ retryLock: false }` and renames once (the deployed baseline, which the download writes without the build lease). Also used by the download's page-tree swap (`writePageTree`) for the move of its own new tree into `pages/` and the move of the previous tree back, both folders under a name only that run knows. NOT used by `safe-fs.js` (a maker's files and the diagnostic status file keep their own 25-400 ms waits), by the folder move-aside of `clearWorkspace` (one attempt: the approval was for the folder as it is now), by the page-tree swap's move of the maker's `pages/` aside (one attempt: a wait would let the checks made on it go stale) or by `temp-workspace.js` (its own shorter waits). A test that keeps a rename failing for good calls `tests/helpers/short-rename-wait.js`, which also restores the process totalhydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)verify-spec.js ← spec-vs-deployed reconciliation core (checks are ordered tasks on a pool of 4)status-reasons-keys.js ← a table's status reasons (with their states) and alternate keys (with their columns), one narrow read each (`readStatusReasons`, `readAlternateKeys`: `{ state: 'ok' | 'absent' | 'error' }`, never a throw), and the checks of the declared ones against them (`statusReasonChecks`, held to the build's own `statusReasonTargets`; `alternateKeyChecks`) — verify's `status-reason` and `alternate-key` checks@@ -4018,6 +4084,29 @@ Fluent UI V9 styles are Griffel's, and Griffel's runtime silently drops ten shor- **`check-griffel-styles.js`** has no notion of what is deployed: it reports every key it finds, a page's old ones included. For a page that already had one, deleting it is the edit that preserves the page (`/genpage`'s edit flow says so).- **Who runs it.** Three places, so no path to an upload skips it. The orchestrators run it per page, before any transpile or upload, for quick feedback: `/genpage` (single page, multi-page, edit flow, and the §7.5 fix after a browser verify) and `/app-builder` (before `promote-intent-pages.js`, and for a page edited by hand before a rebuild). The page-builder worker has no shell, so its Step 2.6 gives it the rule and a Grep self-review instead. And the code **enforces** it where pages are uploaded, whatever the instructions did or did not get run: `genpage-upload.js` reads the code file first and refuses a create with `code: "griffel-shorthand"` (file, line, column, longhands and what each way out does in `error`, the same list in `problems`; before a backend is made or anything is read from the environment; a file it cannot read is refused) and, for an update, any key the deployed page did not already have (above), and the build's pages phase halts as `pages-griffel-shorthand` in its pre-write scan, before any page is created or updated, for each page that run uploads that is new or changed (a changed-only run checks only the pages it selects; a full build checks every implemented page). Both write the page from the text they checked, never from the file again: the upload script reads the code file once and sends exactly those bytes (an update reads the deployed page and the app's navigation first — seconds in which the file can be saved), and its base marker records their hash; the build writes every page from the text its scan read, and records their hash. `genpage-upload.js` refuses `--compiled-code-file`, since that JavaScript would be deployed instead of the checked TypeScript (the SDK compiles the page itself, from the TypeScript it is given). Both build their text with `describeGriffelRefusal` / `describeGriffelWarning`, so one defect has one wording. It is deliberately not part of `genpage-worker-output.js` / `promote-intent-pages.js`: their failure sends the page back for a full rewrite, and this one is fixed by a targeted edit. The one rule text is the same in `references/rules.md`, the genpage skill and edit flow, the page-builder agent and the app-builder skill, and `genpage-dispatch-contract.test.js` fails if any drops it or the command (and if `verify-flow.md` or the app-builder edit step drops the check).+### Page scroll context++The generative-page host renders a page inside a container of fixed height (the page root's parent is a host `FluentProvider` div with a definite height) and nothing above the page scrolls: every ancestor is `overflow: hidden` or `visible`, and the window does not scroll. So a page that does not establish its own scroll context shows only what fits, and everything below the fold is cut off with no scrollbar and no error (AB#6793599). The reported pages were flex columns with no bounded height; the rule that said otherwise lived only in the dark-mode section of `references/rules.md`. Live-verified on the host: a root with `height: "100%"` and `overflowY: "auto"` scrolls to its end; `overflowY` alone, `minHeight: "100%"`, and a two-div wrapper around a bare inner root all clip; a fixed header over a `flex: 1`, `minHeight: 0`, `overflowY: "auto"` body scrolls; and a content-box root with `height: "100%"` and 16 px of vertical padding scrolls but keeps its last 16 px below the visible area, which `boxSizing: "border-box"` fixes.++- **The rule** (`scripts/lib/page-scroll.js`). It parses the page with the vendored TypeScript, follows the default export (through `memo`/`forwardRef`, an alias, an error-boundary class, a function declared below its `export default`, body components and components that render their `children` inside a box of their own) to the page's top element, and requires an element from there down that is bounded (a definite `height`/`maxHeight`, or a growing flex item in a bounded flex column with its automatic minimum removed) and scrolls (`overflowY` auto or scroll), with every element above it bounded. A percentage `height`/`maxHeight` is bounded only under a parent of *definite* height (a `height`, or a growing flex item of a definite column): a parent bounded by `maxHeight` alone bounds itself, but a `height: "100%"` child of it grows (CSS 2 §10.5). A `minHeight` that may be larger than the bound defeats it. One that is the same value as the bound (`calc()` included, whitespace aside) fits; two literals of the same unit (px, %, rem, em, vh) are compared within that unit, never converted, and a larger one fails; one the check cannot compare (px against a percentage or a rem, a token) is `scroll-context-unproven` with reason `min-height` (or the token's own reason). The alternatives of a condition (`a ? <X/> : <Y/>`, `a && <X/>`, a local component's arms, a `.map` callback's returns) are on screen one at a time, so each one that renders content must provide. One that renders nothing, or only recognised state views, is not judged: `Spinner`, `ProgressBar`, `Skeleton`, `MessageBar` and the Fluent text components (`Text`, `Body1`, `Caption1`, `Title1`, …), holding only text, values, their own parts (`MessageBarBody`, `SkeletonItem`, an action `Button`) and inline tags (`STATE_VIEWS` in the lib). Any other library or imported component in an alternative (a `Card` holding rows) is content whose layout the check cannot see, and is judged; one alternative that scrolls beside one that does not, or cannot be shown to, is `scroll-context-unproven` with reason `partial-alternatives`. It reads `makeStyles` slots (through `mergeClasses` and conditions) and inline styles; what it cannot read is `scroll-context-unproven` with a `reason`, never a pass. An element on that path that fills its container — its `height` or `maxHeight` is exactly `"100%"` or `calc(100% - N px)` with N smaller than its vertical padding in px, and its used height, `max(minHeight, min(height, maxHeight))` as CSS sizes it, is not provably smaller than the container by at least that padding (only `calc(100% - N px)` with N at least the padding proves it: `height: "100%"` under `maxHeight: "calc(100% - 64px)"` leaves room, but not under a looser `maxHeight: "150%"`, a fixed `maxHeight` the check cannot compare with the host, or with a `minHeight: "100%"` that wins over the maximum) — with vertical padding (any padding key that is not literally 0, a token or shorthand included) and no `boxSizing: "border-box"` is `scroll-context-padding`; `50%`, a calc() that leaves room for the padding or whose padding is a token, a box sized by flex or by a fixed length, and a scroll container in a flex column are not. That includes a bounded root that does not scroll around a scrolling body, because its padding pushes the body's end below the host in the same way (reasoned from the measurement, not measured).+- **The remedy always works.** Each message gives one edit: `height: "100%"`, `overflowY: "auto"`, `boxSizing: "border-box"` (plus `minHeight: 0` when the element has a `minHeight` that may be larger than its container, or one the check cannot read) on the top element's `makeStyles` slot (with any overflow key in that slot deleted), or as the last keys of its inline `style`, made its last attribute, when its class cannot be read (an inline style wins over every class). For a library top element (`<Card>`), the edit wraps it in a `<div>` that has those keys. `page-scroll.test.js` applies the remedy to every shape the check rejects, including a template-string `className`, a spread of attributes and a `minHeight` that wins, and requires a pass. In a bounded flex column the message also advises `flexShrink: 0` on items that clip their own content: a Fluent `Card` is `overflow: hidden`, so it has no automatic minimum height and would be squeezed.+- **Who runs it.** `check-griffel-styles.js` runs it on every file with a default export, after the Griffel check. Its problems are appended to `problems` with exit 3, without the lib's internal `fix` object. The generation flows judge pages in full: `/genpage` 5b step 9 and 5c, the §7.5 fix when verification follows generation, and `/app-builder` Phase 1.5 step 5. The flows that change a page the run did not generate pass `--existing`: the `/genpage` edit flow (its Phase 5 check, and the §7.5 fix when verification follows an edit) and the `/app-builder` hand edit. There the problems go to `notes` and do not change `ok` or the exit code, and the flow tells the maker and offers the edit, applied only if they agree. The one exception: when the maker's requested edit itself rewrites the page's top-level layout, that layout is new code written in this run, so the agent applies the remedy as part of that edit and tells the maker in one sentence that it did. `edit-flow.md` and `verify-flow.md` §7.5 state this in the same words, and `genpage-dispatch-contract.test.js` pins both halves and that no note is applied without asking. If the scroll check itself throws — including when the vendored compiler is missing or corrupt — the CLI adds a `scroll-check-failed` note and leaves the Griffel result and exit code as they were; it never reports a silent clean result. The page-builder worker has no shell, so it gets the rule and a self-review. The Layer 2 eval grades every generated page with the same lib (`evals/model-apps/genpage/lib/scroll-context.js`); the pages captured before the rule are listed with their verdicts and report a skip.+- **Browser verification** (`skills/genpage/verify-flow.md` 7.2 and 7.4) cannot scroll the window or read the document's height, since neither moves in the host: it finds the element that scrolls and holds more than it shows, scrolls it to the end, and requires the last content's bottom to be at or above the lowest point the scroller and its clipping ancestors leave visible. Content inside a scroll region of its own (a list in a fixed-height panel) is left out of that measure; each such region is then scrolled to its own end and measured the same way, so a region that has not been scrolled is not taken for a cut-off page, and a padded region that overhangs its panel is still caught. With no scroller, content below the window is the clipping defect. `genpage-dispatch-contract.test.js` pins those scripts; they were run against an offline replica of the host (a bare root, the remedy, a padded content-box root, a short page, a root with a scrolling list and a footer, and a root with a padded list that overhangs its panel).+- **Known limits.**+ - Not enforced at upload or build: `genpage-upload.js` and the build do not run this check, so a page that skipped the flows' step ships as it is. The Griffel refusals there suggest `check-griffel-styles.js`, which on such a page also lists its scroll problems; the suggested command adds `--existing` for a page that already exists (an upload that updates one, or a build whose page is not new), so its scroll findings are notes there.+ - An edit that removes a page's existing scroll context is reported only as a note (`--existing` does not compare with the deployed page).+ - `@media` and selector blocks are not read, so a media query that removes the scroll at one width is missed.+ - Only a component's final return is judged, so an early return (a loading or error view) is not checked, and the state views of a library top element are not followed.+ - Grid items are never taken as bounded, and what a library component does inside itself is not seen.+ - A loading or empty alternative wrapped in an element of the page's own (`loading ? <div><Spinner/></div> : <div scrolls/>`) is judged like content, so such a page is `partial-alternatives` until the scroll context moves to an element both alternatives share (the remedy on the top element does that).+ - A `minHeight` in px under a `height: "100%"`, or in one unit under a height in another, cannot be compared, so it is unproven rather than failed; the remedy's `minHeight: 0` resolves it.+ - The state-view list is by name: a page's own component named `Spinner` is followed as the page's code, but an imported component named like a state view, or a `MessageBar` holding only a value that is itself tall content (`<MessageBar>{rows}</MessageBar>`), is passed over.+ - Margins and borders are not added to the height. Whether bounded siblings add up (a `height: "100%"` child under a header overflows by the header's height) is not checked.+ - The `flexShrink: 0` advice is not checked.+ - A file is judged only if a regex finds a default export first, so a fragment's output is unchanged.+ - Keyboard: after a click on a row, focus lands on the host's own `#mainContent` wrapper, not in the page's scroller, so PageDown and End scroll nothing until focus is inside the scroller. No rule or check covers this.+ - The canonical page error block in `references/rules.md` ("Missing Error Handling") still renders a bare `<div>` as its `PageBody`, because tests execute it as written. `page-scroll.test.js` lists it as an excerpt.+### DataAPIThe DataAPI (`props.dataApi`) provides typed CRUD operations against Dataverse tables. It uses RuntimeTypes.ts (generated by `scripts/genpage.js types`, which replaced `pac model genpage generate-types`) for type safety. Column names must be verified from the generated schema — never guessed.diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.mdindex faa6162d8..7404a817a 100644--- a/plugins/model-apps/CHANGELOG.md+++ b/plugins/model-apps/CHANGELOG.md@@ -5,6 +5,22 @@ 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.25.0]++- **Pages scroll:** the rules teach a bounded, scrolling page root; `check-griffel-styles.js` stops a generated page whose layout it can show would clip below the fold, or that it cannot read, with exit 3 and the fix (AB#6793599).+- With `--existing` (downloaded pages) the same finding is a note and the exit code is unchanged.+- **Failure-safe downloads:** the new `pages/` tree is staged and swapped in whole after the download's checks; a refusal or failure before then leaves `pages/` as it was, and a failed swap puts it back (#814).+- If a swap cannot be undone, or a run stops mid-swap, the previous pages stay in the named `.pages-replace.*` folder to copy back; a later download reports it.+- The download checks its own folders before each operation and refuses one a link has replaced.+- **Adopt configuration made before opting in:** under `configurationIdentity: "stable-v1"`, an environment variable, connection reference or Custom API at another id can be adopted with the approvals the stop prints (#807).+- The stop names each row and the fields a later edit would change; adopting sends nothing, that build changes only those fields, and a changed, unreadable or out-of-solution row is refused.+- **Evals:** app-builder fixtures 22-24 now grade the declared dashboard tiles, rule shape and flow stages (#817).++### Limits++- The scroll check reads only the layouts it recognises (not `@media` or selector overrides, nor sibling heights) and refuses some valid layouts it cannot compare; its fix always passes. Upload and build do not run it.+- Duplicate-detection rules made before opting in cannot be adopted yet (#807 stays open); a rule whose first publication is unproven is still published by hand (#808).+- An adopted form whose layers read apart still needs the printed `publication-risk` approval (#797).## [2.24.0]- **Command buttons, read-only:** `scripts/list-command-states.js` lists an app's modern command buttons by row id: each button's bar, scope, stored hidden and disabled flags, and the reasons a button is not a candidate. Nothing is written (#812).diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.mdindex 970b935ef..f5dffc57b 100644--- a/plugins/model-apps/agents/genpage-page-builder.md+++ b/plugins/model-apps/agents/genpage-page-builder.md@@ -448,6 +448,15 @@ export default GeneratedComponent;});```- **Responsive design** — flexbox, relative units, never `100vh`/`100vw`+- **A scroll context** — the host shows the page in a container of fixed height and never scrolls+ it, so a page that is taller than the container is cut off below the fold, with no error. Give the+ page's top element (the first element your default export renders, through any error boundary or+ body component) `height: "100%"`, `overflowY: "auto"` and `boxSizing: "border-box"` in its+ `makeStyles` slot, or use the fixed-header layout or the themed two-div wrapper of+ `references/rules.md` **Page Layout**; in a bounded flex column, give a `Card` `flexShrink: 0`.+ Join classes with `mergeClasses`, not a string or a template, so the check can read them. Before+ returning, follow the page from its default export to that element and confirm it. The orchestrator's+ `check-griffel-styles.js` refuses a page without one.- **WCAG AA accessibility** — ARIA labels, keyboard navigation, semantic HTML- **Error handling** — every failed data operation goes through the page's one `reportPageError`with its five required arguments — `reportPageError(PAGE_NAME, '<operation>', code, error, '<kind>')`,diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.mdindex 19356dfb3..5100de681 100644--- a/plugins/model-apps/docs/app-builder-capabilities.md+++ b/plugins/model-apps/docs/app-builder-capabilities.md@@ -230,6 +230,7 @@ apart deliberately.- **Validation: every page must be sitemap-placed.** A `pages[]` entry absent from the `appShell` sitemap is rejected; navigation-only (headless) pages are not supported. A "detail" page is a normal sitemap page receiving input via `pageInput`.- **Safety HALTs:** `pages-removed` (live page dropped from spec — re-add or `--allow-destructive` detaches the nav SubArea, page left deployed), `pages-shared-across-apps` (`--allow-destructive` does NOT bypass; detach the page from the other app with `scripts/genpage.js remove-from-app`, or in Maker), `pages-identity-conflict`, `pages-manifest-corrupt`, `pages-existence-failed`, `pages-sitemap-read-failed`, `pages-shared-check-failed`.- **Verify and download** match by id with exact set-equality (EXISTENCE + MEMBERSHIP); a manifest-uncorrelatable page surfaces `unableToRun`.+- **Scroll context of generated pages.** The generative-page host renders a page in a container of fixed height and never scrolls it (measured live at 1366x768 and 1920x1080), so `check-griffel-styles.js` also checks that every page generated in Phase 1.5 has a bounded element that scrolls (`scripts/lib/page-scroll.js`, a static check of the layouts it recognises: `@media` overrides and sibling heights are not read). A layout it can show would clip, or cannot read, is refused with the edit that fixes it; a downloaded page gets a note (`--existing`). Measured in the host: a bare flex-column root clips, and the stated edit (`height: "100%"`, `overflowY: "auto"`, `boxSizing: "border-box"`) scrolls to the last row. (AB#6793599)- **Caller-held page turn ids.** `genpage-upload.js --turn-id <guid> --app-dir <folder>` lets a host retry one complete page edit after a lost answer without recording the turn twice; the id is bound to the complete request (content, binding mode, publication) in `<folder>/.maker-workspace/turns`, and a reuse asking for anything else is refused with nothing written. A host that lends the backend its own SDK passes `deps.turnBindings` (a retained store shared by every process that retries the turn, whose reads see every completed write) and `deps.turnCompilerIdentity`. Under a turn, a resumed create's placement is finished only when the app's published navigation is read and shows the page. The build never passes a turn id. A retry from another folder or machine, or after the store was erased, is unsupported and not detected.### AI-first features — ✅ verified live@@ -343,6 +344,7 @@ apart deliberately.### Edit flow (download → edit → rebuild) — ✅ verified live- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, relationships, sitemap/appShell, generative pages (code, prompt, data sources, model, and connector and Custom API bindings — `pages[].connectorBindings` / `pages[].actionBindings`, stated by an allowlist of the properties the references document, each with a value of a shape known to be safe, and only whole — a list holding a connection id, a credential or anything else is left out of the spec, reported by its place and never its value, and the page keeps it — which a rebuild writes into any environment; what they name is not carried: the download lists the connection references, Custom APIs and service resources another environment must already have, and a rebuild stops, before it writes anything, at a connection reference there that is for another connector), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **File and Image columns** come back typed too — by their `AttributeTypeName` (FileType / ImageType), as both report `AttributeType` "Virtual", which an earlier release left out of every download without a word — with the `maxSizeKb` each was made with (left out when it is 10240 KB, the size a build gives a column that sets none) and, for an Image column the environment reports as the table's primary image, `isPrimaryImage: true` (a read of that detail that fails, or answers without a column, leaves the column typed without it, and the download says which read or column it was; the platform makes a table's first Image column its primary image whatever its create asks, so a rebuild into a fresh environment makes the spec's first Image column the primary image, whichever column carries the flag); the table's own image (`entityimage`) and the platform's companions of each column are not written, nor is the relationship the platform makes with each File or Image column (`FileAttachment_<table>_<column>` to `fileattachment`, `ImageDescriptor_<table>_<column>` to `imagedescriptor`) — the column brings it back, so it is neither carried in `relationships[]` nor warned about — and a column of any other type the App Spec cannot express is left out *and named*. **`relationships[]` are reconstructed** ([#567](https://github.com/microsoft/power-platform-skills/issues/567)): every custom 1:N whose parent is one of the app's tables or a stock table, and every custom N:N between two of the app's tables, each flagged `existing: true` (a teardown of the downloaded spec keeps it), with a deployed schema name kept whenever it is not the one the prefix would generate and a lookup label kept unless it is the default. One that `relationships[]` cannot express — a polymorphic lookup, a parent that is a custom table the app does not include (or whose metadata could not be read), an N:N to a table outside the app — is left out and *named* in the download's warnings and closing note: it stays on the deployed app, so a rebuild into the same environment leaves it alone, but a rebuild into a fresh environment does not create it.+- **Crash-safe page tree.** A download stages the new `pages/` tree in a hidden folder and publishes it only after the download's checks and validation have passed (a lossy download without `--allow-lossy-download`, or an App Spec that fails validation, is refused first). Publishing writes the tree into a hidden swap folder beside `pages/`, checks that every page folder and file it wrote is still there (as a folder or a regular file, not a link), moves the previous tree aside, moves the new one in and removes the previous one last: a refusal or failure before then leaves `pages/` as it was and a failed move puts it back; when that is not possible, or the run stops between the two moves, the previous tree stays in the named hidden folder, which a later download reports. The spec is written after the pages are published, so a failed spec write leaves the new pages with the previous spec. Every operation in the download's own folders first checks the folder is still the one it made. Live-verified against 2.24.0: with folder creation denied in the output folder, and on a lossy-download refusal, 2.24.0 lost the maker's page edits and 2.25.0 kept `pages/` byte for byte. ([#814](https://github.com/microsoft/power-platform-skills/issues/814))- **Portable schema (covered by offline real-bundle round trips):** downloads keep supported column format/length/range/precision options, Boolean labels, date format and AutoNumber masks; primary name length/mask; custom unmanaged Active/Inactive status reasons and alternate keys; solution/global-choice display names; and dashboard tile dimensions. Money numeric precision is retained only for `PrecisionSource: 2`, which the SDK always creates; effective precision still depends on the target transaction currency, so numeric equality is not currency equivalence. Column/organization-controlled and unknown sources are diagnosed with precision omitted, keeping the typed Money column and range. Status labels use the resolved authoring LCID, not the caller's UI language; a missing requested translation is diagnosed rather than substituted. An unavailable optional Keys collection loses no independent table, column or navigation metadata. Values equal to the SDK's create defaults are left implicit, except primary name lengths stay explicit so a fresh build can correct an environment that overrides the table create's length. An own-publisher unmanaged SVG table icon is captured with its `vectorIcon` reference and an `external: true` resource declaration, protecting a shared icon from teardown. Proven-equal status/key definitions and standalone Integer formats send no schema write on a same-environment rebuild; missing definitions and actual format edits still take the existing create/update path. Table icons retain their assignment and specific-table publish even when the saved name matches, so a failed publish can be completed on rerun. Inconclusive or malformed metadata is reported rather than treated as a known default.- **Still outside that schema round trip:** script resources, raster/foreign/managed table icons, `roleGrants[]`, `sampleData`, Boolean defaults, column capabilities, BigInt ranges, DateTime behavior and unsupported/managed status reasons. Existing column length/range edits remain create-only; a downloaded dashboard still needs its source view/chart ids mapped, and its pinned `dashboardId` removed, before creating a separate dashboard in another environment. The new schema coverage is not a claim of full app cloning or new live verification.- Live regression on the edit path found + fixed **4 bugs**, then re-verified clean.diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.mdindex d6c05bf47..f00c708c1 100644--- a/plugins/model-apps/references/app-spec-schema-advanced.md+++ b/plugins/model-apps/references/app-spec-schema-advanced.md@@ -1343,12 +1343,37 @@ the field builds exactly as before.the build with `configuration-row-not-found` and is never replaced by a namesake.- **The binding store comes from the build.** Under the field, a build that cannot open the bindingstore for configuration stops before any request is sent (`create-identity-unverified`).-- **Opting in does not migrate an existing app.** Setting `configurationIdentity: "stable-v1"` does not- migrate an existing app. A namesake created earlier at another id stops the first protected create- with `create-identity-conflict`, even if it is the only match; nothing is created or bound, and no- approval token selects a namesake. Keep the app without the field, or move it to the reserved ids- outside the plugin. An app that already has protected bindings cannot go back: see "Removing the- field" below.+- **Opting in does not migrate an existing app by itself.** Setting `configurationIdentity: "stable-v1"`+ does not move or rename anything. A namesake created earlier at another id stops the first protected+ create with `create-identity-conflict`, even if it is the only match; nothing is created or bound. When+ it is the only match and the item is an environment variable, a connection reference or a Custom API,+ the stop then says whether the build can adopt that row at its own id. It can+ when the row and every solution component under it are in the App Spec's solution (an environment+ variable's value row is never a solution component, so it is not asked to be one); its fixed fields match the+ declaration (the name's case, a variable's type, a reference's connector, a Custom API's binding,+ bound table, function flag and processing steps, a child's type);+ every row under it is one the App Spec declares; the change the build would then make is one it makes+ on a bound row; and an environment variable's value or a connection reference's connection already is+ the one the deployment settings name (the build never writes a first or different one after+ adopting). The stop then lists the fields the build would change afterwards, by+ name only, never a value, and one approval per row: `adopt:<kind>:<key>@<row id>`, with `+<16 hex>`+ on the root when it lists fields, and `adopt:<child kind>:<key>/<child>@<row id>` for each row under+ it. Check that each row is yours, then pass every token as printed with its own `--authorize`. The+ build reads everything again just before it records the binding and sends nothing to adopt; in the+ same build it then sends only the fields the stop listed, and stops that item with nothing sent if it+ finds any other change. If a row is replaced, the field list changes or a membership is removed, the+ tokens adopt nothing and the next build prints new ones; if the row is deleted, the tokens are not used+ and the item is created at its own id. A duplicate rule made before the opt-in is never adopted: its+ stop stays exactly as before, and `adopt:duplicateRule:<key>` keeps its one meaning (the rule at its+ own reserved id, even when the key itself ends in what looks like `@<row id>`). Move that rule to its+ reserved id outside the plugin, or keep the app without the field.+ Otherwise the stop says why the row cannot be adopted. A stop that names several such items lists the+ tokens of each with its own id and field list. Several namesakes of one item stop as before, and the+ plain `adopt:<kind>:<key>` token never selects a namesake. Plugin versions before this form refuse+ the `@<row id>` tokens before anything is sent; after an adoption they bind an adopted row that has+ no rows under it, and stop on one that has with `create-identity-unverified`. You can also keep the+ app without the field, or move it to the reserved ids outside the plugin. An app that already has+ protected bindings cannot go back: see "Removing the field" below.- **An uncertain lookup is not absence.** If the namesake lookup a first create needs cannot be readcompletely (a failed read, a page that cannot be continued), the build stops with`create-identity-unverified` and creates or binds nothing for that item. Restore access or reliablediff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.mdindex 87606e186..d083c531d 100644--- a/plugins/model-apps/references/rules.md+++ b/plugins/model-apps/references/rules.md@@ -128,7 +128,7 @@ export default GeneratedComponent;### Responsive Design- Mobile-first; adapt to 320px, 480px, 768px, 1024px, 1440px breakpoints- Use relative units (%, rem, em); avoid fixed widths-- Root container is flex column; use flex properties to fill space+- Root container is flex column; use flex properties to fill space; it must establish a scroll context (see **Page Layout**)- `boxSizing: border-box`; images: `max-width: 100%, height: auto`- NEVER use `100vh`/`100vw` — the page is hosted inside the designer, not the full window; viewport units (and `position: fixed` overlays) size to the whole designer and bleed over the agent panel- **Media queries go INSIDE the slot they modify** — never as a top-level@@ -151,24 +151,75 @@ const useStyles = makeStyles({### Page Layout- Page-level functions (nav, search, filters) in header opposite title-- Only scrollable bodies scroll, not entire page-- Fix height of parent, set overflow on content area+- **The page must establish its own scroll context.** The host shows a page in a container of fixed+ height and never scrolls it. A page that is taller than that container is cut off below the fold,+ with no scrollbar and no error. So an element from the page's top element down must have a bounded+ height and must scroll. Use one of these three layouts:+ 1. **The whole page scrolls.** Give the page's top element `height: "100%"` (bounded by the host's+ container), `overflowY: "auto"` (it scrolls) and `boxSizing: "border-box"` (its padding stays+ inside that height; without it, a padded top element is taller than the container by its+ padding, and its last content stays cut off).+ 2. **A fixed header and a scrolling body.** The top element has `height: "100%"`,+ `overflow: "hidden"` and is a flex column. The header has `flexShrink: 0`. The body has+ `flex: 1`, `minHeight: 0` and `overflowY: "auto"` (without `minHeight: 0` the body grows with its+ content and the top element clips it).+ 3. **The themed two-div wrapper** (see **Special Patterns > Dark Mode Toggle**): the outer div has+ `height: "100%"` and `overflow: "hidden"`, and the inner `styles.root` is layout 1.+- In a bounded flex column (layouts 1 and 2), give `flexShrink: 0` to each item that clips its own+ content (a `Card`, or a box with an overflow key). Otherwise the column squeezes it to fit, and it+ cuts off its own content.+- These do not make a scroll context: `minHeight: "100%"` (the element grows with its content, so it+ never scrolls), `overflowY: "auto"` on an element whose height is not bounded (it grows too), and+ `100vh` (see **Responsive Design**).+- A `minHeight` wins over a `height`: a top element with `height: "100%"` and `minHeight: 800` is+ 800px tall in a shorter container, and the rest is cut off. Leave `minHeight` off a bounded+ element, set it to `0`, or give it the same value as the `height`.+- `height: "100%"` resolves only against a parent with a definite `height`. Under a parent that has+ only a `maxHeight`, it is ignored and the element grows with its content.+- When a condition chooses what the page shows (a list view or a card view), only one alternative is+ on screen at a time, so each one must scroll. Put the scroll context on an element the+ alternatives share, such as the page's top element. A loading, error or empty view on its own (a+ `Spinner`, a `MessageBar`, a line of `Text`) is fine as an alternative; a `Card` or another+ component that holds content is not.+- `check-griffel-styles.js` checks every generated page for a scroll context (see **Styling gotchas**,+ item 6).- Consistent padding/spacing; strong text contrast- Include hover/focus/active states-### Scrollable Areas-- Use fixed `maxHeight` for parent + `overflow: auto` for scrollable area-- Calculate `maxHeight: calc(100% - [fixed element heights])`-- Only content area scrolls, never entire page-- Example:```typescript-<div style={{ maxHeight: 'calc(100% - 100px)', overflow: 'auto' }}>- <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>- {/* scrollable content */}- </div>-</div>+const useStyles = makeStyles({+ // WRONG: a flex column with no bounded height and nothing that scrolls, so everything below the fold is cut off.+ // root: { display: "flex", flexDirection: "column", gap: tokens.spacingVerticalL, padding: tokens.spacingHorizontalL },++ // CORRECT (layout 1): the top element is bounded by the host's container and scrolls.+ root: {+ height: "100%",+ overflowY: "auto",+ boxSizing: "border-box",+ display: "flex",+ flexDirection: "column",+ gap: tokens.spacingVerticalL,+ padding: tokens.spacingHorizontalL,+ },+ // A Card clips its own content, so in the bounded column it must not shrink.+ card: { flexShrink: 0 },++ // CORRECT (layout 2): a fixed header and a scrolling body.+ // <div className={styles.shell}><div className={styles.header}>…</div><div className={styles.body}>…</div></div>+ shell: { height: "100%", overflow: "hidden", display: "flex", flexDirection: "column" },+ header: { flexShrink: 0, padding: tokens.spacingHorizontalL },+ body: { flex: 1, minHeight: 0, overflowY: "auto", padding: tokens.spacingHorizontalL },+});```+### Scrollable Areas+- A scrolling area inside the page (a list under a toolbar, a side panel) is layout 2 of+ **Page Layout**: a bounded flex column whose scrolling child has `flex: 1`, `minHeight: 0` and+ `overflowY: "auto"`. Use it instead of `maxHeight: calc(100% - [fixed element heights])`, which+ breaks when a header wraps to a second line.+- `overflowY: "auto"` on an element whose height is not bounded never scrolls: the element grows with+ its content, and an ancestor cuts it off.+### Navigation- Multiple screens within a page: Use Fluent UI V9 Tabs/Breadcrumbs- Provide back/forward navigation for wizard flows@@ -216,6 +267,7 @@ const brandTheme = {borderRadiusMedium: "2px",};// In the component: the outer div sets the variables, the inner div reads them.+// styles.root scrolls: height: "100%", overflowY: "auto", boxSizing: "border-box" (see Page Layout).// <div style={{ ...themeToVars(brandTheme), height: "100%", overflow: "hidden" }}>// <div className={styles.root}>{/* … */}</div>// </div>@@ -576,7 +628,7 @@ import { webDarkTheme, webLightTheme } from "@fluentui/react-components";</div>```-**Root div scrolling:** The inner `styles.root` div must have `height: "100%"` and `overflowY: "auto"` so the page content is scrollable. The genpage host provides a fixed-height container — if neither the outer nor inner div establishes a scroll context, content below the fold is unreachable.+**Root div scrolling:** The inner `styles.root` div must have `height: "100%"`, `overflowY: "auto"` and `boxSizing: "border-box"` so the page content is scrollable (layout 3 of **Page Layout**). The genpage host provides a fixed-height container — if neither the outer nor inner div establishes a scroll context, content below the fold is unreachable. A bare inner div (`<div>` with no class) under the outer div is the same failure.**Inherited text color does NOT follow the variable override.** `themeToVars` overrides CSS *variables*, but Fluent typography (`Text`, `Title`, `Body`, etc.) mostly **inherits** its `color` from the light-theme FluentProvider root — and inheritance passes the already-resolved value, so flipping `--colorNeutralForeground1` to white does not recolor inherited text (you get near-black text on a dark background, contrast ~1.07, effectively invisible). **Fix:** set `color: tokens.colorNeutralForeground1` on the page root (`styles.root`) so every descendant inherits the variable-resolved foreground. Raw `<button>` elements (e.g. custom "attention" rows) default to black `buttontext` and need an explicit `color` too. Status-color CSS vars (`--colorStatusDangerForeground1`, etc.) *do* resolve in inline styles via the `themeToVars` wrapper, so status tokens work fine.@@ -591,6 +643,7 @@ Recurring CSS bugs that type-check and compile but render wrong. Check for these3. **`tokens.fontFamilyNumeric` is Bahnschrift, not Segoe UI.** Using it for tabular numbers (counts, %, ranks, dates) renders those digits in Bahnschrift — visibly mismatched against Segoe UI everywhere else. Fix: use `tokens.fontFamilyBase` and keep `fontVariantNumeric: "tabular-nums"` for aligned digits.4. **Gradient hero with white text: `colorPalette*Background2/3` tokens are light tints, not dark.** A gradient built from e.g. `colorPalettePurpleBackground3` / `colorPaletteTealBackground2` with `color: colorNeutralForegroundOnBrand` (white) renders white-on-light → unreadable; those `Background2/3` palette tokens are pale. Fix: build the gradient from the dark, saturated `colorPalette*Foreground2` stops (e.g. `colorPalettePurpleForeground2`, `colorPaletteTealForeground2`), which are dark enough for white text to pass AA.5. **Ten CSS shorthands are unsupported by Griffel — `borderWidth` is the usual one.** Griffel does not support ten CSS shorthands, and `makeStyles` drops them at runtime: the page type-checks, transpiles and deploys, then renders without the border, color or reset. They are `all`, `borderColor`, `borderStyle`, `borderWidth`, `borderBlock`, `borderBlockStart`, `borderBlockEnd`, `borderInline`, `borderInlineStart` and `borderInlineEnd`. Write longhands instead: `borderColor`, `borderStyle` and `borderWidth` become one longhand per side, `border` + `Top`, `Right`, `Bottom` or `Left` + `Color`, `Style` or `Width` (`borderWidth` → `borderTopWidth`, `borderRightWidth`, `borderBottomWidth`, `borderLeftWidth`); `borderBlock`, `borderInline` and their `Start` and `End` forms become the `Width`, `Style` and `Color` longhands of the sides they name (`borderBlockStart` → `borderBlockStartWidth`, `borderBlockStartStyle`, `borderBlockStartColor`; `borderBlock` → those and the three `borderBlockEnd…` ones); `all` has no longhands, so set the properties you need one by one. Every other shorthand (`padding`, `margin`, `border`, `borderRadius`, `gap`, `outline`) is supported, and an inline `style={{ … }}` is not Griffel at all. The browser console logs `@griffel/react: You are using unsupported shorthand CSS property "<name>"` for each one that reaches it. Run `node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<page.tsx>'` on the finished page. `check-griffel-styles.js` prints each problem it finds — a key Griffel drops in a `makeStyles` call, at any depth, with its line, column and longhands, or a call or a style object it cannot read, with what to change — and exits 3 while any is left: fix what it reports and run it again, and do not transpile or upload the page until it exits 0. It reads the style objects written inline in the call, `makeStyles({ … })`, so write them there: one passed or spread in from elsewhere (`makeStyles(styles)`, `...base`) is reported, because the check cannot see its keys, and so is a key computed from an expression (`[key]: …`), whose name it cannot see (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's `...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.+6. **A page with no scroll context is cut off below the fold, with no error.** See **Page Layout**. `check-griffel-styles.js` also checks each page it is given (a file with a default export) for a scroll context, and reports what it finds after the Griffel problems, with the same exit 3: `no-scroll-context` (no element from the page's top element down has a bounded height and scrolls); `scroll-context-unproven` (the check cannot read what decides it, and its `reason` says what: for example a class given as a string or a template, so use `mergeClasses`); and `scroll-context-padding` (the page scrolls, but an element that fills the container has vertical padding without `boxSizing: "border-box"`, so its last content stays cut off). Each message gives the edit that fixes it: apply it and run the check again. With `--existing` (a page this run did not generate, such as a deployed page that an edit changes) the check reports these in `notes` instead, and they do not change the exit code.### Data Fetching: the host double-mount, de-dupe, and cachingdiff --git a/plugins/model-apps/samples/10-detail-with-pageinput.tsx b/plugins/model-apps/samples/10-detail-with-pageinput.tsxindex 6574c0e3c..9364bc5bd 100644--- a/plugins/model-apps/samples/10-detail-with-pageinput.tsx+++ b/plugins/model-apps/samples/10-detail-with-pageinput.tsx@@ -184,6 +184,8 @@ const useStyles = makeStyles({gap: tokens.spacingVerticalL,padding: tokens.spacingHorizontalXL,width: '100%',+ height: '100%',+ overflowY: 'auto',boxSizing: 'border-box',},header: {@@ -192,7 +194,8 @@ const useStyles = makeStyles({gap: tokens.spacingHorizontalM,},title: { flex: 1 },- card: { padding: tokens.spacingHorizontalL },+ // A Card clips its own overflow, so in the bounded root column it must not shrink.+ card: { padding: tokens.spacingHorizontalL, flexShrink: 0 },fieldGrid: {display: 'grid',gridTemplateColumns: 'minmax(140px, max-content) 1fr',diff --git a/plugins/model-apps/samples/11-kanban-with-dnd.tsx b/plugins/model-apps/samples/11-kanban-with-dnd.tsxindex 75009e808..0b3b42148 100644--- a/plugins/model-apps/samples/11-kanban-with-dnd.tsx+++ b/plugins/model-apps/samples/11-kanban-with-dnd.tsx@@ -1,6 +1,7 @@import * as React from 'react';import {makeStyles,+ mergeClasses,tokens,Card,CardHeader,@@ -180,6 +181,7 @@ const useStyles = makeStyles({display: 'flex',flexDirection: 'column',height: '100%',+ overflowY: 'auto',paddingInline: tokens.spacingHorizontalL,paddingBlock: tokens.spacingVerticalL,gap: tokens.spacingVerticalM,@@ -375,9 +377,7 @@ function PageBody(props: GeneratedComponentProps) {<div className={styles.board}>{COLUMNS.map((col) => {const items = tasks.filter((t) => t.statuscode === col.key);- const columnClass = `${styles.column} ${- hoverColumn === col.key ? styles.columnHover : ''- }`;+ const columnClass = mergeClasses(styles.column, hoverColumn === col.key && styles.columnHover);return (<divkey={col.key}@@ -399,9 +399,7 @@ function PageBody(props: GeneratedComponentProps) {</Caption1>) : (items.map((task) => {- const cardClass = `${styles.card} ${- draggingId === task.activityid ? styles.cardDragging : ''- }`;+ const cardClass = mergeClasses(styles.card, draggingId === task.activityid && styles.cardDragging);return (<Cardkey={task.activityid}diff --git a/plugins/model-apps/samples/13-custom-api-invocation.tsx b/plugins/model-apps/samples/13-custom-api-invocation.tsxindex 60d661135..8423b1696 100644--- a/plugins/model-apps/samples/13-custom-api-invocation.tsx+++ b/plugins/model-apps/samples/13-custom-api-invocation.tsx@@ -183,13 +183,17 @@ const useStyles = makeStyles({gap: tokens.spacingVerticalL,padding: tokens.spacingHorizontalXL,width: '100%',+ height: '100%',+ overflowY: 'auto',boxSizing: 'border-box',},+ // A Card clips its own overflow, so in the bounded root column it must not shrink.card: {display: 'flex',flexDirection: 'column',gap: tokens.spacingVerticalM,padding: tokens.spacingHorizontalL,+ flexShrink: 0,},summaryGrid: {display: 'grid',diff --git a/plugins/model-apps/samples/2-wizard-multi-step.tsx b/plugins/model-apps/samples/2-wizard-multi-step.tsxindex bbb2fa2d2..4d7c8aaf6 100644--- a/plugins/model-apps/samples/2-wizard-multi-step.tsx+++ b/plugins/model-apps/samples/2-wizard-multi-step.tsx@@ -154,7 +154,7 @@ function PageBody(props: Props) {};return (- <div style={{ width: '100%', height: '100%', padding: '0.5rem', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>+ <div style={{ width: '100%', height: '100%', overflowY: 'auto', padding: '0.5rem', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', alignItems: 'center' }}><ProgressBarvalue={progress}thickness="large"diff --git a/plugins/model-apps/samples/3-account-crud-dataverse.tsx b/plugins/model-apps/samples/3-account-crud-dataverse.tsxindex adf56b877..e88d6095a 100644--- a/plugins/model-apps/samples/3-account-crud-dataverse.tsx+++ b/plugins/model-apps/samples/3-account-crud-dataverse.tsx@@ -313,7 +313,7 @@ function PageBody(props: GeneratedComponentProps) {];return (- <div style={{ width: "100%", margin: "0 auto", minHeight: "100%", display: "flex", flexDirection: "column", boxSizing: "border-box", padding: "10px" }}>+ <div style={{ width: "100%", margin: "0 auto", height: "100%", overflowY: "auto", display: "flex", flexDirection: "column", boxSizing: "border-box", padding: "10px" }}>{/* Header */}<header style={{ padding: "10px", textAlign: "center" }}><Text as="h1" size={800} weight="semibold">diff --git a/plugins/model-apps/samples/4-file-upload.tsx b/plugins/model-apps/samples/4-file-upload.tsxindex 0c0652af4..37d7445fe 100644--- a/plugins/model-apps/samples/4-file-upload.tsx+++ b/plugins/model-apps/samples/4-file-upload.tsx@@ -132,7 +132,7 @@ function PageBody(props: Props) {};return (- <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>+ <div style={{ display: "flex", flexDirection: "column", gap: "20px", height: "100%", overflowY: "auto", boxSizing: "border-box" }}><Text size={400} block>Upload revocation documentation:</Text>diff --git a/plugins/model-apps/samples/5-navigation-sidebar.tsx b/plugins/model-apps/samples/5-navigation-sidebar.tsxindex 624007bde..e5c098c5b 100644--- a/plugins/model-apps/samples/5-navigation-sidebar.tsx+++ b/plugins/model-apps/samples/5-navigation-sidebar.tsx@@ -154,7 +154,7 @@ function PageBody(props: Props) {);return (- <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>+ <div style={{ width: '100%', height: '100%', overflowY: 'auto', boxSizing: 'border-box', display: 'flex', flexDirection: 'column' }}><style>{`@media (max-width: 768px) {@@ -173,6 +173,7 @@ function PageBody(props: Props) {padding: '10px 20px',color: 'white',height: '60px',+ flexShrink: 0,boxSizing: 'border-box',}}>diff --git a/plugins/model-apps/samples/7-responsive-cards.tsx b/plugins/model-apps/samples/7-responsive-cards.tsxindex 36692ce90..2dfe1472b 100644--- a/plugins/model-apps/samples/7-responsive-cards.tsx+++ b/plugins/model-apps/samples/7-responsive-cards.tsx@@ -110,7 +110,7 @@ class PageErrorBoundary extends React.Component<}const useStyles = makeStyles({- container: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalXXL, padding: tokens.spacingHorizontalM, width: '100%', boxSizing: 'border-box', '@media (max-width: 768px)': { padding: tokens.spacingHorizontalS } },+ container: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalXXL, padding: tokens.spacingHorizontalM, width: '100%', height: '100%', overflowY: 'auto', boxSizing: 'border-box', '@media (max-width: 768px)': { padding: tokens.spacingHorizontalS } },cardsGrid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: tokens.spacingVerticalL, width: '100%', '@media (max-width: 768px)': { gridTemplateColumns: '1fr', gap: tokens.spacingVerticalM } },card: { width: '100%', maxWidth: '480px', height: 'fit-content', cursor: 'pointer', transition: 'transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out', '&:hover': { transform: 'translateY(-2px)', boxShadow: tokens.shadow8 }, '&:focus-visible': { outline: `2px solid ${tokens.colorBrandBackground}`, outlineOffset: '2px' }, '@media (max-width: 768px)': { maxWidth: '100%' } },sectionHeader: { marginBottom: tokens.spacingVerticalM },diff --git a/plugins/model-apps/samples/8-dashboard-with-charts.tsx b/plugins/model-apps/samples/8-dashboard-with-charts.tsxindex 05bea6174..9b221410a 100644--- a/plugins/model-apps/samples/8-dashboard-with-charts.tsx+++ b/plugins/model-apps/samples/8-dashboard-with-charts.tsx@@ -171,6 +171,8 @@ const useStyles = makeStyles({gap: tokens.spacingVerticalL,padding: tokens.spacingHorizontalXL,width: '100%',+ height: '100%',+ overflowY: 'auto',boxSizing: 'border-box',},pageTitle: { marginBottom: tokens.spacingVerticalS },diff --git a/plugins/model-apps/samples/9-list-with-caching.tsx b/plugins/model-apps/samples/9-list-with-caching.tsxindex 81098b890..64db994e9 100644--- a/plugins/model-apps/samples/9-list-with-caching.tsx+++ b/plugins/model-apps/samples/9-list-with-caching.tsx@@ -189,6 +189,8 @@ const useStyles = makeStyles({gap: tokens.spacingVerticalM,padding: tokens.spacingHorizontalXL,width: '100%',+ height: '100%',+ overflowY: 'auto',boxSizing: 'border-box',},header: {diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.jsindex 908bfa1a2..c720571a4 100644--- a/plugins/model-apps/scripts/build-model-app.js+++ b/plugins/model-apps/scripts/build-model-app.js@@ -20,6 +20,8 @@// create-identity-opt-in-required the opt-in was removed while the binding store holds a declared item// create-identity-unverified the binding store or a namesake lookup cannot be used// create-identity-conflict a namesake or a row the binding does not hold stands where a row would go+// (a single namesake: the stop says whether it can be adopted, and prints the+// --authorize adopt:<kind>:<key>@<row id> approvals when it can)// create-completion-required an earlier create is incomplete: complete it under the same ids// create-ownership-required rows to bind: pass each printed --authorize adopt:<kind>:... after checking it// configuration-row-not-found a bound row is gone (never replaced by a namesake)@@ -1476,6 +1478,14 @@ const readLanguageFlag = (flags) => readAliasedFlag(flags, 'language-code', 'lan// adopt:<child kind>:<key>/<child> created and whose answer was lost (child kind environmentVariableValue, customApiRequestParameter,// customApiResponseProperty or duplicateRuleCondition; both parts percent-encoded), exactly as// the stop printed it; one row each, a root's never covers its children (configurationApprovals)+// adopt:<kind>:<key>@<row id>[+<digest>] binding a protected configuration item's namesake, a row a maker made before the+// adopt:<child kind>:<key>/<child>@<row id> opt-in at an id the plugin did not derive, at its own id, sending nothing; exactly+// as the create-identity-conflict stop printed them, one per row (the digest pins the+// fields the build would then change; lib/configuration-protected.js adoptionOf). Kept as+// adopt-row:..., apart from every plain approval; a token whose two readings both name a+// declared item is refused (CONFIGURATION_ADOPT_AMBIGUOUS). Environment variables,+// connection references and Custom APIs only: a duplicate rule is never adopted, so its+// and its conditions' tokens keep only the plain reading above, as in 2.24.0// The family is part of the key because ids collide across families: a view and a chart may share <table>/<name>, and a view// may be named "quickFind". Each approval is stored under its family-typed id (reconcile-common.js approvalKey, the flag minus// its verb) and each guard asks only for its own family, so consent to one artifact never reaches another. The untyped form@@ -1538,8 +1548,10 @@ function authorizationKeys(argv, spec) {: code === 'CONFIGURATION_ADOPT_UNPROTECTED'? `'${token}' binds a row of a protected configuration item, and the spec does not set configurationIdentity "stable-v1", so there is no such row to bind`: code === 'CONFIGURATION_ADOPT_INVALID'- ? `'${token}' is not adopt:<kind>:<declared key> or adopt:<child kind>:<declared key>/<declared child>, as a configuration stop prints it`- : `'${token}' is not <kind>:<declared key>:<field> for a field a configuration change can consent to`)));+ ? `'${token}' is not adopt:<kind>:<declared key> or adopt:<child kind>:<declared key>/<declared child>, as a configuration stop prints it (ending @<row id> when it adopts a namesake)`+ : code === 'CONFIGURATION_ADOPT_AMBIGUOUS'+ ? `'${token}' reads both as the approval of one declared configuration item and, ending @<row id>, as the adoption of another's namesake; it approves neither. Rename one of the two keys`+ : `'${token}' is not <kind>:<declared key>:<field> for a field a configuration change can consent to`)));problems.push(...commandStates.problems);// The ids each approval family's artifacts carry in this spec. A view's or chart's is the reconcile's intent key, `<table>/<name>`// with the table in lower case (a spec whose declared artifact does not compile fails validation before any key is used); a Quickdiff --git a/plugins/model-apps/scripts/check-griffel-styles.js b/plugins/model-apps/scripts/check-griffel-styles.jsindex 73356415f..ad57ceec5 100644--- a/plugins/model-apps/scripts/check-griffel-styles.js+++ b/plugins/model-apps/scripts/check-griffel-styles.js@@ -7,13 +7,28 @@// — which ten properties, and where in the page they count — lives in lib/griffel-styles.js. This wrapper exists so the orchestrator, an AI following SKILL.md,// gets a yes/no answer it cannot talk itself past, instead of a grep it has to read the result of.//+// It runs a second check on a file that is a page (one with a default export): does the page establish its own scroll context? The host shows a page in a+// container of fixed height and never scrolls it, so a page in which nothing both has a bounded height and scrolls is cut off below the fold, silently. That+// rule lives in lib/page-scroll.js (AB#6793599). One command runs both, so no flow that checks a page can skip one of them.+//// Usage:-// node check-griffel-styles.js --file <page.tsx>+// node check-griffel-styles.js --file <page.tsx> [--existing]+//+// `--existing`: the page was not generated in this run (a downloaded page an edit changes, a maker's hand edit). Its scroll-context problems are reported+// in `notes` and do not change `ok` or the exit code: refusing a maker's small edit over a layout they chose would be a regression. Griffel problems are+// judged the same in both modes.//// Output (one JSON line) and exit code:// 0 {"ok":true,"filePath":…,"calls":1,"problems":[]}// 3 {"ok":false,…,"problems":[{"code","property","line","column","longhands","within","value","owner","branch","arms","message"}]} — rewrite those keys with the longhands, then check again// 1 {"ok":false,"error":…} — usage error, or the file cannot be read+// A scroll-context problem is `{"code","line","column","element","message"}` (plus `reason` for `scroll-context-unproven`), appended to `problems` after the+// Griffel ones: `no-scroll-context` (nothing from the page's top element down both has a bounded height and scrolls), `scroll-context-unproven` (the check+// cannot read what decides it: `reason` says what), or `scroll-context-padding` (the page scrolls, but a box that fills its container has vertical padding+// without `boxSizing: "border-box"`, so its end stays cut off). The message gives the edit that fixes it; apply it and check again. With `--existing` the+// same objects go to `"notes":[…]` instead. `notes` is present only when it is not empty, so the output of a fragment, a page that passes and every page+// before this check existed is unchanged; it can also hold `scroll-check-failed` when the scroll check itself fails, which never changes the exit code.+//// `calls` is how many makeStyles calls were read. A problem's `code` is `unsupported-shorthand`; or `unread-style-object`, a style object the checker cannot see — one// passed to the call (`makeStyles(styles)`), a slot or a selector given a variable, a spread of anything but an inline object — whose keys may be any of the ten, or a// computed key it cannot read as a name (`[key]: …`), so it is never reported as clean (write it inline); or — where the checker cannot read the code for certain —@@ -26,8 +41,12 @@const fs = require('node:fs');const path = require('node:path');const { griffelStyleProblems } = require('./lib/griffel-styles.js');+const { pageScrollProblems } = require('./lib/page-scroll.js');-function checkGriffelStyles({ filePath }) {+// `existing`: the page was not generated in this run (a downloaded page an edit touches, a maker's hand edit), so a missing scroll context+// is the maker's to decide on: it is reported in `notes` and does not change `ok` or the exit code. Griffel problems are judged the same in+// both modes.+function checkGriffelStyles({ filePath, existing = false }) {if (!filePath) return { exit: 1, result: { ok: false, error: '--file is required' } };const abs = path.resolve(filePath);let source;@@ -37,13 +56,28 @@ function checkGriffelStyles({ filePath }) {return { exit: 1, result: { ok: false, filePath: abs, error: `--file could not be read: ${(e && e.code) || e}` } };}const { calls, problems } = griffelStyleProblems(source);- return { exit: problems.length ? 3 : 0, result: { ok: problems.length === 0, filePath: abs, calls, problems } };+ let scroll;+ let notes = [];+ try {+ scroll = pageScrollProblems(source).map(({ fix, ...p }) => p);+ } catch (e) {+ // A defect in the scroll check must not take the Griffel check down with it, nor refuse a page over the checker's own failure: it is+ // reported as a note, and the Griffel result stands as it would without the scroll check.+ scroll = [];+ notes = [{ code: 'scroll-check-failed', message: `the scroll-context check could not read the page (${(e && e.message) || e}); open the page and scroll to its end to check it by hand` }];+ }+ if (existing) notes = [...notes, ...scroll];+ const all = existing ? problems : [...problems, ...scroll];+ const result = { ok: all.length === 0, filePath: abs, calls, problems: all };+ if (notes.length) result.notes = notes;+ return { exit: all.length ? 3 : 0, result };}function parseArgv(argv) {const out = {};for (let i = 0; i < argv.length; i += 1) {if (argv[i] === '--file') { out.filePath = argv[i + 1]; i += 1; }+ else if (argv[i] === '--existing') out.existing = true;}return out;}diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.jsindex 1d69e6e56..efe014f8c 100644--- a/plugins/model-apps/scripts/download-model-app.js+++ b/plugins/model-apps/scripts/download-model-app.js@@ -34,8 +34,8 @@// calls, the persona a flow's securityRoles name) is written ready to paste, with what it still needs, to// a NEW file `<out>/.maker-workspace/managed-fragments-<UTC time>-<random>.json` (`managedFragments.file` in the result;// lib/managed-fragments.js). It is created exclusively, so it never replaces, moves or removes a file, and with nothing to write-// nothing is written. So that a failure to write it leaves the folder as it was, the managed download writes the page tree to a-// staging folder inside <out> and publishes it only after the restore, the validation and the fragments file have succeeded.+// nothing is written. So that a failure to write it leaves the folder as it was, the download (every CLI download) writes the+// page tree to a staging folder inside <out> and publishes it only after the restore, the validation and the fragments file have succeeded.// Off by default, so a download without them makes the reads it always made.//// A page's key is its identity in a rebuild, so a download keeps the key each page already has: the one the app's page manifest binds to it, then the one an@@ -62,6 +62,7 @@ const fs = require('node:fs');const path = require('node:path');const crypto = require('node:crypto');const { assertSafeOutputDir, assertPlainFileTarget, writeFileSafe, removeTreeWithRetry } = require('./lib/safe-fs.js');+const { renameWithRetry } = require('./lib/rename-retry.js');const { parseArgs, validateFlags, emitResult, preflightAuth, dataverseOrigin, requireDataverseOrigin, webApiUrl, readOrgLanguageCode, readLanguageCodeFlag } = require('./lib/dataverse-auth.js');const { writeBaseline } = require('./lib/deployed-baseline.js');const { createAzHttpClient } = require('./lib/sdk-http-client.js');@@ -1102,22 +1103,22 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo//// `unkeptBindings` collects the pages whose config.json holds a list of connector or Custom API bindings the spec cannot state: { pageId, field, reason }. The list is not a list, or an entry is not an object// (`pageBindingsProblem`), or an entry holds anything a spec does not state (see the projection below). `reason` names the place and the vetted property, never a value or an unrecognized key.-function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptModels, unkeptBindings) {+function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptModels, unkeptBindings, fsImpl = fs) {const pages = [];- if (!fs.existsSync(pagesRoot)) return pages;+ if (!fsImpl.existsSync(pagesRoot)) return pages;// Read in the pages' own order (comparePages), not the directory's: `readdirSync` lists in the file system's order, which is// not the same on every machine, and this loop decides the order of `pages[]` in the spec and of the unreadable-config and// unkept-model reports. It decides no page key: assignPageKeys mints in the order of the pages' ids, whatever order it is given.const nameOf = (entry) => (nameById && nameById.get(String(entry).toLowerCase())) || entry;- const entries = fs.readdirSync(pagesRoot)+ const entries = fsImpl.readdirSync(pagesRoot).map((entry) => ({ pageId: entry, name: nameOf(entry) })).sort(comparePages).map((page) => page.pageId);for (const entry of entries) {const dir = path.join(pagesRoot, entry);- if (!fs.statSync(dir).isDirectory()) continue;+ if (!fsImpl.statSync(dir).isDirectory()) continue;const tsx = path.join(dir, 'page.tsx');- if (!fs.existsSync(tsx)) continue;+ if (!fsImpl.existsSync(tsx)) continue;let config = {};const configPath = path.join(dir, 'config.json');// Read DIRECTLY and let ENOENT — and ONLY ENOENT — mean "absent, therefore optional".@@ -1131,7 +1132,7 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptMod// 'utf8' decode keeps that BOM as U+FEFF, and JSON.parse REJECTS a leading U+FEFF — so a// perfectly valid downloaded config threw, the old catch substituted `{}`, and the page's// table bindings vanished from the emitted spec. A BOM is an encoding marker, not content.- config = JSON.parse(fs.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));+ config = JSON.parse(fsImpl.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('config.json is not a JSON object');if (Object.prototype.hasOwnProperty.call(config, 'dataSources')) {if (!Array.isArray(config.dataSources)) throw new Error('config.json dataSources is present but is not an array');@@ -1139,6 +1140,9 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptModif (bad !== undefined) throw new Error('config.json dataSources must be an array of non-empty table logical names');}} catch (e) {+ // A folder of a staged download's staging found replaced by a link is not a page's config that cannot be read: it stops the+ // download (generatedFolders).+ if (e && e.code === 'UNSAFE_OUTPUT') throw e;config = {};// Present but unreadable — report it rather than inventing empty metadata. A genuinely absent// config is optional by contract and is NOT reported.@@ -1152,8 +1156,9 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptMod// A file that EXISTS but is blank or unreadable stays explicit, so it still fails closed.let prompt;try {- prompt = fs.readFileSync(path.join(dir, 'prompt.txt'), 'utf8').replace(/^\uFEFF/, '');+ prompt = fsImpl.readFileSync(path.join(dir, 'prompt.txt'), 'utf8').replace(/^\uFEFF/, '');} catch (e) {+ if (e && e.code === 'UNSAFE_OUTPUT') throw e;prompt = (e && e.code === 'ENOENT') ? undefined : '';}// The model that generated the page, as config.json records it. It has to come back with the page:@@ -2961,26 +2966,27 @@ function downloadPublisherPrefix(recovered, appUnique) {// throwing. Unexpected I/O errors propagate as thrown exceptions (caught by main().catch).// A link already under pages/ must be refused before the tree is replaced. rm of a real// parent drops the link name; that is not the same as leaving the other name untouched.-function assertNoPlantedPageLinks(pagesRoot) {+// `fsImpl` is the fs every look goes through (a test seam; production passes none).+function assertNoPlantedPageLinks(pagesRoot, fsImpl = fs) {let entries = [];- try { entries = fs.readdirSync(pagesRoot); } catch (e) {+ try { entries = fsImpl.readdirSync(pagesRoot); } catch (e) {if (e && e.code === 'ENOENT') return;throw e;}for (const entry of entries) {const child = path.join(pagesRoot, entry);let st;- try { st = fs.lstatSync(child); } catch (e) {+ try { st = fsImpl.lstatSync(child); } catch (e) {if (e && e.code === 'ENOENT') continue;throw e;}if (st.isSymbolicLink() || st.isDirectory()) {- assertSafeOutputDir(child);+ assertSafeOutputDir(child, { fs: fsImpl });if (st.isDirectory() && !st.isSymbolicLink()) {- for (const name of fs.readdirSync(child)) assertPlainFileTarget(path.join(child, name));+ for (const name of fsImpl.readdirSync(child)) assertPlainFileTarget(path.join(child, name), { fs: fsImpl });}} else {- assertPlainFileTarget(child);+ assertPlainFileTarget(child, { fs: fsImpl });}}}@@ -2992,47 +2998,350 @@ function assertNoPlantedPageLinks(pagesRoot) {// under pages/ is refused first (assertNoPlantedPageLinks), a folder is made only after the name is checked (assertSafeOutputDir), and// every file is written by writeFileSafe, which refuses a link at the file's own name. A page id reaches here only after the backend has// read it, and the backend reads a GUID and nothing else, so no id can hold a path separator.-function writePageTree(pagesRoot, pages) {- assertSafeOutputDir(pagesRoot, { create: true });- assertNoPlantedPageLinks(pagesRoot);- fs.rmSync(pagesRoot, { recursive: true, force: true });- assertSafeOutputDir(pagesRoot, { create: true });- for (const { pageId, files } of pages) {- const destDir = path.join(pagesRoot, pageId);- assertSafeOutputDir(destDir, { create: true });- for (const [name, text] of Object.entries(files)) writeFileSafe(path.join(destDir, name), text, { encoding: 'utf8' });+//+// The tree is SWAPPED, never rewritten in place (#814). The folder may hold a maker's page edits that were never uploaded, and the old+// way (remove pages/, then write each file) lost them to any failure part-way: a full disk, a permission, a locked file, a crash. Now the+// new tree is written whole beside it first, and the old one is deleted only once the new one has its name:+// 1. check pages/ (the refusals above), so a planted link is refused before anything is made;+// 2. make a swap folder `<out>/.pages-replace.<pid>.<random>.tmp` (makeHiddenDir: a name nobody holds, checked to be the plain folder+// just made before anything is written under it) and write the new tree to its `new` subfolder. It sits in the same folder as+// pages/, so the moves below are renames on one volume, never copies;+// 3. check the new tree (`new`, each page folder in it and each file written there are still there and still what was made) and pages/ again:+// writing took time, and the move below must act on the folders the checks saw;+// 4. move pages/ to the swap folder's `previous` (skipped when there is no pages/);+// 5. move `new` to pages/;+// 6. remove the swap folder, the previous tree in it.+// What a stop between two steps (a crash, a kill, a power cut) leaves on disk:+// before 2: nothing has changed;+// 2 to 4: pages/ as it was, and a swap folder holding all or part of the new tree;+// 4 to 5: no pages/; the previous tree whole in `<swap>/previous`, the new tree in `<swap>/new`;+// 5 to 6: the new pages/, and the previous tree in `<swap>/previous` (whole, or what is left of it once step 6 has begun);+// after 6: the new pages/ and nothing else.+// In no state is a page file deleted before the tree that replaces it is whole on disk. A swap folder left by a stopped run is never+// reused, moved or deleted by a later download (each run makes its own, under a new name). One that holds a `previous` tree may hold the+// maker's only copy of their edits (a stop between 4 and 5 leaves no pages/ at all), so a later download that replaces this pages/ names+// it in one warning (warnStrandedPageTrees), and goes on: it is the maker's to look into and delete. One with no `previous` holds only+// downloaded pages and is not named.+//+// A failure of a step is undone, and said:+// 2 or 3 fails: the swap folder is removed and the error thrown as it came; pages/ is untouched;+// 4 fails: nothing moved (a refused rename moves nothing); the swap folder is removed; pages/ is untouched;+// 5 fails: the previous tree is moved back to pages/. If that fails too, nothing is removed and the error names both folders;+// 6 fails: the download succeeded; a warning names the swap folder, to delete.+// A failure is cleaned up by removing `new` and then the EMPTY swap folder (rmdir, never recursive), so no clean-up can delete the+// previous tree, even after a rename that reported a failure and moved it all the same.+//+// The folders this run makes are held to being what they were made as, before EVERY fs operation on a path in them: each mkdir, each+// file write (writeFileSafe's temp file, its rename into place and the removal of a temp file it gives up on), each rename attempt+// (every retry of the move in and of the move back included), each removal, and each read (a listing, a stat, a file's bytes: a+// staged download reads its staged tree back, and what it reads is what it states in the spec and publishes into pages/). All of them+// go through ONE fs, generatedFolders' `fs`, which checks first that the folder made (the swap folder; a staged download's+// `.download-pages.*` staging folder) and every folder between it and the path are still plain folders at the paths they were made at+// (ownedDir), and that the path itself is not a link. Something that replaced one of them with a link or junction (or moved it away and+// put one at its name) would otherwise have a page written, a tree moved into pages/, a clean-up delete recursively, or page bytes read,+// wherever that link points, outside <out>. Such a replacement is refused (UNSAFE_OUTPUT), and from then on nothing is read, written,+// moved or removed under the folder replaced (nor a folder that holds it removed or moved): the step that met it fails, a clean-up+// leaves it and names it, and the previous pages are moved back only while `previous` itself still passes the check. The managed+// download's staging folder found replaced at any check, its removal after the last read included, refuses the download: nothing read+// from it is published (runDownload). tests/download-model-app.test.js holds the raw fs calls of writePageTree, the staged readback and+// their helpers to that one fs. What a check cannot close is the moment between it and the one syscall it guards, read or write (a path+// is named again by that syscall): no wait sits there, as a retry's wait comes before the next attempt's own check.+//+// Windows: a folder rename is refused (EPERM, EACCES, EBUSY) while a scanner or the search indexer holds a file in it. Step 5 and the+// move back use renameWithRetry (lib/rename-retry.js), which repeats the same rename for a few seconds: the folder moved is one this run+// made or moved into its own swap folder, under a name nobody else knows, each attempt is checked as above before it is made, and the+// target is the name pages/ this run has just vacated, so a repeat means what the first attempt meant (if a folder took that name+// meanwhile, every attempt is refused and the move back or the error that names both folders follows). Step 4 is ONE attempt: it moves+// the maker's own folder, which an editor, a sync client or the maker can change while a wait goes on, so a wait would let the checks of+// step 3 go stale, as rename-retry.js forbids. Its refusal leaves pages/ as it was and fails the download, which can simply be run again.+//+// `opts`: `fs` (every call goes through it: a staged download passes its staging folder's guarded fs, and tests a faulty one), and,+// for tests, `warn` (where the warnings go) and `rename` (renameWithRetry's own test options).+function writePageTree(pagesRoot, pages, opts = {}) {+ const fsImpl = opts.fs || fs;+ const warn = opts.warn || ((line) => process.stderr.write(line));+ // Step 1. The same refusals, made before anything is created, as they always were.+ assertPageTreeReplaceable(pagesRoot, fsImpl);+ // The moves go through the checked real folder (an 8.3 short name or a linked ancestor names the same one); messages name the folders+ // as the caller named pages/.+ const shownRoot = path.dirname(path.resolve(pagesRoot));+ const realRoot = assertSafeOutputDir(shownRoot, { create: true, fs: fsImpl });+ const pagesPath = path.join(realRoot, path.basename(pagesRoot));+ const shown = (p) => path.join(shownRoot, path.relative(realRoot, p));+ warnStrandedPageTrees(realRoot, pagesRoot, shown, warn, fsImpl);+ const guard = generatedFolders(fsImpl, shown);+ const gfs = guard.fs;+ // Throws, with nothing to clean up, when the folder just made is not a plain folder at its own path: nothing is written or removed+ // through a link planted there.+ const swap = makeHiddenDir(realRoot, '.pages-replace', guard);+ const fresh = path.join(swap, 'new');+ const previous = path.join(swap, 'previous');+ // Removes the new tree, then the swap folder if nothing else is in it. Best-effort: the caller has an error to throw already. Through+ // the guarded fs, so a clean-up never descends through a link put in place of either.+ const discard = () => {+ let held = removeTreeWithRetry(fresh, { fs: gfs });+ if (!held) {+ try { gfs.rmdirSync(swap); } catch (e) { held = (e && e.code) || 'UNKNOWN'; }+ }+ if (held === 'UNSAFE_OUTPUT') warn(`WARNING: the folder ${shown(swap)} the downloaded pages were written to was not removed: ${NOT_OWNED_LEFT}\n`);+ else if (held) warn(`WARNING: the folder ${shown(swap)} the downloaded pages were written to could not be removed (${held}): delete it.\n`);+ };+ let hadTree;+ try {+ // Step 2.+ gfs.mkdirSync(fresh);+ for (const { pageId, files } of pages) {+ const destDir = path.join(fresh, pageId);+ gfs.mkdirSync(destDir, { recursive: true });+ for (const [name, text] of Object.entries(files)) writeFileSafe(path.join(destDir, name), text, { encoding: 'utf8', fs: gfs });+ }+ // Step 3. `new` once more too, and each page folder made in it and each file written there, so a replacement found now costs no+ // move of the maker's folder and nothing in its place is moved into pages/. The guarded lstat checks each path as `verify` does+ // (a link or a folder that is not the one made is refused), but the guard lets a missing path through (an operation that creates it+ // must be able to run), so each is also required to be there, as what was made: a folder or a file that is gone (removed after it+ // was written) leaves a tree that is not complete, and it is not published.+ const present = (p, kind) => {+ let stat = null;+ let cause = null;+ try {+ stat = gfs.lstatSync(p);+ } catch (e) {+ if (e && e.code === 'UNSAFE_OUTPUT') throw e;+ cause = e;+ }+ if (stat && (kind === 'folder' ? stat.isDirectory() : stat.isFile())) return;+ // Only a missing path shows the entry is gone; any other error (EIO, EACCES, ...) leaves it unknown, and says so.+ const code = (cause && cause.code) || cause;+ const gone = cause && (cause.code === 'ENOENT' || cause.code === 'ENOTDIR');+ const what = stat ? `is no longer a ${kind}` : gone ? `is no longer there (${code})` : `could not be inspected (${code})`;+ const error = pageTreeError(`could not write the page folder ${pagesRoot}: the ${kind} ${shown(p)} this download wrote ${what}. The page folder is as it was, and the downloaded pages were not moved into it`, cause);+ error.code = 'IO_ERROR';+ throw error;+ };+ present(fresh, 'folder');+ for (const { pageId, files } of pages) {+ const destDir = path.join(fresh, pageId);+ present(destDir, 'folder');+ for (const name of Object.keys(files)) present(path.join(destDir, name), 'file');+ }+ hadTree = assertPageTreeReplaceable(pagesPath, fsImpl);+ } catch (e) {+ discard();+ throw e;+ }+ // Step 4.+ if (hadTree) {+ try {+ gfs.renameSync(pagesPath, previous);+ } catch (e) {+ discard();+ throw pageTreeError(`could not replace the page folder ${pagesRoot}: it could not be moved aside (${(e && e.code) || e}). It is as it was, and the downloaded pages were not written`, e);+ }+ }+ // Step 5.+ try {+ renameWithRetry(gfs, fresh, pagesPath, opts.rename);+ } catch (e) {+ const code = (e && e.code) || e;+ if (!hadTree) {+ discard();+ throw pageTreeError(`could not write the page folder ${pagesRoot}: the downloaded pages could not be moved into it (${code})`, e);+ }+ try {+ renameWithRetry(gfs, previous, pagesPath, opts.rename);+ } catch (back) {+ // `previous`, or a folder above it, is not the folder made: where the previous pages now are is not known here, only where they+ // were moved to. Nothing more is done through it.+ if (back && back.code === 'UNSAFE_OUTPUT') {+ throw pageTreeError(`could not replace the page folder ${pagesRoot}: the downloaded pages could not be moved into it (${code}). The previous pages had been moved to ${shown(previous)}, and that folder or one above it is no longer the folder this download made there (a link or junction was put in its place), so they were not moved back, and nothing more was moved, written or removed through it. Find them where that folder was moved to, and move them back to ${pagesRoot}`, back);+ }+ throw pageTreeError(`could not replace the page folder ${pagesRoot}: the downloaded pages could not be moved into it (${code}), and the previous pages could not be moved back (${(back && back.code) || back}). Nothing was deleted: the previous pages are in ${shown(previous)} and the downloaded pages in ${shown(fresh)}. Move the previous pages back to ${pagesRoot}`, e);+ }+ discard();+ throw pageTreeError(`could not replace the page folder ${pagesRoot}: the downloaded pages could not be moved into it (${code}). The previous pages were put back as they were`, e);+ }+ // Step 6.+ const left = removeTreeWithRetry(swap, { fs: gfs });+ if (left === 'UNSAFE_OUTPUT') warn(`WARNING: the page folder ${pagesRoot} was replaced, but the folder ${shown(swap)} that held the previous pages was not removed: ${NOT_OWNED_LEFT}\n`);+ else if (left) warn(`WARNING: the page folder ${pagesRoot} was replaced, but the folder ${shown(swap)} that holds the previous pages could not be removed (${left}): delete it.\n`);+}++// Why a folder this run made is left behind when it is no longer that folder: the end of each warning that names one.+const NOT_OWNED_LEFT = 'it, or a folder in it, is no longer the folder this download made there (a link or junction was put in its place, or it was moved), and nothing is removed through one. Look into it before you delete anything in it.';++// Names, in one warning each, the swap folders an earlier download left in `realRoot` (it stopped before its step 6) that hold a+// `previous` tree: the page folder as it was before that download, possibly with edits the maker has nowhere else. Looks, never touches:+// such a folder is not moved, reused or deleted. A folder that cannot be read is passed over in silence (this is a hint, never a reason+// to stop a download).+function warnStrandedPageTrees(realRoot, pagesRoot, shown, warn, fsImpl = fs) {+ let names = [];+ // A refusal of a guarded fs (a staged download's staging folder found replaced) is not a folder that cannot be read: it stops.+ try { names = fsImpl.readdirSync(realRoot); } catch (e) { if (e && e.code === 'UNSAFE_OUTPUT') throw e; return; }+ for (const name of names.filter((n) => n.startsWith('.pages-replace.')).sort()) {+ const held = path.join(realRoot, name, 'previous');+ let st;+ try { st = fsImpl.lstatSync(held); } catch (e) { if (e && e.code === 'UNSAFE_OUTPUT') throw e; continue; }+ if (!st.isDirectory()) continue;+ warn(`WARNING: ${shown(held)} holds the page folder as it was before an earlier download that stopped part-way: if it has page edits you need, copy them back into ${pagesRoot}, then delete ${shown(path.join(realRoot, name))}.\n`);}}-// The checks writePageTree makes before it removes anything, made on their own: the managed download asks them before it settles its-// fragments file, so a page tree that cannot be replaced stops it before that file, the pages or the spec are written.-function assertPageTreeReplaceable(pagesRoot) {+// A failure of the swap, with the code of the fs error that caused it, so a caller that tells failures apart by code still can.+function pageTreeError(message, cause) {+ const error = new Error(message);+ if (cause && cause.code) error.code = cause.code;+ error.cause = cause;+ return error;+}++// Whether `dir`, a folder this run made under a real (resolved) parent, is still that folder: 'owned' when it is a plain folder whose+// real path is the path it was made at, 'missing' when nothing is there, 'unsafe' otherwise. A link or junction put in its place fails+// assertSafeOutputDir (it refuses a link as the last component); one put in place of a folder above it changes the real path. Never throws.+function ownedDir(dir, fsImpl = fs) {+ try { fsImpl.lstatSync(dir); } catch (e) { return e && (e.code === 'ENOENT' || e.code === 'ENOTDIR') ? 'missing' : 'unsafe'; }+ try { return assertSafeOutputDir(dir, { fs: fsImpl }) === dir ? 'owned' : 'unsafe'; } catch { return 'unsafe'; }+}++function notOwnedError(shownDir) {+ return Object.assign(new Error(`refusing to use ${shownDir} as an output directory: it is no longer the folder this download made there (a link or junction was put in its place, or above it, or it was moved), so nothing more is read, written, moved or removed through it`), { code: 'UNSAFE_OUTPUT', reason: 'link' });+}++// The fs methods that read, write, make, move or remove, and which of their arguments name a path they act on (a file descriptor is not+// checked: it was opened by a checked call). Reads are held as writes are: what a staged download reads back from its staging folder+// is what it publishes into pages/ and states in the spec, so a read through a folder replaced by a link would hand on bytes from+// wherever that link points. realpathSync (and .native) is checked too: see generatedFolders. A method missing here would go through+// unchecked: tests/download-model-app.test.js fails on a raw call of any such method in writePageTree, the staged readback and their+// helpers, and checks each one listed is refused under a replaced folder.+const GUARDED_FS_METHODS = {+ mkdirSync: [0], mkdtempSync: [0], openSync: [0], writeFileSync: [0], appendFileSync: [0], truncateSync: [0], chmodSync: [0],+ utimesSync: [0], unlinkSync: [0], rmSync: [0], rmdirSync: [0], renameSync: [0, 1], copyFileSync: [0, 1], cpSync: [0, 1], linkSync: [0, 1],+ symlinkSync: [1], createWriteStream: [0],+ readFileSync: [0], readdirSync: [0], opendirSync: [0], statSync: [0], lstatSync: [0], existsSync: [0], accessSync: [0],+ readlinkSync: [0], createReadStream: [0],+};++// The fs a guarded fs checks with: the plain one under any number of guards (a staged download's staging guard holds the swap guard+// writePageTree makes inside it). Each guard's checks (ownedDir) compare real paths, which cover every folder above, so they need not+// themselves run through another guard; the operation still does.+const UNGUARDED_FS = Symbol('unguarded fs');++// The ONE way writePageTree, a staged download's staging and readback, and their helpers touch the folders they make. `adopt(dir)`+// takes a folder just made (refused, and not adopted, unless it is a plain folder at its own path); `fs` is `fsImpl` with every method of+// GUARDED_FS_METHODS checked before it runs, on any path in an adopted folder: the adopted folder and every folder between it and the path+// that exists must be owned (ownedDir), and the path itself, if it exists, must not be a link (nor, when a folder, other than owned).+// A failed check throws UNSAFE_OUTPUT and marks the folder that failed: no later operation runs on a path in it, nor moves or removes a+// folder that holds it. `verify(path)` makes the same check alone; `refused()` answers whether any check has failed (sticky), so a caller+// can refuse to use what it read even where a refusal was caught. Paths outside the adopted folders go through as they are.+function generatedFolders(fsImpl, shown) {+ const plain = fsImpl[UNGUARDED_FS] || fsImpl;+ const roots = [];+ const broken = [];+ const within = (p, dir) => {+ const rel = path.relative(dir, p);+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));+ };+ const refuse = (dir) => {+ if (!broken.includes(dir)) broken.push(dir);+ throw notOwnedError(shown(dir));+ };+ const verify = (target) => {+ const p = path.resolve(String(target));+ const hit = broken.find((b) => within(p, b) || within(b, p));+ if (hit) throw notOwnedError(shown(hit));+ const root = roots.find((r) => within(p, r));+ if (!root) return;+ // The adopted folder down to the path's own folder, top first, so the folder named is the one replaced. Below a missing folder+ // there is nothing to act through: the syscall fails on its own.+ const dirs = [];+ if (p !== root) {+ dirs.push(root);+ for (const part of path.relative(root, path.dirname(p)).split(path.sep).filter(Boolean)) dirs.push(path.join(dirs[dirs.length - 1], part));+ }+ for (const dir of dirs) {+ const state = ownedDir(dir, plain);+ if (state === 'missing') return;+ if (state !== 'owned') refuse(dir);+ }+ let st;+ try { st = plain.lstatSync(p); } catch (e) { if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return; refuse(p); }+ if (st.isSymbolicLink() || (st.isDirectory() && ownedDir(p, plain) !== 'owned')) refuse(p);+ };+ const guarded = Object.create(fsImpl);+ // Defined, not assigned: some of node's fs methods (opendirSync among them) are accessors with a setter, and an assignment through+ // the prototype would call that setter and replace the method of node's own fs, for every caller, with this guard.+ const own = (name, value) => Object.defineProperty(guarded, name, { value, writable: true, enumerable: true, configurable: true });+ own(UNGUARDED_FS, plain);+ for (const [name, at] of Object.entries(GUARDED_FS_METHODS)) {+ own(name, function (...args) {+ for (const i of at) if (typeof args[i] === 'string') verify(args[i]);+ return fsImpl[name](...args);+ });+ }+ // The read a write is aimed by: writeFileSafe and assertSafeOutputDir resolve a folder to its real path and then write under the+ // answer, which, through a folder replaced by a link, is a path outside every adopted folder that no later check would see. So the+ // folder is checked before it is resolved, and an owned folder resolves to itself.+ const realpathSync = function (p, ...rest) {+ if (typeof p === 'string') verify(p);+ return fsImpl.realpathSync(p, ...rest);+ };+ realpathSync.native = function (p, ...rest) {+ if (typeof p === 'string') verify(p);+ return (fsImpl.realpathSync.native || fsImpl.realpathSync)(p, ...rest);+ };+ own('realpathSync', realpathSync);+ return {+ fs: guarded,+ verify,+ refused: () => broken.length > 0,+ adopt(dir) {+ if (ownedDir(dir, plain) !== 'owned') throw notOwnedError(shown(dir));+ roots.push(dir);+ return dir;+ },+ };+}++// The checks writePageTree makes before it removes anything, made on their own: main asks them before it settles the+// managed fragments file and publishes, so a page tree that cannot be replaced stops it before that file, the pages or the spec are written. Answers whether+// there is a tree to replace.+function assertPageTreeReplaceable(pagesRoot, fsImpl = fs) {try {- fs.lstatSync(pagesRoot);+ fsImpl.lstatSync(pagesRoot);} catch (e) {- if (e && e.code === 'ENOENT') return;+ if (e && e.code === 'ENOENT') return false;throw e;}- assertSafeOutputDir(pagesRoot);- assertNoPlantedPageLinks(pagesRoot);+ assertSafeOutputDir(pagesRoot, { fs: fsImpl });+ assertNoPlantedPageLinks(pagesRoot, fsImpl);+ return true;}-// A fresh staging folder for the managed download's page tree, made INSIDE <out> (nothing outside the folder the maker named is written)-// under a hidden name unique to this process and call. `mkdir` without `recursive` fails on a name that exists, so a folder that is-// already there (another run's, or the maker's) is never reused or removed: another name is tried.-function makePageStage(outDir) {- const root = assertSafeOutputDir(outDir, { create: true });+// A fresh folder `<root>/<prefix>.<pid>.<random>.tmp`, hidden, unique to this process and call, adopted by `guard` (generatedFolders).+// `mkdir` without `recursive` fails on a name that exists, so a folder that is already there (another run's, or the maker's) is never+// reused or removed: another name is tried. `root` is a real path (assertSafeOutputDir's answer), and the folder made is checked to be a+// plain folder at its own path before it is answered: one replaced by a link or junction the moment it was made is refused+// (UNSAFE_OUTPUT) and left alone, so nothing is written into, or removed from, where that link points.+function makeHiddenDir(root, prefix, guard) {for (let attempt = 0; ; attempt += 1) {- const dir = path.join(root, `.download-pages.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);+ const dir = path.join(root, `${prefix}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);try {- fs.mkdirSync(dir);- return dir;+ guard.fs.mkdirSync(dir);} catch (e) {if (!(e && e.code === 'EEXIST') || attempt >= 4) throw e;+ continue;}+ return guard.adopt(dir);}}+// A fresh staging folder for a staged download's page tree, made INSIDE <out> (nothing outside the folder the maker named is written)+// under a hidden name unique to this process and call (makeHiddenDir, which also checks it), and the guarded fs (generatedFolders) every+// read, write, move and removal in it goes through: { dir, fs, refused } (refused: whether any check of the folder has failed).+function makePageStage(outDir) {+ const guard = generatedFolders(fs, (p) => p);+ return { dir: makeHiddenDir(assertSafeOutputDir(outDir, { create: true }), '.download-pages', guard), fs: guard.fs, refused: guard.refused };+}+// Reads every page the sitemap names, by id — so nothing outside this app is read — a few at a time, and answers// { ok: true, pages: [{ pageId, files }] } in the sitemap's order, or { ok: false, errors } naming each page that could not be read. A page that// cannot be read is a page the spec would drop: the caller refuses to write one rather than report it as an app without that page. That includes@@ -3046,25 +3355,34 @@ async function readSitemapPages(genpage, ids, concurrency) {return { ok: true, pages: results.map(({ id, page }) => ({ pageId: String(id).toLowerCase(), files: pageFolderFiles(page) })) };}-// `stagePages` (the managed download, main): the page tree is written to a staging folder inside <out> (makePageStage) and read+// `stagePages` (main, for every download it runs): the page tree is written to a staging folder inside <out> (makePageStage) and read// back from there exactly as a download writes it — the same files, the same reverse-resolved page.tsx — and the folder is removed.// The real pages/ folder is not touched: the result's `stagedPages` publishes it later (`check` makes writePageTree's checks without// writing, `publish` writes the tree with writePageTree). main publishes it only after everything that can still stop the download-// has succeeded, so a refusal there leaves a maker's page edits as they were. Without the option the download is exactly as before.+// has succeeded, so a refusal there leaves a maker's page edits as they were. Without the option (a library caller) the download+// writes pages/ itself, as it always did.async function runDownload(options = {}) {if (!options.stagePages) return downloadApp(options);- const stage = { dir: null, pages: null };+ const stage = { dir: null, fs: null, refused: () => false, pages: null };+ let result;+ let left = null;try {- const result = await downloadApp({ ...options, stage });- if (!result.ok || !stage.pages) return result;- const pagesRoot = path.join(path.resolve(options.outDir), 'pages');- const pages = stage.pages;- return { ...result, stagedPages: { check: () => assertPageTreeReplaceable(pagesRoot), publish: () => writePageTree(pagesRoot, pages) } };+ result = await downloadApp({ ...options, stage });} finally {// Best-effort: the pages are in memory by now. A folder that stays is named, so the maker can delete it.- const left = stage.dir ? removeTreeWithRetry(stage.dir) : null;- if (left) process.stderr.write(`WARNING: the download's staging folder ${stage.dir} could not be removed (${left}): delete it.\n`);+ left = stage.dir ? removeTreeWithRetry(stage.dir, { fs: stage.fs }) : null;+ if (left === 'UNSAFE_OUTPUT') process.stderr.write(`WARNING: the download's staging folder ${stage.dir} was not removed: ${NOT_OWNED_LEFT}\n`);+ else if (left) process.stderr.write(`WARNING: the download's staging folder ${stage.dir} could not be removed (${left}): delete it.\n`);+ }+ if (!result.ok || !stage.pages) return result;+ // The staging folder found replaced at any check, its removal included (after the last read): what was read from it cannot be told+ // from what the link supplied, so none of it is published nor reported as the app's pages. Nothing has been written to pages/ yet.+ if (left === 'UNSAFE_OUTPUT' || stage.refused()) {+ throw Object.assign(new Error(`refusing to use the pages read back from the download's staging folder ${stage.dir}: it is no longer the folder this download made there (a link or junction was put in its place, or above it, or it was moved), so what was read from it is not used, and pages/ was not written`), { code: 'UNSAFE_OUTPUT', reason: 'link' });}+ const pagesRoot = path.join(path.resolve(options.outDir), 'pages');+ const pages = stage.pages;+ return { ...result, stagedPages: { check: () => assertPageTreeReplaceable(pagesRoot), publish: () => writePageTree(pagesRoot, pages) } };}async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossy = false, resetPageKeys = false, concurrency, languageCode, includeCapabilities = false, captureTheme = includeCapabilities, stage = null }) {@@ -3239,15 +3557,18 @@ async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossyif (!read.ok) return { ok: false, error: `page download failed: ${read.errors.join('; ')}` };// Staged (see runDownload): the tree is written, read back and reverse-resolved under the staging folder, which stands in for// <out> so each page's codeFile (relative to it) is the one a direct download gives.- if (stage) stage.dir = makePageStage(outDir);+ if (stage) Object.assign(stage, makePageStage(outDir));const treeRoot = stage ? path.join(stage.dir, 'pages') : pagesRoot;const writeRoot = stage ? stage.dir : outDir;- writePageTree(treeRoot, read.pages);+ // Every read and write under the staging folder goes through its guarded fs (generatedFolders): what is read back from it is what+ // is published and stated in the spec. Unstaged (a library caller), the download reads and writes pages/ itself.+ const pageTreeFs = stage ? stage.fs : fs;+ writePageTree(treeRoot, read.pages, { fs: pageTreeFs });const unreadableConfigs = [];const unkeptModels = [];const unkeptBindings = [];- pages = parseDownloadedPages(treeRoot, writeRoot, nameById, unreadableConfigs, unkeptModels, unkeptBindings);+ pages = parseDownloadedPages(treeRoot, writeRoot, nameById, unreadableConfigs, unkeptModels, unkeptBindings, pageTreeFs);// A read error names the file it read; name the one the maker will find.if (stage) for (const u of unreadableConfigs) u.reason = String(u.reason).split(stage.dir).join(path.resolve(outDir));// Reported, not gated: a page whose model is left out rebuilds exactly as every page did before the spec carried models — an@@ -3300,17 +3621,17 @@ async function downloadApp({ sdk, genpage, outDir, appId, appUnique, allowLossy// reverseResolveNavIdsReport); the ids it leaves are reported below.for (const p of pages) {const abs = path.join(writeRoot, p.codeFile);- assertPlainFileTarget(abs); // FAIL on a planted link (no swallow, no write)- const src = fs.readFileSync(abs, 'utf8'); // FAIL on a read error (no swallow)+ assertPlainFileTarget(abs, { fs: pageTreeFs }); // FAIL on a planted link (no swallow, no write)+ const src = pageTreeFs.readFileSync(abs, 'utf8'); // FAIL on a read error (no swallow)const rev = reverseResolveNavIdsReport(src, idToKey); // structural — nav pageId literals only- if (rev.code !== src) writeFileSafe(abs, rev.code, { encoding: 'utf8' }); // FAIL on a write error (no swallow)+ if (rev.code !== src) writeFileSafe(abs, rev.code, { encoding: 'utf8', fs: pageTreeFs }); // FAIL on a write error (no swallow)for (const left of rev.left) navIdsLeft.push({ page: p.name, ...left });}// The staged tree as it now is on disk, read back whole, for runDownload to publish: the bytes writePageTree will write again.if (stage) {stage.pages = read.pages.map(({ pageId, files }) => ({pageId,- files: Object.fromEntries(Object.keys(files).map((name) => [name, fs.readFileSync(path.join(treeRoot, pageId, name), 'utf8')])),+ files: Object.fromEntries(Object.keys(files).map((name) => [name, pageTreeFs.readFileSync(path.join(treeRoot, pageId, name), 'utf8')])),}));}// Every page id of this app still in a downloaded page is reported, whether a call the checker recognised holds it or not (see@@ -3891,8 +4212,9 @@ async function main(deps = {}) {// The page backend reads through the download's own throwaway SDK, lent to it: nothing of its own to make or remove.const genpage = io.makeGenpageSdk(env, { sdk });- // The managed download stages its page tree (runDownload `stagePages`): it is published below, after everything that can still stop it.- const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys, languageCode: session.languageCode, includeCapabilities, ...(includeManaged ? { stagePages: true } : {}) });+ // Every download stages its page tree (runDownload `stagePages`): it is checked and published below, after everything that can still+ // stop the download, so a refusal or a failure before then leaves the maker's pages/ exactly as it was.+ const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys, languageCode: session.languageCode, includeCapabilities, stagePages: true });// The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).makeWritesBlocking(process.stdout, io.stderr);if (!result.ok) { finish(false, result); return; }@@ -3980,12 +4302,13 @@ async function main(deps = {}) {+ ' Review each: change to "selector" if opening the page from the navigation should show a record picker.\n');}- // The fragments file is settled before anything is published: the staged page tree, the spec and the baseline are written only- // after it, so a refusal or a failed write here leaves every one of them as it was. The page tree's own checks come first, so a- // tree that cannot be replaced stops the download before the fragments file is written.+ // The staged page tree is published here, for every download, after validation and everything else that can stop the download: its+ // checks first (writePageTree's own refusals, made without writing), then, for the managed download, the fragments file, then the+ // tree, and only then the spec and the baseline. So a refusal or a failed write before this point leaves pages/, the spec and the+ // baseline as they were, and a tree that cannot be replaced stops the managed download before its fragments file is written.let managedFragments = null;+ if (result.stagedPages) result.stagedPages.check();if (includeManaged) {- if (result.stagedPages) result.stagedPages.check();try {managedFragments = settleFragments(outDir, { app: appUnique, items: fragments });} catch (e) {@@ -3995,8 +4318,8 @@ async function main(deps = {}) {if (managedFragments) {io.stderr.write(`WARNING: ${managedFragments.keys.length} managed item(s) left out only for what the download could not bring are written ready to paste in ${managedFragments.file}: add each "paste" entry to app-spec.json together with what its "needs" lists (from the spec it was built from), then build.\n`);}- if (result.stagedPages) result.stagedPages.publish();}+ if (result.stagedPages) result.stagedPages.publish();writeFileSafe(specPath, JSON.stringify(spec, null, 2));// AB#6726727: the spec just written is this app's server-current edit snapshot, so it is the baseline a later build// lines the live sitemap up against — a nav change made in the designer after this download is then@@ -4085,4 +4408,4 @@ if (require.main === module) {main().catch((err) => emitResult(false, err));}-module.exports = { untypedColumnNames, untypedColumnWarnings, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, pageBindingsReport, pageBindingsNote, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };+module.exports = { untypedColumnNames, untypedColumnWarnings, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, pageBindingsReport, pageBindingsNote, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, writePageTree, generatedFolders, GUARDED_FS_METHODS, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };diff --git a/plugins/model-apps/scripts/genpage-upload.js b/plugins/model-apps/scripts/genpage-upload.jsindex e2efd4b5f..de8cefe86 100644--- a/plugins/model-apps/scripts/genpage-upload.js+++ b/plugins/model-apps/scripts/genpage-upload.js@@ -498,9 +498,11 @@ async function main(argv = process.argv.slice(2), deps = {}) {// its base check, and only a key that page did not have stops the upload (below, once it is read).const styleProblems = griffelStyleProblems(checkedText).problems;// The checker command the message suggests names the file: as one argument no shell reads anything in, or — for a path a shell cannot be given literally — as a- // placeholder, with the path named in a sentence instead (lib/cli-failure.js commandArg; a path can come from an untrusted checkout).+ // placeholder, with the path named in a sentence instead (lib/cli-failure.js commandArg; a path can come from an untrusted checkout). For an update it adds+ // `--existing`: the checker also judges the page's scroll context, which an already deployed page may lack, and holding it to that as a new page would turn a+ // Griffel fix into a layout rewrite the maker did not ask for — with `--existing` those findings are notes (references/rules.md, Styling gotchas 6).const griffelFile = commandArgOrPlaceholder(flags['code-file'], '<file>');- const griffelWords = { surface: 'upload', subject: flags['code-file'], command: `node scripts/check-griffel-styles.js --file ${griffelFile.arg}`, ...(griffelFile.note ? { note: griffelFile.note } : {}) };+ const griffelWords = { surface: 'upload', subject: flags['code-file'], command: `node scripts/check-griffel-styles.js --file ${griffelFile.arg}${updating ? ' --existing' : ''}`, ...(griffelFile.note ? { note: griffelFile.note } : {}) };const stylesRefusal = (problems) => ({ok: false,code: 'griffel-shorthand',diff --git a/plugins/model-apps/scripts/lib/configuration-artifacts.js b/plugins/model-apps/scripts/lib/configuration-artifacts.jsindex 66f31ab57..0e81f02c9 100644--- a/plugins/model-apps/scripts/lib/configuration-artifacts.js+++ b/plugins/model-apps/scripts/lib/configuration-artifacts.js@@ -2625,6 +2625,24 @@ const OVERWRITE_TOKEN = /^overwrite:(environmentVariable|connectionReference|cus// adopt:duplicateRuleCondition:email/e// Read only under the opt-in, checked against the App Spec (the root and the child must be declared) and normalized back// to that spelling, so a key typed in another case still names the one row; a root's approval never covers its children.+// The same tokens with `@<row id>` appended adopt a row a maker made BEFORE the opt-in, at an id the plugin did not derive+// (configuration-protected.js adoptionOf), for an environment variable, a connection reference or a Custom API and their+// children. The id ties the approval to that one row, so it never binds a row deleted and made again, and a root token+// also carries `+<16 hex>` when the build would then change fields of that row, the first 16 hex of the SHA-256 of the+// list of field pointers it printed, so the approval lapses when that list changes, e.g.+// adopt:customApi:contoso_calc@0b7c6f5e-0000-4000-8000-000000000001+3f2a9c0d1e2b4a59+// adopt:customApiRequestParameter:contoso_calc/request%3Aa@0b7c6f5e-0000-4000-8000-000000000002+// The two meanings never meet: a plain approval lands in `rowApprovals` as `adopt:...` exactly as before, and an+// `@<row id>` one as `adopt-row:...` (the same text after the verb), a spelling no plain approval normalizes to, so a+// token read one way is never consumed the other way. A declared key may itself end in what reads like `@<id>`: when the+// whole text names a declared item AND the text before `@<id>` names another, the token is refused as ambiguous+// (CONFIGURATION_ADOPT_AMBIGUOUS) rather than read either way, and the stop never prints an `@<id>` approval that would+// read so (adoptionOf refuses that adoption, saying why). A plugin before this form reads the root suffix as part of the+// declared key, names no declared item and refuses the token before any write.+// A duplicate rule and its conditions are never adopted (adoptionOf), so their tokens keep only the plain reading,+// exactly as before this form: a rule or condition key may contain '@' (it is free text), and `odd@<id>` is just that key.+const ADOPT_AT = /^([\s\S]*)@([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\+([0-9a-f]{16}))?$/i;+const ADOPT_CHILD_AT = /^([\s\S]*)@([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;const ADOPT_ROOT_TOKEN = /^adopt:(environmentVariable|connectionReference|customApi|duplicateRule):([\s\S]+)$/;const ADOPT_CHILD_TOKEN = /^adopt:(environmentVariableValue|customApiRequestParameter|customApiResponseProperty|duplicateRuleCondition):([\s\S]+)$/;const ADOPT_CHILD_PARENT = Object.freeze({@@ -2673,26 +2691,43 @@ function configurationAuthorizationKeys(tokens, spec) {const adoptRoot = ADOPT_ROOT_TOKEN.exec(text);if (adoptRoot) {const [, kind, name] = adoptRoot;- const root = rootOf(kind, name);- if (!root) problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM' });- else if (!protectedSpec) problems.push({ token: text, code: 'CONFIGURATION_ADOPT_UNPROTECTED' });- else rowApprovals.add(`adopt:${kind}:${portKeyOf(kind, root)}`);+ const plain = rootOf(kind, name);+ const atRow = kind === 'duplicateRule' ? null : ADOPT_AT.exec(name);+ const atRoot = atRow ? rootOf(kind, atRow[1]) : undefined;+ if (plain && atRoot) { problems.push({ token: text, code: 'CONFIGURATION_ADOPT_AMBIGUOUS' }); continue; }+ const root = plain || atRoot;+ if (!root) { problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM' }); continue; }+ if (!protectedSpec) { problems.push({ token: text, code: 'CONFIGURATION_ADOPT_UNPROTECTED' }); continue; }+ rowApprovals.add(plain ? `adopt:${kind}:${portKeyOf(kind, root)}`+ : `adopt-row:${kind}:${portKeyOf(kind, root)}@${atRow[2].toLowerCase()}${atRow[3] ? `+${atRow[3].toLowerCase()}` : ''}`);continue;}const adoptChild = ADOPT_CHILD_TOKEN.exec(text);if (adoptChild) {- const [, childKind, rest] = adoptChild;+ const [, childKind, whole] = adoptChild;const parent = ADOPT_CHILD_PARENT[childKind];// Both parts are percent-encoded, so the one '/' is the separator; anything else is not a key the build printed.- const parts = rest.split('/');- const name = parts.length === 2 ? decode(parts[0]) : null;- const slot = parts.length === 2 ? decode(parts[1]) : null;- if (!nonEmptyString(name) || !nonEmptyString(slot)) { problems.push({ token: text, code: 'CONFIGURATION_ADOPT_INVALID' }); continue; }- const root = rootOf(parent, name);- const child = root ? slotOf(childKind, declaredEntry(parent, root), slot) : null;+ const named = (rest) => {+ const parts = rest.split('/');+ const name = parts.length === 2 ? decode(parts[0]) : null;+ const slot = parts.length === 2 ? decode(parts[1]) : null;+ if (!nonEmptyString(name) || !nonEmptyString(slot)) return { invalid: true };+ const root = rootOf(parent, name);+ return { root, child: root ? slotOf(childKind, declaredEntry(parent, root), slot) : null };+ };+ // Both readings, as for a root: the whole text (exactly as before the `@<row id>` form), and the text before a+ // trailing `@<id>` with that id (a printed slot is percent-encoded, '@' as %40, so a printed id is never part of it).+ const plain = named(whole);+ const atRow = childKind === 'duplicateRuleCondition' ? null : ADOPT_CHILD_AT.exec(whole);+ const withId = atRow ? named(atRow[1]) : { child: null };+ if (plain.child && withId.child) { problems.push({ token: text, code: 'CONFIGURATION_ADOPT_AMBIGUOUS' }); continue; }+ const found = plain.child || !withId.child ? plain : withId;+ if (found.invalid) { problems.push({ token: text, code: 'CONFIGURATION_ADOPT_INVALID' }); continue; }+ const { root, child } = found;+ const tail = `${childKind}:${encodeURIComponent(portKeyOf(parent, root))}/${encodeURIComponent(child)}`;if (!child) problems.push({ token: text, code: 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM' });else if (!protectedSpec) problems.push({ token: text, code: 'CONFIGURATION_ADOPT_UNPROTECTED' });- else rowApprovals.add(`adopt:${childKind}:${encodeURIComponent(portKeyOf(parent, root))}/${encodeURIComponent(child)}`);+ else rowApprovals.add(found === plain ? `adopt:${tail}` : `adopt-row:${tail}@${atRow[2].toLowerCase()}`);continue;}const kind = text.slice(0, text.indexOf(':'));diff --git a/plugins/model-apps/scripts/lib/configuration-build.js b/plugins/model-apps/scripts/lib/configuration-build.jsindex ddd3dfa20..dbc38d6be 100644--- a/plugins/model-apps/scripts/lib/configuration-build.js+++ b/plugins/model-apps/scripts/lib/configuration-build.js@@ -181,9 +181,14 @@ function createConfigurationRuntime({ spec, sdk, provision, opts = {}, appUniqueconst others = halts.filter((h) => h !== first).map((h) => `${h.kind} ${h.key} (${h.code})`);// A row of an earlier, unfinished create that no answer proved this build's own is adopted only under the maker's// exact approval token, one per row (managed-create-context.js judgeRows), never wholesale.- const approvals = [...new Set(halts.flatMap((h) => h.approvals || []))];+ const approvals = [...new Set(halts.filter((h) => !h.adoption).flatMap((h) => h.approvals || []))];const approve = approvals.length ? ` Its rows are bound only under these exact approvals, given after checking those rows are yours: ${approvals.map((t) => JSON.stringify(t)).join(', ')}.` : '';- throw fail(first.code, `${first.kind} ${first.key}: ${first.message}${others.length ? ` Also stopped: ${others.join(', ')}.` : ''}${approve}`);+ // A namesake made before the opt-in (configuration-protected.js adoptionHalt) is adopted only under its own exact+ // approvals, and they are printed for EVERY such item of the stop with what they approve — its kind, key and id,+ // the id of each row (in the approvals themselves) and every field the build would then change — never a bare+ // token for an item whose own sentence is not the one shown.+ const adoptions = halts.filter((h) => h.adoption).map((h) => ` Adopt ${h.kind} ${h.key} at its id ${h.adoption.id} (the build would then change ${h.adoption.change}) only under these exact approvals, given after checking those rows are yours: ${h.adoption.approvals.map((t) => JSON.stringify(t)).join(', ')}.`).join('');+ throw fail(first.code, `${first.kind} ${first.key}: ${first.message}${others.length ? ` Also stopped: ${others.join(', ')}.` : ''}${approve}${adoptions}`);},// Plan, apply and observe ONE phase's items. Returns {outcome, blocking, halt, plan}.async apply(phase) {diff --git a/plugins/model-apps/scripts/lib/configuration-create-bindings.js b/plugins/model-apps/scripts/lib/configuration-create-bindings.jsindex b35712997..2b2804c67 100644--- a/plugins/model-apps/scripts/lib/configuration-create-bindings.js+++ b/plugins/model-apps/scripts/lib/configuration-create-bindings.js@@ -563,14 +563,18 @@ function pinApiLabels(artifact, rootMode, slotModes, bases) {* id) holds the fresh readConfigurationRow answer of every row the plan updates with a PATCH: its row version is the only* If-Match the classifier admits for that row, and a Custom API row's labels the App Spec leaves out are kept from it.* `baseGeneration` is the committed group's generation (the binding store's readGroup) an update is planned from: the- * store prepares the attempt only while the group is still at it.+ * store prepares the attempt only while the group is still at it. `childIdOf` ({ <slot>: <id> }, a bound root only) places+ * an existing child at an id the plugin did not derive (one adopted under its `@<id>` approval). `asIs: true` plans the+ * same existing rows read-only: no create row, and each row expected exactly as its base read holds it.* Answers a frozen planned object { kind, key, solution, plan, rows } — `plan` is buildRowPlan's input (with the root's* `baseObservation` when it is an update read fresh); `rows` are its rows with what each must read back as* (`expected`), for a child its slot, and for a PATCHed row its held row version (`ifMatch`). No private input is in* either.*/-function planOf(spec, { kind, key, bindings, solution, intentFor = defaultIntentFor, boundIdOf, componentTypes, boundSlots = [], keptChildren, bases, baseGeneration } = {}) {+function planOf(spec, { kind, key, bindings, solution, intentFor = defaultIntentFor, boundIdOf, componentTypes, boundSlots = [], keptChildren, bases, baseGeneration, childIdOf, asIs = false } = {}) {if (!ROOT_KINDS.has(kind)) throw new TypeError(`planOf: ${kind} is not a configuration root kind`);+ if (asIs && typeof boundIdOf !== 'function') throw new TypeError('planOf: an as-is plan is a plan of a bound row');+ if (asIs && kind === 'duplicateRule') throw new TypeError('planOf: a duplicate rule is never adopted, so never planned as-is');const entry = A.configurationIntentOf(spec, kind, key);const sol = nonEmpty(solution) ? solution : spec && isPlain(spec.solution) && nonEmpty(spec.solution.uniqueName) ? spec.solution.uniqueName : 'Default';const binds = bindings || { environmentVariables: new Map(), connectionReferences: new Map() };@@ -584,12 +588,20 @@ function planOf(spec, { kind, key, bindings, solution, intentFor = defaultIntentif (!parent) throw new TypeError(`planOf: the parent definition "${entry.parentSchemaName}" of "${portKey}" is not declared`);parentDefinitionId = parent.id;}- const artifact = A.buildArtifact({ kind, key: portKey, detail: { entry } }, got.id, got.childIds, { bindings: binds }, parentDefinitionId);+ // A child the root already has at an id this plugin did not derive (a row a maker made before the opt-in, adopted under+ // its own `@<id>` approval: configuration-protected.js adoptionOf) keeps that id; every other child takes its derived one.+ const childIds = { ...got.childIds };+ for (const [slot, rawId] of Object.entries(childIdOf || {})) {+ const id = normalizeGuid(rawId);+ if (!has(got.childIds, slot) || !id || got.intent.boundId === undefined) throw new TypeError(`planOf: ${kind} "${portKey}" has no bound ${slot} child to place at ${rawId}`);+ childIds[slot] = id;+ }+ const artifact = A.buildArtifact({ kind, key: portKey, detail: { entry } }, got.id, childIds, { bindings: binds }, parentDefinitionId);const secrets = new Map();const rootId = normalizeGuid(got.id);const rootMode = got.intent.boundId !== undefined ? 'update' : 'create';const bound = new Set(boundSlots);- if (kind === 'customApi') pinApiLabels(artifact, rootMode, new Map(Object.keys(got.childIds).map((s) => [s, bound.has(s) ? 'update' : 'create'])), bases);+ if (kind === 'customApi') pinApiLabels(artifact, rootMode, new Map(Object.keys(childIds).map((s) => [s, bound.has(s) ? 'update' : 'create'])), bases);const rootExpected = expectedOf(kind, artifact);const root = {kind, key: portKey, id: rootId, parentId: null, slot: null, mode: rootMode, sensitiveInput: false,@@ -600,7 +612,7 @@ function planOf(spec, { kind, key, bindings, solution, intentFor = defaultIntentsecrets.set(rowKey(kind, portKey), artifact.connectionId);}const rows = [root];- for (const [slot, rawId] of Object.entries(got.childIds)) {+ for (const [slot, rawId] of Object.entries(childIds)) {const childKind = childKindOf(kind, slot);const id = normalizeGuid(rawId);const children = kind === 'customApi' ? [...artifact.requestParameters, ...artifact.responseProperties] : kind === 'duplicateRule' ? artifact.conditions : [];@@ -628,6 +640,19 @@ function planOf(spec, { kind, key, bindings, solution, intentFor = defaultIntentif (!id) throw new TypeError(`planOf: the kept ${slot} child of ${kind} "${portKey}" has no id`);rows.push({ kind: 'environmentVariableValue', key: JSON.stringify([portKey, slot]), id, parentId: rootId, slot, mode: 'update', kept: true, expected: {}, sensitiveInput: false });}+ // An as-is plan (`asIs`): the rows of the same plan that already exist, each expected to read back exactly as its own base+ // read holds it, over the same field set — no create row and nothing to send. It is what a read-only acceptance of rows+ // made before the opt-in proves (configuration-protected.js adoptionOf): the build then plans the item as bound and+ // sends only the edit it printed, through its ordinary protected path.+ if (asIs) {+ if (rootMode !== 'update') throw new TypeError(`planOf: ${kind} "${portKey}" is not bound; an as-is plan has nothing to keep`);+ for (let i = rows.length - 1; i >= 0; i -= 1) if (rows[i].mode !== 'update') rows.splice(i, 1);+ for (const r of rows) {+ if (r.kept) continue;+ const own = semanticOf(r.kind, baseOf(bases, r.kind, r.id, r.parentId).decoded);+ r.expected = Object.fromEntries(Object.keys(r.expected).map((f) => [f, has(own, f) ? own[f] : null]));+ }+ }for (const r of rows) {// An updated row keeps what its base read held in the columns this build never writes (PRESERVED): the exact value, so// a row whose implementation was replaced or removed meanwhile is not the row this edit planned.@@ -638,7 +663,10 @@ function planOf(spec, { kind, key, bindings, solution, intentFor = defaultIntent// An update of a bound root records the versions it was prepared from (the binding store's baseObservation); they stay// out of the declaration, which a later fresh read must not change.const versions = rows.filter((r) => r.ifMatch !== undefined).map((r) => ({ kind: r.kind, id: r.id, rowVersion: r.ifMatch }));- const baseObservation = root.ifMatch !== undefined ? { rowVersion: root.ifMatch, savedSha256: sha({ rows: versions }) } : null;+ // A root read without a row version records a null one in its as-is plan: its base is then proved by the content+ // projection alone (baseOf).+ const baseObservation = root.ifMatch !== undefined ? { rowVersion: root.ifMatch, savedSha256: sha({ rows: versions }) }+ : asIs ? { rowVersion: null, savedSha256: sha({ rows: versions }) } : null;const members = [];if (!isRestrictedSolution(sol)) {for (const r of rows) {@@ -1445,6 +1473,7 @@ module.exports = {createSetClassifier,readConfigurationRow,readConfigurationConflicts,+ readAllPages,readComponentTypes,observe,editShapeOf,diff --git a/plugins/model-apps/scripts/lib/configuration-protected.js b/plugins/model-apps/scripts/lib/configuration-protected.jsindex e079a11f3..568435f02 100644--- a/plugins/model-apps/scripts/lib/configuration-protected.js+++ b/plugins/model-apps/scripts/lib/configuration-protected.js@@ -21,10 +21,13 @@// checked change set the SDK sends (the root PATCH with new children, or two or more new children); a removal, a change// to a child's fixed fields or any other combination is refused.+const crypto = require('node:crypto');const B = require('./configuration-create-bindings.js');const A = require('./configuration-artifacts.js');-const { normalizeGuid, isAuthorized, approvalKey } = require('./reconcile-common.js');+const { normalizeGuid, isAuthorized, approvalKey, canonicalJson } = require('./reconcile-common.js');const { hasUnsyncedEdits } = require('./unsynced-edits.js');+const { defaultApprovalToken } = require('./managed-create-context.js');+const { attemptProvenUnsent } = require('./managed-bindings.js');const IDENTITY = 'stable-v1';const EDIT_CODE = 'configuration-edit-unsupported';@@ -99,6 +102,24 @@ function declaredItems(spec) {return out;}+// declaredItems with every data-source variable after the declared parent it names, the order the build itself makes+// them in (configuration-artifacts.js planEnvironmentVariables), so the preflight forecasts a parent's adoption+// (env.adopting) before it plans the child under it. A cycle or an undeclared parent keeps the declared order.+function parentsFirst(spec, items) {+ const parentOf = new Map();+ for (const e of Array.isArray(spec && spec.environmentVariables) ? spec.environmentVariables : []) {+ if (e && typeof e.schemaName === 'string' && e.type === 'dataSource' && typeof e.parentSchemaName === 'string') parentOf.set(A.portKeyOf('environmentVariable', e.schemaName), A.portKeyOf('environmentVariable', e.parentSchemaName));+ }+ const waiting = items.slice();+ const out = [];+ const pending = (pk) => waiting.some((x) => x.kind === 'environmentVariable' && A.portKeyOf(x.kind, x.key) === pk);+ while (waiting.length) {+ const i = waiting.findIndex((x) => x.kind !== 'environmentVariable' || !parentOf.has(A.portKeyOf(x.kind, x.key)) || !pending(parentOf.get(A.portKeyOf(x.kind, x.key))));+ out.push(...waiting.splice(i < 0 ? 0 : i, 1));+ }+ return out;+}+// A child record's slot: the driver keys a child row `JSON.stringify([<root key>, <slot>])` (planOf).function slotOf(record) {try {@@ -109,19 +130,47 @@ function slotOf(record) {}}+/**+ * A plan's `boundIdOf` for the OTHER declared items it refers to: a data-source variable's declared parent, planned at+ * the row it really is — its committed binding's root id (its derived id when it was created; a maker's row when it was+ * adopted) or, while this build adopts it, the namesake its adoption names (env.adopting) — so a child is planned under+ * that row rather than at the parent's derived id, where an adopted parent is not. Undefined (the derived id, as before)+ * for anything else, for the item itself (locateItem plans its own binding) and for a parent nothing is bound or+ * adopted at. Reads the local store only.+ */+function parentIdOf(env, kind, portKey) {+ return (k, pk) => {+ if (k !== 'environmentVariable' || (k === kind && pk === portKey)) return undefined;+ let group = null;+ try { group = env.store.readGroup(k, pk); } catch { group = null; }+ const root = group && group.committed ? (group.committed.records || []).find((r) => r.kind === k && r.key === pk) : null;+ if (root) return normalizeGuid(root.id);+ return env.adopting instanceof Map ? env.adopting.get(pk) : undefined;+ };+}+/*** Locate one declared item by its binding and plan it, reading only:* { state: 'unbound', planned } no committed binding: a create at the derived ids;* { state: 'pending', planned, token, edit } an attempt is pending (recoverPending decides it from its own expectation);+ * `adoption` marks an attempt over existing rows only with nothing committed: an+ * adoption that never sends (adoptNamesake), planned here as the unbound item it was;* { state: 'bound', planned } the committed binding, every bound row read fresh at its exact id.* A bound row read absent is `configuration-row-not-found` (never replaced by a namesake), an unreadable one or a binding* whose ids the declaration no longer derives is `create-identity-unverified`; both throw, typed.*/async function locateItem(env, kind, key) {const { spec, store, dataverse, solution, bindings, componentTypes } = env;- const fresh = B.planOf(spec, { kind, key, bindings, solution, componentTypes });+ const portKey = A.portKeyOf(kind, key);+ const fresh = B.planOf(spec, { kind, key, bindings, solution, componentTypes, boundIdOf: parentIdOf(env, kind, portKey) });const group = store.readGroup(kind, fresh.key);- if (group.pending && !group.committed) return { state: 'pending', planned: fresh, token: group.pending.token, edit: false, attempt: group.pending, declaredKey: key };+ if (group.pending && !group.committed) {+ // An attempt over existing rows only, with nothing committed for the item, can only be an adoption of a row made+ // before the opt-in (adoptNamesake): it never sends, so it is never recovered as a create (run refuses it).+ const rows = group.pending.rowProtocol && Array.isArray(group.pending.rowProtocol.rows) ? group.pending.rowProtocol.rows : [];+ const adoption = rows.length > 0 && rows.every((r) => r.mode === 'update');+ return { state: 'pending', planned: fresh, token: group.pending.token, edit: false, adoption, attempt: group.pending, declaredKey: key };+ }if (!group.committed) return { state: 'unbound', planned: fresh };const records = group.committed.records || [];const root = records.find((r) => r.kind === kind && r.key === fresh.key);@@ -143,6 +192,9 @@ async function locateItem(env, kind, key) {const declaredSlots = new Set(fresh.rows.filter((r) => r.slot !== null).map((r) => r.slot));const boundSlots = [];const keptChildren = {};+ // A child adopted at the id a maker's row already had (adoptNamesake) stays at that id; a created child is at the id+ // the declaration derives, and the check below still holds it to that.+ const childIdOf = {};for (const r of records) {if (r === root) continue;const slot = slotOf(r);@@ -157,11 +209,13 @@ async function locateItem(env, kind, key) {}bases.set(normalizeGuid(r.id), await read(r));boundSlots.push(slot);+ if (r.origin === 'adopted') childIdOf[slot] = normalizeGuid(r.id);}const planned = B.planOf(spec, {- kind, key, bindings, solution, componentTypes, bases, boundSlots, keptChildren, baseGeneration: group.committed.generation,- // Only this item is bound in its own plan: another item of the kind is planned (and judged) on its own.- boundIdOf: (k, pk) => (k === kind && pk === fresh.key ? rootId : undefined),+ kind, key, bindings, solution, componentTypes, bases, boundSlots, keptChildren, childIdOf, baseGeneration: group.committed.generation,+ // Only this item is bound in its own plan: another item of the kind is planned (and judged) on its own; a declared+ // parent it refers to is planned at the row it is bound at (parentIdOf).+ boundIdOf: (k, pk) => (k === kind && pk === fresh.key ? rootId : parentIdOf(env, kind, fresh.key)(k, pk)),});for (const r of records) {const row = planned.rows.find((x) => x.kind === r.kind && x.key === r.key);@@ -255,12 +309,297 @@ async function firstCreateVerdict(dataverse, planned, { exactId }) {const conflicts = await B.readConfigurationConflicts(dataverse, planned);if (conflicts.state === 'clear') return null;const ids = conflicts.rows.flatMap((r) => r.ids || []);- return {+ const verdict = {code: conflicts.code || UNVERIFIED_CODE,message: conflicts.state === 'conflict'? `the ${planned.kind} "${planned.key}" has a namesake at another id (${ids.join(', ')}); a protected create never binds a namesake, and no service changes were sent by this build`: `the ${planned.kind} "${planned.key}" namesake query could not be completed; nothing is created on a read that may have missed a namesake, and no service changes were sent by this build`,};+ // Whether this is the one case adoptionOf can take up (exactly one namesake of the root, and nothing else in the way).+ // Kept off the halt itself (not enumerable, so `...verdict` never carries it into a stop): several namesakes skip the+ // adoption reads altogether and keep today's stop and today's requests.+ const own = conflicts.rows.find((r) => r.kind === planned.kind && r.key === planned.key);+ const single = conflicts.state === 'conflict' && !!own && own.state === 'conflict' && own.ids.length === 1 && conflicts.rows.every((r) => r === own || r.state === 'clear');+ Object.defineProperty(verdict, 'single', { value: single });+ return verdict;+}++// Fields the protected path never changes on a row that exists: what the platform fixes on create (a type, a binding, a+// connector) and the name the row is found by. A namesake whose App Spec differs in one of them is not+// the item the App Spec declares, so it is never adopted (a different case of the name included: an adopted row keeps+// the name it has, and the App Spec would then name it in another spelling).+const IMMUTABLE = Object.freeze({+ environmentVariable: ['schemaName', 'type', 'secretStore', 'parentDefinitionId'],+ environmentVariableValue: [],+ connectionReference: ['logicalName', 'connectorId', 'customConnectorId'],+ customApi: ['uniqueName', 'binding', 'boundEntityLogicalName', 'isFunction', 'allowedProcessingSteps', 'enabledForWorkflow'],+ customApiRequestParameter: ['uniqueName', 'type', 'entityLogicalName', 'isOptional'],+ customApiResponseProperty: ['uniqueName', 'type', 'entityLogicalName'],+});+// The kinds a namesake made before the opt-in may be adopted for. A duplicate rule is not one of them: the build plans a+// bound rule's later edit and publication outside the protected update path, where an adoption's printed field list could+// not hold it, so a rule's namesake keeps the stop it had before adoption existed (no adoption reads, no approvals).+const ADOPTABLE = new Set(['environmentVariable', 'connectionReference', 'customApi']);+// One JSON Pointer reference token (RFC 6901): '~' is written '~0' and '/' is written '~1'.+// See: https://www.rfc-editor.org/rfc/rfc6901#section-3+const pointerToken = (s) => String(s).replace(/~/g, '~0').replace(/\//g, '~1');+// The `+<16 hex>` an adoption's root approval carries when the build would then change the row: the first 16 hex of the+// SHA-256 of the sorted pointer list it printed, so an approval given for one list never covers another.+const pointerDigest = (pointers) => crypto.createHash('sha256').update(canonicalJson(pointers)).digest('hex').slice(0, 16);+const rowKeyOf = (r) => `${r.kind}\u0000${r.key}`;++/**+ * Whether an unbound item's one namesake — a row a maker made before the opt-in, at an id this plugin did not derive —+ * can be adopted at its own id, and on what terms. Reads only; sends nothing. Answers+ * null not that case (the derived id is not free, the namesake query is not exactly+ * one root at another id and nothing else): the first-create verdict stands;+ * { adoptable: false, id, reason } it is that case, and it cannot be adopted (why, in words);+ * { adoptable: true, id, overlay, asIs, observation, pointers, digest, tokens, printed, tokenOf }.+ * The namesake and every row under it are read exactly, at their ids (bases), and every row under it is paired with the+ * declaration: one value, an API child by its unique name. Two plans are made from those same reads:+ * overlay the item as the build would then make it (bound at the namesake; a declared child with no pair is a create+ * at its derived id): judged exactly as a bound item's edit is (judgeBoundShape, editVerdict / childVerdict);+ * asIs the same existing rows, each expected as it reads now (planOf asIs), with their members planned: what a read-only acceptance of the adoption proves (observation).+ * `pointers` lists every field the overlay would change (`/<field>`, `/<slot>/<field>`, `/<slot>` for a new child; names+ * only, a private value never), and `printed` are the exact approvals the stop prints: the root's `@<id>` (with `+<digest>`+ * of the pointers when there are any) and each child's `@<id>`; `tokens` are the same approvals as the parser types them.+ * It refuses whatever the protected path would not then make on its own+ * terms: a row under the namesake that the App Spec does not declare (a removal), a first value or a value or connection+ * that differs from the deployment settings (a private value is never written after an adoption), a changed fixed field,+ * a row outside the solution, or any read that does not complete.+ */+async function adoptionOf(env, item, declaredKey) {+ const { spec, dataverse, solution, bindings, componentTypes } = env;+ const fresh = item.planned;+ const { kind } = fresh;+ if (!ADOPTABLE.has(kind)) return null;+ const derived = await B.readConfigurationRow(dataverse, kind, fresh.plan.rows[0].id);+ if (derived.state !== 'absent') return null;+ const conflicts = await B.readConfigurationConflicts(dataverse, fresh);+ if (conflicts.state !== 'conflict') return null;+ const own = conflicts.rows.find((r) => r.kind === kind && r.key === fresh.key);+ if (!own || own.state !== 'conflict' || own.ids.length !== 1 || conflicts.rows.some((r) => r !== own && r.state !== 'clear')) return null;+ const id = normalizeGuid(own.ids[0]);+ const refuse = (reason) => ({ adoptable: false, id, reason });+ const root = await B.readConfigurationRow(dataverse, kind, id);+ if (root.state !== 'present' || root.parentId !== null) return refuse('it could not be read exactly');+ if (root.decoded.unmodelled.length) return refuse(`it holds columns the plugin does not manage (${root.decoded.unmodelled.join(', ')})`);++ // Every row under it, listed completely and read exactly (the listing as observe's child graph reads it).+ const listed = [];+ for (const [childKind, k] of Object.entries(B.KINDS)) {+ if (!k.parentSet || k.parentSet !== B.KINDS[kind].set) continue;+ const page = await B.readAllPages(dataverse, `/${k.set}?$select=${k.pk},${k.parentColumn}&$filter=${k.parentColumn} eq ${id}`);+ if (!page.complete) return refuse('the rows under it could not be listed completely');+ for (const r of page.rows) {+ const childId = r && typeof r[k.pk] === 'string' ? normalizeGuid(r[k.pk]) : '';+ if (!childId || normalizeGuid(r[k.parentColumn]) !== id || listed.some((c) => c.id === childId)) return refuse('the rows under it could not be listed completely');+ const got = await B.readConfigurationRow(dataverse, childKind, childId);+ if (got.state !== 'present' || got.parentId !== id) return refuse(`the ${childKind} ${childId} under it could not be read exactly`);+ if (got.decoded.unmodelled.length) return refuse(`the ${childKind} ${childId} under it holds columns the plugin does not manage`);+ listed.push({ kind: childKind, id: childId, read: got });+ }+ }+ const lower = (s) => (typeof s === 'string' ? s.toLowerCase() : s);+ const bases = new Map([[id, root]]);+ const childIdOf = {};+ const boundSlots = [];+ const keptChildren = {};+ const taken = new Set();+ for (const row of fresh.rows) {+ if (row.slot === null) continue;+ const pairs = listed.filter((c) => c.kind === row.kind && (row.kind === 'environmentVariableValue' || lower(c.read.decoded.fields.uniqueName) === lower(row.expected.uniqueName)));+ if (pairs.length > 1 || pairs.some((c) => taken.has(c.id))) return refuse(`more than one row under it could be its ${row.slot}`);+ if (!pairs.length) continue;+ taken.add(pairs[0].id);+ childIdOf[row.slot] = pairs[0].id;+ boundSlots.push(row.slot);+ bases.set(pairs[0].id, pairs[0].read);+ }+ // A value the deployment settings do not name stays as it is (held, never sent), as a bound variable's does; settings+ // that clear it would delete it, a removal the protected path does not make.+ const values = listed.filter((c) => c.kind === 'environmentVariableValue' && !taken.has(c.id));+ if (values.length && clearsValue(bindings, fresh.key)) return refuse('its deployment settings clear the value it holds, which deletes a row');+ if (values.length === 1 && !fresh.rows.some((r) => r.slot === 'value')) {+ keptChildren.value = values[0].id;+ taken.add(values[0].id);+ }+ const extra = listed.filter((c) => !taken.has(c.id));+ if (extra.length) return refuse(`it has rows under it that the App Spec does not declare (${extra.map((c) => `${c.kind} ${c.id}`).join(', ')}); removals are not supported`);++ const options = {+ kind, key: declaredKey, bindings, solution, componentTypes, bases, boundSlots, keptChildren, childIdOf,+ boundIdOf: (k, pk) => (k === kind && pk === fresh.key ? id : parentIdOf(env, kind, fresh.key)(k, pk)),+ };+ let overlay;+ let asIs;+ try {+ overlay = B.planOf(spec, options);+ asIs = B.planOf(spec, { ...options, asIs: true });+ } catch (error) {+ return refuse(`it cannot be planned from its reads (${error.message})`);+ }+ const judged = await judgeBoundShape(dataverse, kind, overlay);+ if (judged.halt) return refuse(judged.halt.message);+ const { shape } = judged;+ if (shape.removals.length) return refuse(`it has rows under it that the App Spec does not declare (${shape.removals.join(', ')}); removals are not supported`);+ if (shape.creates.includes('environmentVariableValue')) return refuse('the build would then write a first value to it; set its value outside the plugin to the one in the deployment settings first');+ const verdict = kind === 'customApi' ? editVerdict(kind, shape) : await childVerdict(env, overlay, shape);+ if (verdict) return refuse(`the change the build would then make to it is not one the protected path makes (${verdict.code})`);+ if (shape.creates.length) {+ const news = await B.readConfigurationConflicts(dataverse, overlay);+ if (news.state !== 'clear') return refuse(`the namesake query of a row the build would then add under it answered ${news.state}`);+ }++ // What the build would then change, by name.+ const changed = changedPointers(overlay, asIs);+ if (changed.refusal) return refuse(changed.refusal);+ const { pointers } = changed;++ const observation = await B.observe(dataverse, asIs);+ const reason = asIsReason(asIs, observation);+ if (reason) return refuse(reason);+ const digest = pointers.length ? pointerDigest(pointers) : '';+ // Each row's approval in two spellings: the one the stop prints (adopt:...@<id>) and the typed one the parser makes of+ // it (adopt-row:..., configuration-artifacts.js configurationAuthorizationKeys), the only spelling given approvals are+ // matched in, so a plain `adopt:` approval is never consumed as an adoption. A printed spelling that the parser would+ // not read back as exactly that row's approval (it also names another declared item) is never printed: not adoptable.+ const rootToken = `adopt-row:${kind}:${fresh.key}@${id}${digest ? `+${digest}` : ''}`;+ const tokenOf = (family, rootKey, row) => (row.parentId === null ? rootToken : `adopt-row:${defaultApprovalToken(family, rootKey, row).slice('adopt:'.length)}@${normalizeGuid(row.id)}`);+ const tokens = asIs.plan.rows.map((r) => tokenOf(kind, fresh.key, r));+ const printed = tokens.map((t) => `adopt:${t.slice('adopt-row:'.length)}`);+ const readBack = A.configurationAuthorizationKeys(printed, spec);+ if (readBack.problems.length || readBack.rowApprovals.size !== tokens.length || !tokens.every((t) => readBack.rowApprovals.has(t))) {+ return refuse('an approval of it would also read as the approval of another declared item, so none is printed; rename the key of one of the two');+ }+ return { adoptable: true, id, overlay, asIs, observation, pointers, digest, tokens, printed, tokenOf };+}++// The field pointers a plan would change on the rows of an as-is plan, sorted (a row it adds is its slot's pointer), or+// { refusal } when one is a field the build never changes on a row that exists. Rows are matched by plan key; a row of+// the plan the as-is plan does not hold is a change of its whole slot. Both plans hold the same field set per row+// (planOf asIs). The adoption's stop prints this list, and the build's edit of the row in that invocation is held to it+// (update).+function changedPointers(plan, asIs) {+ const sameAsIs = new Map(asIs.rows.map((r) => [rowKeyOf(r), r]));+ const pointers = [];+ for (const r of plan.rows) {+ const at = r.slot === null ? '' : `/${pointerToken(r.slot)}`;+ const now = sameAsIs.get(rowKeyOf(r));+ if (r.mode === 'create' || !now) { pointers.push(at); continue; }+ if (r.kept) continue;+ for (const f of Object.keys(r.expected)) {+ if (canonicalJson(r.expected[f] === undefined ? null : r.expected[f]) === canonicalJson(now.expected[f] === undefined ? null : now.expected[f])) continue;+ if (IMMUTABLE[r.kind].includes(f)) return { refusal: `its ${r.slot === null ? '' : `${r.slot} `}${f} differs from the App Spec's, and the build never changes it on a row that exists` };+ pointers.push(`${at}/${pointerToken(f)}`);+ }+ }+ return { pointers: pointers.sort() };+}+// Why an as-is plan's fresh observation does not prove the rows as they were read (null when it does): every row+// present at its id and parent and exactly its expectation (which covers its fields, unmodelled and preserved columns+// and, on the root, any row under it the plan does not hold), every private input readable and matching the deployment+// settings, and every member in the solution.+function asIsReason(asIs, observation) {+ const seen = new Map(observation.rows.map((r) => [rowKeyOf(r), r]));+ for (const row of asIs.rows) {+ const s = seen.get(rowKeyOf(row));+ if (!s || s.state !== 'present') return `its ${row.slot === null ? 'row' : row.slot} could not be read again exactly`;+ if (normalizeGuid(s.id) !== row.id || (s.parentId ? normalizeGuid(s.parentId) : null) !== row.parentId || s.projectionSha256 !== row.expectedSha256) {+ return 'it changed while it was read';+ }+ if (row.sensitiveInput && s.privateState !== 'match') {+ return row.kind === 'connectionReference'+ ? 'the connection it holds is not the one its deployment settings name (or cannot be read); the build never writes a connection after adopting'+ : 'the value it holds is not the one its deployment settings name (or cannot be read); the build never writes a value after adopting';+ }+ }+ if (observation.members.some((m) => m.state === 'absent')) return `it (or a row under it) is not in the solution ${asIs.solution}; add it there first`;+ if (observation.members.some((m) => m.state !== 'present')) return 'its solution membership could not be read';+ return null;+}++// The preflight stop of a namesake (firstCreateVerdict) with what adoptionOf found: today's sentence first, unchanged,+// then how it can be adopted or why it cannot be. An adoptable one carries `adoption` — its id, the fields the build would+// then change and its exact printed approvals — which configuration-build.js renders for EVERY such item of the stop, so+// no approval is printed without the rows and the change it approves.+function adoptionHalt(verdict, adoption) {+ if (!adoption) return verdict;+ if (!adoption.adoptable) return { ...verdict, id: adoption.id, message: `${verdict.message}. It cannot be adopted at its id ${adoption.id}: ${adoption.reason}.` };+ const change = adoption.pointers.length ? `only these fields, ${adoption.pointers.join(', ')}` : 'nothing in it';+ return {+ ...verdict, id: adoption.id, adoption: { id: adoption.id, change, approvals: adoption.printed.slice() },+ message: `${verdict.message}. It can instead be adopted at its id ${adoption.id}, after checking that row is yours; the build would then change ${change}.`,+ };+}++// Whether the maker asked to adopt the item's namesake: an approval of its root in the typed `@<row id>` form.+const adoptionAsked = (ctx, kind, portKey) => !!ctx && typeof ctx.approvals === 'function'+ && ctx.approvals().some((t) => typeof t === 'string' && t.startsWith(`adopt-row:${kind}:${portKey}@`));++/**+ * Adopt an unbound item's namesake at its own id, sending nothing (resolve, under the exact approvals adoptionOf+ * printed). The as-is plan is begun as an attempt (prepared and marked sending, with its expected proof), the store is+ * captured, and adoptionOf runs again — every read, the verdicts over the same declaration, the membership, the private+ * inputs and the as-is observation — after the capture and immediately before the acceptance, which must find the same+ * rows, the same pointer list and the same approvals; the acceptance (acceptReadOnly with the adoption's own approval+ * spellings) then commits the group read-only, or nothing. Any refusal, unreadable read or throw releases the attempt+ * (epoch-checked, while it provably sent nothing) and throws, typed: nothing is written to the service or the store.+ * Answers { state: 'present', id, adoption }: the item is bound at the namesake (`adoption` is what the acceptance proved,+ * which the port holds this invocation's edit of it to: update), and the build sends the printed edit, if any,+ * through update() like any bound item's; or null when there is no single namesake to adopt any more (approvals given for+ * a row since deleted adopt nothing, and the item is created at its derived id as the preflight forecast).+ */+async function adoptNamesake(env, ctx, item, declaredKey) {+ const { kind, key } = item.planned;+ const given = new Set(ctx.approvals());+ const fail = (reason, code = CONFLICT_CODE) => stop(code, `the ${kind} "${key}" namesake was not adopted: ${reason}; nothing was written`, { kind, key });+ const first = await adoptionOf(env, item, declaredKey);+ // No single namesake at another id any more (the row was deleted, or another appeared): there is nothing to adopt, and+ // the item is planned exactly as the preflight forecast it (a create at its derived id, or today's stop).+ if (!first) return null;+ if (!first.adoptable) throw fail(first.reason);+ if (!first.tokens.every((t) => given.has(t))) throw fail(`it is adopted only under these exact approvals: ${first.printed.join(', ')}`);+ const [attempt] = ctx.begin([first.asIs.plan]);+ let committed = false;+ try {+ const [capture] = ctx.captureReadOnly([attempt.token]);+ const again = await adoptionOf(env, item, declaredKey);+ if (!again || !again.adoptable) throw fail(again ? again.reason : 'it changed while it was read');+ if (again.id !== first.id || again.digest !== first.digest || canonicalJson(again.pointers) !== canonicalJson(first.pointers)+ || !sameRows(again.asIs.plan.rows, first.asIs.plan.rows) || !again.tokens.every((t) => given.has(t))) {+ throw fail('it changed while it was read');+ }+ const [accepted] = ctx.acceptReadOnly([{ token: attempt.token, observation: again.observation, capture, declarationSha256: again.asIs.plan.declarationSha256, approvalTokenOf: again.tokenOf }]);+ if (!accepted || accepted.verdict.action !== 'commit' || !accepted.group) {+ const h = haltOf(kind, key, accepted ? accepted.verdict : { code: UNVERIFIED_CODE });+ throw stop(h.code, h.message, h);+ }+ committed = true;+ return { state: 'present', id: first.id, adoption: again };+ } finally {+ if (!committed) ctx.release(attempt);+ }+}++// An adoption attempt (locateItem `adoption`) that provably sent nothing — only prepared, or marked sending with nothing+// dispatched (managed-bindings.js attemptProvenUnsent) — can be retired and the adoption made again; anything else is+// state this build cannot explain, never recovered as a create.+const adoptionUnsent = (store, attempt) => attempt.phase === 'prepared' || (typeof store.snapshot === 'function' && attemptProvenUnsent(attempt, store.snapshot().envelope.workflowEffects));+const adoptionStuck = (kind, key) => stop(UNVERIFIED_CODE, `the ${kind} "${key}" has a pending adoption this build cannot retire; nothing is sent for it`, { kind, key });++// Retire an adoption attempt that provably sent nothing (resolve), under a fresh claim so the store's epoch check holds:+// resume answers its new epoch, and release retires it only while its record still proves nothing was sent.+function retireAdoption(env, ctx, item) {+ const { kind, key } = item.planned;+ if (!adoptionUnsent(env.store, item.attempt)) throw adoptionStuck(kind, key);+ let resumed;+ try {+ [resumed] = ctx.resume([{ token: item.token, claim: item.attempt.phase === 'prepared' ? 'first' : 'continue' }]);+ } catch {+ throw adoptionStuck(kind, key);+ }+ if (!resumed || !ctx.release(resumed)) throw adoptionStuck(kind, key);}/**@@ -432,10 +771,17 @@ const haltOf = (kind, key, verdict) => ({// What every protected read needs, read once per build: the solution's component types (membership is planned only// outside the restricted solutions, but the read is cheap and fail-closed).+// A variable whose namesake can be adopted: its children are planned under that row (parentIdOf), as resolve binds it before+// them, so one stop can print the approvals of both. Without every approval of the parent the parent itself stops the build+// here, before anything is sent, so a child is never adopted under a parent this build does not adopt.+function adopting(env, kind, portKey, id) {+ if (kind === 'environmentVariable') env.adopting.set(portKey, normalizeGuid(id));+}+async function environmentOf({ spec, store, dataverse, solution, bindings }) {const types = await B.readComponentTypes(dataverse);if (!types || !types.complete) throw stop(UNVERIFIED_CODE, 'the solution component types could not be read');- return { spec, store, dataverse, solution, bindings, componentTypes: types.types };+ return { spec, store, dataverse, solution, bindings, componentTypes: types.types, adopting: new Map() };}/**@@ -471,13 +817,15 @@ async function replaceLocalCopy(dataverse, sdk, kind, id) {async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, solution, bindings, sdk = null, authorizedOverwrite = null }) {if (!configurationIdentityOf(spec)) return { halts: [] };const halts = [];+ // The maker's approvals as given (exact spellings): an adoption is forecast as made only when every one it needs is here.+ const given = new Set(ctx && typeof ctx.approvals === 'function' ? ctx.approvals() : []);let env;try {env = await environmentOf({ spec, store, dataverse, solution, bindings });} catch (error) {return { halts: [{ kind: 'configuration', key: '*', code: error.code || UNVERIFIED_CODE, message: error.message }] };}- for (const { kind, key } of declaredItems(spec)) {+ for (const { kind, key } of parentsFirst(spec, declaredItems(spec))) {try {const item = await locateItem(env, kind, key);// Every later step of a bound or pending item reads its row into the workspace over the local copy (locate's@@ -485,7 +833,7 @@ async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, so// read the service directly (B.readConfigurationRow / B.observe), never the workspace copy.// The copy is replaced only under the maker's exact overwrite approval for this item, never by the build on its// own (a failed send included): a diff says that the copy differs, never whose the difference is.- if (item.state !== 'unbound' && sdk) {+ if (item.state !== 'unbound' && !item.adoption && sdk) {const id = item.planned.plan.rows[0].id;if (await hasUnsyncedEdits(sdk, kind, id)) {if (!approvesOverwrite(authorizedOverwrite, overwriteKey(kind, item.planned.key))) {@@ -498,6 +846,17 @@ async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, so}}}+ if (item.state === 'pending' && item.adoption) {+ // An adoption that never sent is retired by resolve and made again: forecast it as the unbound item it was.+ if (!adoptionUnsent(store, item.attempt)) { const e = adoptionStuck(kind, item.planned.key); halts.push({ kind, key: item.planned.key, code: e.code, message: e.message }); continue; }+ const verdict = await firstCreateVerdict(env.dataverse, item.planned, { exactId: true });+ if (verdict) {+ const adoption = verdict.code === CONFLICT_CODE && verdict.id === undefined && verdict.single ? await adoptionOf(env, item, key) : null;+ if (adoption && adoption.adoptable) adopting(env, kind, item.planned.key, adoption.id);+ if (!adoption || !adoption.adoptable || !adoption.tokens.every((t) => given.has(t))) halts.push({ kind, key: item.planned.key, ...adoptionHalt(verdict, adoption) });+ }+ continue;+ }if (item.state === 'pending') {const rec = await recoverPending(env, ctx, item);if (rec.verdict.action === 'halt') {@@ -528,6 +887,15 @@ async function preflightProtectedConfiguration({ spec, store, ctx, dataverse, so// version PATCH included), so a create that cannot be made stops the build with nothing sent. resolve/run check// both again at dispatch, since a row can appear between this read and the create.const verdict = await firstCreateVerdict(env.dataverse, item.planned, { exactId: true });+ // A single namesake at another id (a row made before the opt-in) may be adopted at that id instead, under the+ // exact approvals adoptionOf prints; with all of them given, resolve adopts it and this is not a stop.+ if (verdict && verdict.code === CONFLICT_CODE && verdict.id === undefined && verdict.single) {+ const adoption = await adoptionOf(env, item, key);+ if (adoption && adoption.adoptable) adopting(env, kind, item.planned.key, adoption.id);+ if (adoption && adoption.adoptable && adoption.tokens.every((t) => given.has(t))) continue;+ halts.push({ kind, key: item.planned.key, ...adoptionHalt(verdict, adoption) });+ continue;+ }if (verdict) halts.push({ kind, key: item.planned.key, ...verdict });continue;} else if (item.state !== 'bound') continue;@@ -588,6 +956,15 @@ async function addMissingMembers(dataverse, planned, scope) {function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, bindings, apiBase = null, sdk = null }) {let envPromise = null;const env = () => (envPromise = envPromise || environmentOf({ spec, store, dataverse, solution, bindings }));+ // The items this port adopted (resolve), by kind and port key: the as-is plan the acceptance proved and the field+ // pointers its stop printed. This invocation's edit of such an item is held to exactly them (update); a later build has a+ // new port, and the item is an ordinary bound one there.+ const adoptedHere = new Map();+ const adopted = (kind, answer) => {+ if (!answer) return null;+ adoptedHere.set(`${kind}\u0000${answer.adoption.asIs.key}`, { asIs: answer.adoption.asIs, pointers: answer.adoption.pointers });+ return { state: answer.state, id: answer.id };+ };// A send this port ran that did not settle (a throw, a refused push, an answer that never came) leaves the workspace copy// exactly as it is: the build's own change, and any edit a maker wrote meanwhile through the same workspace. The copy is// shared with the maker and the SDK has no operation that compares it and replaces it in one step, so no check made@@ -613,7 +990,13 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, bin}return { state: 'present', id: rootId };}- if (item.state === 'pending') {+ if (item.state === 'pending' && item.adoption) {+ // An adoption attempt sends nothing: one that provably sent nothing is retired, then the item is the unbound one+ // it was (adopted afresh under the approvals, or created); anything else stops, typed.+ retireAdoption(await env(), ctx, item);+ const answer = adoptionAsked(ctx, kind, item.planned.key) ? adopted(kind, await adoptNamesake(await env(), ctx, item, key)) : null;+ if (answer) return answer;+ } else if (item.state === 'pending') {const rec = await recoverPending(await env(), ctx, item);let { verdict } = rec;const { observation } = rec;@@ -632,6 +1015,9 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, binif (verdict.action === 'commit') return { state: 'present', id: rootId };const h = haltOf(kind, item.planned.key, verdict);throw stop(h.code, h.message, h);+ } else if (adoptionAsked(ctx, kind, item.planned.key)) {+ const answer = adopted(kind, await adoptNamesake(await env(), ctx, item, key));+ if (answer) return answer;}const read = await B.readConfigurationRow(dataverse, kind, rootId);if (read.state === 'absent') return { state: 'absent', id: rootId };@@ -641,6 +1027,8 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, binasync run({ kind, key }, fn) {const item = await locateItem(await env(), kind, key);let resumed = null;+ // An adoption attempt is never sent as a create: its rows are a maker's, at ids no create derives.+ if (item.state === 'pending' && item.adoption) throw stop(UNVERIFIED_CODE, `the ${kind} "${item.planned.key}" has a pending adoption, which is never sent as a create`, { kind, key: item.planned.key });if (item.state === 'pending' && !item.edit) {const { verdict } = await recoverPending(await env(), ctx, item);if (verdict.action !== 'resume') throw stop(UNVERIFIED_CODE, `the ${kind} "${item.planned.key}" pending attempt is not one to send again`, { kind, key: item.planned.key });@@ -695,6 +1083,17 @@ function protectedConfigurationPort({ spec, store, ctx, dataverse, solution, binif (!rec.sameRows) { const h = haltOf(kind, planned.key, pendingEditChanged(planned)); throw stop(h.code, h.message, h); }resumed = { token: item.token, claim: rec.verdict.claim, baseObservation: planned.plan.baseObservation || null };}+ const frozen = adoptedHere.get(`${kind}\u0000${planned.key}`);+ if (frozen) {+ // An item adopted in this invocation is edited only as its stop said: its rows still exactly as the acceptance+ // proved them, and the fields this plan would change exactly the ones printed. A maker's edit made before this read+ // fails the first check; one made after it changes the row version this plan's PATCH of the root is conditioned on+ // (locateItem read it), so the service refuses that PATCH. Either way nothing else is sent.+ const reason = asIsReason(frozen.asIs, await B.observe(dataverse, frozen.asIs));+ const changed = reason ? null : changedPointers(planned, frozen.asIs);+ const why = reason || (changed.refusal ? changed.refusal : canonicalJson(changed.pointers) !== canonicalJson(frozen.pointers) ? `the fields it would now change (${changed.pointers.join(', ') || 'none'}) are not the ones its adoption approved (${frozen.pointers.join(', ') || 'none'})` : null);+ if (why) throw stop(CONFLICT_CODE, `the ${kind} "${planned.key}" adopted in this build was not edited: ${why}; nothing was sent for it. Run the build again to plan it from the row as it is now`, { kind, key: planned.key, id: planned.plan.rows[0].id });+ }if (planned.rows.some((r) => r.mode === 'create')) {const conflicts = await B.readConfigurationConflicts(dataverse, planned);if (conflicts.state !== 'clear') throw stop(conflicts.code || UNVERIFIED_CODE, `the ${kind} "${planned.key}" namesake query answered ${conflicts.state}`, { kind, key: planned.key });diff --git a/plugins/model-apps/scripts/lib/managed-create-context.js b/plugins/model-apps/scripts/lib/managed-create-context.jsindex 762b937c1..624c0deea 100644--- a/plugins/model-apps/scripts/lib/managed-create-context.js+++ b/plugins/model-apps/scripts/lib/managed-create-context.js@@ -399,6 +399,14 @@ function createManagedCreateContext({ store, approvals = [], notFoundCode, appro}return { ...outcome, localError, checked };},+ /**+ * The invocation's approval tokens, as given (a copy). A driver whose tokens carry more than the default spelling (an+ * adoption of a row made at another id, configuration-protected.js) reads here which ones the maker gave before it+ * plans anything.+ */+ approvals() {+ return [...approved];+ },/** This process's in-memory answers for one attempt. */facts(token) {return (facts.get(token) || []).slice();@@ -489,7 +497,8 @@ function createManagedCreateContext({ store, approvals = [], notFoundCode, appro/*** Accept, WITHOUT sending anything, attempts deliberately planned over existing rows only (every row `update`, the* expected proof carrying the base observation it read) and never sent: items [{ token, observation, capture,- * declarationSha256? }], `capture` from captureReadOnly before `observation` was read. Each item must be the+ * declarationSha256?, approvalTokenOf? }], `capture` from captureReadOnly before `observation` was read; an item's own+ * `approvalTokenOf` spells its rows' tokens in place of the context's (an adoption names each row's id). Each item must be the* declaration it was prepared for, show nothing dispatched, and read back exactly — rows, parents, content, members,* rule state, and a private input readable and matching — with every row the group does not bind approved by its* own exact token (rows 3-8 of the recovery table, with no answer or receipt counted). This is not the generic@@ -504,8 +513,8 @@ function createManagedCreateContext({ store, approvals = [], notFoundCode, approconst env = snapshot();const results = [];const proposals = [];- for (const { token, observation, capture, declarationSha256 } of items) {- const { a, verdict } = readOnlyVerdict(env, { token, observation, declarationSha256 });+ for (const { token, observation, capture, declarationSha256, approvalTokenOf: itemTokenOf } of items) {+ const { a, verdict } = readOnlyVerdict(env, { token, observation, declarationSha256, itemTokenOf });if (!capture || capture.token !== token) throw new TypeError(`the managed ${a.family} "${a.key}" has no capture taken before its fresh read (captureReadOnly)`);results.push({ family: a.family, key: a.key, token, verdict });if (verdict.action === 'commit') proposals.push({ ...proposalOf(a, observation, verdict.rows, env), capture });@@ -516,7 +525,7 @@ function createManagedCreateContext({ store, approvals = [], notFoundCode, approreturn results;},/**- * The verdict acceptReadOnly would give each item [{ token, observation, declarationSha256? }], judged exactly as it+ * The verdict acceptReadOnly would give each item [{ token, observation, declarationSha256?, approvalTokenOf? }], judged exactly as it* judges (the declaration, the zero dispatch, then rows 3-8 with no answer or receipt counted), WITHOUT committing* anything: a read-only preflight names the halt before the build sends anything, and a commit here is only a* forecast — the acceptance itself re-reads, re-captures and re-judges. Answers [{ family, key, token, verdict }].@@ -524,8 +533,8 @@ function createManagedCreateContext({ store, approvals = [], notFoundCode, approjudgeReadOnly(items) {store.refresh();const env = snapshot();- return items.map(({ token, observation, declarationSha256 }) => {- const { a, verdict } = readOnlyVerdict(env, { token, observation, declarationSha256 });+ return items.map(({ token, observation, declarationSha256, approvalTokenOf: itemTokenOf }) => {+ const { a, verdict } = readOnlyVerdict(env, { token, observation, declarationSha256, itemTokenOf });return { family: a.family, key: a.key, token, verdict };});},@@ -533,7 +542,7 @@ function createManagedCreateContext({ store, approvals = [], notFoundCode, appro// One item of a read-only acceptance, judged (acceptReadOnly, judgeReadOnly). Throws when the attempt is not a plan of// existing rows with a base observation: only such a plan is ever accepted without a send.- function readOnlyVerdict(env, { token, observation, declarationSha256 }) {+ function readOnlyVerdict(env, { token, observation, declarationSha256, itemTokenOf }) {const a = attemptOf(env, token);const name = `the managed ${a.family} "${a.key}"`;if (!a.rowProtocol || !a.expected || !a.expected.baseObservation || a.rowProtocol.rows.some((r) => r.mode !== 'update')) {@@ -547,7 +556,7 @@ function createManagedCreateContext({ store, approvals = [], notFoundCode, appro} else if (!attemptProvenUnsent(a, env.workflowEffects)) {verdict = halt(STORE_CODES.pending, `${name} attempt may have sent something; it is recovered from its original expectation, never accepted read-only`);} else {- verdict = judgeRows(a, observation, { approvals: approved, boundRecords: group ? group.records : [], notFoundCode, approvalTokenOf, readOnly: true });+ verdict = judgeRows(a, observation, { approvals: approved, boundRecords: group ? group.records : [], notFoundCode, approvalTokenOf: typeof itemTokenOf === 'function' ? itemTokenOf : approvalTokenOf, readOnly: true });}return { a, verdict };}diff --git a/plugins/model-apps/scripts/lib/page-scroll.js b/plugins/model-apps/scripts/lib/page-scroll.jsnew file mode 100644index 000000000..83cac5ee1--- /dev/null+++ b/plugins/model-apps/scripts/lib/page-scroll.js@@ -0,0 +1,1362 @@+'use strict';+// Does a generated page establish its own scroll context? (AB#6793599)+//+// The generative-page host renders a page inside a container of fixed height and does not scroll it. A page in which no element both has a+// bounded height and scrolls (`overflowY: "auto"`) therefore shows only what fits: everything below the fold is cut off, with no scrollbar,+// silently — the page type-checks, transpiles, deploys and looks fine until it holds more rows than the window. Two independently generated+// dashboards shipped that way. The rule that said otherwise lived only in the dark-mode section of references/rules.md, so a page without+// theming read it as not applying, and nothing checked it. check-griffel-styles.js runs this check on every page the flows check for Griffel+// shorthands (one command, so no flow can skip one of the two).+//+// The model, for the element tree the page's default export returns (top element first):+// bounded(E) E's height cannot grow with its content: a definite `height` or `maxHeight` (a percentage, a length or a calc() without a+// viewport unit), OR E grows (`flex: 1`, `flexGrow` > 0) inside a bounded flex column AND its automatic minimum is removed+// (`minHeight: 0`, or E is a scroll container: CSS computes `min-height: auto` to 0 for one).+// https://www.w3.org/TR/css-flexbox-1/#min-size-auto+// scrolls(E) bounded(E), and E's computed `overflow-y` is auto, scroll or overlay. A `visible` overflow-y computes to `auto` when+// overflow-x is anything but visible or clip, so `overflowX: "auto"` alone makes a box scroll both ways.+// https://www.w3.org/TR/css-overflow-3/#overflow-properties+// provides(E) scrolls(E), OR bounded(E) and one of E's children provides.+// A page passes when the top element of every return judged provides. That one recursion accepts the three shapes a page uses: a root that+// scrolls; a bounded outer wrapper whose inner root scrolls (the dark-mode two-div wrapper); a bounded root that does not scroll, with a fixed+// header and a flex body (`flex: 1`, `minHeight: 0`, `overflowY: "auto"`) or a `maxHeight` region that scrolls. A scroll region inside an+// element that is NOT bounded does not count: the unbounded element grows past the host's container, and the rest of the page is clipped.+//+// A page that passes can still lose its end: a box on the path to the scroll that fills its container (`height: "100%"`) and has vertical+// padding is, in the default content-box model, taller than the container by that padding, and the host clips the overhang — measured on the+// host, the last 16px of a page with 16px padding stayed below the visible area at both window sizes, while the same page with+// `boxSizing: "border-box"` showed its end. That is `scroll-context-padding`, for every such box on the path (the scrolling root, the wrapper+// around it, and a bounded root around a scrolling body, whose padding pushes the body's end down the same way).+//+// Error directions. A false accept ships the clipped page this check exists for. A false reject costs the agent that is generating the page+// one edit — the remedy every message gives (`height: "100%"`, `overflowY: "auto"`, `boxSizing: "border-box"` on the top element), which is+// safe on every layout (a root whose content already fits shows no scrollbar) and which this check always accepts (page-scroll.test.js+// pins that invariant, for every shape it rejects). So what the check cannot read is never a pass: it is `scroll-context-unproven`, with+// the reason and the remedy, as griffel-styles.js reports a style object it cannot see. A page the plugin did not generate in this run (a+// downloaded page an edit touches) is a different case — refusing a maker's small edit over a defect they did not make would be a regression —+// and the CLI turns the result into a note there (`--existing`).+//+// What it does not see (known limits, plugin AGENTS.md "Page scroll context"): `@media` and selector blocks (only base keys are read, so a+// media query that removes the scroll at one width is missed); whether the bounded boxes' heights add up (a `height: 100%` child under a+// header overflows its parent by the header's height); grid tracks (a grid item is never taken as bounded); and what a library component+// (Fluent) does inside itself — its `className`/`style` are read, as Fluent v9 applies them to the component's root slot, but its children are+// content that never provides the scroll context.+//+// It reads the page with the TypeScript parser the plugin vendors (lib/typescript-compiler.js), not with the source-literals lexer: it needs+// the JSX tree and has to follow one component into another (`GeneratedComponent → PageErrorBoundary → PageBody`), which a lexer cannot.+// Loading the parser costs ~0.2 s, once per command, and only for a file that has a default export.++const { isStackOverflow } = require('./page-nesting.js');++const REMEDY_KEYS = 'height: "100%", overflowY: "auto", boxSizing: "border-box"';+const RULE_REFERENCE = 'references/rules.md, "Page Layout"';++// The keys the decision reads. Anything else in a style object (colours, padding, gap, …) cannot change it.+const DECISIVE = new Set(['height', 'maxHeight', 'minHeight', 'display', 'flexDirection', 'flex', 'flexGrow', 'overflow', 'overflowX', 'overflowY']);+// The keys that decide whether a box that fills its container overhangs it: vertical padding in the default content-box model is added to+// the height, so `height: "100%"` plus 16px of padding is 32px taller than the container (measured on the host: the last 16px of the page+// stay below the visible area). `boxSizing: "border-box"` puts the padding inside the height.+// https://www.w3.org/TR/css-sizing-3/#box-sizing+const PADDING_KEYS = ['padding', 'paddingTop', 'paddingBottom', 'paddingBlock', 'paddingBlockStart', 'paddingBlockEnd'];+const READ_KEYS = new Set([...DECISIVE, 'boxSizing', ...PADDING_KEYS]);+// Keys a page's remedy overwrites on the class it changes; a second class that sets one of these could still win over it.+const OVERFLOW_KEYS = ['overflow', 'overflowX', 'overflowY'];++// Components that render their children and no box of their own.+const TRANSPARENT = /^(?:(?:React\.)?(?:Fragment|StrictMode|Suspense)|[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\.(?:Provider|Consumer))$/;++// The library components a loading, empty or error state is made of (Fluent UI v9) — a spinner, a progress bar, a skeleton, a message bar,+// or a line of text (`<Text>No accounts found.</Text>`): an alternative that renders only these is a state view,+// and is not judged beside one that scrolls. Inside one only text, values, these parts and inline tags may appear — a `MessageBar` with a+// `MessageBarBody` and an action `Button` is a state view; a `Spinner` beside a `<div>` of rows, or a `Card` / `DataGrid` / imported+// component of any kind, is content and is judged. Matched on the last segment of the tag, so `Fluent.Spinner` counts.+// loading ? <Spinner label="Loading" /> : <div scrolls/> → the Spinner is a state view+// error ? <MessageBar intent="error"><MessageBarBody>{error}</MessageBarBody></MessageBar> : <div scrolls/> → a state view+// mode ? <div scrolls/> : <Card>{rows}</Card> → judged (a Card may hold the page's content)+const STATE_VIEWS = /^(?:Spinner|ProgressBar|Skeleton|MessageBar|Text|Caption[12](?:Strong(?:er)?)?|Body[12](?:Strong(?:er)?)?|Subtitle[12]|Title[123]|Label)$/;+const STATE_VIEW_PARTS = /^(?:SkeletonItem|MessageBarBody|MessageBarTitle|MessageBarActions|Button|Link|Text)$/;+const STATE_VIEW_INLINE = /^(?:span|strong|b|em|i|code|br|a)$/;++// What each `reason` of a scroll-context-unproven problem means, for its message.+const REASONS = {+ 'string-class': 'the class is a string or a template (a global CSS class, or class names joined into one string), whose styles the check cannot read',+ 'computed-class': 'the class is computed by code the check cannot follow',+ 'unknown-slot': 'the class names a slot its makeStyles call does not have',+ 'unread-styles': 'the makeStyles call or slot is not an object written in place',+ 'style-expression': 'the inline style is not an object written in place',+ 'spread-attributes': 'a spread of attributes after className or style may replace them',+ 'unread-value': 'a height, overflow or flex key is set to a value the check cannot read (a variable, a token or a call)',+ 'unread-spread': 'a spread of an object not written in place may set a height, overflow or flex key',+ 'computed-key': 'a computed key may set a height, overflow or flex key',+ 'conditional-class': 'a class applied under a condition sets a height, overflow or flex key',+ 'conditional-spread': 'a spread chosen by a condition sets a height, overflow or flex key',+ 'conflicting-keys': 'its classes set both a shorthand and its longhand (`overflow` and `overflowY`, or `flex` and `flexGrow`) to different effect',+ 'unresolved-children': 'part of its content is computed by code the check cannot follow (a variable or a call)',+ 'unresolved-return': 'the page returns something the check cannot follow (a variable or a call)',+ 'unresolved-component': 'the page returns a component that is not written in this file',+ 'library-top': 'the page\'s top element is a library component, whose own layout the check cannot see',+ 'fragment-top': 'the page returns several elements side by side, which the host lays out in a way the check cannot see',+ portal: 'the page returns a portal',+ recursive: 'the page\'s components render each other in a cycle',+ 'children-top': 'the page returns `children` it is never given',+ 'partial-alternatives': 'a condition renders content that establishes a scroll context in one alternative and content that does not in another, and each alternative is shown alone',+ 'min-height': 'a minHeight may be larger than the height that bounds the element, and a minimum wins over a height',+};++/**+ * The scroll-context problems of one page.+ * @param {string} source - the page's TSX+ * @param {{ ts?: object }} [options] - `ts`: a TypeScript compiler to use instead of the vendored one (tests)+ * @returns {object[]} each `{ code, line, column, element, reason?, fix, message }` — code `no-scroll-context`, `scroll-context-unproven`+ * (with `reason`) or `scroll-context-padding`; `fix` is `{ kind: 'class', hook, slot }`, `{ kind: 'style' }` or `{ kind: 'wrap', line,+ * column }`. Empty when the page provides a scroll context or is not+ * judged — no default export (a fragment, not a page), a parse error (the compile gate reports it), or a page that renders nothing+ */+function pageScrollProblems(source, options) {+ return analyzePageScroll(source, options).problems;+}++/**+ * The scroll-context verdict of one page, with what it was based on.+ * @returns {{ judged: boolean, why?: string, problems: object[], verdicts: { line: number, column: number, element: string, verdict: string, reason?: string }[] }}+ * @throws when the page has a default export and the vendored TypeScript compiler cannot be loaded (`code: 'scroll-compiler-unavailable'`)+ */+function analyzePageScroll(source, { ts = null } = {}) {+ const text = String(source == null ? '' : source);+ // Cheap gate before the parser is loaded: a file with no default export is a fragment, not a page (the Griffel tests check fragments, and so+ // may a flow), and its result must stay what it was before this check existed. `export { Page as default }` is the other way to write one.+ if (!/\bexport\s+default\b|\bas\s+default\b/.test(text)) return notJudged('no default export');+ let compiler = ts;+ if (!compiler) {+ try {+ compiler = require('./typescript-compiler.js').loadVendoredTypeScript();+ } catch (e) {+ // A compiler that is missing, or fails its provenance check, must not read as "this page is fine": the check did not run. It throws, and+ // the CLI turns that into a visible `scroll-check-failed` note (check-griffel-styles.js), leaving the Griffel result as it is. Returning+ // "not judged" here instead made a page with no scroll context exit 0 with nothing said.+ const error = new Error(`the vendored TypeScript compiler could not be loaded: ${(e && e.message) || e}`);+ error.code = 'scroll-compiler-unavailable';+ throw error;+ }+ }+ try {+ return new PageReader(compiler, text).analyze();+ } catch (error) {+ // A page nested deeper than the parser's stack is refused by the compile, with its own message (page-nesting.js); this check adds nothing.+ if (isStackOverflow(error)) return notJudged('nested too deeply');+ throw error;+ }+}++function notJudged(why) {+ return { judged: false, why, problems: [], verdicts: [] };+}++// Three-valued logic: true, false, or unknown ({ v: null, reason, node }). An unknown carries the first thing that made it so, for the message.+const TRUE = { v: true };+const FALSE = { v: false };+const unknownOf = (reason, node) => ({ v: null, reason, node });+function or(...xs) {+ if (xs.some((x) => x.v === true)) return TRUE;+ return xs.find((x) => x.v === null) || FALSE;+}+function and(...xs) {+ if (xs.some((x) => x.v === false)) return FALSE;+ return xs.find((x) => x.v === null) || TRUE;+}++// A value read from a style object: known (`{ known: true, value }`) or not (`{ known: false, reason, node }`).+const known = (value) => ({ known: true, value });+const unread = (reason, node) => ({ known: false, reason, node });++class PageReader {+ constructor(ts, text) {+ this.ts = ts;+ this.sf = ts.createSourceFile('page.tsx', text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ this.components = new Map();+ this.hooks = new Map();+ this.imported = new Set();+ this.makeStylesNames = new Set(['makeStyles']);+ this.mergeClassesNames = new Set(['mergeClasses']);+ this.shorthandsNames = new Set(['shorthands']);+ this.typographyNames = new Set(['typographyStyles']);+ this.namespaces = new Set();+ this.bindingsCache = new Map();+ }++ analyze() {+ const { ts, sf } = this;+ if (sf.parseDiagnostics.length > 0) return notJudged('parse error');+ const exported = this.collect();+ if (!exported) return notJudged('no default export');+ const tops = exported.kind === 'component'+ ? this.componentCandidates(exported.node, null, [])+ : [{ kind: 'unresolved', reason: 'unresolved-component', node: exported.node }];+ if (!tops.length) return notJudged('renders nothing');+ const problems = [];+ const verdicts = [];+ const seen = new Set();+ const paddedAt = new Set();+ for (const top of tops) {+ const at = top.node.getStart(sf);+ if (seen.has(at)) continue;+ seen.add(at);+ let result = top.kind === 'unresolved' ? unknownOf(top.reason, top.node) : this.provides(top, null, []);+ // A library component at the top that does not itself scroll: its children sit in slots whose layout the check cannot see.+ if (top.kind === 'library' && result.v === false) result = unknownOf('library-top', top.node);+ const place = this.place(top.node);+ const element = this.elementName(top);+ verdicts.push({ ...place, element, verdict: result.v === true ? 'pass' : result.v === false ? 'fail' : 'unproven', ...(result.v === null ? { reason: result.reason } : {}) });+ if (result.v === true) {+ for (const { box, parent } of result.path) {+ const at = box.node.getStart(sf);+ const fills = paddedAt.has(at) ? null : this.overhangs(box, parent);+ if (!fills) continue;+ paddedAt.add(at);+ const where = this.place(box.node);+ const name = this.elementName(box);+ const fix = this.fixFor(box, 'padding');+ problems.push({ code: 'scroll-context-padding', ...where, element: name, fix, message: paddingMessage(name, where, fix, fills) });+ }+ continue;+ }+ const fix = this.fixFor(top, 'scroll');+ problems.push(result.v === false+ ? { code: 'no-scroll-context', ...place, element, fix, message: failMessage(element, place, fix) }+ : { code: 'scroll-context-unproven', ...place, element, reason: result.reason, fix, message: unprovenMessage(element, place, result, this.place(result.node || top.node), fix) });+ }+ return { judged: true, problems, verdicts };+ }++ // ─── The page's top-level declarations ─────────────────────────────────────────────────────────────────────────────────────────────────++ collect() {+ const { ts, sf } = this;+ // The default export is resolved AFTER every declaration is read: a function declaration is hoisted, so `export default Page;` may come+ // before `function Page() {…}`, and resolving it where it is written found no component and called the page unresolved.+ let exported = null;+ const aliases = new Map();+ for (const st of sf.statements) {+ if (ts.isImportDeclaration(st)) this.readImport(st);+ }+ for (const st of sf.statements) {+ const isDefault = !!(ts.canHaveModifiers(st) && ts.getModifiers(st) || []).find((m) => m.kind === ts.SyntaxKind.DefaultKeyword);+ if (ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st)) {+ if (st.name) this.components.set(st.name.text, st);+ if (isDefault) exported = () => ({ kind: 'component', node: st });+ } else if (ts.isVariableStatement(st)) {+ for (const d of st.declarationList.declarations) {+ if (!ts.isIdentifier(d.name) || !d.initializer) continue;+ const init = strip(ts, d.initializer);+ if (this.isMakeStylesCall(init)) this.hooks.set(d.name.text, this.readHook(init));+ const component = this.unwrapComponent(init);+ if (component && component.node) this.components.set(d.name.text, component.node);+ else if (component && component.alias) aliases.set(d.name.text, component.alias);+ else if (ts.isIdentifier(init)) aliases.set(d.name.text, init.text);+ }+ } else if (ts.isExportAssignment(st) && !st.isExportEquals) {+ exported = () => this.exportedFrom(strip(ts, st.expression), aliases);+ } else if (ts.isExportDeclaration(st) && !st.moduleSpecifier && st.exportClause && ts.isNamedExports(st.exportClause)) {+ for (const el of st.exportClause.elements) {+ if (el.name.text === 'default') exported = () => this.exportedFrom((el.propertyName || el.name), aliases);+ }+ }+ }+ for (const [name, target] of aliases) if (!this.components.has(name) && this.components.has(target)) this.components.set(name, this.components.get(target));+ return exported ? exported() : null;+ }++ readImport(st) {+ const { ts } = this;+ const clause = st.importClause;+ if (!clause) return;+ const from = ts.isStringLiteral(st.moduleSpecifier) ? st.moduleSpecifier.text : '';+ const styling = /^@fluentui\/react-components$|^@griffel\/(?:react|core)$/.test(from);+ if (clause.name) this.imported.add(clause.name.text);+ const bindings = clause.namedBindings;+ if (bindings && ts.isNamespaceImport(bindings)) {+ this.imported.add(bindings.name.text);+ if (styling) this.namespaces.add(bindings.name.text);+ } else if (bindings) {+ for (const el of bindings.elements) {+ this.imported.add(el.name.text);+ if (!styling) continue;+ const original = (el.propertyName || el.name).text;+ if (original === 'makeStyles') this.makeStylesNames.add(el.name.text);+ if (original === 'mergeClasses') this.mergeClassesNames.add(el.name.text);+ if (original === 'shorthands') this.shorthandsNames.add(el.name.text);+ if (original === 'typographyStyles') this.typographyNames.add(el.name.text);+ }+ }+ }++ // `makeStyles(…)`, an alias of it, or `Fluent.makeStyles(…)` through a namespace import of a styling module.+ isCallTo(node, names, member) {+ const { ts } = this;+ if (!ts.isCallExpression(node)) return false;+ const callee = strip(ts, node.expression);+ if (ts.isIdentifier(callee)) return names.has(callee.text);+ return ts.isPropertyAccessExpression(callee) && callee.name.text === member && ts.isIdentifier(callee.expression) && this.namespaces.has(callee.expression.text);+ }++ isMakeStylesCall(node) {+ return this.isCallTo(node, this.makeStylesNames, 'makeStyles');+ }++ // A component as written: a function, an arrow, a class, or one wrapped in `memo`/`forwardRef` (unwrapped one level).+ unwrapComponent(node) {+ const { ts } = this;+ if (ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isClassExpression(node)) return { node };+ if (ts.isCallExpression(node) && /^(?:React\.)?(?:memo|forwardRef)$/.test(node.expression.getText(this.sf)) && node.arguments.length) {+ const inner = strip(ts, node.arguments[0]);+ if (ts.isIdentifier(inner)) return { alias: inner.text };+ return this.unwrapComponent(inner);+ }+ return null;+ }++ exportedFrom(node, aliases) {+ const { ts } = this;+ if (ts.isIdentifier(node)) {+ let name = node.text;+ for (let hops = 0; aliases.has(name) && hops < 8; hops += 1) name = aliases.get(name);+ return this.components.has(name) ? { kind: 'component', node: this.components.get(name) } : { kind: 'unresolved', node };+ }+ const component = this.unwrapComponent(node);+ if (component && component.node) return { kind: 'component', node: component.node };+ if (component && component.alias && this.components.has(component.alias)) return { kind: 'component', node: this.components.get(component.alias) };+ return { kind: 'unresolved', node };+ }++ // ─── makeStyles ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++ // The slots of one `makeStyles({ … })` call: slot → facts. A call given anything but an object written in place is unread as a whole.+ readHook(call) {+ const { ts } = this;+ const arg = call.arguments[0] && strip(ts, call.arguments[0]);+ const hook = { slots: new Map(), rest: null };+ if (!arg || !ts.isObjectLiteralExpression(arg)) {+ hook.rest = unread('unread-styles', call);+ return hook;+ }+ for (const p of arg.properties) {+ if (ts.isSpreadAssignment(p)) {+ // Slots a spread brings in are unknown; slots written after it are read as written.+ hook.slots.clear();+ hook.rest = unread('unread-styles', p);+ continue;+ }+ const name = p.name && propertyName(ts, p.name);+ if (name == null) {+ hook.slots.clear();+ hook.rest = unread('unread-styles', p);+ continue;+ }+ const value = ts.isPropertyAssignment(p) ? strip(ts, p.initializer) : null;+ hook.slots.set(name, value && ts.isObjectLiteralExpression(value) ? this.readStyleObject(value) : { keys: new Map(), rest: unread('unread-styles', p) });+ }+ return hook;+ }++ // The decisive keys of one style object, as JavaScript resolves them: a key's last definition wins. `rest` is set when something the+ // check cannot read (a spread, a computed key) may have set any key not written after it.+ // { height: '100%', ...shorthands.overflow('hidden', 'auto'), ':hover': { … } }+ // → height "100%", overflowX "hidden", overflowY "auto"; the selector block is not read (base keys only).+ readStyleObject(obj) {+ const { ts } = this;+ const facts = { keys: new Map(), rest: null };+ let order = 0;+ const set = (key, value) => facts.keys.set(key, { value, order: order++ });+ const unreadAll = (reason, node) => {+ facts.keys.clear();+ facts.rest = unread(reason, node);+ };+ for (const p of obj.properties) {+ if (ts.isSpreadAssignment(p)) {+ this.readSpread(strip(ts, p.expression), set, unreadAll);+ continue;+ }+ const name = p.name ? propertyName(ts, p.name) : null;+ if (name == null) {+ unreadAll('computed-key', p);+ continue;+ }+ if (!READ_KEYS.has(name)) continue;+ if (ts.isPropertyAssignment(p)) set(name, readValue(ts, p.initializer));+ else set(name, unread('unread-value', p));+ }+ return facts;+ }++ readSpread(e, set, unreadAll) {+ const { ts } = this;+ if (ts.isObjectLiteralExpression(e)) {+ const inner = this.readStyleObject(e);+ if (inner.rest) unreadAll(inner.rest.reason, inner.rest.node);+ for (const [k, v] of [...inner.keys].sort((a, b) => a[1].order - b[1].order)) set(k, v.value);+ return;+ }+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && ts.isIdentifier(e.expression.expression)) {+ const owner = e.expression.expression.text;+ const helper = e.expression.name.text;+ if (this.shorthandsNames.has(owner)) {+ if (e.arguments.some((a) => ts.isSpreadElement(a))) return unreadAll('unread-spread', e);+ // Griffel's shorthands.overflow(overflowX, overflowY = overflowX), shorthands.flex(grow | 'auto' | 'none' | …, shrink?, basis?) and+ // the padding helpers write longhands; every other helper writes keys this check does not read (borders, margins, gaps, inset, …).+ if (helper === 'overflow') {+ const x = e.arguments[0] ? readValue(ts, e.arguments[0]) : unread('unread-value', e);+ set('overflowX', x);+ set('overflowY', e.arguments[1] ? readValue(ts, e.arguments[1]) : x);+ } else if (helper === 'flex') {+ set('flexGrow', e.arguments[0] ? flexGrowOfShorthand(readValue(ts, e.arguments[0])) : unread('unread-value', e));+ } else if (helper === 'padding' || helper === 'paddingBlock') {+ // shorthands.padding(all) / (vertical, horizontal) / (top, horizontal, bottom) / (top, right, bottom, left), and+ // shorthands.paddingBlock(start, end = start): only the vertical sides are kept.+ const a = e.arguments.map((x) => readValue(ts, x));+ if (!a.length) return;+ set(helper === 'padding' ? 'paddingTop' : 'paddingBlockStart', a[0]);+ set(helper === 'padding' ? 'paddingBottom' : 'paddingBlockEnd', helper === 'padding' && a.length >= 3 ? a[2] : helper === 'paddingBlock' && a.length >= 2 ? a[1] : a[0]);+ }+ return;+ }+ }+ if (ts.isPropertyAccessExpression(e) && ts.isIdentifier(e.expression) && this.typographyNames.has(e.expression.text)) return; // font longhands only+ if (ts.isConditionalExpression(e) || (ts.isBinaryExpression(e) && [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(e.operatorToken.kind))) {+ const arms = ts.isConditionalExpression(e) ? [e.whenTrue, e.whenFalse] : e.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ? [e.right] : [e.left, e.right];+ for (const arm of arms.map((a) => strip(ts, a))) {+ if (isNothing(ts, arm)) continue;+ if (!ts.isObjectLiteralExpression(arm)) return unreadAll('unread-spread', arm);+ const inner = this.readStyleObject(arm);+ if (inner.rest) return unreadAll('conditional-spread', arm);+ for (const k of inner.keys.keys()) set(k, unread('conditional-spread', arm));+ }+ return;+ }+ unreadAll('unread-spread', e);+ }++ // ─── Components and what they render ───────────────────────────────────────────────────────────────────────────────────────────────────++ // The expressions a component renders, in source order: an arrow's expression body, or every `return` of its body (not of a function+ // nested in it), or a class's `render()`.+ renderExpressions(component) {+ const { ts } = this;+ if (ts.isClassDeclaration(component) || ts.isClassExpression(component)) {+ const render = component.members.find((m) => ts.isMethodDeclaration(m) && m.name && propertyName(ts, m.name) === 'render' && m.body);+ return render ? returnsOf(ts, render.body) : [];+ }+ if (!component.body) return [];+ if (!ts.isBlock(component.body)) return [component.body];+ return returnsOf(ts, component.body);+ }++ // The top boxes a component renders. Only its FINAL return is judged: earlier returns are early exits — a loading spinner, an error bar, an+ // empty state in a small box — and measured on the shipped pages, judging them refuses pages whose main view scrolls. When the final return+ // renders no element (`if (data) return <Main/>; return <Spinner/>;`), the earlier ones are judged instead. A recognised state view in an+ // arm beside an element (`error ? <MessageBar/> : <div …>`) is not judged; one that is all the component renders is. Any other library+ // component in an arm (`mode ? <div …> : <Card>{rows}</Card>`) is judged as a top of its own (`library-top` when it does not scroll).+ componentCandidates(component, children, stack, site) {+ if (stack.includes(component)) return [{ kind: 'unresolved', reason: 'recursive', node: site || component }];+ const inner = [...stack, component];+ const exprs = this.renderExpressions(component);+ if (!exprs.length) return [];+ const last = this.expandTop(exprs[exprs.length - 1], component, children, inner);+ const pick = (list) => list.filter((c) => c.kind === 'element' || c.kind === 'unresolved' || (c.kind === 'library' && !this.isStateView(c)));+ if (pick(last).length) return pick(last);+ const earlier = exprs.slice(0, -1).flatMap((e) => this.expandTop(e, component, children, inner));+ if (pick(earlier).length) return pick(earlier);+ return [...last, ...earlier];+ }++ // What one rendered expression is, as the single box at the top of what it renders: one candidate per alternative (each arm of a+ // condition). `children` is the call site's children, for a component that renders `children`; `scope` the component it is written in.+ expandTop(expr, scope, children, stack) {+ const { ts } = this;+ const e = strip(ts, expr);+ if (ts.isConditionalExpression(e)) return [...this.expandTop(e.whenTrue, scope, children, stack), ...this.expandTop(e.whenFalse, scope, children, stack)];+ if (ts.isBinaryExpression(e)) {+ const op = e.operatorToken.kind;+ if (op === ts.SyntaxKind.AmpersandAmpersandToken) return this.expandTop(e.right, scope, children, stack);+ if (op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken) return [...this.expandTop(e.left, scope, children, stack), ...this.expandTop(e.right, scope, children, stack)];+ }+ if (isNothing(ts, e) || ts.isStringLiteralLike(e) || ts.isNumericLiteral(e) || ts.isTemplateExpression(e)) return [];+ if (this.isChildren(e)) return children ? children.top() : [{ kind: 'unresolved', reason: 'children-top', node: e }];+ if (ts.isJsxFragment(e)) return this.singleTop(this.childBoxes(e.children, scope, children, stack), e);+ if (ts.isJsxElement(e) || ts.isJsxSelfClosingElement(e)) {+ const open = ts.isJsxElement(e) ? e.openingElement : e;+ const tag = open.tagName.getText(this.sf);+ if (isIntrinsic(tag)) return [{ kind: 'element', node: e, scope, children }];+ if (TRANSPARENT.test(tag)) return ts.isJsxElement(e) ? this.singleTop(this.childBoxes(e.children, scope, children, stack), e) : [];+ if (this.components.has(tag) && !this.imported.has(tag)) {+ const callChildren = ts.isJsxElement(e) ? this.childrenOf(e, scope, children, stack) : null;+ return this.componentCandidates(this.components.get(tag), callChildren, stack, e);+ }+ return [{ kind: 'library', node: e, scope }];+ }+ if (ts.isCallExpression(e) && /(?:^|\.)createPortal$/.test(e.expression.getText(this.sf))) return [{ kind: 'unresolved', reason: 'portal', node: e }];+ return [{ kind: 'unresolved', reason: 'unresolved-return', node: e }];+ }++ // Several boxes side by side at the top are laid out by the host's container, which the check cannot see; one is that box.+ singleTop(boxes, node) {+ if (boxes.length === 0) return [];+ if (boxes.every((b) => b.alternativeOf === boxes[0].alternativeOf && b.alternativeOf !== undefined)) return boxes;+ if (boxes.length === 1) return boxes;+ return [{ kind: 'unresolved', reason: 'fragment-top', node }];+ }++ // The call site's children of a component, read lazily: as top boxes (a component that returns `children`) and as child boxes (one that+ // renders `{children}` inside an element of its own).+ childrenOf(element, scope, children, stack) {+ return {+ top: () => this.singleTop(this.childBoxes(element.children, scope, children, stack), element),+ boxes: () => this.childBoxes(element.children, scope, children, stack),+ tree: () => this.childTree(element.children, scope, children, stack),+ };+ }++ // Is a library box a recognised state view (STATE_VIEWS), with nothing inside but text, values, its own parts and inline tags?+ isStateView(box) {+ const { ts } = this;+ if (box.kind !== 'library') return false;+ const node = box.node;+ const open = ts.isJsxElement(node) ? node.openingElement : ts.isJsxSelfClosingElement(node) ? node : null;+ if (!open || !STATE_VIEWS.test(lastSegment(open.tagName.getText(this.sf)))) return false;+ // Every JSX element a value inside renders (`{error && <b>{error}</b>}`) must be small too.+ const small = (n) => {+ if (ts.isJsxText(n)) return true;+ if (ts.isJsxFragment(n)) return n.children.every(small);+ if (ts.isJsxElement(n) || ts.isJsxSelfClosingElement(n)) {+ const tag = (ts.isJsxElement(n) ? n.openingElement : n).tagName.getText(this.sf);+ if (!(isIntrinsic(tag) ? STATE_VIEW_INLINE.test(tag) : STATE_VIEW_PARTS.test(lastSegment(tag)))) return false;+ return ts.isJsxSelfClosingElement(n) || n.children.every(small);+ }+ let ok = true;+ const visit = (x) => {+ if (!ok) return;+ if (ts.isJsxElement(x) || ts.isJsxSelfClosingElement(x) || ts.isJsxFragment(x)) ok = small(x);+ else ts.forEachChild(x, visit);+ };+ visit(n);+ return ok;+ };+ return ts.isJsxSelfClosingElement(node) || node.children.every(small);+ }++ isChildren(e) {+ const { ts } = this;+ if (ts.isIdentifier(e)) return e.text === 'children';+ return ts.isPropertyAccessExpression(e) && e.name.text === 'children' && /^(?:this\.)?props$|^[A-Za-z_$][\w$]*$/.test(e.expression.getText(this.sf));+ }++ // Every box an element's children render, flattened through fragments, transparent components, conditions, `.map(…)` callbacks and the+ // components written in this file. Each alternative of one child carries the same `alternativeOf`, so the top can tell "one box, two+ // possible" from "two boxes side by side".+ childBoxes(nodes, scope, children, stack) {+ const { ts } = this;+ const out = [];+ let index = 0;+ for (const child of nodes) {+ if (ts.isJsxText(child)) continue;+ const group = index++;+ const add = (boxes) => {+ for (const b of boxes) out.push(b.alternativeOf === undefined ? { ...b, alternativeOf: group } : b);+ };+ if (ts.isJsxExpression(child)) {+ if (child.expression) add(this.boxesOfExpression(child.expression, scope, children, stack));+ } else {+ add(this.boxesOfExpression(child, scope, children, stack));+ }+ }+ return out;+ }++ boxesOfExpression(expr, scope, children, stack) {+ const { ts } = this;+ const e = strip(ts, expr);+ if (ts.isConditionalExpression(e)) return [...this.boxesOfExpression(e.whenTrue, scope, children, stack), ...this.boxesOfExpression(e.whenFalse, scope, children, stack)];+ if (ts.isBinaryExpression(e)) {+ const op = e.operatorToken.kind;+ if (op === ts.SyntaxKind.AmpersandAmpersandToken) return this.boxesOfExpression(e.right, scope, children, stack);+ if (op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken) return [...this.boxesOfExpression(e.left, scope, children, stack), ...this.boxesOfExpression(e.right, scope, children, stack)];+ }+ if (isNothing(ts, e) || ts.isStringLiteralLike(e) || ts.isNumericLiteral(e) || ts.isTemplateExpression(e)) return [];+ if (this.isChildren(e)) return children ? children.boxes() : [{ kind: 'unresolved', reason: 'unresolved-children', node: e }];+ if (ts.isArrayLiteralExpression(e)) return e.elements.flatMap((el) => this.boxesOfExpression(el, scope, children, stack));+ if (ts.isJsxFragment(e)) return this.childBoxes(e.children, scope, children, stack).map(({ alternativeOf, ...b }) => b);+ if (ts.isJsxElement(e) || ts.isJsxSelfClosingElement(e)) {+ const open = ts.isJsxElement(e) ? e.openingElement : e;+ const tag = open.tagName.getText(this.sf);+ if (isIntrinsic(tag)) return [{ kind: 'element', node: e, scope, children }];+ if (TRANSPARENT.test(tag)) return ts.isJsxElement(e) ? this.childBoxes(e.children, scope, children, stack).map(({ alternativeOf, ...b }) => b) : [];+ if (this.components.has(tag) && !this.imported.has(tag)) {+ const callChildren = ts.isJsxElement(e) ? this.childrenOf(e, scope, children, stack) : null;+ return this.componentCandidates(this.components.get(tag), callChildren, stack, e);+ }+ return [{ kind: 'library', node: e, scope }];+ }+ if (ts.isCallExpression(e)) {+ const callee = e.expression.getText(this.sf);+ // A portal renders somewhere else, so it is not part of this box's content.+ if (/(?:^|\.)createPortal$/.test(callee)) return [];+ // `items.map((item) => <div …/>)`: the boxes are what the callback returns.+ if (ts.isPropertyAccessExpression(e.expression) && /^(?:map|flatMap)$/.test(e.expression.name.text) && e.arguments.length) {+ const cb = strip(ts, e.arguments[0]);+ if (ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) {+ const exprs = ts.isBlock(cb.body) ? returnsOf(ts, cb.body) : [cb.body];+ return exprs.flatMap((x) => this.boxesOfExpression(x, scope, children, stack));+ }+ }+ }+ return [{ kind: 'unresolved', reason: 'unresolved-children', node: e }];+ }++ // What an element's children render, as the decision walks it: `seq` (boxes side by side — one that provides is enough), `alt` (the+ // alternatives of a condition — only one is on screen at a time, so each one must provide) and `leaf` (one box). The flat list of+ // `childBoxes` cannot tell the two apart: `{mode ? <div scrolls/> : <div tall/>}` read as two siblings passed on the arm that scrolls,+ // and the other arm shipped clipped.+ // <div>{a}{b ? <X/> : <Y/>}{c && <Z/>}</div> → seq[ a, alt[X, Y], alt[Z, nothing] ]+ childTree(nodes, scope, children, stack) {+ const { ts } = this;+ const items = [];+ for (const child of nodes) {+ if (ts.isJsxText(child)) continue;+ if (ts.isJsxExpression(child)) {+ if (child.expression) items.push(this.treeOf(child.expression, scope, children, stack));+ } else {+ items.push(this.treeOf(child, scope, children, stack));+ }+ }+ return seqOf(items);+ }++ treeOf(expr, scope, children, stack) {+ const { ts } = this;+ const e = strip(ts, expr);+ const tree = (x) => this.treeOf(x, scope, children, stack);+ if (ts.isConditionalExpression(e)) return altOf([tree(e.whenTrue), tree(e.whenFalse)]);+ if (ts.isBinaryExpression(e)) {+ const op = e.operatorToken.kind;+ if (op === ts.SyntaxKind.AmpersandAmpersandToken) return altOf([tree(e.right), NOTHING]);+ if (op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken) return altOf([tree(e.left), tree(e.right)]);+ }+ if (ts.isArrayLiteralExpression(e)) return seqOf(e.elements.map(tree));+ if (ts.isJsxFragment(e)) return this.childTree(e.children, scope, children, stack);+ if (this.isChildren(e) && children) return children.tree();+ if (ts.isJsxElement(e) || ts.isJsxSelfClosingElement(e)) {+ const open = ts.isJsxElement(e) ? e.openingElement : e;+ const tag = open.tagName.getText(this.sf);+ if (!isIntrinsic(tag) && TRANSPARENT.test(tag)) return ts.isJsxElement(e) ? this.childTree(e.children, scope, children, stack) : NOTHING;+ if (!isIntrinsic(tag) && this.components.has(tag) && !this.imported.has(tag)) {+ // What a component renders at its top is one box of several possible (each arm of its final return): alternatives.+ const callChildren = ts.isJsxElement(e) ? this.childrenOf(e, scope, children, stack) : null;+ return altOf(this.componentCandidates(this.components.get(tag), callChildren, stack, e).map(leafOf));+ }+ }+ // `items.map((item) => …)`: each item renders one of what the callback returns.+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && /^(?:map|flatMap)$/.test(e.expression.name.text) && e.arguments.length) {+ const cb = strip(ts, e.arguments[0]);+ if (ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) return altOf((ts.isBlock(cb.body) ? returnsOf(ts, cb.body) : [cb.body]).map(tree));+ }+ return seqOf(this.boxesOfExpression(e, scope, children, stack).map(leafOf));+ }++ // ─── The decision ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++ // provides(box) for a box under `parent` (`null` at the top of the page; else `{ flexColumn, definite }` of a bounded parent). A pass+ // carries the path of boxes from this one down to the one that scrolls, each with its parent, for the padding check.+ provides(box, parent, stack) {+ if (box.kind === 'unresolved') return unknownOf(box.reason, box.node);+ const style = this.styleOf(box);+ const bounded = this.bounded(style, parent);+ if (bounded.v === false) return FALSE;+ // What the box provides once bounded. With its bound unproven, a box that provably provides nothing even then (an inline overflow of+ // hidden over text) still fails: bounded or not, it does not scroll.+ const once = this.providesIfBounded(box, style, parent, stack);+ if (bounded.v === null) return once.v === false ? FALSE : bounded;+ return once;+ }++ providesIfBounded(box, style, parent, stack) {+ const scrolls = scrollsY(style);+ if (scrolls.v === true) return { v: true, path: [{ box, parent }] };+ // Bounded and not (provably) scrolling: one of its children may. A library component's children sit in slots the check cannot see.+ const { ts } = this;+ if (box.kind !== 'element' || !ts.isJsxElement(box.node)) return scrolls.v === null ? scrolls : FALSE;+ const here = {+ flexColumn: and(oneOf(style.get('display'), ['flex', 'inline-flex']), oneOf(style.get('flexDirection'), ['column', 'column-reverse'])),+ definite: this.definiteOf(style, parent),+ };+ const r = this.providesTree(this.childTree(box.node.children, box.scope, box.children || null, stack), here, stack);+ if (r.v === true) return { v: true, path: [{ box, parent }, ...r.path] };+ if (scrolls.v === null) return scrolls;+ return r.v === null ? r : FALSE;+ }++ // provides() over a tree of children (childTree): side by side, one that provides is enough; of alternatives, each one that is rendered+ // must. An alternative that renders nothing, or only recognised state views (STATE_VIEWS: a Spinner, a MessageBar — a loading, empty or+ // error state), is not judged — the same treatment a state view gets at the top of the page. Any other library component in an+ // alternative (a `Card` holding rows) is judged: its layout is opaque, so beside an alternative that scrolls it is unproven. One alternative that provides beside one that+ // does not is `partial-alternatives`: the check cannot tell whether that condition is ever met, and the one that does not scroll is clipped+ // whenever it is.+ providesTree(node, parent, stack) {+ if (node.t === 'leaf') return this.provides(node.box, parent, stack);+ if (node.t === 'seq') {+ let unproven = null;+ for (const item of node.items) {+ const r = this.providesTree(item, parent, stack);+ if (r.v === true) return r;+ if (r.v === null && !unproven) unproven = r;+ }+ return unproven || FALSE;+ }+ const judged = [];+ for (const arm of node.arms) {+ const r = this.providesTree(arm, parent, stack);+ if (r.v !== true && leavesOf(arm).every((b) => this.isStateView(b))) continue;+ judged.push({ arm, r });+ }+ if (judged.length && judged.every((x) => x.r.v === true)) return { v: true, path: judged.flatMap((x) => x.r.path) };+ const missing = judged.find((x) => x.r.v === false);+ if (missing && judged.some((x) => x.r.v === true)) {+ const first = leavesOf(missing.arm)[0];+ return unknownOf('partial-alternatives', first ? first.node : null);+ }+ const unproven = judged.find((x) => x.r.v === null);+ return unproven ? unproven.r : FALSE;+ }++ // bounded(E): E's height cannot grow with its content. A percentage `height`/`maxHeight` resolves only against a parent of DEFINITE height+ // (`parent.definite`): a parent bounded by `maxHeight` alone bounds itself, but a `height: "100%"` child of it computes to `auto` and grows+ // past it (CSS 2 §10.5, https://www.w3.org/TR/CSS2/visudet.html#the-height-property). A `minHeight` wins over both, so one that may be+ // larger than the bound defeats it (minFits).+ bounded(style, parent) {+ const top = parent === null;+ const resolves = top ? TOP_PERCENT_IS_BOUNDED : parent.definite;+ const height = style.get('height');+ const maxHeight = style.get('maxHeight');+ const direct = and(or(definite(height, resolves), definite(maxHeight, resolves)), minFits(style.get('minHeight'), height !== undefined ? height : maxHeight));+ if (direct.v === true || top) return direct;+ return or(direct, and(parent.flexColumn, growsOf(style), flexMinZero(style)));+ }++ // definite(E): is E's height one a child's percentage resolves against? A definite `height` (not `maxHeight`: a box bounded only by its+ // maximum has an `auto` height), or a flex item that grows in a flex column of definite height, which is definite once flexed+ // (https://www.w3.org/TR/css-flexbox-1/#definite-sizes).+ definiteOf(style, parent) {+ const resolves = parent === null ? TOP_PERCENT_IS_BOUNDED : parent.definite;+ const height = style.get('height');+ const own = and(definite(height, resolves), minFits(style.get('minHeight'), height));+ if (own.v === true || parent === null) return own;+ return or(own, and(parent.flexColumn, parent.definite, growsOf(style), flexMinZero(style)));+ }++ // ─── An element's style: its classes, then its inline style ────────────────────────────────────────────────────────────────────────────++ // The effective decisive keys of one element: `get(key)` → a known value, an unread one, or undefined (not set). An inline style wins over+ // every class; among classes, a later argument of mergeClasses wins; a class applied under a condition makes every key it sets unknown.+ styleOf(box) {+ if (box.style) return box.style;+ const { ts } = this;+ const open = ts.isJsxElement(box.node) ? box.node.openingElement : box.node;+ let classes = { layers: [] };+ let inline = null;+ let classAttr = null;+ let styleAttr = null;+ let spreadAfter = false;+ for (const attr of open.attributes.properties) {+ if (ts.isJsxSpreadAttribute(attr)) {+ classes = { unread: unread('spread-attributes', attr) };+ inline = { keys: new Map(), rest: unread('spread-attributes', attr) };+ spreadAfter = true;+ continue;+ }+ const name = attr.name.getText(this.sf);+ if (name === 'className') {+ classAttr = attr;+ spreadAfter = false;+ const init = attr.initializer;+ if (!init) classes = { unread: unread('computed-class', attr) };+ else if (ts.isStringLiteral(init)) classes = init.text.trim() ? { unread: unread('string-class', init) } : { layers: [] };+ else if (ts.isJsxExpression(init) && init.expression) classes = this.classLayers(init.expression, box.scope, false);+ else classes = { unread: unread('computed-class', attr) };+ } else if (name === 'style') {+ styleAttr = attr;+ spreadAfter = false;+ const init = attr.initializer;+ const e = init && ts.isJsxExpression(init) && init.expression ? strip(ts, init.expression) : null;+ inline = e && ts.isObjectLiteralExpression(e) ? this.readStyleObject(e) : { keys: new Map(), rest: unread('style-expression', attr) };+ }+ }+ const get = (key) => effective(classes, inline, key);+ box.style = { get, classes, inline, classAttr, styleAttr, spreadAfter };+ return box.style;+ }++ classLayers(expr, scope, conditional) {+ const { ts } = this;+ const e = strip(ts, expr);+ if (isNothing(ts, e) || (ts.isStringLiteralLike(e) && !e.text.trim())) return { layers: [] };+ if (ts.isStringLiteralLike(e) || ts.isTemplateExpression(e)) return { unread: unread('string-class', e) };+ if (ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e)) {+ const slotName = ts.isPropertyAccessExpression(e) ? e.name.text : (ts.isStringLiteralLike(strip(ts, e.argumentExpression)) ? strip(ts, e.argumentExpression).text : null);+ const owner = strip(ts, e.expression);+ const binding = ts.isIdentifier(owner) ? this.bindings(scope).get(owner.text) : null;+ if (binding && binding.hook && slotName != null) return this.slotLayer(binding.hook, slotName, e, conditional);+ return { unread: unread('computed-class', e) };+ }+ if (ts.isIdentifier(e)) {+ const binding = this.bindings(scope).get(e.text);+ if (binding && binding.slot) return this.slotLayer(binding.hook, binding.slot, e, conditional);+ return { unread: unread('computed-class', e) };+ }+ if (this.isCallTo(e, this.mergeClassesNames, 'mergeClasses')) {+ const layers = [];+ for (const arg of e.arguments) {+ if (ts.isSpreadElement(arg)) return { unread: unread('computed-class', arg) };+ const r = this.classLayers(arg, scope, conditional);+ if (r.unread) return r;+ layers.push(...r.layers);+ }+ return { layers };+ }+ if (ts.isBinaryExpression(e) && [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(e.operatorToken.kind)) {+ const arms = e.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ? [e.right] : [e.left, e.right];+ return this.armsLayers(arms, scope);+ }+ if (ts.isConditionalExpression(e)) return this.armsLayers([e.whenTrue, e.whenFalse], scope);+ return { unread: unread('computed-class', e) };+ }++ armsLayers(arms, scope) {+ const layers = [];+ for (const arm of arms) {+ const r = this.classLayers(arm, scope, true);+ if (r.unread) return r;+ layers.push(...r.layers);+ }+ return { layers };+ }++ slotLayer(hookName, slotName, node, conditional) {+ const hook = this.hooks.get(hookName);+ if (!hook) return { unread: unread('computed-class', node) };+ if (hook.slots.has(slotName)) return { layers: [{ facts: hook.slots.get(slotName), conditional, node, hook: hookName, slot: slotName }] };+ return { unread: hook.rest ? unread(hook.rest.reason, hook.rest.node) : unread('unknown-slot', node) };+ }++ // The names a component binds to its style hooks: `const styles = useStyles();` → styles: { hook }, and+ // `const { root } = useStyles();` → root: { hook, slot: 'root' }. Searched through the whole component, so a render helper nested in it+ // that reads the component's `styles` is read too.+ bindings(scope) {+ if (this.bindingsCache.has(scope)) return this.bindingsCache.get(scope);+ const { ts } = this;+ const map = new Map();+ const visit = (n) => {+ if (ts.isVariableDeclaration(n) && n.initializer) {+ const init = strip(ts, n.initializer);+ if (ts.isCallExpression(init) && ts.isIdentifier(init.expression) && this.hooks.has(init.expression.text)) {+ const hook = init.expression.text;+ if (ts.isIdentifier(n.name) && !map.has(n.name.text)) map.set(n.name.text, { hook });+ if (ts.isObjectBindingPattern(n.name)) {+ for (const el of n.name.elements) {+ if (el.dotDotDotToken || !ts.isIdentifier(el.name)) continue;+ const slot = el.propertyName ? propertyName(ts, el.propertyName) : el.name.text;+ if (slot != null && !map.has(el.name.text)) map.set(el.name.text, { hook, slot });+ }+ }+ }+ }+ ts.forEachChild(n, visit);+ };+ if (scope) visit(scope);+ this.bindingsCache.set(scope, map);+ return map;+ }++ // ─── The remedy each problem gives ─────────────────────────────────────────────────────────────────────────────────────────────────────++ // Where to write the remedy so that the check then provably accepts the page:+ // class — the element's own makeStyles slot, when its classes and inline style are all read and nothing else can override the keys the+ // remedy writes (no other class sets an overflow key, the inline style sets none of the remedy's keys, no spread of attributes+ // follows);+ // style — otherwise its inline style (an inline style wins over every class, so the keys written there are what the element gets);+ // wrap — when the top is not an element of the page (a library component, several elements, a portal, something computed): a <div>+ // around what the component returns.+ // `mode` is 'scroll' (the remedy is REMEDY_KEYS on the page's top) or 'padding' (it is `boxSizing: "border-box"` on the box that+ // overhangs; a library component takes it too, as Fluent v9 applies className and style to the component's root slot).+ fixFor(box, mode) {+ if (box.kind === 'unresolved' || (mode === 'scroll' && box.kind !== 'element')) return { kind: 'wrap', ...this.place(box.node) };+ const style = this.styleOf(box);+ // A bounded flex column shrinks its items to fit, and an item that clips its own overflow (a Fluent Card is overflow: hidden) has no+ // automatic minimum height, so it is squeezed and its content cut off inside it: the remedy on a flex column says so.+ const column = mode === 'scroll' && and(oneOf(style.get('display'), ['flex', 'inline-flex']), oneOf(style.get('flexDirection'), ['column', 'column-reverse'])).v === true;+ // A minHeight the remedy's `height: "100%"` does not provably win over (a larger one, or one the check cannot compare) is neutralised by+ // the remedy too: `minHeight: 0`.+ const minHeight = mode === 'scroll' && minFits(style.get('minHeight'), known('100%')).v !== true;+ const extra = { ...(column ? { flexColumn: true } : {}), ...(minHeight ? { minHeight: true } : {}) };+ if (canFixOnClass(style, mode, minHeight)) {+ const target = [...style.classes.layers].reverse().find((l) => !l.conditional);+ return { kind: 'class', hook: target.hook, slot: target.slot, ...extra };+ }+ return { kind: 'style', ...extra };+ }++ // Does a box on the path to the scroll provably overhang its container by its vertical padding? Only a box whose height is the whole of its+ // container's can, and only that case is refused: `height` or `maxHeight` of exactly "100%" (measured on the host: the last 16px of a page+ // with 16px padding stayed cut off), or `calc(100% - N)` whose N is smaller than a vertical padding the check can read in px. `50%`, or+ // `calc(100% - 64px)` with 16px padding on each side, leave room for the padding and are not refused; nor is a calc() whose padding is a+ // token, whose overhang the check cannot prove. One sized by flex is laid out with its padding counted, and a fixed length is the size the+ // author chose. A scroll container in a flex column also shrinks to fit (its automatic minimum height is 0).+ // Returns the value that fills the container ("100%", "calc(100% - 8px)"), or null.+ overhangs(box, parent) {+ const style = this.styleOf(box);+ const sizing = style.get('boxSizing');+ if (sizing && sizing.known && String(sizing.value).trim().toLowerCase() === 'border-box') return null;+ if (parent && parent.flexColumn.v === true && scrollContainer(style).v === true) return null;+ if (!PADDING_KEYS.some((key) => verticalPadding(key, style.get(key)))) return null;+ // CSS sizes the box at max(minHeight, min(height, maxHeight)) (CSS 2 §10.7), so a second bound clears the overhang only when that used+ // height is provably smaller than the container by at least the padding. Each key is classed as+ // fill — "100%", or calc(100% - N px) with N smaller than the vertical padding in px: the box would overhang at this size;+ // room — calc(100% - N px) with N at least that padding: the box ends far enough above the container's end;+ // maybe — any other known value ("150%", "50%", "400px", a calc() beside token padding): its distance from the container's height is+ // not known in px, so it neither proves an overhang on its own nor clears one;+ // and the box is refused only when its height or maxHeight fills, as before. Then:+ // height "100%" + maxHeight "calc(100% - 64px)", 16px padding → min(fill, room) = room → not refused+ // height "100%" + maxHeight "150%" → min(fill, maybe) = maybe → refused+ // height "100%" + minHeight "100%" + maxHeight "calc(100% - 64px)" → max(fill, room) = fill → refused (the minimum wins)+ // An unread height or maxHeight (from a spread or a token) is passed over, as it was before a second key was weighed; an unread+ // minHeight may be the larger, so it cannot clear the overhang.+ // https://www.w3.org/TR/CSS2/visudet.html#min-max-heights+ const padding = verticalPaddingPx(style);+ const classOf = (v) => {+ if (typeof v.value !== 'string') return 'maybe';+ const s = v.value.trim().toLowerCase().replace(/\s+/g, ' ');+ if (s === '100%') return 'fill';+ const calc = /^calc\( ?100% - (\d+(?:\.\d+)?)px ?\)$/.exec(s);+ if (!calc || padding === null) return 'maybe';+ return padding > Number(calc[1]) ? 'fill' : 'room';+ };+ let fills = null;+ const bounds = [];+ for (const key of ['height', 'maxHeight']) {+ const v = style.get(key);+ if (v === undefined || !v.known || (typeof v.value === 'string' && /^(?:auto|none)$/i.test(v.value.trim()))) continue;+ const c = classOf(v);+ if (c === 'fill') fills = fills || v.value.trim();+ bounds.push(c);+ }+ if (!fills) return null;+ const used = bounds.includes('room') ? 'room' : bounds.includes('maybe') ? 'maybe' : 'fill';+ if (used !== 'room') return fills;+ const min = style.get('minHeight');+ if (min === undefined || (min.known && (isAutoMin(min) || isZero(min).v === true))) return null;+ return min.known && classOf(min) === 'room' ? null : fills;+ }++ place(node) {+ const { line, character } = this.sf.getLineAndCharacterOfPosition(node.getStart(this.sf));+ return { line: line + 1, column: character + 1 };+ }++ elementName(box) {+ const { ts } = this;+ if (ts.isJsxElement(box.node)) return box.node.openingElement.tagName.getText(this.sf);+ if (ts.isJsxSelfClosingElement(box.node)) return box.node.tagName.getText(this.sf);+ if (ts.isJsxFragment(box.node)) return '<>';+ return box.node.getText(this.sf).split('\n')[0].slice(0, 40);+ }+}++// Can the remedy go on the element's own makeStyles slot and provably win there? The slot must be the last class applied without a condition,+// every class and the inline style must be read, and nothing applied after the slot (a conditional class, the inline style, a spread of+// attributes) may set a key the remedy writes. For the scroll remedy, no other class may set an overflow key either: of a shorthand and its+// longhand on two Griffel classes, which one wins is not visible in the source (see `effective`).+function canFixOnClass(style, mode, minHeight = false) {+ if (style.spreadAfter || style.classes.unread) return false;+ const layers = style.classes.layers;+ const target = [...layers].reverse().find((l) => !l.conditional);+ if (!target || target.facts.rest) return false;+ const writes = mode === 'padding' ? ['boxSizing'] : ['height', ...OVERFLOW_KEYS, 'boxSizing', ...(minHeight ? ['minHeight'] : [])];+ for (const layer of layers) {+ if (layer === target) continue;+ if (layer.facts.rest) return false;+ if (mode !== 'padding' && layer.conditional && [...layer.facts.keys.keys()].some((k) => DECISIVE.has(k) || k === 'boxSizing')) return false;+ if (mode === 'padding' && layer.conditional && layer.facts.keys.has('boxSizing')) return false;+ if (mode !== 'padding' && OVERFLOW_KEYS.some((k) => layer.facts.keys.has(k))) return false;+ }+ if (style.inline) {+ if (style.inline.rest) return false;+ if (writes.some((k) => style.inline.keys.has(k))) return false;+ }+ return true;+}++// ─── Effective values ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++function factValue(facts, key) {+ if (facts.keys.has(key)) return facts.keys.get(key).value;+ return facts.rest || undefined;+}++// One key through the class layers: the last layer that sets it wins; a conditional layer that sets it makes it unknown.+function classValue(classes, key) {+ if (classes.unread) return classes.unread;+ for (let i = classes.layers.length - 1; i >= 0; i -= 1) {+ const layer = classes.layers[i];+ const v = factValue(layer.facts, key);+ if (v === undefined) continue;+ if (layer.conditional) return unread(v.known ? 'conditional-class' : v.reason, v.known ? layer.node : v.node);+ return v;+ }+ return undefined;+}++// Pairs of a longhand and the shorthand that also sets it. `derive` turns the shorthand's value into the longhand's.+const PAIRS = {+ overflowY: { shorthand: 'overflow', derive: (v) => String(v).trim().split(/\s+/).pop() },+ overflowX: { shorthand: 'overflow', derive: (v) => String(v).trim().split(/\s+/)[0] },+ flexGrow: { shorthand: 'flex', derive: (v) => flexGrowOfFlex(v) },+};++function effective(classes, inline, key) {+ const pair = PAIRS[key];+ if (inline) {+ // An inline style is one object, so of a shorthand and its longhand the one written last wins (React sets them in order).+ if (!pair) {+ const v = factValue(inline, key);+ if (v !== undefined) return v;+ } else {+ const long = inline.keys.get(key);+ const short = inline.keys.get(pair.shorthand);+ if (long || short) {+ const pick = !short || (long && long.order > short.order) ? long.value : derived(short.value, pair);+ return pick;+ }+ if (inline.rest) return inline.rest;+ }+ }+ if (!pair) return classValue(classes, key);+ const long = classValue(classes, key);+ const short = classValue(classes, pair.shorthand);+ if (short === undefined) return long;+ if (long === undefined) return derived(short, pair);+ // Both set on classes: which one Griffel's atomic classes let win is not something the source shows, so only an agreement is read.+ const fromShort = derived(short, pair);+ if (long.known && fromShort.known && sameEffect(key, long.value, fromShort.value)) return long;+ if (!long.known) return long;+ if (!fromShort.known) return fromShort;+ return unread('conflicting-keys', null);+}++function derived(value, pair) {+ if (!value.known) return value;+ const v = pair.derive(value.value);+ return v && v.known === false ? v : known(v);+}++function sameEffect(key, a, b) {+ if (key === 'flexGrow') return Number(a) > 0 === Number(b) > 0;+ return String(a).trim().toLowerCase() === String(b).trim().toLowerCase();+}++// `flex: 1` → 1; `flex: "1 1 0"` → 1; `flex: "auto"` → 1; `flex: "none"` / `"initial"` → 0. https://www.w3.org/TR/css-flexbox-1/#flex-common+function flexGrowOfFlex(v) {+ if (typeof v === 'number') return v;+ const first = String(v).trim().toLowerCase().split(/\s+/)[0];+ if (first === 'auto') return 1;+ if (first === 'none' || first === 'initial') return 0;+ const n = Number(first);+ return Number.isFinite(n) ? n : unread('unread-value', null);+}++function flexGrowOfShorthand(value) {+ if (!value.known) return value;+ const g = flexGrowOfFlex(value.value);+ return g && g.known === false ? g : known(g);+}++// ─── The predicates ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++// Is a height or max-height value definite? A percentage resolves against the parent's height: `resolves` says whether that is definite (at+// the top of the page it is the host's container, which is). A viewport unit is not taken as bounded: the host draws its own header above+// the page, so `100vh` is taller than the container the page gets.+function definite(value, resolves) {+ if (value === undefined) return FALSE;+ if (!value.known) return unknownOf(value.reason, value.node);+ const v = value.value;+ if (typeof v === 'number') return Number.isFinite(v) ? TRUE : FALSE;+ const s = String(v).trim().toLowerCase();+ if (!s || /^(?:auto|none|fit-content|min-content|max-content|unset|initial|inherit|revert|revert-layer)$/.test(s)) return FALSE;+ if (/\d(?:d|s|l)?v(?:h|w|min|max|b|i)\b/.test(s)) return FALSE;+ if (/%/.test(s)) return resolves;+ if (/^-?(?:\d+\.?\d*|\.\d+)(?:px|rem|em|pt|pc|cm|mm|in|q|ex|ch)?$/.test(s) || /^(?:calc|min|max|clamp)\(/.test(s)) return TRUE;+ return unknownOf('unread-value', null);+}++// `height: "100%"` on the page's top element resolves against the host's container, which has a fixed height.+const TOP_PERCENT_IS_BOUNDED = TRUE;++// A length as a number and its unit, for comparing two of them within that unit: 2000 → 2000 px, "480px" → 480 px, "100%" → 100 %,+// "30rem" → 30 rem. Two values are compared only in the same unit, never converted: a min-height and a height of the same box resolve+// `%` against the same containing block, `em` against the same font size, `rem` and the viewport units against the same root and viewport.+// Anything else (a calc(), a token) is not measured.+function measure(value) {+ if (!value || !value.known) return null;+ if (typeof value.value === 'number') return Number.isFinite(value.value) ? { n: value.value, unit: 'px' } : null;+ const m = /^(-?(?:\d+\.?\d*|\.\d+))(px|%|rem|em|vh|vw|dvh|svh|lvh)$/.exec(String(value.value).trim().toLowerCase());+ return m ? { n: Number(m[1]), unit: m[2] } : null;+}++// The same CSS text, whitespace and case aside: "calc(100% - 64px)" and "calc(100% - 64px)" are one value.+function sameValue(a, b) {+ if (!a || !b || !a.known || !b.known) return false;+ const norm = (v) => (typeof v === 'number' ? `${v}px` : String(v).trim().toLowerCase().replace(/\s+/g, ' '));+ return norm(a.value) === norm(b.value);+}++// A `minHeight` that is not provably at most the height that bounds the box: CSS applies the minimum over the height and the maximum, so a+// root with `height: "100%"` and `minHeight: 2000` is 2000px tall in a 720px host, scrolls by 40px and keeps the rest cut off.+// unset, auto, 0 → fits+// "100%" under height "100%", 300 ≤ 480 → fits (the same unit, and not larger)+// "calc(100% - 64px)" under the same → fits (the same value)+// "10rem" / "30rem" under "30rem" → fits (compared in rem)+// 2000 under height 480, "40rem" / "30rem", "60%" vs "50%" → does not fit+// "400px" under "100%", a token → cannot tell (`min-height`, or the token's own reason)+// https://www.w3.org/TR/CSS2/visudet.html#min-max-heights+function minFits(min, bound) {+ if (min === undefined || isAutoMin(min)) return TRUE;+ if (!min.known) return unknownOf(min.reason, min.node);+ if (isZero(min).v === true) return TRUE;+ if (sameValue(min, bound)) return TRUE;+ const a = measure(min);+ const b = measure(bound);+ if (a && b && a.unit === b.unit) return a.n <= b.n ? TRUE : FALSE;+ return unknownOf('min-height', null);+}++function isAutoMin(value) {+ return value.known && typeof value.value === 'string' && /^(?:auto|initial|unset|revert|revert-layer)$/.test(value.value.trim().toLowerCase());+}++// Is a flex item's automatic minimum height removed, so that it shrinks to the column it grows in? `minHeight: 0` does, and so does being a+// scroll container (CSS computes `min-height: auto` to 0 for one) — unless a `minHeight` of its own is set, which then is its minimum: one+// that is not zero may be larger than the room the column has left (`min-height`), and on a box that does not clip it is not removed at all.+// https://www.w3.org/TR/css-flexbox-1/#min-size-auto+function flexMinZero(style) {+ const min = style.get('minHeight');+ if (min === undefined || isAutoMin(min)) return scrollContainer(style);+ if (!min.known) return unknownOf(min.reason, min.node);+ if (isZero(min).v === true) return TRUE;+ return scrollContainer(style).v === false ? FALSE : unknownOf('min-height', null);+}++// The tree childTree builds.+const NOTHING = { t: 'seq', items: [] };+const leafOf = (box) => ({ t: 'leaf', box });+const seqOf = (items) => (items.length === 1 ? items[0] : { t: 'seq', items });+const altOf = (arms) => (arms.length === 0 ? NOTHING : arms.length === 1 ? arms[0] : { t: 'alt', arms });+function leavesOf(node) {+ if (node.t === 'leaf') return [node.box];+ return (node.t === 'seq' ? node.items : node.arms).flatMap(leavesOf);+}++// Does one padding key set a vertical padding that is not zero? "Not literally 0" is the test: a token (`tokens.spacingVerticalL`), a variable+// or any other value the check cannot read counts as padding, as `boxSizing: "border-box"` is right whatever the value is. For the+// `padding` / `paddingBlock` shorthands only the vertical parts count:+// padding: "0 16px" → top 0, bottom 0 → no vertical padding+// padding: "8px 16px 0" → top 8px → padding+// paddingBlock: "0 12px" → start 0, end 12px → padding+function verticalPadding(key, value) {+ if (value === undefined) return false;+ if (!value.known) return true;+ const zero = (s) => /^0(?:\.0*)?(?:px|%|rem|em)?$/.test(s);+ if (typeof value.value === 'number') return value.value !== 0;+ const parts = String(value.value).trim().split(/\s+/);+ if (key === 'padding') return [parts[0], parts.length >= 3 ? parts[2] : parts[0]].some((p) => !zero(p));+ if (key === 'paddingBlock') return [parts[0], parts[1] || parts[0]].some((p) => !zero(p));+ return !zero(parts[0]);+}++function isZero(value) {+ if (value === undefined) return FALSE;+ if (!value.known) return unknownOf(value.reason, value.node);+ return /^0(?:\.0*)?(?:px|%|rem|em)?$/.test(String(value.value).trim()) ? TRUE : FALSE;+}++// The least vertical padding (top + bottom, in px) a box has, or null when a padding key is set to something not in px (a token, rem, a+// variable). Of two keys that set one side (`padding` and `paddingTop`), the smaller counts: which one wins is not always visible in the+// source, and a refusal must hold whichever does.+// padding: "8px 16px" → 8 + 8+// padding: 16, paddingBottom: 0 → 16 + 0+// paddingBlock: tokens.spacingL → null+function verticalPaddingPx(style) {+ const px = (part) => {+ if (typeof part === 'number') return Number.isFinite(part) ? part : null;+ const s = String(part).trim().toLowerCase();+ if (/^0+(?:\.0*)?$/.test(s)) return 0;+ const m = /^(\d+(?:\.\d+)?)px$/.exec(s);+ return m ? Number(m[1]) : null;+ };+ const sides = { top: [], bottom: [] };+ for (const key of PADDING_KEYS) {+ const value = style.get(key);+ if (value === undefined) continue;+ if (!value.known) return null;+ const parts = typeof value.value === 'number' ? [value.value] : String(value.value).trim().split(/\s+/);+ const [top, bottom] = key === 'padding' ? [parts[0], parts.length >= 3 ? parts[2] : parts[0]]+ : key === 'paddingBlock' ? [parts[0], parts[1] === undefined ? parts[0] : parts[1]]+ : /Top$|Start$/.test(key) ? [parts[0], undefined] : [undefined, parts[0]];+ for (const [side, part] of [['top', top], ['bottom', bottom]]) {+ if (part === undefined) continue;+ const n = px(part);+ if (n === null) return null;+ sides[side].push(n);+ }+ }+ const least = (list) => (list.length ? Math.min(...list) : 0);+ return least(sides.top) + least(sides.bottom);+}++function oneOf(value, options) {+ if (value === undefined) return FALSE;+ if (!value.known) return unknownOf(value.reason, value.node);+ return options.includes(String(value.value).trim().toLowerCase()) ? TRUE : FALSE;+}++function growsOf(style) {+ const g = style.get('flexGrow');+ if (g === undefined) return FALSE;+ if (!g.known) return unknownOf(g.reason, g.node);+ const n = typeof g.value === 'number' ? g.value : Number(String(g.value).trim());+ return Number.isFinite(n) && n > 0 ? TRUE : FALSE;+}++// The computed overflow of each axis: when one axis is neither visible nor clip, a visible other axis computes to auto (and clip to hidden).+function computedOverflow(style) {+ const x = style.get('overflowX');+ const y = style.get('overflowY');+ if ((x && !x.known) || (y && !y.known)) return { unknown: (y && !y.known) ? y : x };+ const norm = (v) => (v === undefined ? 'visible' : String(v.value).trim().toLowerCase());+ let ox = norm(x);+ let oy = norm(y);+ const open = (v) => v === 'visible' || v === 'clip';+ if (!open(ox) || !open(oy)) {+ const fix = (v) => (v === 'visible' ? 'auto' : v === 'clip' ? 'hidden' : v);+ ox = fix(ox);+ oy = fix(oy);+ }+ return { x: ox, y: oy };+}++function scrollsY(style) {+ // An overflow-y of auto or scroll is what the box computes whatever overflow-x is (only a `visible` or `clip` y depends on x), so a known y+ // decides even when x cannot be read — the case of an inline remedy on an element whose classes the check cannot read.+ const y = style.get('overflowY');+ if (y && y.known && ['auto', 'scroll', 'overlay'].includes(String(y.value).trim().toLowerCase())) return TRUE;+ const c = computedOverflow(style);+ if (c.unknown) return unknownOf(c.unknown.reason, c.unknown.node);+ if (['auto', 'scroll', 'overlay'].includes(c.y)) return TRUE;+ if (['visible', 'hidden', 'clip'].includes(c.y)) return FALSE;+ return unknownOf('unread-value', null);+}++function scrollContainer(style) {+ const y = style.get('overflowY');+ if (y && y.known && ['auto', 'scroll', 'overlay', 'hidden'].includes(String(y.value).trim().toLowerCase())) return TRUE;+ const c = computedOverflow(style);+ if (c.unknown) return unknownOf(c.unknown.reason, c.unknown.node);+ return c.x !== 'visible' || c.y !== 'visible' ? (c.x === 'clip' && c.y === 'clip' ? FALSE : TRUE) : FALSE;+}++// ─── Messages ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────++const WHY = 'The host shows a page in a container of fixed height and does not scroll it, so whatever does not fit is cut off with no scrollbar.';++const SHRINK = ' That element is a flex column, which shrinks its items to fit once its height is bounded: give flexShrink: 0 to each of its items that clips its own content (a Card, or a box with an overflow key), or they are squeezed and cut off inside.';++function fixText(element, place, fix) {+ const shrink = fix.flexColumn ? SHRINK : '';+ // The remedy also writes `minHeight: 0` when the element has a minHeight that may be larger than its container: a minimum wins over a height.+ const keys = fix.minHeight ? `${REMEDY_KEYS}, minHeight: 0` : REMEDY_KEYS;+ if (fix.kind === 'class') {+ return `Add ${keys} to the "${fix.slot}" slot of ${fix.hook} (the class of the page's top <${element}> at line ${place.line}), and delete any overflow key or shorthands.overflow(…) from that slot (${RULE_REFERENCE}).${shrink}`;+ }+ if (fix.kind === 'style') {+ return `Write ${keys} as the last keys of the inline style of the page's top <${element}> at line ${place.line} — style={{ …, ${keys} }}, and a style given as an expression becomes style={{ ...thatExpression, ${keys} }} — and make style its last attribute: an inline style wins over every class, so the check can read it (${RULE_REFERENCE}).${shrink}`;+ }+ return `Wrap what the page returns at line ${place.line} in <div style={{ ${REMEDY_KEYS} }}>…</div> (${RULE_REFERENCE}).`;+}++function failMessage(element, place, fix) {+ return `the page has no scroll context: nothing from its top <${element}> at line ${place.line} down both has a bounded height and scrolls. ${WHY} ${fixText(element, place, fix)}`;+}++function unprovenMessage(element, place, result, at, fix) {+ const where = result.node ? ` (line ${at.line})` : '';+ return `the check cannot prove the page scrolls: ${REASONS[result.reason] || result.reason}${where}. ${WHY} ${fixText(element, place, fix)}`;+}++function paddingMessage(element, place, fix, fills) {+ const add = 'boxSizing: "border-box"';+ const how = fix.kind === 'class'+ ? `Add ${add} to the "${fix.slot}" slot of ${fix.hook} (the class of that <${element}>)`+ : `Write ${add} as the last key of the inline style of that <${element}> and make style its last attribute`;+ return `the page scrolls, but its <${element}> at line ${place.line} fills its container (${fills}) and has vertical padding in the default content-box model, so it is taller than its container by that padding and the end of the page stays cut off below the visible area. ${how} (${RULE_REFERENCE}).`;+}++// ─── Small TypeScript helpers ────────────────────────────────────────────────────────────────────────────────────────────────────────────++function strip(ts, node) {+ let n = node;+ while (n && (ts.isParenthesizedExpression(n) || ts.isAsExpression(n) || ts.isNonNullExpression(n) || ts.isTypeAssertionExpression(n) || (ts.isSatisfiesExpression && ts.isSatisfiesExpression(n)))) n = n.expression;+ return n;+}++function isNothing(ts, e) {+ return e.kind === ts.SyntaxKind.NullKeyword || e.kind === ts.SyntaxKind.TrueKeyword || e.kind === ts.SyntaxKind.FalseKeyword+ || (ts.isIdentifier(e) && e.text === 'undefined') || ts.isVoidExpression(e);+}++function lastSegment(tag) {+ return tag.slice(tag.lastIndexOf('.') + 1);+}++function isIntrinsic(tag) {+ return /^[a-z]/.test(tag) && !tag.includes('.');+}++function propertyName(ts, name) {+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name) || ts.isNoSubstitutionTemplateLiteral(name)) return name.text;+ if (ts.isComputedPropertyName(name)) {+ const e = strip(ts, name.expression);+ if (ts.isStringLiteralLike(e) || ts.isNumericLiteral(e)) return e.text;+ }+ return null;+}++// A value as written: a string or a number. Anything else (a token, a variable, a call, a template with a substitution) is unread.+function readValue(ts, node) {+ const e = strip(ts, node);+ if (ts.isStringLiteralLike(e)) return known(e.text);+ if (ts.isNumericLiteral(e)) return known(Number(e.text));+ if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(e.operand)) return known(-Number(e.operand.text));+ return unread('unread-value', e);+}++// Every `return` of a function body, in source order, not counting functions and classes nested in it.+function returnsOf(ts, body) {+ const out = [];+ const visit = (n) => {+ if (ts.isReturnStatement(n)) {+ if (n.expression) out.push(n.expression);+ return;+ }+ if (n !== body && (ts.isFunctionLike(n) || ts.isClassLike(n))) return;+ ts.forEachChild(n, visit);+ };+ visit(body);+ return out;+}++module.exports = { pageScrollProblems, analyzePageScroll, REMEDY_KEYS };diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.jsindex f3b307677..39795bdeb 100644--- a/plugins/model-apps/scripts/lib/sdk-build.js+++ b/plugins/model-apps/scripts/lib/sdk-build.js@@ -9889,7 +9889,9 @@ async function runSdkBuildPhases(spec, opts, owed) {const problems = griffelStyleProblems(code).problems;if (problems.length) {const standing = griffelStanding(p, sourceSha);- const words = { surface: 'build', subject: `page "${p.name}"`, command: 'node scripts/check-griffel-styles.js --file <page.tsx>' };+ // A page that is not new is deployed already, possibly without a scroll context, so the suggested checker run passes `--existing`: its scroll findings are then+ // notes, and the Griffel fix asked for here is not turned into a layout rewrite the maker did not ask for (references/rules.md, Styling gotchas 6).+ const words = { surface: 'build', subject: `page "${p.name}"`, command: `node scripts/check-griffel-styles.js --file <page.tsx>${standing === 'new' ? '' : ' --existing'}` };const file = normalizePageSource(p).codeFile;if (standing === 'new' || standing === 'changed') {const note = standing === 'changed' ? 'Its source changed since the last build recorded for it, so it is held to the check as a new page is; left as it was, it would only be warned about.' : '';diff --git a/plugins/model-apps/scripts/tests/build-model-app.test.js b/plugins/model-apps/scripts/tests/build-model-app.test.jsindex cf1942853..a1a528971 100644--- a/plugins/model-apps/scripts/tests/build-model-app.test.js+++ b/plugins/model-apps/scripts/tests/build-model-app.test.js@@ -1605,6 +1605,61 @@ test('--authorize adopt:<configuration kind>:... approves binding exactly the on}});+test('--authorize adopt:...@<row id>[+digest] approves the one namesake row the stop printed; the plain form, every problem and every rule token are read as before', () => {+ const { authorizationKeys } = require(path.join(__dirname, '..', 'build-model-app.js'));+ const ID = '0B7C6F5E-0000-4000-8000-00000000000A';+ const id = ID.toLowerCase();+ const spec = (over = {}) => ({+ configurationIdentity: 'stable-v1',+ customApis: [{ uniqueName: 'contoso_Calc', requestParameters: [{ uniqueName: 'A', type: 'String' }] }],+ environmentVariables: [{ schemaName: 'contoso_ApiBase', type: 'string', value: 'x' }],+ // A rule key may itself end in what reads like an id: the whole text names it first.+ duplicateDetectionRules: [{ key: `odd@${id}`, name: 'Odd', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }] },+ { key: 'Email rule', name: 'Same email', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }] }],+ ...over,+ });+ const ok = authorizationKeys(['--authorize', `adopt:customApi:CONTOSO_CALC@${ID}+3F2A9C0D1E2B4A59`, '--authorize', `adopt:customApiRequestParameter:contoso_calc/request%3AA@${ID}`,+ '--authorize', `adopt:environmentVariable:contoso_apibase@${ID}`,+ '--authorize', `adopt:duplicateRule:odd@${id}`, '--authorize', 'adopt:customApi:contoso_calc'], spec());+ assert.strictEqual(ok.error, null);+ // The id and digest in lower case, after the key in the stop's own spelling. The two meanings are typed apart: an+ // `@<row id>` approval as adopt-row:, which no plain approval reads as, and the plain form (`odd@<id>` is a declared+ // rule's whole key) as adopt:, exactly as before.+ assert.deepStrictEqual([...ok.configurationApprovals].sort(), [+ `adopt-row:customApi:contoso_calc@${id}+3f2a9c0d1e2b4a59`, `adopt-row:customApiRequestParameter:contoso_calc/request%3Aa@${id}`,+ `adopt-row:environmentVariable:contoso_apibase@${id}`,+ 'adopt:customApi:contoso_calc', `adopt:duplicateRule:odd@${id}`,+ ]);+ for (const [key, over, why] of [+ [`adopt:customApi:contoso_Other@${id}`, {}, /names a configuration item the spec does not declare/],+ [`adopt:customApiRequestParameter:contoso_calc/request%3Ab@${id}`, {}, /names a configuration item the spec does not declare/],+ // Not an id, or a digest on a child or of another length: the text is read whole, as before, and names nothing.+ ['adopt:customApi:contoso_calc@not-an-id', {}, /names a configuration item the spec does not declare/],+ [`adopt:customApi:contoso_calc@${id}+3f2a`, {}, /names a configuration item the spec does not declare/],+ [`adopt:customApiRequestParameter:contoso_calc/request%3Aa@${id}+3f2a9c0d1e2b4a59`, {}, /names a configuration item the spec does not declare/],+ [`adopt:customApiRequestParameter:contoso_calc@${id}`, {}, /is not adopt:<kind>:<declared key> or adopt:<child kind>/],+ [`adopt:customApi:contoso_Calc@${id}`, { configurationIdentity: undefined }, /does not set configurationIdentity "stable-v1", so there is no such row to bind/],+ // A duplicate rule or condition is never adopted: an `@<id>` ending is part of its key, exactly as in 2.24.0.+ [`adopt:duplicateRuleCondition:Email%20rule/e@${id}`, {}, /names a configuration item the spec does not declare/],+ [`adopt:duplicateRule:Email rule@${id}`, {}, /names a configuration item the spec does not declare/],+ // Both readings name a declared item (`contoso_calc` as well as `contoso_calc@<id>`, a key no valid App Spec has but+ // the parser does not assume so), or a declared child: refused, never read either way.+ [`adopt:customApi:contoso_calc@${id}`, { customApis: [{ uniqueName: 'contoso_Calc' }, { uniqueName: `contoso_calc@${id}` }] }, /reads both as the approval of one declared configuration item and, ending @<row id>, as the adoption of another's namesake/],+ [`adopt:customApiRequestParameter:contoso_calc/request%3AA@${id}`, { customApis: [{ uniqueName: 'contoso_Calc', requestParameters: [{ uniqueName: 'A' }, { uniqueName: `A@${id}` }] }] }, /reads both as the approval/],+ ]) {+ const r = authorizationKeys(['--authorize', key], spec(over));+ assert.match(r.error || '', why, key);+ assert.strictEqual(r.configurationApprovals.size, 0, key);+ }+ // A rule or condition whose own key ends in what reads like `@<id>`, beside one named by the text before it: the token+ // is the plain approval of the whole key, as in 2.24.0, never refused and never an adoption.+ const rules = { duplicateDetectionRules: [{ key: 'odd', name: 'Odd 2', entity: 'contact', conditions: [{ key: 'e', column: 'emailaddress1', match: 'exact' }, { key: `e@${id}`, column: 'lastname', match: 'exact' }] },+ { key: `odd@${id}`, name: 'Odd', entity: 'contact', conditions: [] }] };+ const plain = authorizationKeys(['--authorize', `adopt:duplicateRule:odd@${id}`, '--authorize', `adopt:duplicateRuleCondition:odd/e@${id}`], spec(rules));+ assert.strictEqual(plain.error, null);+ assert.deepStrictEqual([...plain.configurationApprovals].sort(), [`adopt:duplicateRule:odd@${id}`, `adopt:duplicateRuleCondition:odd/e%40${id}`]);+});+test('--authorize adopt:/overwrite: approve exactly the declared view or chart they name, in separate sets, under its family', () => {const { authorizationKeys } = require(path.join(__dirname, '..', 'build-model-app.js'));const spec = {diff --git a/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js b/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.jsindex bc0afc09a..99d7bfdda 100644--- a/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js+++ b/plugins/model-apps/scripts/tests/configuration-build-real-bundle.test.js@@ -1189,6 +1189,40 @@ test('protected configuration through the build command: a first create whose naassert.deepEqual(first.org.unexpected, []);});+// Opting in over two APIs made without it: one stop names both namesakes, each with its own id, the fields the build would then+// change and its exact approvals, and those approvals given back on the command line adopt both and send only the printed edit.+test('protected configuration through the build command: a stop over several namesakes shows each one\u2019s id and fields beside its approvals, and those approvals adopt them', async () => {+ const twoApis = (description) => {+ const spec = apiSpec();+ spec.customApis.push({ ...structuredClone(spec.customApis[0]), uniqueName: 'contoso_Other', displayName: 'Other', description, isFunction: false, requestParameters: [], responseProperties: [] });+ return spec;+ };+ const plain = twoApis('Maker text');+ delete plain.configurationIdentity;+ const made = await runCommand(plain);+ succeeded(made, 'the ordinary create');+ const idOf = (name) => made.org.rows('customapis').find((r) => r.uniquename === name).customapiid;+ const mark = made.org.requests.length;+ const stopped = await runCommand(twoApis('Replacement'), { org: made.org, appDir: made.appDir, argv: DATA });+ assert.equal(stopped.thrown && stopped.thrown.code, 'create-identity-conflict', stopped.thrown && stopped.thrown.message);+ assert.notEqual(stopped.exitCode, 0);+ assert.deepEqual(made.org.writes(mark), [], 'nothing is written');+ // The error main() throws is the one the command prints whole (its own top-level catch, emitResult).+ const shown = stopped.thrown.message;+ for (const [key, name, change] of [['contoso_calc', 'contoso_Calc', 'nothing in it'], ['contoso_other', 'contoso_Other', 'only these fields, /description']]) {+ const sentence = `Adopt customApi ${key} at its id ${idOf(name)} (the build would then change ${change}) only under these exact approvals, given after checking those rows are yours: "adopt:customApi:${key}@${idOf(name)}`;+ assert.ok(shown.includes(sentence), `${key}: ${shown.slice(-1500)}`);+ }+ const tokens = [...stopped.thrown.message.matchAll(/given after checking those rows are yours: ((?:"(?:[^"\\]|\\.)*"(?:, )?)+)\./g)].flatMap((m) => JSON.parse(`[${m[1]}]`));+ assert.equal(tokens.length, 4, tokens.join(' '));+ const before = made.org.requests.length;+ const done = await runCommand(twoApis('Replacement'), { org: made.org, appDir: made.appDir, argv: [...DATA, ...authorize(tokens)] });+ succeeded(done, 'the adoption');+ assert.deepEqual(made.org.writes(before).filter((w) => /customapi/i.test(w)), [`PATCH /customapis(${idOf('contoso_Other')})`]);+ assert.equal(made.org.rows('customapis').length, 2);+ assert.equal(made.org.rows('customapis').find((r) => r.uniquename === 'contoso_Other').description, 'Replacement');+ assert.deepEqual(made.org.unexpected, []);+});test('protected configuration through the build command: a first create whose namesake query cannot be completed stops before the first write', async () => {let failing = false;const org = commandOrg({ intercept: (req) => (failing && req.method === 'GET' && /^\/customapis\?/.test(req.path) && /\$filter=uniquename/.test(decodeURIComponent(req.path))diff --git a/plugins/model-apps/scripts/tests/configuration-protected.test.js b/plugins/model-apps/scripts/tests/configuration-protected.test.jsindex ec3b2ff11..a94134d94 100644--- a/plugins/model-apps/scripts/tests/configuration-protected.test.js+++ b/plugins/model-apps/scripts/tests/configuration-protected.test.js@@ -16,7 +16,7 @@ const { createManagedCreateContext } = require('../lib/managed-create-context.jsconst { openManagedBindings, managedManifestView } = require('../lib/managed-bindings.js');const { readerFor } = require('../verify-model-app.js');const { createConfigurationRuntime } = require('../lib/configuration-build.js');-const { readDeploymentBindings } = require('../lib/configuration-artifacts.js');+const { readDeploymentBindings, configurationAuthorizationKeys } = require('../lib/configuration-artifacts.js');const { runSdkBuild } = require('../lib/sdk-build.js');const { STAGES } = require('../lib/stages.js');const { RETRY } = require('../lib/retry-policy.js');@@ -91,8 +91,16 @@ async function harness({ hookup = true, intercept } = {}) {}// A later process over the same binding store: a fresh managed create context (none of the earlier answers), with the// maker's exact approvals.-function reopen(h, approvals = []) {- const ctx = createManagedCreateContext({ store: h.store, approvals, notFoundCode: B.NOT_FOUND_CODE });+// An `@<row id>` approval reaches the context as the build's parser types it (build-model-app.js, through+// configurationAuthorizationKeys, against `typedAs`); a token it refuses is passed as given, so a test can still offer one,+// and `typedAs: null` passes every token as given.+function reopen(h, approvals = [], typedAs = configSpec()) {+ const typed = approvals.flatMap((t) => {+ if (!typedAs || !/@[0-9a-f]{8}-/i.test(t)) return [t];+ const read = configurationAuthorizationKeys([t], typedAs);+ return read.problems.length ? [t] : [...read.rowApprovals];+ });+ const ctx = createManagedCreateContext({ store: h.store, approvals: typed, notFoundCode: B.NOT_FOUND_CODE });return { ...h, ctx, protectedConfiguration: P.createProtectedConfiguration({ store: h.store, gate: h.gate, ctx, apiBase: `${h.org.origin}/api/data/v9.0` }) };}// One configuration pass as the build runs it: the preflight, then the data-model step. Answers what it sent.@@ -1371,4 +1379,803 @@ test('verify and the build preflight agree on every state of a bound protected rtry { await agreeOn(state); } catch (error) { failures.push(String(error.message).split('\n').filter(Boolean).slice(0, 3).join(' | ').slice(0, 300)); }}assert.deepEqual(failures, [], 'every state agrees');-});\ No newline at end of file+});++// ---------------------------------------------------------------------------------------------+// A row a maker made BEFORE the opt-in (here by a build without it, so at an id the service picked) is a namesake to the+// first protected create. It is adopted at its own id only under the exact `@<row id>` approvals the stop prints, and+// read-only: nothing is sent to adopt it, and it is never bound while anything about it differs from what the stop said.++const PK = { environmentvariabledefinitions: 'environmentvariabledefinitionid', customapis: 'customapiid', duplicaterules: 'duplicateruleid', customapirequestparameters: 'customapirequestparameterid' };+const apiOnly = (over) => configSpec({ environmentVariables: [], duplicateDetectionRules: [], ...(over ? api(over) : {}) });+const ADOPT_KINDS = [+ { kind: 'environmentVariable', key: 'contoso_apibase', set: 'environmentvariabledefinitions', spec: () => variableOnly(), children: 0 },+ { kind: 'customApi', key: 'contoso_calc', set: 'customapis', spec: () => apiOnly(), children: 2 },+];+const withoutOptIn = (spec) => { const { configurationIdentity, ...plain } = spec; return plain; };+// The maker's rows, made by a build without the opt-in: the plain path creates them by name.+async function madeBeforeOptIn(h, spec, opts = {}) {+ const out = await pass(h, withoutOptIn(spec), opts);+ assert.equal(out.halt, null, out.halt && `${out.halt.code}: ${out.halt.message}`);+ return out;+}+const idIn = (h, set) => h.org.rows(set)[0][PK[set]];+// The approvals a stop printed, of every item it names: configuration-build.js quotes each one.+function printedApprovals(halt) {+ const all = [...(halt ? halt.message : '').matchAll(/given after checking those rows are yours: ((?:"(?:[^"\\]|\\.)*"(?:, )?)+)\./g)];+ return all.flatMap((m) => JSON.parse(`[${m[1]}]`));+}+// The stop a namesake gets today, before anything this change adds to it.+const namesakeStop = (kind, key, ids) => `${kind} ${key}: the ${kind} "${key}" has a namesake at another id (${ids}); a protected create never binds a namesake, and no service changes were sent by this build`;+function assertNothingHeld(h, kind, key, label) {+ const group = h.store.readGroup(kind, key);+ assert.equal(group.committed, null, `${label}: nothing is bound`);+ assert.equal(group.pending, null, `${label}: no attempt is left`);+}+const settingsOf = (spec, Value) => readDeploymentBindings({ EnvironmentVariables: [{ SchemaName: 'contoso_ApiBase', Value }] }, spec);+async function removeMembership(h, objectId) {+ const member = h.org.rows('solutioncomponents').find((c) => c.objectid === objectId);+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/solutioncomponents(${member.solutioncomponentid})`, method: 'DELETE', headers: {} });+ assert.ok(res.statusCode < 300, `DELETE solutioncomponents: ${res.statusCode}`);+}+async function joinSolution(h, id, componentType) {+ const res = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/AddSolutionComponent`, method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ SolutionUniqueName: SOL, ComponentId: id, ComponentType: componentType, AddRequiredComponents: false }) });+ assert.ok(res.statusCode < 300, `AddSolutionComponent: ${res.statusCode}`);+}++test('a protected row made before the opt-in is adopted at its own id only under the exact approvals its stop prints, and nothing is sent', async () => {+ for (const { kind, key, set, spec, children } of ADOPT_KINDS) {+ const h = await harness();+ await madeBeforeOptIn(h, spec());+ const id = idIn(h, set);+ const stop = await pass(reopen(h), spec());+ assert.equal(stop.halt && stop.halt.code, 'create-identity-conflict', stop.halt && stop.halt.message);+ assert.equal(stop.halt.phase, 'preflight');+ assert.ok(stop.halt.message.startsWith(`${namesakeStop(kind, key, id)}. It can instead be adopted at its id ${id}, after checking that row is yours; the build would then change nothing in it.`), stop.halt.message);+ assert.deepEqual(stop.sent, [], kind);+ const tokens = printedApprovals(stop.halt);+ assert.equal(tokens[0], `adopt:${kind}:${key}@${id}`, kind);+ assert.equal(tokens.length, 1 + children, tokens.join(' '));+ for (const t of tokens.slice(1)) assert.match(t, /^adopt:[A-Za-z]+:[^@/]+\/[^@/]+@[0-9a-f-]{36}$/);+ // Nothing short of every exact approval adopts: not the root's alone, not the children's, not the plain token+ // (which still means the row at the derived id only).+ for (const partial of [tokens.slice(0, 1), tokens.slice(1), [`adopt:${kind}:${key}`]]) {+ if (!partial.length || (partial.length === tokens.length)) continue;+ const out = await pass(reopen(h, partial), spec());+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', `${kind} ${partial}`);+ assert.deepEqual(out.sent, [], `${kind} ${partial}`);+ assertNothingHeld(h, kind, key, `${kind} ${partial}`);+ }+ const done = await pass(reopen(h, tokens), spec());+ assert.equal(done.halt, null, done.halt && `${done.halt.code}: ${done.halt.message}`);+ assert.deepEqual(done.sent, [], `${kind}: adopting sends nothing`);+ const group = committed(h, kind, key);+ assert.equal(group.records.length, 1 + children, kind);+ assert.ok(group.records.every((r) => r.origin === 'adopted'), kind);+ assert.equal(group.records.find((r) => r.kind === kind).id, id, kind);+ assert.equal(h.store.readGroup(kind, key).pending, null);+ assert.equal(h.org.rows(set).length, 1, `${kind}: nothing is made beside it`);+ const rerun = await pass(reopen(h), spec());+ assert.equal(rerun.halt, null, rerun.halt && `${rerun.halt.code}: ${rerun.halt.message}`);+ assert.deepEqual(rerun.sent, [], `${kind}: the next build sends nothing`);+ }+});++test('a namesake the build would then change prints the fields it would send, and its root approval lapses when they change', async () => {+ const h = await harness();+ await madeBeforeOptIn(h, apiOnly());+ const id = idIn(h, 'customapis');+ // Another protected item, created at its derived id: the adoption leaves its binding byte for byte.+ await created(h, variableOnly());+ const other = JSON.stringify(h.store.readGroup('environmentVariable', 'contoso_apibase'));+ const spec = configSpec({ duplicateDetectionRules: [], ...api({ description: 'Adds two numbers' }) });+ const stop = await pass(reopen(h), spec);+ assert.equal(stop.halt && stop.halt.code, 'create-identity-conflict', stop.halt && stop.halt.message);+ assert.ok(stop.halt.message.includes(`It can instead be adopted at its id ${id}, after checking that row is yours; the build would then change only these fields, /description.`), stop.halt.message);+ assert.deepEqual(stop.sent, []);+ const tokens = printedApprovals(stop.halt);+ const [root] = tokens;+ assert.match(root, new RegExp(`^adopt:customApi:contoso_calc@${id}\\+[0-9a-f]{16}$`));+ // The root approval without the digest of that list, or with another one, adopts nothing.+ for (const wrong of [root.replace(/\+.*$/, ''), root.replace(/\+.*$/, '+0123456789abcdef')]) {+ const out = await pass(reopen(h, [wrong, ...tokens.slice(1)]), spec);+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', wrong);+ assert.deepEqual(out.sent, [], wrong);+ assertNothingHeld(h, 'customApi', 'contoso_calc', wrong);+ }+ // The App Spec changed again after the stop: the build would now send another list, so the approvals given lapse.+ const more = configSpec({ duplicateDetectionRules: [], ...api({ description: 'Adds two numbers', displayName: 'Calculator' }) });+ const lapsed = await pass(reopen(h, tokens), more);+ assert.equal(lapsed.halt && lapsed.halt.code, 'create-identity-conflict', lapsed.halt && lapsed.halt.message);+ assert.ok(lapsed.halt.message.includes('only these fields, /description, /displayName.'), lapsed.halt.message);+ assert.notEqual(printedApprovals(lapsed.halt)[0], root);+ assert.deepEqual(lapsed.sent, []);+ assertNothingHeld(h, 'customApi', 'contoso_calc', 'lapsed');+ // Under the exact approvals: adopted read-only, then the printed edit is sent once through the bound path.+ const done = await pass(reopen(h, tokens), spec);+ assert.equal(done.halt, null, done.halt && `${done.halt.code}: ${done.halt.message}`);+ assert.deepEqual(done.sent.map((r) => `${r.method} ${r.path.split('?')[0]}`), [`PATCH /customapis(${id})`]);+ assert.equal(h.org.rows('customapis')[0].description, 'Adds two numbers');+ assert.equal(JSON.stringify(h.store.readGroup('environmentVariable', 'contoso_apibase')), other, 'another item\'s binding is unchanged');+ const rerun = await pass(reopen(h), spec);+ assert.equal(rerun.halt, null);+ assert.deepEqual(rerun.sent, []);+});++test('a namesake that cannot be adopted says why after today\'s stop, and is never bound, approvals given or not', async () => {+ const CASES = [+ { name: 'outside the solution', kind: 'environmentVariable', key: 'contoso_apibase', set: 'environmentvariabledefinitions', spec: variableOnly(),+ make: async (h) => { await madeBeforeOptIn(h, variableOnly()); await removeMembership(h, idIn(h, 'environmentvariabledefinitions')); },+ reason: /is not in the solution ContosoSol; add it there first\.$/ },+ { name: 'a child the App Spec does not declare', kind: 'customApi', key: 'contoso_calc', set: 'customapis', spec: apiOnly(),+ make: (h) => madeBeforeOptIn(h, apiOnly({ requestParameters: [...API.requestParameters, { uniqueName: 'B', type: 'integer' }] })), reason: /removals are not supported\.$/ },+ { name: 'a name in another case', kind: 'environmentVariable', key: 'contoso_apibase', set: 'environmentvariabledefinitions',+ spec: configSpec({ customApis: [], duplicateDetectionRules: [], environmentVariables: [{ schemaName: 'contoso_APIBase', type: 'string', defaultValue: 'https://api.contoso.com' }] }),+ make: (h) => madeBeforeOptIn(h, variableOnly()), reason: /its schemaName differs from the App Spec's/ },+ { name: 'a value that differs', kind: 'environmentVariable', key: 'contoso_apibase', set: 'environmentvariabledefinitions', spec: variableOnly(),+ opts: { configurationBindings: settingsOf(variableOnly(), 'https://two.contoso.com') },+ make: (h) => madeBeforeOptIn(h, variableOnly(), { configurationBindings: settingsOf(variableOnly(), 'https://one.contoso.com') }), reason: /never writes a value after adopting\.$/ },+ { name: 'a first value', kind: 'environmentVariable', key: 'contoso_apibase', set: 'environmentvariabledefinitions', spec: variableOnly(),+ opts: { configurationBindings: settingsOf(variableOnly(), 'https://one.contoso.com') },+ make: (h) => madeBeforeOptIn(h, variableOnly()), reason: /would then write a first value to it/ },+ ];+ for (const c of CASES) {+ const h = await harness();+ await c.make(h);+ const id = idIn(h, c.set);+ const before = JSON.stringify(h.org.rows(c.set));+ for (const approvals of [[], [`adopt:${c.kind}:${c.key}@${id}`]]) {+ const out = await pass(reopen(h, approvals), c.spec, c.opts);+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', `${c.name}: ${out.halt && out.halt.message}`);+ assert.equal(out.halt.phase, 'preflight', c.name);+ const [head, tail] = out.halt.message.split(`. It cannot be adopted at its id ${id}: `);+ assert.equal(head, namesakeStop(c.kind, c.key, id), c.name);+ assert.match(tail || '', c.reason, `${c.name}: ${out.halt.message}`);+ assert.ok(!/exact approvals/.test(out.halt.message), `${c.name}: no approval is printed`);+ assert.deepEqual(out.sent, [], c.name);+ assertNothingHeld(h, c.kind, c.key, c.name);+ }+ assert.equal(JSON.stringify(h.org.rows(c.set)), before, `${c.name}: the row is untouched`);+ }+});++test('several namesakes keep today\'s stop byte for byte, and no namesake keeps today\'s requests', async () => {+ const h = await harness();+ const ids = [];+ for (let i = 0; i < 2; i += 1) {+ const id = await insertRow(h.org, 'environmentvariabledefinitions', VARIABLE_ROW);+ await joinSolution(h, id, 380);+ ids.push(id);+ }+ const out = await pass(reopen(h, ids.map((id) => `adopt:environmentVariable:contoso_apibase@${id}`)), variableOnly());+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict');+ const listed = /namesake at another id \(([^)]*)\)/.exec(out.halt.message)[1];+ assert.deepEqual(listed.split(', ').sort(), ids.slice().sort());+ assert.equal(out.halt.message, namesakeStop('environmentVariable', 'contoso_apibase', listed));+ assert.deepEqual(out.sent, []);+ assertNothingHeld(h, 'environmentVariable', 'contoso_apibase', 'several');+ // No namesake: the first create is exactly today's, an approval of the derived id included.+ const plain = await harness();+ const first = await pass(reopen(plain, ['adopt:environmentVariable:contoso_apibase']), variableOnly());+ assert.equal(first.halt, null, first.halt && first.halt.message);+ assert.deepEqual(first.sent.map((r) => `${r.method} ${r.path.split('(')[0].split('?')[0]}`), ['POST /environmentvariabledefinitions']);+ assert.equal(committed(plain, 'environmentVariable', 'contoso_apibase').records[0].origin, 'created');+});++test('a namesake that changes after its adoption began is not adopted: nothing is sent or bound, and the attempt is retired', async () => {+ const CASES = [+ // A declared field edited by hand: the build would now change it, a list the approvals were not given for.+ { name: 'a maker edit', kind: 'customApi', key: 'contoso_calc', set: 'customapis', spec: apiOnly({ description: 'Adds two numbers' }), change: (h, id) => patchRow(h, 'customapis', id, { description: 'Changed by hand' }) },+ { name: 'a membership removed', kind: 'customApi', key: 'contoso_calc', set: 'customapis', spec: apiOnly(), change: (h, id) => removeMembership(h, id) },+ { name: 'a variable edited', kind: 'environmentVariable', key: 'contoso_apibase', set: 'environmentvariabledefinitions', spec: variableOnly(), change: (h, id) => patchRow(h, 'environmentvariabledefinitions', id, { defaultvalue: 'https://other.contoso.com' }) },+ ];+ for (const c of CASES) {+ // The change lands in the riskiest window: after the attempt began and the store was captured, before the+ // acceptance — on the first service read the build makes once begin has run.+ let armed = false;+ let id = null;+ const own = new Set();+ const h = await harness({ intercept: async () => {+ if (!armed) return undefined;+ armed = false;+ const from = h.org.requests.length;+ await c.change(h, id);+ for (const r of h.org.requests.slice(from)) own.add(r);+ return undefined;+ } });+ await madeBeforeOptIn(h, c.spec);+ id = idIn(h, c.set);+ const tokens = printedApprovals((await pass(reopen(h), c.spec)).halt);+ const approved = reopen(h, tokens);+ const runtime = createConfigurationRuntime({ spec: c.spec, sdk: approved.sdk, opts: { protectedConfiguration: approved.protectedConfiguration }, appUniqueName: 'contoso_configured' });+ assert.deepEqual(await runtime.preflight(), { halts: [] }, `${c.name}: the preflight forecasts the adoption`);+ const begin = approved.ctx.begin;+ let began = 0;+ approved.ctx.begin = (plans) => { const out = begin(plans); began += 1; armed = true; return out; };+ const mark = h.org.requests.length;+ const step = await runtime.apply('data-model');+ assert.equal(began, 1, `${c.name}: the adoption began`);+ assert.equal(armed, false, `${c.name}: the change landed`);+ assert.deepEqual(step.halt && step.halt.items.map((i) => i.code), ['create-identity-conflict'], `${c.name}: ${JSON.stringify(step.halt && step.halt.items)}`);+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET' && !own.has(r)), [], `${c.name}: nothing is sent`);+ assertNothingHeld(h, c.kind, c.key, c.name);+ assert.deepEqual(h.store.snapshot().envelope.attempts, [], `${c.name}: the attempt is retired`);+ // The next build stops on what is there now: the approvals given for the earlier rows adopt nothing.+ const next = await pass(reopen(h, tokens), c.spec);+ assert.equal(next.halt && next.halt.code, 'create-identity-conflict', c.name);+ assert.deepEqual(next.sent, [], c.name);+ assertNothingHeld(h, c.kind, c.key, c.name);+ }+});++test('an approval given for a row that was then replaced, or whose child was, adopts nothing: the stop names the new rows; one for a row since deleted lets the item be created', async () => {+ // The root replaced: deleted and made again by name, at another id.+ const h = await harness();+ await madeBeforeOptIn(h, apiOnly());+ const tokens = printedApprovals((await pass(reopen(h), apiOnly())).halt);+ const old = idIn(h, 'customapis');+ const del = await h.org.request({ url: `${h.org.origin}/api/data/v9.2/customapis(${old})`, method: 'DELETE', headers: {} });+ assert.ok(del.statusCode < 300);+ await madeBeforeOptIn(h, apiOnly());+ const fresh = idIn(h, 'customapis');+ assert.notEqual(fresh, old);+ const out = await pass(reopen(h, tokens), apiOnly());+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', out.halt && out.halt.message);+ assert.equal(printedApprovals(out.halt)[0], `adopt:customApi:contoso_calc@${fresh}`);+ assert.deepEqual(out.sent, []);+ assertNothingHeld(h, 'customApi', 'contoso_calc', 'root replaced');++ // A child replaced: the same parameter made again under the same API, at another id, and put in the solution.+ const c = await harness();+ await madeBeforeOptIn(c, apiOnly());+ const childTokens = printedApprovals((await pass(reopen(c), apiOnly())).halt);+ const [param] = c.org.rows('customapirequestparameters');+ const member = c.org.rows('solutioncomponents').find((m) => m.objectid === param.customapirequestparameterid);+ const gone = await c.org.request({ url: `${c.org.origin}/api/data/v9.2/customapirequestparameters(${param.customapirequestparameterid})`, method: 'DELETE', headers: {} });+ assert.ok(gone.statusCode < 300);+ const copy = Object.fromEntries(Object.entries(param).filter(([k]) => !['customapirequestparameterid', '_customapiid_value', 'versionnumber'].includes(k) && !k.startsWith('@')));+ const made = await insertRow(c.org, 'customapirequestparameters', { ...copy, '[email protected]': `/customapis(${param._customapiid_value})` });+ await joinSolution(c, made, member.componenttype);+ const again = await pass(reopen(c, childTokens), apiOnly());+ assert.equal(again.halt && again.halt.code, 'create-identity-conflict', again.halt && again.halt.message);+ assert.ok(printedApprovals(again.halt).some((t) => t.endsWith(`@${made}`)), again.halt.message);+ assert.deepEqual(again.sent, []);+ assertNothingHeld(c, 'customApi', 'contoso_calc', 'child replaced');++ // The namesake deleted after the stop: its approvals adopt nothing, and the item is created at its derived id, as the+ // preflight forecasts and as a build with no namesake does.+ const d = await harness();+ await madeBeforeOptIn(d, variableOnly());+ const varTokens = printedApprovals((await pass(reopen(d), variableOnly())).halt);+ const was = idIn(d, 'environmentvariabledefinitions');+ const dropped = await d.org.request({ url: `${d.org.origin}/api/data/v9.2/environmentvariabledefinitions(${was})`, method: 'DELETE', headers: {} });+ assert.ok(dropped.statusCode < 300);+ const created = await pass(reopen(d, varTokens), variableOnly());+ assert.equal(created.halt, null, created.halt && created.halt.message);+ assert.deepEqual(created.sent.map((r) => `${r.method} ${r.path.split('(')[0].split('?')[0]}`), ['POST /environmentvariabledefinitions']);+ const record = committed(d, 'environmentVariable', 'contoso_apibase').records[0];+ assert.equal(record.origin, 'created');+ assert.notEqual(record.id, was);+});++test('an adoption cut off after it began is retired and made again under its approvals, and is never sent as a create', async () => {+ for (const at of ['prepared', 'sending']) {+ const h = await harness();+ await madeBeforeOptIn(h, apiOnly());+ const id = idIn(h, 'customapis');+ const tokens = printedApprovals((await pass(reopen(h), apiOnly())).halt);+ // The process stops right after the attempt is written: before it is marked sending, or right after.+ const cut = reopen(h, tokens);+ if (at === 'prepared') {+ const mark = h.store.markAttemptSetSending;+ h.store.markAttemptSetSending = () => { h.store.markAttemptSetSending = mark; throw new Error('the process stopped'); };+ } else {+ const begin = cut.ctx.begin;+ cut.ctx.begin = (plans) => { begin(plans); throw new Error('the process stopped'); };+ }+ const crashed = await pass(cut, apiOnly());+ assert.ok(crashed.halt, at);+ assert.deepEqual(crashed.sent, [], at);+ const pending = h.store.readGroup('customApi', 'contoso_calc').pending;+ assert.equal(pending && pending.phase, at, at);+ assert.equal(committed(h, 'customApi', 'contoso_calc'), null, at);++ // A later build without the approvals stops as before, and the create path refuses the attempt outright.+ const asked = await pass(reopen(h), apiOnly());+ assert.equal(asked.halt && asked.halt.code, 'create-identity-conflict', `${at}: ${asked.halt && asked.halt.message}`);+ assert.deepEqual(asked.sent, [], at);+ const port = reopen(h).protectedConfiguration.port({ spec: apiOnly(), dataverse: h.sdk.dataverse, solution: SOL, bindings: undefined, sdk: h.sdk });+ const mark = h.org.requests.length;+ let refused = null;+ try { await port.run({ kind: 'customApi', key: 'contoso_Calc' }, async () => { throw new Error('never sent'); }); } catch (error) { refused = error; }+ assert.equal(refused && refused.code, 'create-identity-unverified', refused && refused.message);+ assert.match(refused.message, /pending adoption, which is never sent as a create/);+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), [], `${at}: run sends nothing`);++ // Under the approvals: the attempt is retired and the adoption made again, read-only.+ const done = await pass(reopen(h, tokens), apiOnly());+ assert.equal(done.halt, null, done.halt && `${at}: ${done.halt.code}: ${done.halt.message}`);+ assert.deepEqual(done.sent, [], at);+ const group = h.store.readGroup('customApi', 'contoso_calc');+ assert.equal(group.pending, null, at);+ assert.equal(group.committed.records.find((r) => r.kind === 'customApi').id, id, at);+ assert.equal(h.org.rows('customapis').length, 1, `${at}: nothing is created`);+ }+});+// ---------------------------------------------------------------------------------------------+// Adoption edges: what an approved adoption may and may not do, every item a stop prints approvals for, and the reads it costs.++const sentLines = (sent) => sent.map((r) => `${r.method} ${r.path}`);++test('an adopted variable keeps its private value, given or not, and nothing is sent', async () => {+ for (const withSettings of [true, false]) {+ const h = await harness();+ const spec = variableOnly();+ const opts = { configurationBindings: settingsOf(spec, 'https://one.contoso.com') };+ await madeBeforeOptIn(h, spec, opts);+ const given = withSettings ? opts : {};+ const stopped = await pass(reopen(h), spec, given);+ const tokens = printedApprovals(stopped.halt);+ assert.equal(tokens.length, 2, stopped.halt && stopped.halt.message);+ const out = await pass(reopen(h, tokens, spec), spec, given);+ assert.equal(out.halt, null, out.halt && out.halt.message);+ assert.deepEqual(sentLines(out.sent), [], `settings given: ${withSettings}`);+ assert.equal(committed(h, 'environmentVariable', 'contoso_apibase').records.length, 2);+ }+});++const DATA_SOURCE = '/providers/Microsoft.PowerApps/apis/shared_sharepointonline';+const dataSources = () => configSpec({+ customApis: [], duplicateDetectionRules: [],+ environmentVariables: [+ { schemaName: 'contoso_Parent', type: 'dataSource', connectorId: DATA_SOURCE, parameterKey: 'dataset' },+ { schemaName: 'contoso_Child', type: 'dataSource', connectorId: DATA_SOURCE, parameterKey: 'table', parentSchemaName: 'contoso_Parent' },+ ],+});++test('a data-source variable and its parent, both made before the opt-in, are adopted together, or the parent first and then the child', async () => {+ // Together: one stop prints both, and one build adopts both, the child against its parent's adopted row.+ {+ const h = await harness();+ const spec = dataSources();+ await madeBeforeOptIn(h, spec);+ const stopped = await pass(reopen(h), spec);+ const tokens = printedApprovals(stopped.halt);+ assert.equal(tokens.length, 2, stopped.halt && stopped.halt.message);+ const out = await pass(reopen(h, tokens, spec), spec);+ assert.equal(out.halt, null, out.halt && out.halt.message);+ assert.deepEqual(sentLines(out.sent), []);+ assert.ok(committed(h, 'environmentVariable', 'contoso_parent') && committed(h, 'environmentVariable', 'contoso_child'));+ }+ // The parent first: a later stop offers the child alone, against the parent's binding (not its derived id).+ {+ const h = await harness();+ const spec = dataSources();+ await madeBeforeOptIn(h, spec);+ const parentOnly = { ...spec, environmentVariables: spec.environmentVariables.slice(0, 1) };+ const parentStop = await pass(reopen(h), parentOnly);+ const parentAdopted = await pass(reopen(h, printedApprovals(parentStop.halt), spec), parentOnly);+ assert.equal(parentAdopted.halt, null, parentAdopted.halt && parentAdopted.halt.message);+ const childStop = await pass(reopen(h), spec);+ const tokens = printedApprovals(childStop.halt);+ assert.equal(tokens.length, 1, childStop.halt && childStop.halt.message);+ assert.match(tokens[0], /^adopt:environmentVariable:contoso_child@/);+ const out = await pass(reopen(h, tokens, spec), spec);+ assert.equal(out.halt, null, out.halt && out.halt.message);+ assert.deepEqual(sentLines(out.sent), []);+ assert.ok(committed(h, 'environmentVariable', 'contoso_child'));+ }+});++test('a request parameter added in the adoption build is created under its approvals', async () => {+ const h = await harness();+ await madeBeforeOptIn(h, apiOnly());+ const spec = apiOnly({ requestParameters: [...API.requestParameters, { uniqueName: 'B', type: 'string' }] });+ const stopped = await pass(reopen(h), spec);+ const tokens = printedApprovals(stopped.halt);+ assert.equal(tokens.length, 3, stopped.halt && stopped.halt.message);+ const out = await pass(reopen(h, tokens, spec), spec);+ assert.equal(out.halt, null, out.halt && out.halt.message);+ assert.ok(out.sent.some((r) => r.method === 'POST'), sentLines(out.sent).join(' '));+});++test('a maker edit made after the adoption is accepted stops the same build: nothing but the printed fields is ever sent', async () => {+ let armed = false;+ const own = new Set();+ let id;+ const h = await harness({ intercept: async () => {+ if (!armed) return undefined;+ armed = false;+ const mark = h.org.requests.length;+ await patchRow(h, 'customapis', id, { displayname: 'Unseen maker edit' });+ for (const r of h.org.requests.slice(mark)) own.add(r);+ return undefined;+ } });+ await madeBeforeOptIn(h, apiOnly({ displayName: 'Calculator' }));+ id = idIn(h, 'customapis');+ const spec = apiOnly({ displayName: 'Calculator', description: 'Adds numbers' });+ const stopped = await pass(reopen(h), spec);+ assert.match(stopped.halt.message, /only these fields, \/description\./);+ const approved = reopen(h, printedApprovals(stopped.halt), spec);+ const accept = approved.ctx.acceptReadOnly;+ approved.ctx.acceptReadOnly = (items) => { const out = accept(items); armed = true; return out; };+ const out = await pass(approved, spec);+ assert.equal(armed, false, 'the maker edit was made');+ assert.equal(out.halt && out.halt.code, 'configuration-incomplete', out.halt && out.halt.message);+ assert.match(out.halt.message, /customApi contoso_Calc \(create-identity-conflict\)/);+ // Refused, not unknown: the item's stop says nothing was sent for it.+ assert.deepEqual(out.step.outcome.refused.map((r) => `${r.kind}:${r.code}`), ['customApi:create-identity-conflict']);+ assert.deepEqual(out.step.outcome.unknown, []);+ assert.deepEqual(sentLines(out.sent.filter((r) => !own.has(r))), [], 'nothing is sent');+ assert.equal(h.org.rows('customapis')[0].displayname, 'Unseen maker edit');+ assert.notEqual(h.org.rows('customapis')[0].description, 'Adds numbers', 'the approved edit is not sent either');+ // A later build plans the item from the row as it is now, as an ordinary bound one: the App Spec's values are sent.+ const later = await pass(reopen(h), spec);+ assert.equal(later.halt, null, later.halt && later.halt.message);+ assert.deepEqual(later.sent.map((r) => `${r.method} ${r.path.split('?')[0]}`), [`PATCH /customapis(${id})`]);+ assert.equal(h.org.rows('customapis')[0].description, 'Adds numbers');+});++// A duplicate rule and its conditions are never adopted: a rule's namesake keeps the stop it had before adoption existed,+// byte for byte, after the same reads, and no approval, typed or raw, binds it or lets anything be sent. An adopted rule+// would be reconciled by the ordinary rule path, which neither holds an edit to the fields its stop printed nor keeps+// from publishing a rule a maker changed after the acceptance.+const anyId = (text) => text.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '<id>');+const RULE_STOP_READS = [+ "GET /EntityDefinitions(LogicalName='connectionreference')?$select=ObjectTypeCode",+ "GET /EntityDefinitions(LogicalName='customapi')?$select=ObjectTypeCode",+ "GET /EntityDefinitions(LogicalName='duplicaterule')?$select=ObjectTypeCode",+ "GET /EntityDefinitions(LogicalName='customapirequestparameter')?$select=ObjectTypeCode",+ "GET /EntityDefinitions(LogicalName='customapiresponseproperty')?$select=ObjectTypeCode",+ "GET /EntityDefinitions(LogicalName='duplicaterulecondition')?$select=ObjectTypeCode",+ 'GET /duplicaterules(<id>)?$select=duplicateruleid,name,description,baseentityname,matchingentityname,iscasesensitive,excludeinactiverecords,statecode,statuscode',+ "GET /duplicaterules?$select=duplicateruleid,name&$filter=name eq 'Same email'",+ 'GET /duplicateruleconditions?$filter=_regardingobjectid_value eq <id>&$select=duplicateruleconditionid,baseattributename,matchingattributename,operatorcode,operatorparam,ignoreblankvalues,_regardingobjectid_value',+];+const onlyRule = (over = {}) => configSpec({ environmentVariables: [], customApis: [], ...rule(over) });++test('a duplicate rule made before the opt-in keeps its stop byte for byte: no adoption is offered or taken, and nothing is sent', async () => {+ const CASES = [+ { name: 'published', spec: onlyRule() },+ { name: 'unpublished', spec: onlyRule({ status: 'unpublished' }) },+ { name: 'its description differs', before: onlyRule({ description: 'Original' }), spec: onlyRule({ description: 'Changed' }) },+ ];+ for (const c of CASES) {+ const h = await harness();+ await madeBeforeOptIn(h, c.before || c.spec);+ const id = idIn(h, 'duplicaterules');+ const condition = h.org.rows('duplicateruleconditions')[0].duplicateruleconditionid;+ const rows = () => JSON.stringify([h.org.rows('duplicaterules'), h.org.rows('duplicateruleconditions')]);+ const before = rows();+ const mark = h.org.requests.length;+ const stop = await pass(reopen(h), c.spec);+ assert.equal(stop.halt && stop.halt.code, 'create-identity-conflict', c.name);+ assert.equal(stop.halt.phase, 'preflight', c.name);+ assert.equal(stop.halt.message, namesakeStop('duplicateRule', 'email', id), c.name);+ assert.deepEqual(h.org.requests.slice(mark).map((r) => anyId(`${r.method} ${r.path}`)), RULE_STOP_READS, `${c.name}: the reads of 2.24.0`);+ // The approvals a plugin that adopted rules would print: the parser reads them whole, as 2.24.0 does, so they name no+ // declared item; given anyway, raw or in the typed spelling, they adopt nothing.+ const wouldBe = [`adopt:duplicateRule:email@${id}`, `adopt:duplicateRuleCondition:email/e@${condition}`];+ assert.deepEqual(configurationAuthorizationKeys(wouldBe, c.spec).problems.map((p) => p.code), ['CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM', 'CONFIGURATION_AUTHORIZATION_UNKNOWN_ITEM'], c.name);+ for (const approvals of [wouldBe, wouldBe.map((a) => a.replace(/^adopt:/, 'adopt-row:')), ['adopt:duplicateRule:email', 'adopt:duplicateRuleCondition:email/e']]) {+ const out = await pass(reopen(h, approvals, null), c.spec);+ assert.equal(out.halt && out.halt.message, namesakeStop('duplicateRule', 'email', id), `${c.name}: ${approvals}`);+ assert.deepEqual(out.sent, [], `${c.name}: ${approvals}`);+ assertNothingHeld(h, 'duplicateRule', 'email', `${c.name}: ${approvals}`);+ }+ assert.equal(rows(), before, `${c.name}: the rule is untouched`);+ }+});++test('a rule a maker edits during a build given the approvals a rule adoption would need is neither rewritten nor published', async () => {+ // Two windows: right after an acceptance, which a rule never reaches, and the build's first request.+ for (const status of ['published', 'unpublished']) for (const window of ['after acceptance', 'first request']) {+ const label = `${status}, ${window}`;+ let armed = false;+ let id;+ const own = new Set();+ const h = await harness({ intercept: async () => {+ if (!armed) return undefined;+ armed = false;+ const mark = h.org.requests.length;+ await patchRow(h, 'duplicaterules', id, { description: 'Unseen maker edit' });+ for (const r of h.org.requests.slice(mark)) own.add(r);+ return undefined;+ } });+ const spec = onlyRule({ description: 'Original', status });+ await madeBeforeOptIn(h, spec);+ id = idIn(h, 'duplicaterules');+ const condition = h.org.rows('duplicateruleconditions')[0].duplicateruleconditionid;+ const stopped = await pass(reopen(h), spec);+ const approvals = printedApprovals(stopped.halt);+ // The typed spellings an adoption would be matched in, given even though the stop printed none.+ const given = reopen(h, [...approvals, `adopt-row:duplicateRule:email@${id}`, `adopt-row:duplicateRuleCondition:email/e@${condition}`], approvals.length ? spec : null);+ const accept = given.ctx.acceptReadOnly;+ let accepted = 0;+ given.ctx.acceptReadOnly = (items) => { const out = accept(items); accepted += 1; if (window === 'after acceptance') armed = true; return out; };+ if (window === 'first request') armed = true;+ const out = await pass(given, spec);+ assert.deepEqual(sentLines(out.sent.filter((r) => !own.has(r))), [], `${label}: no PATCH and no PublishDuplicateRule`);+ assert.equal(accepted, 0, `${label}: a rule is never accepted as adopted`);+ assert.deepEqual(approvals, [], `${label}: the stop prints no approval`);+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict', label);+ assert.equal(h.org.rows('duplicaterules')[0].description, window === 'first request' ? 'Unseen maker edit' : 'Original', label);+ assertNothingHeld(h, 'duplicateRule', 'email', label);+ }+});++test('a stop naming several adoptable namesakes shows each one\'s id and fields beside its approvals', async () => {+ const h = await harness();+ const before = apiOnly({ uniqueName: 'contoso_First', isFunction: false, requestParameters: [], responseProperties: [] });+ before.customApis.push({ uniqueName: 'contoso_Second', description: 'Maker text', isFunction: false, requestParameters: [], responseProperties: [] });+ await madeBeforeOptIn(h, before);+ const idOf = (name) => h.org.rows('customapis').find((r) => r.uniquename === name).customapiid;+ const spec = structuredClone(before);+ spec.customApis[1].description = 'Replacement';+ const stopped = await pass(reopen(h), spec);+ const message = stopped.halt.message;+ for (const [key, name, change] of [['contoso_first', 'contoso_First', 'nothing in it'], ['contoso_second', 'contoso_Second', 'only these fields, /description']]) {+ const id = idOf(name);+ assert.ok(message.includes(`Adopt customApi ${key} at its id ${id} (the build would then change ${change}) only under these exact approvals, given after checking those rows are yours: "adopt:customApi:${key}@${id}`), message);+ }+ assert.equal(printedApprovals(stopped.halt).length, 2);+ const out = await pass(reopen(h, printedApprovals(stopped.halt), spec), spec);+ assert.equal(out.halt, null, out.halt && out.halt.message);+});++test('the build\'s own error names every adoptable namesake with its id and fields, before anything is sent', async () => {+ const h = await harness();+ const before = apiOnly({ uniqueName: 'contoso_First', isFunction: false, requestParameters: [], responseProperties: [] });+ before.customApis.push({ uniqueName: 'contoso_Second', description: 'Maker text', isFunction: false, requestParameters: [], responseProperties: [] });+ await madeBeforeOptIn(h, before);+ const idOf = (name) => h.org.rows('customapis').find((r) => r.uniquename === name).customapiid;+ const spec = structuredClone(before);+ spec.customApis[1].description = 'Replacement';+ assert.deepEqual(validateAppSpec(spec).errors, []);+ const mark = h.org.requests.length;+ let caught;+ try {+ await runSdkBuild(spec, { sdk: h.sdk, apply: true, phases: STAGES.data, workspaceDir: makeTempDir('cfg-protected-ws-'), protectedConfiguration: reopen(h).protectedConfiguration, emit: () => {} });+ } catch (error) {+ caught = error;+ }+ assert.equal(caught && caught.code, 'create-identity-conflict', caught && caught.message);+ for (const [key, name, change] of [['contoso_first', 'contoso_First', 'nothing in it'], ['contoso_second', 'contoso_Second', 'only these fields, /description']]) {+ const id = idOf(name);+ assert.ok(caught.message.includes(`Adopt customApi ${key} at its id ${id} (the build would then change ${change}) only under these exact approvals, given after checking those rows are yours: "adopt:customApi:${key}@${id}`), caught.message);+ }+ assert.deepEqual(h.org.requests.slice(mark).filter((r) => r.method !== 'GET'), [], 'zero service mutations');+});++test('a rule key that ends in what reads like a row id keeps its ordinary meaning, and a rule namesake is never offered', async () => {+ const h = await harness();+ const initial = onlyRule({ status: 'unpublished', conditions: [] });+ await madeBeforeOptIn(h, initial);+ const id = idIn(h, 'duplicaterules');+ const spec = structuredClone(initial);+ const secondKey = `email@${id}`;+ spec.duplicateDetectionRules.push({ key: secondKey, name: 'Another rule', entity: 'contact', status: 'unpublished', conditions: [] });+ const typed = `adopt:duplicateRule:${secondKey}`;+ const parsed = configurationAuthorizationKeys([typed], spec);+ assert.deepEqual(parsed.problems, []);+ assert.deepEqual([...parsed.rowApprovals], [typed], 'the plain approval of the rule keyed email@<id>, as in 2.24.0');+ const out = await pass(reopen(h, [...parsed.rowApprovals], null), spec);+ assert.equal(out.halt && out.halt.code, 'create-identity-conflict');+ assert.equal(out.halt.message, namesakeStop('duplicateRule', 'email', id));+ assert.deepEqual(out.sent, []);+ assert.equal(committed(h, 'duplicateRule', 'email'), null);+});+test('a failed continuation page of the membership or the children is never read as a complete adoption read', async () => {+ for (const set of ['solutioncomponents', 'customapirequestparameters']) {+ let active = false;+ let root;+ const h = await harness({ intercept: ({ method, path }) => {+ if (!active || method !== 'GET' || !path.startsWith(`/${set}?`)) return undefined;+ if (set !== 'solutioncomponents' && !path.includes(root) && !path.includes('$skiptoken=more')) return undefined;+ if (/\$skiptoken=/.test(path)) return { statusCode: 503, body: { error: { code: '0x80040216', message: 'busy' } } };+ return { statusCode: 200, body: { value: [], '@odata.nextLink': `${h.org.origin}/api/data/v9.0/${set}?$skiptoken=more` } };+ } });+ await madeBeforeOptIn(h, apiOnly());+ root = idIn(h, 'customapis');+ const tokens = printedApprovals((await pass(reopen(h), apiOnly())).halt);+ active = true;+ const out = await pass(reopen(h, tokens), apiOnly());+ assert.ok(out.halt, set);+ assert.deepEqual(sentLines(out.sent), [], set);+ assert.ok(h.org.requests.some((r) => r.path.includes('$skiptoken=more')), set);+ assertNothingHeld(h, 'customApi', 'contoso_calc', set);+ }+});++test('complete continuation pages supply the children and the membership of an adoption', async () => {+ let active = false;+ let root;+ let continued = 0;+ const h = await harness({ intercept: ({ method, path }) => {+ if (!active || method !== 'GET') return undefined;+ const set = path.startsWith('/solutioncomponents?') ? 'solutioncomponents'+ : path.startsWith('/customapirequestparameters?') && (path.includes(root) || path.includes('$skiptoken=more')) ? 'customapirequestparameters' : null;+ if (!set) return undefined;+ if (path.includes('$skiptoken=more')) { continued += 1; return { statusCode: 200, body: { value: h.org.rows(set) } }; }+ return { statusCode: 200, body: { value: [], '@odata.nextLink': `${h.org.origin}/api/data/v9.0/${set}?$skiptoken=more` } };+ } });+ await madeBeforeOptIn(h, apiOnly());+ root = idIn(h, 'customapis');+ const tokens = printedApprovals((await pass(reopen(h), apiOnly())).halt);+ active = true;+ const out = await pass(reopen(h, tokens), apiOnly());+ assert.equal(out.halt, null, out.halt && out.halt.message);+ assert.ok(continued > 2, `continued ${continued}`);+ assert.deepEqual(sentLines(out.sent), []);+});++test('a connection reference is adopted only with its matching private connection', async () => {+ const spec = configSpec({ environmentVariables: [], customApis: [], duplicateDetectionRules: [],+ connectionReferences: [{ logicalName: 'contoso_sp', connectorId: DATA_SOURCE }] });+ const good = readDeploymentBindings({ ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: 'conn-one' }] }, spec);+ const bad = readDeploymentBindings({ ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: 'conn-two' }] }, spec);+ const h = await harness();+ const opts = { configurationBindings: good, connections: async () => [{ connectionId: 'conn-one', connectorId: DATA_SOURCE }] };+ await madeBeforeOptIn(h, spec, opts);+ const stop = await pass(reopen(h), spec, opts);+ const tokens = printedApprovals(stop.halt);+ assert.equal(tokens.length, 1, stop.halt && stop.halt.message);+ const refused = await pass(reopen(h, tokens, spec), spec, { ...opts, configurationBindings: bad });+ assert.ok(refused.halt);+ assert.deepEqual(sentLines(refused.sent), []);+ assertNothingHeld(h, 'connectionReference', 'contoso_sp', 'private connection mismatch');+ const accepted = await pass(reopen(h, tokens, spec), spec, opts);+ assert.equal(accepted.halt, null, accepted.halt && accepted.halt.message);+ assert.deepEqual(sentLines(accepted.sent), []);+});++test('a request parameter added while the adoption is captured is refused, and nothing is bound', async () => {+ let armed = false;+ let root;+ const h = await harness({ intercept: async () => {+ if (!armed) return undefined;+ armed = false;+ await insertRow(h.org, 'customapirequestparameters', { uniquename: 'MakerChild', name: 'MakerChild', type: 10, '[email protected]': `/customapis(${root})` });+ return undefined;+ } });+ await madeBeforeOptIn(h, apiOnly());+ root = idIn(h, 'customapis');+ const approved = reopen(h, printedApprovals((await pass(reopen(h), apiOnly())).halt));+ const capture = approved.ctx.captureReadOnly;+ approved.ctx.captureReadOnly = (items) => { const out = capture(items); armed = true; return out; };+ const out = await pass(approved, apiOnly());+ assert.ok(out.halt);+ assertNothingHeld(h, 'customApi', 'contoso_calc', 'new child during adoption');+});++test('a read-only acceptance needs an attempt begun with its expected proof, never one only prepared', async () => {+ const h = await harness();+ const spec = apiOnly({ isFunction: false, requestParameters: [], responseProperties: [] });+ await madeBeforeOptIn(h, spec);+ const id = idIn(h, 'customapis');+ const approved = reopen(h, [`adopt:customApi:contoso_calc@${id}`]);+ const tokenOf = () => `adopt-row:customApi:contoso_calc@${id}`;+ const base = await B.readConfigurationRow(h.sdk.dataverse, 'customApi', id);+ const types = await B.readComponentTypes(h.sdk.dataverse);+ const planned = B.planOf(spec, { kind: 'customApi', key: 'contoso_Calc', solution: SOL, componentTypes: types.types, bases: new Map([[id, base]]), boundIdOf: () => id, asIs: true });+ const built = require('../lib/managed-create-context.js').buildRowPlan(planned.plan);+ const [unbegun] = h.store.prepareAttemptSet([built.prepare]);+ const [capture0] = approved.ctx.captureReadOnly([unbegun]);+ const observation0 = await B.observe(h.sdk.dataverse, planned);+ assert.throws(() => approved.ctx.acceptReadOnly([{ token: unbegun, capture: capture0, observation: observation0, declarationSha256: planned.plan.declarationSha256, approvalTokenOf: tokenOf }]),+ /not a plan of existing rows with a base observation/);+ h.store.retireUnsentAttempt({ token: unbegun, baseGeneration: null });+ const [begun] = approved.ctx.begin([planned.plan]);+ const [capture1] = approved.ctx.captureReadOnly([begun.token]);+ const observation1 = await B.observe(h.sdk.dataverse, planned);+ const [accepted] = approved.ctx.acceptReadOnly([{ token: begun.token, capture: capture1, observation: observation1, declarationSha256: planned.plan.declarationSha256, approvalTokenOf: tokenOf }]);+ assert.equal(accepted.verdict.action, 'commit');+ assert.equal(accepted.group.records[0].origin, 'adopted');+});++test('adoption analysis costs reads only for a single namesake under the opt-in', async () => {+ const gets = {};+ for (const roots of [0, 1, 2]) {+ const h = await harness();+ const spec = variableOnly();+ if (roots > 0) await madeBeforeOptIn(h, spec);+ if (roots === 2) await joinSolution(h, await insertRow(h.org, 'environmentvariabledefinitions', VARIABLE_ROW), 380);+ for (const optIn of [false, true]) {+ const runtime = createConfigurationRuntime({ spec: optIn ? spec : withoutOptIn(spec), sdk: h.sdk, opts: { protectedConfiguration: reopen(h).protectedConfiguration }, appUniqueName: 'contoso_configured' });+ const mark = h.org.requests.length;+ try { await runtime.preflight(); } catch { /* the namesake stops are judged elsewhere */ }+ const since = h.org.requests.slice(mark);+ assert.deepEqual(sentLines(since.filter((r) => r.method !== 'GET')), []);+ gets[`${roots}:${optIn ? 'opt-in' : 'plain'}`] = since.length;+ }+ }+ assert.deepEqual(gets, { '0:plain': 0, '0:opt-in': 8, '1:plain': 0, '1:opt-in': 18, '2:plain': 0, '2:opt-in': 8 });+});++// ---------------------------------------------------------------------------------------------+// After an adoption is accepted, the same build sends at most the fields its stop printed, for every kind that adopts: a+// maker edit made right after the acceptance, to a field outside that list, stops the item with nothing sent and the+// maker's value kept. A later build plans the item from the row as it is now, as an ordinary bound one.++async function editedAfterAcceptance({ before, spec, beforeOpts = {}, opts = {}, edit, expectList }) {+ let armed = false;+ const own = new Set();+ const h = await harness({ intercept: async () => {+ if (!armed) return undefined;+ armed = false;+ const mark = h.org.requests.length;+ await edit(h);+ for (const r of h.org.requests.slice(mark)) own.add(r);+ return undefined;+ } });+ await madeBeforeOptIn(h, before, beforeOpts);+ const stopped = await pass(reopen(h), spec, opts);+ assert.equal(stopped.halt && stopped.halt.code, 'create-identity-conflict', stopped.halt && stopped.halt.message);+ assert.ok(stopped.halt.message.includes(`the build would then change ${expectList}`), stopped.halt.message);+ const approved = reopen(h, printedApprovals(stopped.halt), spec);+ const accept = approved.ctx.acceptReadOnly;+ let accepted = 0;+ approved.ctx.acceptReadOnly = (items) => { const out = accept(items); accepted += 1; armed = true; return out; };+ const out = await pass(approved, spec, opts);+ assert.equal(accepted, 1, 'the adoption was accepted');+ assert.equal(armed, false, 'the maker edit was made');+ return { h, out, sent: out.sent.filter((r) => !own.has(r)) };+}+function assertItemStopped(out, sent, kind, code = 'create-identity-conflict') {+ assert.equal(out.halt && out.halt.code, 'configuration-incomplete', out.halt && out.halt.message);+ assert.deepEqual(out.step.outcome.refused.map((r) => `${r.kind}:${r.code}`), [`${kind}:${code}`]);+ assert.deepEqual(out.step.outcome.unknown, []);+ assert.deepEqual(sentLines(sent), [], 'nothing is sent');+}++test('an adopted environment variable edited by a maker right after the acceptance is not edited by the same build', async () => {+ const VAR = { schemaName: 'contoso_ApiBase', type: 'string', name: 'API base', description: 'Original', defaultValue: 'https://api.contoso.com' };+ const before = configSpec({ customApis: [], duplicateDetectionRules: [], environmentVariables: [VAR] });+ const spec = configSpec({ customApis: [], duplicateDetectionRules: [], environmentVariables: [{ ...VAR, defaultValue: 'https://new.contoso.com' }] });+ for (const [column, value] of [['description', 'Maker description'], ['displayname', 'Maker name']]) {+ const edit = (h) => patchRow(h, 'environmentvariabledefinitions', idIn(h, 'environmentvariabledefinitions'), { [column]: value });+ const { h, out, sent } = await editedAfterAcceptance({ before, spec, edit, expectList: 'only these fields, /defaultValue' });+ assertItemStopped(out, sent, 'environmentVariable');+ const [row] = h.org.rows('environmentvariabledefinitions');+ assert.equal(row[column], value, `${column}: the maker value is kept`);+ assert.equal(row.defaultvalue, 'https://api.contoso.com', `${column}: the approved edit is not sent either`);+ const later = await pass(reopen(h), spec);+ assert.equal(later.halt, null, later.halt && later.halt.message);+ assert.equal(h.org.rows('environmentvariabledefinitions')[0].defaultvalue, 'https://new.contoso.com');+ }+});++test('an adopted environment variable value changed by a maker right after the acceptance is not written back by the same build', async () => {+ const spec = variableOnly();+ const settings = { configurationBindings: settingsOf(spec, 'https://one.contoso.com') };+ const edit = (h) => patchRow(h, 'environmentvariablevalues', h.org.rows('environmentvariablevalues')[0].environmentvariablevalueid, { value: 'https://maker.contoso.com' });+ // Without the approval to replace a value, the build's own gate refuses writing the deployment settings' value back;+ // with it, the adoption's hold does: nothing beyond the printed list (here nothing) is sent in the adopting build.+ for (const [opts, code] of [[settings, 'DESTRUCTIVE_CHANGE_UNAUTHORIZED'], [{ ...settings, authorizedDestructive: new Set(['environmentVariableValue:contoso_apibase:value']) }, 'create-identity-conflict']]) {+ const { h, out, sent } = await editedAfterAcceptance({ before: spec, spec, beforeOpts: settings, opts, edit, expectList: 'nothing in it' });+ assertItemStopped(out, sent, 'environmentVariable', code);+ assert.equal(h.org.rows('environmentvariablevalues')[0].value, 'https://maker.contoso.com', `${code}: the maker value is kept`);+ }+});++test('an adopted connection reference edited by a maker right after the acceptance is not edited by the same build', async () => {+ const REF = { logicalName: 'contoso_sp', connectorId: DATA_SOURCE, name: 'SharePoint', description: 'Original' };+ const before = configSpec({ environmentVariables: [], customApis: [], duplicateDetectionRules: [], connectionReferences: [REF] });+ const spec = configSpec({ environmentVariables: [], customApis: [], duplicateDetectionRules: [], connectionReferences: [{ ...REF, description: 'Approved' }] });+ const settings = (s, more = {}) => ({ configurationBindings: readDeploymentBindings({ ConnectionReferences: [{ LogicalName: 'contoso_sp', ConnectionId: 'conn-one' }] }, s),+ connections: async () => [{ connectionId: 'conn-one', connectorId: DATA_SOURCE }, { connectionId: 'conn-two', connectorId: DATA_SOURCE }], ...more });+ // A connection the maker changed is one the build would replace: refused by the build's own gate without the approval+ // to replace it, and by the adoption's hold with it.+ let replace = null;+ for (const [column, value, code] of [['connectionreferencedisplayname', 'Maker name', 'create-identity-conflict'], ['connectionid', 'conn-two', 'DESTRUCTIVE_CHANGE_UNAUTHORIZED'], ['connectionid', 'conn-two', 'create-identity-conflict']]) {+ const approved = column === 'connectionid' && code === 'create-identity-conflict';+ const edit = (h) => patchRow(h, 'connectionreferences', h.org.rows('connectionreferences')[0].connectionreferenceid, { [column]: value });+ const { h, out, sent } = await editedAfterAcceptance({ before, spec, beforeOpts: settings(before), opts: settings(spec, approved ? { authorizedDestructive: new Set(replace) } : {}), edit, expectList: 'only these fields, /description' });+ assertItemStopped(out, sent, 'connectionReference', code);+ if (code === 'DESTRUCTIVE_CHANGE_UNAUTHORIZED') replace = out.step.outcome.refused[0].authorize;+ const [row] = h.org.rows('connectionreferences');+ assert.equal(row[column], value, `${column} ${code}: the maker value is kept`);+ assert.equal(row.description, 'Original', `${column} ${code}: the approved edit is not sent either`);+ }+ assert.ok(replace && replace.length, 'the replacement approval was named');+});diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.jsindex 533373db6..a8d8ee134 100644--- a/plugins/model-apps/scripts/tests/download-model-app.test.js+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js@@ -1553,34 +1553,7 @@ test('env-wide id→name used as the page name; sitemap title is fallback only',// ── the page folders a download writes from what the SDK read ─────────────────────────────────────────────────────────────────────-// An app with the given pages in its navigation, served through the stand-in SDK the other runDownload tests use.-function pagesApp(pageIds) {- const APP_ID = 'a1b2c3d4-0000-4000-8000-000000000001';- const LAYER = 'c0ffee00-0000-4000-8000-00000000dddd';- const xml = `<SiteMap><Area><Group>${pageIds.map((id, i) => `<SubArea GenPageId="${id}" Title="Title ${i}"/>`).join('')}<SubArea Entity="contoso_item"/></Group></Area></SiteMap>`;- const sdk = {- fetchArtifact: async () => ({- name: 'Pages App', description: '',- siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [- ...pageIds.map((id, i) => ({ type: 'GenPage', genPageId: id, title: `Title ${i}` })),- { type: 'Entity', entity: 'contoso_item' },- ] }] }] },- }),- queryRecords: async (logical, opts) => {- const filter = (opts && opts.filter) || '';- if (logical === 'appmodule') {- const m = filter.match(/uniquename eq '([^']+)'/);- if (m) return m[1] === 'test_pages' ? [{ appmoduleid: APP_ID, appmoduleidunique: LAYER }] : [];- return [{ appmoduleid: APP_ID, appmoduleidunique: LAYER, uniquename: 'test_pages' }];- }- if (logical === 'appmodulecomponent') return [{ objectid: '5111e0f2-0000-4000-8000-0000000000aa', componenttype: 62 }];- if (logical === 'sitemap') return [{ sitemapxml: xml }];- return [];- },- fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Item', primaryNameAttribute: `${String(logical).split('_')[0]}_name` }),- };- return { sdk: currentReadSdk(sdk, { appId: APP_ID, layerId: LAYER, sitemapXml: xml }), appId: APP_ID, appUnique: 'test_pages' };-}+const { pagesApp } = require('./helpers/page-swap.js');test('runDownload writes pages/<id>/{page.tsx,config.json,prompt.txt} from the page the SDK read — the source exactly as stored, no BOM and no CRLF added', async () => {const GP_A = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';@@ -1669,6 +1642,1092 @@ test('runDownload replaces the pages tree as a whole — a page deleted since th}});+// ── a new page tree is swapped in whole, never written over the old one (#814) ───────────────────────────────────────────────────────+// pages/ can hold a maker's page edits that were never uploaded. A download used to remove it and then write the new tree file by file, so+// any failure part-way lost them. These tests fail an fs call at each step of the swap, through both callers, and check what is on disk;+// stop a child process dead at each step and check what the next download does with what it left; and plant links where the swap's own+// folders were made, to check nothing is written or removed through them.++const { spawnSync } = require('node:child_process');+const { writePageTree, generatedFolders, GUARDED_FS_METHODS } = require('../download-model-app.js');+const { freshRenameWaitTotal } = require('./helpers/short-rename-wait.js');+const { SWAP_A, SWAP_B, DOWNLOADED_A, seedEditedPages, treeBytes, swapGenpage, swapDownload } = require('./helpers/page-swap.js');++const CRASH_CHILD = path.join(__dirname, 'helpers', 'page-swap-crash-child.js');++// The hidden folders a download makes in <out>: the swap folder, and the managed download's staging folder.+const leftovers = (out) => fs.readdirSync(out).filter((n) => n.startsWith('.pages-replace.') || n.startsWith('.download-pages.'));+// A path under the managed download's staging folder: its tree is written by the same swap, and the faults below are for pages/ only.+const staged = (p) => String(p).split(/[\\/]/).some((seg) => seg.startsWith('.download-pages.'));+// The folder `<out>/<prefix>*` that `p` is, or is in, when there is one (null otherwise): `p` may name <out> by its real path.+function topFolder(out, p, prefix) {+ for (const base of new Set([out, fs.realpathSync.native(out)])) {+ const rel = path.relative(base, String(p));+ const first = rel.split(path.sep)[0];+ if (!rel.startsWith('..') && !path.isAbsolute(rel) && first.startsWith(prefix)) return path.join(base, first);+ }+ return null;+}++// Makes fs[method] throw `code` for the calls `when` picks (all others go through), and answers the list of the calls it failed.+function failFs(t, method, when, code) {+ const real = fs[method];+ const failed = [];+ t.mock.method(fs, method, function (...args) {+ if (when(...args)) {+ failed.push(args);+ throw Object.assign(new Error(`${code}: injected, ${method} '${args[0]}'`), { code, syscall: method, path: String(args[0]) });+ }+ return real.apply(this, args);+ });+ return failed;+}++// What the download writes to stderr, as a list of lines.+function stderrLines(t) {+ const lines = [];+ t.mock.method(process.stderr, 'write', (line) => { lines.push(String(line)); return true; });+ return lines;+}++// A folder outside <out> with a tree in it (`new/keep.txt` sits where the swap's `new` would be, if a link led a download there).+function outsideTree() {+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-outside-'));+ fs.mkdirSync(path.join(outside, 'new'));+ fs.writeFileSync(path.join(outside, 'new', 'keep.txt'), 'not the download\'s');+ fs.writeFileSync(path.join(outside, 'keep.txt'), 'not the download\'s either');+ return outside;+}++// Runs one call that stands for another process moving, removing or replacing a folder the download (or its guard) has just made or+// written. On Windows an antivirus or indexer handle on such a folder refuses that call for a moment (EPERM, EACCES or EBUSY; seen in+// these tests on a loaded machine), and that other process would simply try again, so the test does too (up to about 2 s). Above all, a+// refusal must not escape a hook that runs inside one of the download's own fs calls: the download would take it for a refusal of its+// own call and try that call again after it had in fact happened (seen: a page's rename retried after it was done, ENOENT, IO_ERROR+// instead of the refusal under test). Any other error, and every error on another platform, is thrown at once.+const HOOK_LOCK_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']);+function hookRetry(call) {+ for (let i = 0; ; i += 1) {+ try {+ return call();+ } catch (e) {+ if (process.platform !== 'win32' || !HOOK_LOCK_CODES.has(e && e.code) || i >= 80) throw e;+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);+ }+ }+}++// Makes the folder `<out>/<prefix>*` the download makes a junction to `outside` the moment it is made (on POSIX, 'junction' makes a plain+// folder symlink): what another process that can write <out> could do between the mkdir and the first use. Answers the folders replaced.+function plantAtMkdir(t, out, prefix, outside) {+ const real = fs.mkdirSync;+ const planted = [];+ t.mock.method(fs, 'mkdirSync', function (p, ...rest) {+ const result = real.call(this, p, ...rest);+ if (!planted.length && topFolder(out, p, prefix) === path.resolve(String(p))) {+ hookRetry(() => fs.rmdirSync(p));+ hookRetry(() => fs.symlinkSync(outside, p, 'junction'));+ planted.push(String(p));+ }+ return result;+ });+ return planted;+}++// A warning about a folder of the swap or of the staging (the stand-in app's own warnings, about its tables, are not about pages).+const swapWarning = (line) => line.includes('.pages-replace.') || line.includes('.download-pages.');++// The downloaded tree in pages/: the app's two pages, the first as the stand-in genpage serves it, nothing of the maker's.+function assertDownloadedTree(out, label) {+ assert.deepStrictEqual(fs.readdirSync(path.join(out, 'pages')).sort(), [SWAP_A, SWAP_B].sort(), label);+ assert.strictEqual(fs.readFileSync(path.join(out, 'pages', SWAP_A, 'page.tsx'), 'utf8'), DOWNLOADED_A, label);+}++// Both callers of the swap: a direct download writes pages/ itself; the managed download stages the tree and publishes it after.+const SWAP_CALLERS = [+ ['a direct download', (out) => swapDownload(out, false), 'direct'],+ ['the managed download\'s publish', (out) => swapDownload(out, true), 'managed'],+];++for (const [caller, download, mode] of SWAP_CALLERS) {+ test(`${caller}: a page that fails to write part-way leaves the maker's pages/ byte for byte as it was, and no swap folder (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-write-'));+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ // The second page's first file: the first page is whole on disk by then.+ const failed = failFs(t, 'openSync', (p) => !staged(p) && path.basename(path.dirname(String(p))) === SWAP_B, 'ENOSPC');+ await assert.rejects(download(out), /ENOSPC/);+ t.mock.restoreAll();+ assert.strictEqual(failed.length, 1, 'the write of the second page failed');+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before, 'the edited page and the maker\'s own page are as they were');+ assert.deepStrictEqual(leftovers(out), [], 'the part-written tree is removed');+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });++ test(`${caller}: pages/ that cannot be moved aside is left as it was, and the download fails saying so (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-aside-'));+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const failed = failFs(t, 'renameSync', (from, to) => !staged(to) && path.basename(String(to)) === 'previous', 'EIO');+ await assert.rejects(download(out), (e) => e.code === 'EIO' && /could not replace the page folder .*could not be moved aside \(EIO\)\. It is as it was/.test(e.message));+ t.mock.restoreAll();+ assert.strictEqual(failed.length, 1);+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before);+ assert.deepStrictEqual(leftovers(out), []);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });++ test(`${caller}: a new tree that cannot be moved into pages/ puts the previous pages back as they were (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-into-'));+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const failed = failFs(t, 'renameSync', (from, to) => !staged(to) && path.basename(String(from)) === 'new' && path.basename(String(to)) === 'pages', 'EIO');+ await assert.rejects(download(out), (e) => e.code === 'EIO' && /could not be moved into it \(EIO\)\. The previous pages were put back as they were$/.test(e.message));+ t.mock.restoreAll();+ assert.strictEqual(failed.length, 1);+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before);+ assert.deepStrictEqual(leftovers(out), []);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });++ test(`${caller}: a new tree that cannot be moved in, nor the previous pages back, deletes nothing and names both folders (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-back-'));+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const failed = failFs(t, 'renameSync', (from, to) => !staged(to) && path.basename(String(to)) === 'pages', 'EIO');+ let error;+ await assert.rejects(download(out), (e) => { error = e; return true; });+ t.mock.restoreAll();+ assert.strictEqual(failed.length, 2, 'the move in, then the move back');+ const swaps = leftovers(out);+ assert.strictEqual(swaps.length, 1);+ const swap = path.join(out, swaps[0]);+ assert.strictEqual(error.code, 'EIO');+ assert.ok(error.message.includes(`the previous pages are in ${path.join(swap, 'previous')} and the downloaded pages in ${path.join(swap, 'new')}`), error.message);+ assert.ok(!fs.existsSync(path.join(out, 'pages')));+ assert.deepStrictEqual(treeBytes(path.join(swap, 'previous')), before, 'the maker\'s pages, whole');+ assert.strictEqual(fs.readFileSync(path.join(swap, 'new', SWAP_A, 'page.tsx'), 'utf8'), DOWNLOADED_A, 'the downloaded pages, whole');+ assert.ok(fs.existsSync(path.join(swap, 'new', SWAP_B, 'page.tsx')));+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });++ test(`${caller}: a swap folder that cannot be removed at the end leaves the download a success, and a warning names the folder to delete (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-left-'));+ try {+ seedEditedPages(out);+ const failed = failFs(t, 'rmSync', (p) => !staged(p) && path.basename(String(p)).startsWith('.pages-replace.'), 'EIO');+ const lines = stderrLines(t);+ await download(out);+ t.mock.restoreAll();+ assert.strictEqual(failed.length, 1);+ assertDownloadedTree(out, 'the new tree is in place');+ const swaps = leftovers(out);+ assert.strictEqual(swaps.length, 1);+ const warnings = lines.filter((l) => l.includes(swaps[0]));+ assert.strictEqual(warnings.length, 1, lines.join(''));+ assert.match(warnings[0], /^WARNING: the page folder .* was replaced, but the folder .* that holds the previous pages could not be removed \(EIO\): delete it\.\n$/);+ assert.ok(warnings[0].includes(path.join(out, swaps[0])));+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });++ test(`${caller}: a swap folder replaced by a junction the moment it is made is refused before anything is written, and what it points to is untouched (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-plant-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const outsideBefore = treeBytes(outside);+ const planted = plantAtMkdir(t, out, '.pages-replace.', outside);+ // Were the pages written through the junction, this failure would send the clean-up after them, into `outside`.+ failFs(t, 'openSync', (p) => !staged(p) && path.basename(path.dirname(String(p))) === SWAP_B, 'ENOSPC');+ await assert.rejects(download(out), (e) => e.code === 'UNSAFE_OUTPUT' && e.message.includes(path.basename(planted[0])));+ t.mock.restoreAll();+ assert.strictEqual(planted.length, 1, 'the swap folder was replaced');+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'nothing written to, or removed from, where the junction points');+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before);+ assert.deepStrictEqual(leftovers(out), [path.basename(planted[0])], 'the junction is left where it was put');+ assert.ok(fs.lstatSync(planted[0]).isSymbolicLink());+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+ });++ test(`${caller}: a swap folder replaced by a junction while the pages are written is not cleaned up through it: what it points to is untouched, and a warning names it (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-late-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const outsideBefore = treeBytes(outside);+ const realOpen = fs.openSync;+ let swap = null;+ t.mock.method(fs, 'openSync', function (p, ...rest) {+ const top = staged(p) ? null : topFolder(out, p, '.pages-replace.');+ if (top && !swap && path.basename(path.dirname(String(p))) === SWAP_B) {+ // The first page is written; the swap folder is moved away and a junction put at its name, then the write fails.+ swap = top;+ hookRetry(() => fs.renameSync(top, path.join(path.dirname(top), 'moved-away')));+ hookRetry(() => fs.symlinkSync(outside, top, 'junction'));+ throw Object.assign(new Error('ENOSPC: injected'), { code: 'ENOSPC', syscall: 'open', path: String(p) });+ }+ return realOpen.call(this, p, ...rest);+ });+ const lines = stderrLines(t);+ await assert.rejects(download(out), /ENOSPC/);+ t.mock.restoreAll();+ assert.ok(swap, 'the swap folder was replaced');+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'the clean-up did not descend through the junction');+ assert.ok(fs.lstatSync(swap).isSymbolicLink(), 'the junction is left where it was put');+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before);+ const warnings = lines.filter((l) => l.includes(path.basename(swap)));+ assert.strictEqual(warnings.length, 1, lines.join(''));+ assert.match(warnings[0], /^WARNING: the folder .* the downloaded pages were written to was not removed: it, or a folder in it, is no longer the folder this download made there .*Look into it before you delete anything in it\.\n$/);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+ });++ test(`${caller}: a swap folder replaced by a junction between two file writes is refused at the next write: nothing is written where it points, and a warning names it (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-between-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ // A file of the first page where the next write would land, through the junction.+ fs.mkdirSync(path.join(outside, 'new', SWAP_A));+ fs.writeFileSync(path.join(outside, 'new', SWAP_A, 'config.json'), 'not the download\'s config');+ const before = treeBytes(path.join(out, 'pages'));+ const outsideBefore = treeBytes(outside);+ const realRename = fs.renameSync;+ let swap = null;+ t.mock.method(fs, 'renameSync', function (from, to) {+ const result = realRename.call(this, from, to);+ const top = staged(to) ? null : topFolder(out, to, '.pages-replace.');+ if (top && !swap && path.basename(String(to)) === 'page.tsx' && path.basename(path.dirname(String(to))) === SWAP_A) {+ // The first page's page.tsx is written whole; then the swap folder is moved away and a junction put at its name.+ swap = top;+ hookRetry(() => realRename(top, path.join(out, 'moved-away')));+ hookRetry(() => fs.symlinkSync(outside, top, 'junction'));+ }+ return result;+ });+ const lines = stderrLines(t);+ let error;+ await assert.rejects(download(out), (e) => { error = e; return true; });+ t.mock.restoreAll();+ assert.ok(swap, 'the swap folder was replaced');+ assert.strictEqual(error.code, 'UNSAFE_OUTPUT', error.stack);+ assert.ok(error.message.includes(path.basename(swap)), error.message);+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'nothing written to, or removed from, where the junction points');+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before, 'the maker\'s pages/ as it was');+ assert.ok(fs.lstatSync(swap).isSymbolicLink(), 'the junction is left where it was put');+ assert.ok(fs.existsSync(path.join(out, 'moved-away', 'new', SWAP_A, 'page.tsx')), 'the swap folder moved away is left as it is');+ const warnings = lines.filter((l) => l.includes(path.basename(swap)));+ assert.strictEqual(warnings.length, 1, lines.join(''));+ assert.match(warnings[0], /^WARNING: the folder .* the downloaded pages were written to was not removed: it, or a folder in it, is no longer the folder this download made there .*Look into it before you delete anything in it\.\n$/);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+ });++ test(`${caller}: a page folder of the new tree replaced by a junction once its files are written is refused before the maker's pages/ is moved: nothing published from where it points (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-pagedir-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const outsideBefore = treeBytes(outside);+ const realMkdir = fs.mkdirSync;+ let swap = null;+ let pageDir = null;+ t.mock.method(fs, 'mkdirSync', function (p, ...rest) {+ const top = staged(p) ? null : topFolder(out, p, '.pages-replace.');+ if (top && !pageDir && path.basename(String(p)) === SWAP_B && path.basename(path.dirname(String(p))) === 'new') {+ // The first page is written whole; its folder in `new` is moved away and a junction put at its name, before the second page.+ swap = top;+ pageDir = path.join(path.dirname(String(p)), SWAP_A);+ hookRetry(() => fs.renameSync(pageDir, path.join(out, 'moved-away')));+ hookRetry(() => fs.symlinkSync(outside, pageDir, 'junction'));+ }+ return realMkdir.call(this, p, ...rest);+ });+ const lines = stderrLines(t);+ let error;+ await assert.rejects(download(out), (e) => { error = e; return true; });+ t.mock.restoreAll();+ assert.ok(pageDir, 'the page folder was replaced');+ assert.strictEqual(error.code, 'UNSAFE_OUTPUT', error.stack);+ assert.ok(error.message.includes(path.join(path.basename(swap), 'new', SWAP_A)), error.message);+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before, 'the maker\'s pages/ as it was, not moved aside');+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'nothing written to, moved from or removed from where the junction points');+ assert.ok(fs.lstatSync(pageDir).isSymbolicLink(), 'the junction is left where it was put');+ const warnings = lines.filter((l) => l.includes(path.basename(swap)));+ assert.strictEqual(warnings.length, 1, lines.join(''));+ assert.match(warnings[0], /^WARNING: the folder .* the downloaded pages were written to was not removed: it, or a folder in it, is no longer the folder this download made there .*Look into it before you delete anything in it\.\n$/);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+ });++ test(`${caller}: a swap folder replaced by a junction while the move into pages/ is refused for a moment moves no tree from where it points, and the error says where the previous pages were moved (#814)`, async (t) => {+ freshRenameWaitTotal(t);+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-retry-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ fs.mkdirSync(path.join(outside, 'new', SWAP_A));+ fs.writeFileSync(path.join(outside, 'new', SWAP_A, 'page.tsx'), 'not the download\'s page');+ const before = treeBytes(path.join(out, 'pages'));+ const outsideBefore = treeBytes(outside);+ const realRename = fs.renameSync;+ let swap = null;+ let attempts = 0;+ t.mock.method(fs, 'renameSync', function (from, to) {+ const top = staged(from) || staged(to) ? null : topFolder(out, from, '.pages-replace.');+ if (top && path.basename(String(from)) === 'new' && path.basename(String(to)) === 'pages') {+ attempts += 1;+ if (!swap) {+ // A lock refuses the first move in (Windows waits and tries again); meanwhile the swap folder is moved away and a junction+ // put at its name.+ swap = top;+ hookRetry(() => realRename(top, path.join(out, 'moved-away')));+ hookRetry(() => fs.symlinkSync(outside, top, 'junction'));+ throw Object.assign(new Error('EBUSY: injected, rename'), { code: 'EBUSY', syscall: 'rename' });+ }+ }+ return realRename.call(this, from, to);+ });+ const lines = stderrLines(t);+ let error;+ await assert.rejects(download(out), (e) => { error = e; return true; });+ t.mock.restoreAll();+ assert.ok(swap, 'the swap folder was replaced');+ assert.strictEqual(attempts, 1, 'no later attempt reached the rename');+ assert.strictEqual(error.code, 'UNSAFE_OUTPUT', error.stack);+ assert.ok(error.message.includes(path.join(path.basename(swap), 'previous')) && /so they were not moved back/.test(error.message), error.message);+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'nothing moved from, written to or removed from where the junction points');+ assert.deepStrictEqual(treeBytes(path.join(out, 'moved-away', 'previous')), before, 'the maker\'s pages, whole, where the swap folder was moved');+ assert.ok(!fs.existsSync(path.join(out, 'pages')), 'no pages/ published');+ assert.ok(fs.lstatSync(swap).isSymbolicLink(), 'the junction is left where it was put');+ assert.deepStrictEqual(lines.filter(swapWarning), [], 'nothing was cleaned up, so nothing to warn of');+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+ });++ test(`${caller}: with no pages/ yet, the download writes it, warns nothing and leaves no swap folder (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-first-'));+ try {+ const lines = stderrLines(t);+ await download(out);+ t.mock.restoreAll();+ assertDownloadedTree(out, 'pages/ is written');+ assert.deepStrictEqual(lines.filter(swapWarning), []);+ assert.deepStrictEqual(leftovers(out), []);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });++ test(`${caller}: a swap folder name that is already taken is left as it is, and another name is made (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-taken-'));+ try {+ seedEditedPages(out);+ const real = fs.mkdirSync;+ const tried = [];+ t.mock.method(fs, 'mkdirSync', function (p, ...rest) {+ if (topFolder(out, p, '.pages-replace.') === path.resolve(String(p))) {+ tried.push(String(p));+ // The first name tried is taken by the time the download makes it (another run's folder, or the maker's).+ if (tried.length === 1) {+ real.call(fs, p);+ fs.writeFileSync(path.join(String(p), 'keep.txt'), 'someone else\'s');+ }+ }+ return real.call(this, p, ...rest);+ });+ const lines = stderrLines(t);+ await download(out);+ t.mock.restoreAll();+ assert.strictEqual(tried.length, 2, 'a second name was made');+ assert.notStrictEqual(tried[0], tried[1]);+ assertDownloadedTree(out, 'pages/ is replaced');+ assert.deepStrictEqual(leftovers(out), [path.basename(tried[0])], 'the taken folder is not removed, and the swap folder made is');+ assert.deepStrictEqual(treeBytes(tried[0]), { 'keep.txt': Buffer.from('someone else\'s').toString('hex') });+ assert.deepStrictEqual(lines.filter(swapWarning), [], 'one with no previous pages in it is not named');+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });++ test(`${caller}: a swap folder an earlier download left with previous pages in it is named in one warning, and not touched (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-stranded-'));+ const clean = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-clean-'));+ try {+ const STRANDED = '.pages-replace.1.deadbeef.tmp';+ const NEW_ONLY = '.pages-replace.2.cafef00d.tmp';+ for (const dir of [out, clean]) seedEditedPages(dir);+ fs.mkdirSync(path.join(out, STRANDED, 'previous'), { recursive: true });+ fs.cpSync(path.join(out, 'pages'), path.join(out, STRANDED, 'previous'), { recursive: true });+ fs.mkdirSync(path.join(out, NEW_ONLY, 'new', SWAP_A), { recursive: true });+ fs.writeFileSync(path.join(out, NEW_ONLY, 'new', SWAP_A, 'page.tsx'), DOWNLOADED_A);+ const strandedBefore = treeBytes(path.join(out, STRANDED));+ const newOnlyBefore = treeBytes(path.join(out, NEW_ONLY));++ const lines = stderrLines(t);+ await download(out);+ const cleanAt = lines.length;+ await download(clean);+ t.mock.restoreAll();++ assertDownloadedTree(out, 'pages/ is replaced all the same');+ assert.deepStrictEqual(leftovers(out).sort(), [STRANDED, NEW_ONLY].sort(), 'both left where they are');+ assert.deepStrictEqual(treeBytes(path.join(out, STRANDED)), strandedBefore);+ assert.deepStrictEqual(treeBytes(path.join(out, NEW_ONLY)), newOnlyBefore);+ const warning = `WARNING: ${path.join(out, STRANDED, 'previous')} holds the page folder as it was before an earlier download that stopped part-way: if it has page edits you need, copy them back into ${path.join(out, 'pages')}, then delete ${path.join(out, STRANDED)}.\n`;+ const own = lines.slice(0, cleanAt);+ assert.deepStrictEqual(own.filter((l) => l.includes('.pages-replace.')), [warning], 'one warning, for the folder with previous pages only');+ // Apart from that warning, the download says what a download with no folder left says.+ const shape = (list, dir) => list.filter((l) => l !== warning).map((l) => l.split(dir).join('<out>'));+ assert.deepStrictEqual(shape(own, out), shape(lines.slice(cleanAt), clean));+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(clean, { recursive: true, force: true });+ }+ });++ // A child process downloads into <out> and is stopped dead at a boundary of the swap (page-swap-crash-child.js); the disk is checked,+ // then a download is run again in the same <out>: it replaces pages/, and every folder the stopped one left is left byte for byte.+ for (const point of ['partial', 'staged', 'aside', 'in', 'removed']) {+ test(`${caller}: stopped dead at '${point}', the disk holds the maker's pages whole, and the next download replaces pages/ without touching what was left (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), `dl-swap-crash-${point}-`));+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const child = spawnSync(process.execPath, [CRASH_CHILD, out, mode, point], { encoding: 'utf8', timeout: 120000 });+ assert.strictEqual(child.status, 86, `the child stopped at '${point}': ${child.stderr}`);++ const swaps = leftovers(out);+ const swap = swaps.length ? path.join(out, swaps[0]) : null;+ const has = (rel) => fs.existsSync(path.join(swap, rel));+ if (point === 'removed') {+ assert.deepStrictEqual(swaps, []);+ assertDownloadedTree(out, 'the new tree is in place');+ } else {+ assert.strictEqual(swaps.length, 1, swaps.join());+ assert.ok(swaps[0].startsWith('.pages-replace.'));+ }+ if (point === 'partial' || point === 'staged') {+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before, 'pages/ as it was');+ assert.ok(!has('previous'));+ assert.strictEqual(fs.readFileSync(path.join(swap, 'new', SWAP_A, 'page.tsx'), 'utf8'), DOWNLOADED_A);+ assert.strictEqual(has(path.join('new', SWAP_B, 'page.tsx')), point === 'staged', 'the second page is written only once the tree is whole');+ }+ if (point === 'aside') {+ assert.ok(!fs.existsSync(path.join(out, 'pages')), 'no pages/ between the two moves');+ assert.deepStrictEqual(treeBytes(path.join(swap, 'previous')), before, 'the maker\'s pages, whole');+ assert.ok(has(path.join('new', SWAP_B, 'page.tsx')), 'the new tree, whole');+ }+ if (point === 'in') {+ assertDownloadedTree(out, 'the new tree is in place');+ assert.deepStrictEqual(treeBytes(path.join(swap, 'previous')), before, 'the maker\'s pages, whole');+ assert.ok(!has('new'));+ }++ const left = Object.fromEntries(swaps.map((n) => [n, treeBytes(path.join(out, n))]));+ const lines = stderrLines(t);+ await download(out);+ t.mock.restoreAll();+ assertDownloadedTree(out, 'the next download replaces pages/');+ assert.deepStrictEqual(leftovers(out), swaps, 'it removes its own swap folder, and only that');+ for (const n of swaps) assert.deepStrictEqual(treeBytes(path.join(out, n)), left[n], `${n} is left byte for byte`);+ const named = lines.filter((l) => l.includes('.pages-replace.'));+ if (point === 'aside' || point === 'in') {+ assert.strictEqual(named.length, 1, lines.join(''));+ assert.ok(named[0].startsWith(`WARNING: ${path.join(swap, 'previous')} holds the page folder as it was`), named[0]);+ } else {+ assert.deepStrictEqual(named, [], 'a folder with no previous pages in it is not named');+ }+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });+ }+}++test('the managed download: a staging folder replaced by a junction the moment it is made is refused before anything is written, and what it points to is untouched (#814)', async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-stage-plant-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const outsideBefore = treeBytes(outside);+ const planted = plantAtMkdir(t, out, '.download-pages.', outside);+ const lines = stderrLines(t);+ await assert.rejects(swapDownload(out, true), (e) => e.code === 'UNSAFE_OUTPUT' && e.message.includes(path.basename(planted[0])));+ t.mock.restoreAll();+ assert.strictEqual(planted.length, 1, 'the staging folder was replaced');+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'nothing written to, or removed from, where the junction points');+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before);+ assert.deepStrictEqual(leftovers(out), [path.basename(planted[0])], 'the junction is left where it was put');+ assert.ok(fs.lstatSync(planted[0]).isSymbolicLink());+ assert.deepStrictEqual(lines.filter(swapWarning), [], 'no clean-up was tried through it');+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+});++test('a download that replaces pages/ writes the same tree as before and leaves no swap folder; a managed download not yet published leaves pages/ untouched', async () => {+ for (const [caller, download] of SWAP_CALLERS) {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-ok-'));+ try {+ seedEditedPages(out);+ await download(out);+ assertDownloadedTree(out, `${caller}: the app's pages only, as before`);+ assert.deepStrictEqual(leftovers(out), [], caller);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ }+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-unpublished-'));+ try {+ seedEditedPages(out);+ const before = treeBytes(path.join(out, 'pages'));+ const result = await runDownload({ ...pagesApp([SWAP_A, SWAP_B]), genpage: swapGenpage(), outDir: out, stagePages: true });+ assert.ok(result.ok, JSON.stringify(result));+ result.stagedPages.check();+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before);+ assert.deepStrictEqual(leftovers(out), []);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+});++// ── the CLI: every download stages its page tree and publishes it only after everything that can still stop it (#814) ──────────────────++const { main: downloadMain } = require('../download-model-app.js');++// The first page navigates to the second, so the download rewrites its page.tsx (the navigation id becomes a PAGEREF_ token).+const NAVIGATING_A = `export default function A() {\n Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "${SWAP_B}", data: {} });\n return null;\n}\n`;+const navigatingGenpage = () => fakeGenpage({ pages: [{ pageId: SWAP_A, name: 'Alpha', source: NAVIGATING_A }, { pageId: SWAP_B, name: 'Beta' }] });++// download-model-app.js main over the two-page app, with only its connections replaced: the real runDownload runs, as main asks it to+// (`asked` keeps what it was asked), and `wrap` may change the result it answers. Answers what main emitted or threw, what it and the+// download printed, and every SDK and page backend call the download made.+async function cliDownload(t, out, { argv = [], wrap, validateAppSpec, ask = (args) => args } = {}) {+ const app = pagesApp([SWAP_A, SWAP_B]);+ const genpage = navigatingGenpage();+ const requests = [];+ let recording = false;+ const sdk = new Proxy(app.sdk, {+ get(target, prop) {+ const value = target[prop];+ if (typeof value !== 'function') return value;+ return (...args) => { if (recording) requests.push(`${String(prop)} ${JSON.stringify(args)}`); return value.apply(target, args); };+ },+ });+ const asked = [];+ const emitted = [];+ const said = [];+ const printed = stderrLines(t);+ let thrown = null;+ try {+ await downloadMain({+ argv: ['--env', 'https://contoso.crm.dynamics.com', '--app', app.appUnique, '--out', out, ...argv],+ stderr: { write: (text) => { said.push(String(text)); return true; } },+ exit: () => {},+ emitResult: (ok, payload) => emitted.push({ ok, payload }),+ preflightAuth: async () => ({ ok: true }),+ makeDownloadSdk: async () => ({ sdk, cleanup() {} }),+ makeGenpageSdk: () => genpage,+ runDownload: async (args) => {+ asked.push(args);+ recording = true;+ try {+ const result = await runDownload(ask(args));+ return wrap ? wrap(result) : result;+ } finally {+ recording = false;+ }+ },+ ...(validateAppSpec ? { validateAppSpec } : {}),+ });+ } catch (e) {+ thrown = e;+ }+ t.mock.restoreAll();+ return { asked, emitted, said: said.join(''), printed: printed.join(''), thrown, requests, pageCalls: genpage.calls.map((c) => `${c.method} ${JSON.stringify(c.args)}`) };+}++const MAKER_SPEC = '{\n "note": "the maker\'s app-spec.json"\n}\n';++// What a stop leaves to compare: pages/ byte for byte, the spec as it was, and no hidden folder of the download's.+function assertNothingPublished(out, before, label) {+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before, `${label}: the maker's edited page and their own page are as they were`);+ assert.deepStrictEqual(leftovers(out), [], `${label}: no staging or swap folder is left`);+ assert.strictEqual(fs.readFileSync(path.join(out, 'app-spec.json'), 'utf8'), MAKER_SPEC, `${label}: app-spec.json is unchanged`);+}++const CLI_STOPS = [+ ['a lossy download without --allow-lossy-download', {+ wrap: (r) => (r.ok ? { ...r, droppedSubareas: 1, droppedSubareaDetails: [{ type: 'Dashboard', id: 'd1', title: 'Board' }] } : r),+ }, (res) => {+ assert.strictEqual(res.emitted.length, 1);+ assert.strictEqual(res.emitted[0].ok, false);+ assert.match(res.emitted[0].payload.error, /1 sitemap subarea\(s\) could not be round-tripped/);+ }],+ ['a downloaded App Spec that fails validation', {+ validateAppSpec: () => ({ ok: false, errors: ['injected'], warnings: [] }),+ }, (res) => {+ assert.strictEqual(res.emitted.length, 1);+ assert.strictEqual(res.emitted[0].ok, false);+ assert.strictEqual(res.emitted[0].payload.error, 'downloaded App Spec failed validation');+ }],+ ['a write of the navigation rewrite of a page.tsx that fails', {+ fault: (t) => {+ const realOpen = fs.openSync;+ const failed = [];+ // writeFileSafe's temporary file for <pages>/<A>/page.tsx, the rewrite's own write: under the staging folder now, under <out>+ // itself before. writePageTree writes into its swap folder's `new` instead, so it is not hit.+ t.mock.method(fs, 'openSync', function (p, flags, ...rest) {+ const dir = path.dirname(String(p));+ if (flags === 'wx' && path.basename(String(p)).startsWith('.page.tsx.') && path.basename(dir) === SWAP_A && path.basename(path.dirname(dir)) === 'pages') {+ failed.push(String(p));+ throw Object.assign(new Error(`ENOSPC: injected, open '${p}'`), { code: 'ENOSPC', syscall: 'open', path: String(p) });+ }+ return realOpen.call(this, p, flags, ...rest);+ });+ return failed;+ },+ }, (res, failed) => {+ assert.strictEqual(failed.length, 1, 'the rewrite of the navigating page was the write that failed');+ assert.ok(res.thrown && res.thrown.code === 'IO_ERROR' && /ENOSPC: injected/.test(res.thrown.message), String(res.thrown && res.thrown.stack));+ assert.deepStrictEqual(res.emitted.filter((e) => e.ok), [], 'no success emitted');+ }],+];++for (const [stop, { wrap, validateAppSpec, fault }, assertStopped] of CLI_STOPS) {+ test(`the CLI without --include-managed: ${stop} stops the download with the maker's pages/ and app-spec.json as they were, and nothing left (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-stop-'));+ try {+ seedEditedPages(out);+ fs.writeFileSync(path.join(out, 'app-spec.json'), MAKER_SPEC);+ const before = treeBytes(path.join(out, 'pages'));+ const failed = fault ? fault(t) : null;+ const res = await cliDownload(t, out, { wrap, validateAppSpec });+ assert.strictEqual(res.asked.length, 1);+ assertStopped(res, failed);+ assertNothingPublished(out, before, stop);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });+}++// The staged tree was read back and validated; the tree the swap writes for publication is written again. An entry of that tree that+// is gone before the swap (a page folder, or one file of it) is not a tree to publish: what the maker had is kept, byte for byte.+for (const [missing, removed] of [['a page folder', []], ['the page.tsx of a page folder', ['page.tsx']]]) {+ test(`the CLI without --include-managed: ${missing} of the tree written for publication, removed before the swap, stops the download with every output as it was (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-missing-'));+ try {+ seedEditedPages(out);+ fs.writeFileSync(path.join(out, 'app-spec.json'), MAKER_SPEC);+ fs.mkdirSync(path.join(out, '.maker-workspace'));+ fs.writeFileSync(path.join(out, '.maker-workspace', 'last-applied.json'), 'the maker\'s baseline\r\n');+ fs.writeFileSync(path.join(out, '.maker-workspace', 'managed-fragments-earlier.json'), 'the maker\'s fragments\r\n');+ const before = treeBytes(out);+ const mkdir = fs.mkdirSync;+ let gone = null;+ // The swap's own `new/<B>` (not the staging folder's): page A of the tree to publish is written in full by then.+ t.mock.method(fs, 'mkdirSync', function (p, ...args) {+ if (!gone && !staged(p) && path.basename(String(p)) === SWAP_B && path.basename(path.dirname(String(p))) === 'new') {+ gone = path.join(path.dirname(String(p)), SWAP_A, ...removed);+ fs.rmSync(gone, { recursive: true });+ }+ return mkdir.call(this, p, ...args);+ });+ const res = await cliDownload(t, out);+ assert.ok(gone, 'page A of the tree to publish was removed before page B was written');+ assert.deepStrictEqual(res.emitted.filter((e) => e.ok), [], `no success: ${JSON.stringify(res.emitted)}`);+ assert.ok(res.thrown && res.thrown.code === 'IO_ERROR', String(res.thrown && res.thrown.stack));+ assert.ok(res.thrown.message.includes(path.join(SWAP_A, ...removed)) && /no longer there \(ENOENT\)/.test(res.thrown.message), res.thrown.message);+ assert.deepStrictEqual(treeBytes(out), before, 'pages/, the spec, the baseline and the fragments file are as they were');+ assert.deepStrictEqual(leftovers(out), [], 'no staging or swap folder is left');+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+ });+}++// Only a missing path (ENOENT, ENOTDIR) shows an entry is gone: any other error of the last inspection says so, with its code.+test('writePageTree: a file of the new tree that cannot be inspected before the swap is named as such, not as gone, and pages/ is as it was (#814)', () => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-inspect-'));+ try {+ seedEditedPages(out);+ const before = treeBytes(out);+ const suffix = path.join('new', SWAP_A, 'page.tsx');+ const eio = Object.assign(new Error('EIO: injected, lstat'), { code: 'EIO', syscall: 'lstat' });+ let written = false;+ let reads = 0;+ let stillThere = null;+ // Once the file is in place (writeFileSafe's rename onto it), the guard's own check reads it first; the second read is the final+ // check's, and it fails while the file is there.+ const faulty = { ...fs, renameSync(from, to) {+ fs.renameSync(from, to);+ if (String(to).endsWith(suffix)) written = true;+ }, lstatSync(p, ...args) {+ if (written && String(p).endsWith(suffix) && ++reads === 2) {+ stillThere = fs.lstatSync(p).isFile();+ throw eio;+ }+ return fs.lstatSync(p, ...args);+ } };+ assert.throws(() => writePageTree(path.join(out, 'pages'), [{ pageId: SWAP_A, files: { 'page.tsx': DOWNLOADED_A } }], { fs: faulty, warn: () => {} }), (e) => {+ assert.strictEqual(e.code, 'IO_ERROR');+ assert.strictEqual(e.cause, eio);+ assert.match(e.message, /the file .*page\.tsx this download wrote could not be inspected \(EIO\)\. The page folder is as it was/);+ assert.doesNotMatch(e.message, /no longer there/);+ return true;+ });+ assert.strictEqual(stillThere, true, 'the file was there when its inspection failed');+ assert.deepStrictEqual(treeBytes(out), before, 'pages/ is as it was');+ assert.deepStrictEqual(leftovers(out), [], 'the swap folder is removed');+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+});++test('the CLI without --include-managed: a successful download answers, asks, prints and writes exactly what it did when it wrote pages/ itself (#814)', async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-cli-same-'));+ const seed = () => {+ for (const name of fs.readdirSync(out)) fs.rmSync(path.join(out, name), { recursive: true, force: true });+ seedEditedPages(out);+ };+ try {+ // As the CLI ran before: the same main, with runDownload asked to write pages/ itself.+ seed();+ const direct = await cliDownload(t, out, { ask: ({ stagePages, ...args }) => args });+ const directTree = treeBytes(out);+ seed();+ const now = await cliDownload(t, out);+ const nowTree = treeBytes(out);+ assert.strictEqual(now.asked[0].stagePages, true, 'the CLI stages the page tree');+ assert.strictEqual(direct.thrown, null, String(direct.thrown && direct.thrown.stack));+ assert.strictEqual(now.thrown, null, String(now.thrown && now.thrown.stack));+ assert.strictEqual(now.emitted.length, 1);+ assert.strictEqual(now.emitted[0].ok, true, JSON.stringify(now.emitted));+ assert.deepStrictEqual(now.emitted, direct.emitted, 'the same result');+ assert.deepStrictEqual(now.requests, direct.requests, 'the same SDK requests');+ assert.deepStrictEqual(now.pageCalls, direct.pageCalls, 'the same page backend calls');+ assert.strictEqual(now.said, direct.said, 'the same lines from main');+ assert.strictEqual(now.printed, direct.printed, 'the same lines from the download');+ assert.deepStrictEqual(nowTree, directTree, 'the same spec, baseline and pages/, byte for byte');+ assert.ok(fs.readFileSync(path.join(out, 'pages', SWAP_A, 'page.tsx'), 'utf8').includes('PAGEREF_'), 'the navigating page was rewritten');+ assert.ok(fs.existsSync(path.join(out, 'app-spec.json')));+ assert.deepStrictEqual(leftovers(out), []);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+});++test('writePageTree on Windows: a moment\'s lock on the move into pages/ is waited out, but the move of the maker\'s pages/ aside is one attempt (#814)', (t) => {+ freshRenameWaitTotal(t);+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-win32-'));+ try {+ seedEditedPages(out);+ const pagesRoot = path.join(out, 'pages');+ const before = treeBytes(pagesRoot);+ const tree = [{ pageId: SWAP_A, files: { 'page.tsx': DOWNLOADED_A } }];+ const win32 = { platform: 'win32', pause: () => {} };+ // An fs whose folder rename that `match` picks is refused with EBUSY (a scanner holding a file in it) `times` times, then goes through.+ const locked = (match, times) => {+ const calls = [];+ let left = times;+ const fsImpl = { ...fs, renameSync(from, to) {+ if (match(from, to)) {+ calls.push([from, to]);+ if (left > 0) {+ left -= 1;+ throw Object.assign(new Error('EBUSY: resource busy or locked, rename'), { code: 'EBUSY', syscall: 'rename' });+ }+ }+ return fs.renameSync(from, to);+ } };+ return { calls, fsImpl };+ };++ const aside = locked((from, to) => path.basename(to) === 'previous', 1);+ assert.throws(() => writePageTree(pagesRoot, tree, { fs: aside.fsImpl, rename: win32, warn: () => {} }), (e) => e.code === 'EBUSY' && /could not be moved aside \(EBUSY\)/.test(e.message));+ assert.strictEqual(aside.calls.length, 1, 'the maker\'s folder is moved once or not at all: a wait would let the checks made on it go stale');+ assert.deepStrictEqual(treeBytes(pagesRoot), before);+ assert.deepStrictEqual(leftovers(out), []);++ const into = locked((from, to) => path.basename(from) === 'new' && path.basename(to) === 'pages', 2);+ const warned = [];+ writePageTree(pagesRoot, tree, { fs: into.fsImpl, rename: win32, warn: (line) => warned.push(line) });+ assert.strictEqual(into.calls.length, 3, 'refused twice, then moved');+ assert.deepStrictEqual(treeBytes(pagesRoot), { [`${SWAP_A}/page.tsx`]: Buffer.from(DOWNLOADED_A).toString('hex') });+ assert.deepStrictEqual(leftovers(out), []);+ assert.deepStrictEqual(warned, []);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ }+});++test('writePageTree, a move into pages/ waited out: each attempt is checked first, so a swap folder replaced by a junction during the wait moves nothing from where it points (#814)', (t) => {+ freshRenameWaitTotal(t);+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-wait-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ fs.mkdirSync(path.join(outside, 'new', SWAP_A));+ fs.writeFileSync(path.join(outside, 'new', SWAP_A, 'page.tsx'), 'not the download\'s page');+ const pagesRoot = path.join(out, 'pages');+ const before = treeBytes(pagesRoot);+ const outsideBefore = treeBytes(outside);+ const renames = [];+ const fsImpl = { ...fs, renameSync(from, to) {+ if (path.basename(from) === 'new' && path.basename(to) === 'pages') {+ renames.push(from);+ throw Object.assign(new Error('EBUSY: resource busy or locked, rename'), { code: 'EBUSY', syscall: 'rename' });+ }+ return fs.renameSync(from, to);+ } };+ let swap = null;+ // The wait between two attempts (Windows' lock wait, on every platform here): the swap folder is moved away and a junction put at its name.+ const pause = () => {+ if (swap) return;+ swap = path.dirname(renames[0]);+ hookRetry(() => fs.renameSync(swap, path.join(out, 'moved-away')));+ hookRetry(() => fs.symlinkSync(outside, swap, 'junction'));+ };+ const warned = [];+ assert.throws(+ () => writePageTree(pagesRoot, [{ pageId: SWAP_A, files: { 'page.tsx': DOWNLOADED_A } }], { fs: fsImpl, rename: { platform: 'win32', pause }, warn: (line) => warned.push(line) }),+ (e) => e.code === 'UNSAFE_OUTPUT' && /so they were not moved back/.test(e.message),+ );+ assert.ok(swap, 'the move in was waited out once');+ assert.strictEqual(renames.length, 1, 'the attempt after the wait was refused before it renamed');+ assert.deepStrictEqual(treeBytes(outside), outsideBefore);+ assert.deepStrictEqual(treeBytes(path.join(out, 'moved-away', 'previous')), before);+ assert.ok(!fs.existsSync(pagesRoot));+ assert.deepStrictEqual(warned, []);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+});++// The managed download reads its staged tree back from the staging folder (the page metadata the spec states, each page file whose page+// ids it rewrites, and every file it then publishes): what it reads is what it publishes. A staging folder replaced by a junction once+// written, between two of those reads, or after the last of them (found when it is removed) hands on nothing from where the junction+// points: the download is refused, and pages/ is not written.+for (const point of ['once written', 'between two reads', 'after the last read']) {+ test(`the managed download, its staging folder replaced by a junction ${point}: refused, nothing read through it published, pages/ and the junction's target untouched (#814)`, async (t) => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-stage-read-'));+ const outside = outsideTree();+ try {+ seedEditedPages(out);+ for (const id of [SWAP_A, SWAP_B]) {+ fs.mkdirSync(path.join(outside, 'pages', id), { recursive: true });+ fs.writeFileSync(path.join(outside, 'pages', id, 'page.tsx'), `not the download's page ${id}`);+ fs.writeFileSync(path.join(outside, 'pages', id, 'config.json'), '{"dataSources":[]}');+ }+ const before = treeBytes(path.join(out, 'pages'));+ const outsideBefore = treeBytes(outside);+ // The download makes its staging folder in <out> named by its real path (assertSafeOutputDir answers realpath.native), which is not+ // the path os.tmpdir() gave when a folder above it is a link or a short name: /var -> /private/var on macOS, C:\Users\RUNNER~1 on+ // Windows CI. Match either name, or the hooks below never see the staging folder and nothing is planted.+ const outNames = new Set([out, fs.realpathSync.native(out)]);+ const isStage = (p) => outNames.has(path.dirname(p)) && path.basename(p).startsWith('.download-pages.');+ let planted = null;+ const plant = (stage) => {+ planted = stage;+ hookRetry(() => fs.renameSync(stage, path.join(out, 'moved-away')));+ hookRetry(() => fs.symlinkSync(outside, stage, 'junction'));+ };+ const lines = stderrLines(t);+ if (point === 'once written') {+ // The last write in the staging folder: the removal of writePageTree's own swap folder, once the tree is moved into place.+ const rm = fs.rmSync;+ t.mock.method(fs, 'rmSync', function (p) {+ const result = rm.apply(this, arguments);+ if (!planted && path.basename(String(p)).startsWith('.pages-replace.') && isStage(path.dirname(String(p)))) plant(path.dirname(String(p)));+ return result;+ });+ } else if (point === 'between two reads') {+ // The second read of the first page's page.tsx (rewritten, then read again for publication): the reads after it are of another folder.+ const read = fs.readFileSync;+ let seen = 0;+ t.mock.method(fs, 'readFileSync', function (p) {+ const result = read.apply(this, arguments);+ const file = String(p);+ if (!planted && path.basename(file) === 'page.tsx' && path.basename(path.dirname(file)) === SWAP_A && isStage(path.dirname(path.dirname(path.dirname(file)))) && ++seen === 2) {+ plant(path.dirname(path.dirname(path.dirname(file))));+ }+ return result;+ });+ } else {+ // The check of the staging folder its own removal makes, after everything was read from it (not the removal of writePageTree's swap folder in it).+ const lstat = fs.lstatSync;+ t.mock.method(fs, 'lstatSync', function (p) {+ if (!planted && isStage(String(p))) {+ const limit = Error.stackTraceLimit;+ Error.stackTraceLimit = Infinity;+ const stack = new Error().stack;+ Error.stackTraceLimit = limit;+ if (/\bremoveTreeWithRetry\b/.test(stack) && !/\bwritePageTree\b/.test(stack)) plant(String(p));+ }+ return lstat.apply(this, arguments);+ });+ }+ // Found at a read, the read is refused; found only at the removal, after the last read, what was read is refused all the same.+ const refusal = point === 'after the last read' ? /^refusing to use the pages read back from the download's staging folder .*, and pages\/ was not written$/ : /^refusing to use .* as an output directory: /;+ await assert.rejects(swapDownload(out, true), (e) => e.code === 'UNSAFE_OUTPUT' && e.message.includes(planted) && refusal.test(e.message));+ t.mock.restoreAll();+ assert.ok(planted, 'the staging folder was replaced');+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'nothing written, moved or removed where the junction points');+ assert.deepStrictEqual(treeBytes(path.join(out, 'pages')), before, 'pages/ is the maker\'s, as it was');+ // Its removal refused too (nothing is removed through a junction), and the folder named.+ const named = lines.filter((l) => l.includes('.download-pages.'));+ assert.strictEqual(named.length, 1, named.join(''));+ assert.ok(named[0].startsWith(`WARNING: the download's staging folder ${planted} was not removed: it, or a folder in it, is no longer the folder this download made there`), named[0]);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+ });+}+test('generatedFolders: each guarded fs method is refused on a path in a folder it made once that folder is replaced by a junction, and stays refused (#814)', () => {+ const base = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'dl-guard-')));+ const outside = outsideTree();+ try {+ const guard = generatedFolders(fs, (p) => p);+ const made = path.join(base, 'made');+ fs.mkdirSync(made);+ assert.strictEqual(guard.adopt(made), made);+ // While it is the folder made, the guarded fs acts as fs does.+ guard.fs.mkdirSync(path.join(made, 'new'));+ guard.fs.writeFileSync(path.join(made, 'new', 'a.txt'), 'a');+ assert.strictEqual(fs.readFileSync(path.join(made, 'new', 'a.txt'), 'utf8'), 'a');+ const source = path.join(base, 'source.txt');+ fs.writeFileSync(source, 'source');+ hookRetry(() => fs.renameSync(made, path.join(base, 'moved-away')));+ hookRetry(() => fs.symlinkSync(outside, made, 'junction'));+ const outsideBefore = treeBytes(outside);+ // `new/keep.txt` is a file where the junction points: an unchecked call would write, move or remove it.+ const target = path.join(made, 'new', 'keep.txt');+ const calls = [];+ for (const [name, at] of Object.entries(GUARDED_FS_METHODS)) {+ for (const i of at) calls.push([`${name} (argument ${i})`, () => guard.fs[name](...[0, 1].map((n) => (n === i ? target : source)))]);+ }+ calls.push(['realpathSync', () => guard.fs.realpathSync(path.join(made, 'new'))]);+ calls.push(['realpathSync.native', () => guard.fs.realpathSync.native(path.join(made, 'new'))]);+ calls.push(['verify', () => guard.verify(made)]);+ for (const [name, call] of calls) assert.throws(call, (e) => e.code === 'UNSAFE_OUTPUT', name);+ assert.deepStrictEqual(treeBytes(outside), outsideBefore, 'nothing written, moved or removed where the junction points');+ assert.deepStrictEqual(fs.readFileSync(source, 'utf8'), 'source');+ // A folder found replaced is not trusted again, even put back as it was.+ hookRetry(() => fs.rmSync(made));+ hookRetry(() => fs.renameSync(path.join(base, 'moved-away'), made));+ assert.throws(() => guard.fs.writeFileSync(path.join(made, 'new', 'b.txt'), 'b'), (e) => e.code === 'UNSAFE_OUTPUT');+ assert.throws(() => guard.fs.rmSync(base, { recursive: true }), (e) => e.code === 'UNSAFE_OUTPUT', 'nor is a folder that holds it removed');+ assert.ok(!fs.existsSync(path.join(made, 'new', 'b.txt')));+ // A path outside the folders made goes through as it is; a folder that is a junction is not adopted.+ guard.fs.writeFileSync(path.join(base, 'free.txt'), 'free');+ const planted = path.join(base, 'planted');+ fs.symlinkSync(outside, planted, 'junction');+ assert.throws(() => guard.adopt(planted), (e) => e.code === 'UNSAFE_OUTPUT');+ } finally {+ fs.rmSync(base, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+});++test('writePageTree, the staged readback and their helpers make no raw fs read, write, mkdir, rename or removal: each one in a folder they made goes through the one guarded fs (#814)', () => {+ const read = (file) => fs.readFileSync(path.join(__dirname, '..', file), 'utf8').replace(/\r\n/g, '\n');+ // A top-level function, from its `function` line to its closing brace (the first line that is just `}`).+ const body = (text, name) => {+ const start = text.search(new RegExp(`^(?:async )?function ${name}\\(`, 'm'));+ assert.ok(start >= 0, `function ${name} found`);+ return text.slice(start, text.indexOf('\n}\n', start) + 2);+ };+ const MUTATING = ['writeFile', 'appendFile', 'mkdir', 'mkdtemp', 'rename', 'rm', 'rmdir', 'unlink', 'open', 'copyFile', 'cp', 'symlink', 'link', 'chmod', 'truncate', 'utimes'];+ const READING = ['readFile', 'readdir', 'opendir', 'stat', 'lstat', 'exists', 'access', 'readlink', 'realpath'];+ const raw = (names, methods = MUTATING) => new RegExp(`(?<![\\w.])(?:${names})\\.(?:promises\\b|(?:${methods.join('|')})(?:Sync)?\\b|create(?:Write|Read)Stream\\b)`, 'g');+ // Each method that is a raw call here is one the guarded fs checks (realpathSync, and its .native, by a method of its own).+ for (const name of MUTATING.concat(READING.filter((m) => m !== 'realpath')).map((m) => `${m}Sync`).concat(['createWriteStream', 'createReadStream'])) {+ assert.ok(GUARDED_FS_METHODS[name], `${name} is guarded`);+ }+ const source = read('download-model-app.js');+ for (const name of ['writePageTree', 'warnStrandedPageTrees', 'ownedDir', 'generatedFolders', 'assertPageTreeReplaceable', 'assertNoPlantedPageLinks', 'makeHiddenDir', 'makePageStage', 'runDownload', 'parseDownloadedPages']) {+ const text = body(source, name);+ assert.deepStrictEqual(text.match(raw('fs|fsImpl')) || [], [], `${name}: a raw fs call`);+ // A read goes through the fs the function is given (the guarded one, for a folder the download made), never node's own.+ assert.deepStrictEqual(text.match(raw('fs', READING)) || [], [], `${name}: a raw fs read`);+ for (const call of text.match(/\b(?:writeFileSafe|renameWithRetry|removeTreeWithRetry)\([^;]*/g) || []) {+ assert.match(call, /\b(?:gfs|stage\.fs)\b/, `${name}: ${call}`);+ }+ // The only folder made unchecked is the one the maker named (or its parent): what is made in it goes through makeHiddenDir.+ for (const call of text.match(/\bassertSafeOutputDir\([^)]*create: true/g) || []) assert.match(call, /^assertSafeOutputDir\((?:shownRoot|outDir), /, `${name}: ${call}`);+ }+ // The managed download writes its staged tree, reads it back and rewrites its page files through the staging folder's guarded fs:+ // from the tree's write to the last read of it, no fs call is node's own, and each helper that takes an fs is given that one.+ const download = body(source, 'downloadApp');+ assert.match(download, /const pageTreeFs = stage \? stage\.fs : fs;\n {4}writePageTree\(treeRoot, read\.pages, \{ fs: pageTreeFs \}\);/);+ const from = download.indexOf('const pageTreeFs = stage');+ const to = download.indexOf('\n }\n', download.indexOf('stage.pages = read.pages.map('));+ assert.ok(from > 0 && to > from, 'the staged readback found');+ const readback = download.slice(from, to);+ assert.deepStrictEqual(readback.match(/(?<![\w.])fs\.\w+/g) || [], [], 'a raw fs call in the staged readback');+ const calls = readback.match(/\b(?:writePageTree|parseDownloadedPages|assertPlainFileTarget|writeFileSafe)\([^;]*/g) || [];+ assert.deepStrictEqual([...new Set(calls.map((c) => c.split('(')[0]))].sort(), ['assertPlainFileTarget', 'parseDownloadedPages', 'writeFileSafe', 'writePageTree']);+ for (const call of calls) assert.match(call, /\bpageTreeFs\b/, call);+ const reads = readback.match(/\b[\w.]+\.readFileSync\(/g) || [];+ assert.ok(reads.length >= 2);+ for (const call of reads) assert.strictEqual(call, 'pageTreeFs.readFileSync(', call);+ // The shared helpers act only through the fs they are given: safe-fs.js makes no call of node's own fs at all.+ const safeFs = read(path.join('lib', 'safe-fs.js'));+ assert.deepStrictEqual(safeFs.match(/(?<![\w.])fs\.\w+/g) || [], [], 'safe-fs.js');+ assert.deepStrictEqual(body(read(path.join('lib', 'rename-retry.js')), 'renameWithRetry').match(raw('fs')) || [], [], 'rename-retry.js renameWithRetry');+});++test('writePageTree refuses a link planted in pages/ before it makes anything: same refusal, no swap folder, the link and its target untouched', () => {+ const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-link-'));+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-swap-outside-'));+ try {+ fs.writeFileSync(path.join(outside, 'keep.txt'), 'keep');+ fs.mkdirSync(path.join(out, 'pages'));+ fs.symlinkSync(outside, path.join(out, 'pages', SWAP_A), 'junction');+ assert.throws(() => writePageTree(path.join(out, 'pages'), [{ pageId: SWAP_A, files: { 'page.tsx': DOWNLOADED_A } }]), (e) => e.code === 'UNSAFE_OUTPUT');+ assert.deepStrictEqual(leftovers(out), []);+ assert.ok(fs.lstatSync(path.join(out, 'pages', SWAP_A)).isSymbolicLink());+ assert.deepStrictEqual(fs.readdirSync(outside), ['keep.txt']);+ } finally {+ fs.rmSync(out, { recursive: true, force: true });+ fs.rmSync(outside, { recursive: true, force: true });+ }+});+test('runDownload: the ids are folder names only after the backend has read them — a navigation naming anything but a page id is never read, so it cannot name a path', async () => {const out = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-ids-'));try {@@ -3670,6 +4729,27 @@ test('a config that exists but cannot be READ is recorded unreadable, not treatefs.rmSync(root, { recursive: true, force: true });});+test('parseDownloadedPages: a refusal of the fs it reads with (a staging folder found replaced) stops it, never an unreadable config or an absent prompt (#814)', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'dl-refused-read-'));+ try {+ const d = path.join(root, '55555555-5555-5555-5555-555555555555');+ fs.mkdirSync(d, { recursive: true });+ fs.writeFileSync(path.join(d, 'page.tsx'), 'export default () => null;', 'utf8');+ fs.writeFileSync(path.join(d, 'config.json'), '{"dataSources":[]}', 'utf8');+ fs.writeFileSync(path.join(d, 'prompt.txt'), 'a prompt', 'utf8');+ for (const file of ['config.json', 'prompt.txt']) {+ const refusing = { ...fs, readFileSync(p, ...rest) {+ if (path.basename(String(p)) === file) throw Object.assign(new Error(`refusing to use ${root} as an output directory`), { code: 'UNSAFE_OUTPUT' });+ return fs.readFileSync(p, ...rest);+ } };+ const unreadable = [];+ assert.throws(() => parseDownloadedPages(root, root, null, unreadable, [], [], refusing), (e) => e.code === 'UNSAFE_OUTPUT', file);+ assert.deepStrictEqual(unreadable, [], file);+ }+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});// --- Task D: downloaded page config and prompt must be exact and fail closed ----------------------diff --git a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.jsindex 0c3d28a91..2b776a56a 100644--- a/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js+++ b/plugins/model-apps/scripts/tests/genpage-dispatch-contract.test.js@@ -420,6 +420,105 @@ test('the paths that re-upload a page after a browser-verify fix or a hand editassert.match(agents, /the build's pages phase halts as `pages-griffel-shorthand` in its pre-write scan/);});+// The scroll-context check (AB#6793599) rides on the same command, so every flow above that checks a page gets it. These pins hold the one thing the command line cannot show: which+// flows judge a page as generated (a missing scroll context is a problem: exit 3) and which as existing (`--existing`: it is a note for the maker). A generation flow that gained+// `--existing` would ship clipped pages again with no error; an edit flow that lost it would refuse a maker's small edit over a layout they chose. page-scroll.test.js runs the rule.+test('the generation flows judge a page\'s scroll context, and the flows that change an existing page report it as a note to offer the maker', () => {+ const docs = griffelDocs();+ const full = (text, target, name) => {+ const at = text.indexOf(`node "\${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file ${target}`);+ assert.ok(at >= 0, `${name} runs the checker`);+ assert.doesNotMatch(text.slice(at, text.indexOf('\n', at)), /--existing/, `${name} judges a generated page in full`);+ };+ const skill = docs['create flow'];+ const fastPath = skill.split(/#### 5b\. Single-page fast path/)[1].split(/#### 5c\. Multi-page/)[0];+ full(fastPath, "'<working-dir>/<filename>.tsx'", 'single-page generation');+ assert.match(squash(fastPath), /The same command checks that the page establishes a scroll context \(`references\/rules\.md`, \*\*Page Layout\*\*\)[^.]*\. `no-scroll-context`, `scroll-context-unproven` and `scroll-context-padding` are problems like any other, each with the edit that fixes it: apply it and run the check again\./);+ const multiPage = skill.split(/#### 5c\. Multi-page/)[1].split(/### Phase 6: Deploy/)[0];+ full(multiPage, "'<working-dir>/<filename>.tsx'", 'multi-page generation');+ assert.match(squash(multiPage), /its scroll context included \(step 9\)/);+ assert.match(squash(skill), /The upload does not check a page's scroll context: only `check-griffel-styles\.js` does \(Phase 5b step 9\)\./, 'the upload gate is not mistaken for this one');+ const fix = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'verify-flow.md')).split('## 7.5 Fix and Re-deploy')[1];+ full(fix, "'<working-dir>/<file>.tsx'", 'the browser-verify fix');+ assert.match(squash(fix), /The same command checks that the fixed page still establishes a scroll context/);+ // The same fix step is also reached from the edit flow, for a page that was downloaded: there it keeps `--existing`, and the edit flow says so on the way in. Without it, a fix+ // after an edit would be refused over a layout the maker chose (or the maker would be told to rewrite it).+ assert.ok(fix.includes(`node "\${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<page-id>/page.tsx' --existing`), 'a fix reached from the edit flow checks an existing page');+ assert.match(squash(fix), /If you came from \*\*Edit Phase 7\*\*, the page was downloaded, not generated, so check it as Edit Phase 5 does — with `--existing`/);+ assert.match(squash(fix), /Handle each note as Edit Phase 5 says: When the maker's requested edit/);+ const appBuilder = docs['app-builder'];+ full(appBuilder, '<working-dir>/<file>', 'app-builder generation');+ assert.match(squash(appBuilder), /The same command checks that each page establishes a scroll context/);++ const edit = docs['edit flow'];+ assert.ok(edit.includes(`node "\${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<page-id>/page.tsx' --existing`), 'an edited page is an existing one');+ const editVerify = edit.split('## Edit Phase 7')[1].split('## Edit Phase 8')[0];+ assert.match(squash(editVerify), /check the fix with the `--existing` command that 7\.5 gives for the edit flow, not the command for a generated page/, 'the edit flow enters the browser-verify fix as an existing page');+ // A downloaded page's scroll note is the maker's to accept, with one exception: a layout the maker asked to rewrite is new code written in this run, so it follows the rule, and the+ // maker is told. Both flows state it in the same words, and neither may read as leave to change a layout nobody asked to change.+ const ruling = (text) => {+ const s = squash(text);+ const at = s.indexOf("When the maker's requested edit itself rewrites the page's top-level layout");+ assert.ok(at >= 0, 'the ruling is stated');+ return s.slice(at, s.indexOf('to change.', at) + 'to change.'.length);+ };+ const [inEdit, inFix] = [ruling(edit), ruling(fix)];+ assert.equal(inFix, inEdit, 'the edit flow and the browser-verify fix state the ruling in the same words');+ assert.match(inEdit, /^When the maker's requested edit itself rewrites the page's top-level layout, that layout is new code written in this run and must follow the scroll rule: apply the remedy as part of that edit, and tell the maker in one sentence that you did\./, 'a rewrite the maker asked for: the remedy is applied, and the maker is told');+ assert.match(inEdit, /Any other scroll note on a downloaded page is offer-only: tell the maker that content below the fold may be cut off, offer the edit its message gives, and apply it only if they agree\./, 'any other note: offered, applied only on agreement');+ assert.match(inEdit, /A note is never a reason to change a layout the maker did not ask to change\.$/);+ for (const [name, text] of [['edit flow', edit], ['browser-verify fix', fix]]) {+ assert.doesNotMatch(squash(text), /(?:note|remedy|layout|scroll)[^.]*without asking/, `${name} never applies a scroll note without asking`);+ assert.doesNotMatch(text, /apply the\s+edit the note gives without asking/);+ assert.doesNotMatch(text, /only if they agree[\s\S]{0,80}unless the fix itself rewrites/, `${name} gives no exception to agreement beyond the maker's own rewrite`);+ }+ const editing = appBuilder.split('## Editing a deployed app')[1].split('## What the builder does')[0];+ assert.ok(editing.includes('node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file <page.tsx> --existing'), 'a page edited by hand is an existing one');+ assert.match(squash(editing), /`--existing` reports the page's scroll context \(`references\/rules\.md`, \*\*Page Layout\*\*\) in `notes` without changing the exit code/);++ // The rule the page builder writes from, and the worker's own instruction.+ const rules = squash(docs.rules);+ assert.match(rules, /\*\*The page must establish its own scroll context\.\*\*/);+ assert.match(rules, /`height: "100%"` \(bounded by the host's container\), `overflowY: "auto"` \(it scrolls\) and `boxSizing: "border-box"`/);+ assert.match(rules, /6\. \*\*A page with no scroll context is cut off below the fold, with no error\.\*\*/);+ assert.match(squash(docs['page-builder']), /- \*\*A scroll context\*\* — [^]*`height: "100%"`, `overflowY: "auto"` and `boxSizing: "border-box"`[^]*The orchestrator's `check-griffel-styles\.js` refuses a page without one\./);+});++// In the host nothing above the page scrolls (the window stays at the top), so a check that scrolls the window or reads the document's height sees a clipped page as a short one,+// and a snapshot lists cut-off elements too. These pins hold the browser check to the page's own scroller and to a measured proof that the last content can be seen.+test('browser verify finds the page\'s own scroller and proves the last content is inside the visible area', () => {+ const verify = readDoc(path.join(PLUGIN, 'skills', 'genpage', 'verify-flow.md'));+ const structural = verify.split('## 7.2 ')[1].split('## 7.3 ')[0];+ const visual = verify.split('## 7.4 ')[1].split('## 7.5 ')[0];+ for (const [name, text] of [['7.2', structural], ['7.4', visual]]) {+ assert.doesNotMatch(text, /window\.scroll(To|By)\(|document\.documentElement\.scrollHeight/, `${name} must not scroll or measure the window`);+ }+ assert.match(structural, /getComputedStyle\(el\)\.overflowY\)[^]*el\.scrollHeight > el\.clientHeight \+ 1/, 'the scroller is an element that scrolls and holds more than it shows');+ assert.match(structural, /el\.scrollTop = el\.scrollHeight;/, 'it is scrolled to the end');+ assert.match(structural, /lastContentVisible: lastContentBottom <= visibleBottom \+ 1/, 'the last content is measured against the lowest visible point');+ assert.match(structural, /if \(a === el \|\| getComputedStyle\(a\)\.overflowY !== 'visible'\)/, 'the visible area is cut by every clipping ancestor (a padded root overhangs the host)');+ assert.match(squash(structural), /A `browser_snapshot` is not proof that content can be seen/);+ assert.match(squash(structural), /Any entry is content below the visible area that nothing can scroll to: the page has no scroll context\./);+ assert.match(structural, /document\.querySelector\('\[data-verify-scroller\]'\)\.scrollTop = 0/, 'the reset scrolls the same element back');+ // A scroll region inside the page's scroller (a list in a fixed-height panel) is not cut off until its own end is: its content is left out of the page's last content, and each+ // region is scrolled to its end and measured the same way, so a padded region that overhangs its panel is still caught.+ const scripts = [...structural.matchAll(/```javascript\n([^]*?)```/g)].map((m) => m[1]);+ assert.equal(scripts.length, 6, 'find, cut-off, end of the scroller, its regions, one screen at a time, reset');+ const [, , end, regions] = scripts;+ const own = "const own = (d) => { for (let a = d.parentElement; a && a !== el; a = a.parentElement) if (scrolls(a)) return false; return true; };";+ for (const [name, script] of [['the end of the scroller', end], ['each region', regions]]) {+ assert.ok(script.includes(own), `${name} leaves out what a region of its own holds`);+ assert.match(script, /\.querySelectorAll\('\*'\)\]\.filter\(own\)/, `${name} measures only its own content`);+ assert.match(script, /lastContentVisible: lastContentBottom <= visibleBottom \+ 1/);+ assert.match(script, /if \(a === el \|\| getComputedStyle\(a\)\.overflowY !== 'visible'\)/);+ }+ assert.match(end, /regions \};/, 'the end proof says how many regions to check');+ assert.match(regions, /return regions\.map\(\(el\) => \{\s*el\.scrollTop = el\.scrollHeight;/, 'each region is scrolled to its own end');+ assert.match(squash(structural), /Every entry's `lastContentVisible` must be `true`/);+ assert.match(structural, /document\.querySelectorAll\('\[data-verify-scroller\] \*'\)\.forEach\(\(el\) => \{ if \(el\.scrollTop\) el\.scrollTop = 0; \}\)/, 'the reset scrolls the regions back too');+ assert.match(squash(visual), /scrolling the page's scroller \(7\.2\), not the window/);+});+// A page deployed by an earlier release can already hold a key Griffel drops (its only guard was a grep for `borderWidth`), and it renders without it today. Sending the same bytes again// ships nothing new, and refusing them stops a rebuild over a page nobody touched — whose way through, the longhands, CHANGES how the page renders. So the gates hold a page to what a run// would ADD, and say what each way out does. These are instructions nothing executes, so a document that drops the distinction — or the advice that goes with it — is invisible untildiff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.jsindex 670bf3d00..1e0e9fff2 100644--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js@@ -1655,10 +1655,30 @@ test('an UPDATE of a page that already has the keys — sent as it is, or editedassert.ok(warning.startsWith(`${file} updates a page that is already deployed, and the deployed page already had these, set the same, so the upload goes on. It writes CSS that Griffel drops at runtime, so the page renders without it as it does today: `), `${what}: ${warning}`);for (const needle of ['borderWidth', 'borderColor', 'borderStyle']) assert.ok(warning.includes(`${file}:${placeOf(local, needle)}: \`${needle}\` is not supported by Griffel`), `${what}: ${needle}, at its place in the file that is uploaded`);assert.ok(warning.includes(BOTH_WAYS_OUT), `${what}: both ways out`);- assert.match(warning, new RegExp(`Edit the file to do either \\(\`node scripts/check-griffel-styles\\.js --file ${escapeRe(commandArg(file))}\` lists every one\\); an upload that adds anything the check reports, or sets one of these to another value, is refused\\.$`), what);+ assert.match(warning, new RegExp(`Edit the file to do either \\(\`node scripts/check-griffel-styles\\.js --file ${escapeRe(commandArg(file))} --existing\` lists every one\\); an upload that adds anything the check reports, or sets one of these to another value, is refused\\.$`), what);}});+test('the check an UPDATE suggests is the one for a deployed page: with the Griffel key fixed, it exits 0 and reports a missing scroll context as a note, not a refusal', async () => {+ // A deployed page with a key Griffel drops and no scroll context (a bare root). The upload warns, and suggests the checker; run as suggested on the file once the key is+ // fixed, the checker must not turn the maker's Griffel fix into a refusal of the page's layout.+ const deployed = `${GRIFFEL_IMPORT}const useStyles = makeStyles({ root: { borderWidth: '1px' } });\nexport default function P() {\n const s = useStyles();\n return <div className={s.root}>rows</div>;\n}\n`;+ const { file, r } = await griffelUpdate(deployed, deployed);+ assert.strictEqual(r.ok, true, JSON.stringify(r.payload));+ const warning = r.payload.warnings.find((w) => /Griffel/.test(w));+ const command = /`node scripts\/check-griffel-styles\.js ([^`]+)`/.exec(warning)[1];+ assert.strictEqual(command, `--file ${commandArg(file)} --existing`);+ fs.writeFileSync(file, deployed.replace("borderWidth: '1px'", "borderTopWidth: '1px'"));+ const res = require('node:child_process').spawnSync(process.execPath, [path.join(__dirname, '..', 'check-griffel-styles.js'), '--file', file, '--existing'], { encoding: 'utf8' });+ assert.strictEqual(res.status, 0, res.stdout + res.stderr);+ const out = JSON.parse(res.stdout);+ assert.deepStrictEqual(out.problems, []);+ assert.deepStrictEqual(out.notes.map((n) => n.code), ['no-scroll-context']);+ // The same file run without --existing — what a create is told to run — is held to the scroll rule as a new page.+ const strict = require('node:child_process').spawnSync(process.execPath, [path.join(__dirname, '..', 'check-griffel-styles.js'), '--file', file], { encoding: 'utf8' });+ assert.strictEqual(strict.status, 3, strict.stdout);+});+test('an UPDATE that ADDS a key the deployed page did not have is refused, naming only the new key — and --overwrite-deployed is no way past it', async () => {const added = GRIFFEL_BAD.replace('});\nexport default', " card: { borderStyle: 'dashed' },\n});\nexport default");for (const extra of [[], ['--overwrite-deployed']]) {@@ -1672,7 +1692,8 @@ test('an UPDATE that ADDS a key the deployed page did not have is refused, naminassert.ok(error.includes(`${file}:${placeOf(added, "borderStyle: 'dashed'")}: \`borderStyle\` is not supported by Griffel`), 'the new key, where it is');for (const old of ['borderWidth', 'borderColor']) assert.ok(!error.includes(`${file}:${placeOf(added, old)}:`), `${old} was already deployed, so it is not what stops the upload`);assert.ok(error.includes(BOTH_WAYS_OUT));- assert.match(error, /Fix it in the file \(`node scripts\/check-griffel-styles\.js --file [^`]+` lists every one\), then re-run the upload\.$/);+ // An update suggests the check with --existing: the page is deployed already, so its scroll findings are notes (Styling gotchas 6).+ assert.match(error, /Fix it in the file \(`node scripts\/check-griffel-styles\.js --file [^`]+ --existing` lists every one\), then re-run the upload\.$/);}});diff --git a/plugins/model-apps/scripts/tests/griffel-styles.test.js b/plugins/model-apps/scripts/tests/griffel-styles.test.jsindex 459c1efee..164126c06 100644--- a/plugins/model-apps/scripts/tests/griffel-styles.test.js+++ b/plugins/model-apps/scripts/tests/griffel-styles.test.js@@ -1430,6 +1430,140 @@ test('check-griffel-styles CLI: a call the checker cannot read for certain fails});});+// ─── The scroll-context check the CLI also runs (AB#6793599) ────────────────────────────────────────────────────────────────────++// The work item's page: the default export renders a flex column with no bounded height and nothing that scrolls, so the host's+// fixed-height container cuts it off below the fold.+const SCROLL_HEAD = "import * as React from 'react';\nimport { makeStyles, tokens, Card, Text } from '@fluentui/react-components';\n";+const unscrolledPage = (root = "display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalL") =>+ `${SCROLL_HEAD}const useStyles = makeStyles({\n root: { ${root} },\n});\nexport default function GeneratedComponent() {\n const styles = useStyles();\n return (\n <div className={styles.root}>\n <Card><Text>One</Text></Card>\n </div>\n );\n}\n`;++test('check-griffel-styles CLI: a page with no scroll context fails the check (exit 3) with the scroll problem\'s place and remedy', () => {+ withPage(unscrolledPage(), (file) => {+ const res = runCli('--file', file);+ assert.equal(res.status, 3, res.stderr);+ const out = JSON.parse(res.stdout);+ assert.equal(out.ok, false);+ assert.equal(out.notes, undefined);+ assert.deepEqual(out.problems.map((p) => Object.keys(p)), [['code', 'line', 'column', 'element', 'message']], 'the lib\'s fix object stays internal');+ assert.deepEqual(out.problems.map(({ code, line, column, element }) => ({ code, line, column, element })), [{ code: 'no-scroll-context', line: 9, column: 5, element: 'div' }]);+ assert.ok(out.problems[0].message.includes('Add height: "100%", overflowY: "auto", boxSizing: "border-box" to the "root" slot of useStyles'), out.problems[0].message);+ });+});++test('check-griffel-styles CLI: the remedied page passes, and its output is exactly what it was before the scroll check existed', () => {+ withPage(unscrolledPage("height: '100%', overflowY: 'auto', boxSizing: 'border-box', display: 'flex', flexDirection: 'column'"), (file) => {+ const res = runCli('--file', file);+ assert.equal(res.status, 0, res.stdout);+ assert.deepEqual(JSON.parse(res.stdout), { ok: true, filePath: path.resolve(file), calls: 1, problems: [] });+ });+});++test('check-griffel-styles CLI: the Griffel problems come first, then the scroll ones, and either alone fails the page', () => {+ withPage(unscrolledPage("display: 'flex', flexDirection: 'column', borderWidth: '1px'"), (file) => {+ const out = JSON.parse(runCli('--file', file).stdout);+ assert.deepEqual(out.problems.map((p) => p.code), ['unsupported-shorthand', 'no-scroll-context']);+ });+});++test('check-griffel-styles CLI: --existing reports a scroll problem as a note — exit 0 — and still fails a Griffel problem', () => {+ withPage(unscrolledPage(), (file) => {+ const res = runCli('--file', file, '--existing');+ assert.equal(res.status, 0, res.stdout);+ const out = JSON.parse(res.stdout);+ assert.equal(out.ok, true);+ assert.deepEqual(out.problems, []);+ assert.deepEqual(out.notes.map((n) => n.code), ['no-scroll-context']);+ });+ withPage(unscrolledPage("display: 'flex', flexDirection: 'column', borderWidth: '1px'"), (file) => {+ const res = runCli('--existing', '--file', file);+ assert.equal(res.status, 3);+ const out = JSON.parse(res.stdout);+ assert.deepEqual(out.problems.map((p) => p.code), ['unsupported-shorthand']);+ assert.deepEqual(out.notes.map((n) => n.code), ['no-scroll-context']);+ });+});++test('check-griffel-styles CLI: a top element the check cannot read is unproven (exit 3) and says why', () => {+ const source = `${SCROLL_HEAD}export default function GeneratedComponent() {\n return <div className="page"><Text>Rows</Text></div>;\n}\n`;+ withPage(source, (file) => {+ const res = runCli('--file', file);+ assert.equal(res.status, 3);+ const [problem] = JSON.parse(res.stdout).problems;+ assert.deepEqual({ code: problem.code, reason: problem.reason }, { code: 'scroll-context-unproven', reason: 'string-class' });+ assert.deepEqual(Object.keys(problem), ['code', 'line', 'column', 'element', 'reason', 'message']);+ });+});++test('check-griffel-styles CLI: a padded content-box root reports scroll-context-padding with the border-box remedy', () => {+ withPage(unscrolledPage("height: '100%', overflowY: 'auto', padding: tokens.spacingHorizontalL"), (file) => {+ const res = runCli('--file', file);+ assert.equal(res.status, 3);+ const [problem] = JSON.parse(res.stdout).problems;+ assert.equal(problem.code, 'scroll-context-padding');+ assert.match(problem.message, /boxSizing: "border-box"/);+ });+});++test('check-griffel-styles CLI: a failure inside the scroll check is a note and leaves the Griffel result as it was', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'griffel-scroll-throw-'));+ try {+ const preload = path.join(dir, 'break-scroll.js');+ fs.writeFileSync(preload, `require(${JSON.stringify(path.join(__dirname, '..', 'lib', 'page-scroll.js'))}).pageScrollProblems = () => { throw new Error('boom'); };\n`);+ withPage(unscrolledPage(), (file) => {+ const res = spawnSync(process.execPath, ['-r', preload, SCRIPT, '--file', file], { encoding: 'utf8' });+ assert.equal(res.status, 0, res.stdout);+ const out = JSON.parse(res.stdout);+ assert.deepEqual(out.problems, []);+ assert.deepEqual(out.notes.map((n) => n.code), ['scroll-check-failed']);+ assert.match(out.notes[0].message, /boom/);+ });+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});++test('check-griffel-styles CLI: a vendored compiler that is missing or corrupt is a visible note, never a silent clean result, and the Griffel exit stands', () => {+ // A real copy of the CLI, its lib and its vendored compiler, with the compiler damaged on disk the way a broken install would be.+ const scripts = path.join(__dirname, '..');+ const damages = [['missing', (file) => fs.rmSync(file)], ['corrupt', (file) => fs.writeFileSync(file, Buffer.from('not a brotli stream'))]];+ for (const [damage, breakIt] of damages) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'griffel-scroll-compiler-'));+ try {+ const cli = path.join(dir, 'check-griffel-styles.js');+ fs.copyFileSync(SCRIPT, cli);+ fs.cpSync(path.join(scripts, 'lib'), path.join(dir, 'lib'), { recursive: true });+ fs.cpSync(path.join(scripts, 'vendor', 'typescript'), path.join(dir, 'vendor', 'typescript'), { recursive: true });+ breakIt(path.join(dir, 'vendor', 'typescript', 'typescript.min.js.br'));+ withPage(unscrolledPage(), (file) => {+ const res = spawnSync(process.execPath, [cli, '--file', file], { encoding: 'utf8' });+ assert.equal(res.status, 0, `${damage}: ${res.stdout}${res.stderr}`);+ const out = JSON.parse(res.stdout);+ assert.equal(out.ok, true, damage);+ assert.deepEqual(out.notes.map((n) => n.code), ['scroll-check-failed'], damage);+ assert.match(out.notes[0].message, /vendored TypeScript compiler could not be loaded/, damage);+ });+ withPage(`${unscrolledPage()}const useMore = makeStyles({ bad: { borderWidth: 1 } });\n`, (file) => {+ const res = spawnSync(process.execPath, [cli, '--file', file], { encoding: 'utf8' });+ assert.equal(res.status, 3, `${damage}: ${res.stdout}${res.stderr}`);+ const out = JSON.parse(res.stdout);+ assert.ok(out.problems.some((p) => p.property === 'borderWidth'), damage);+ assert.deepEqual(out.notes.map((n) => n.code), ['scroll-check-failed'], damage);+ });+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+ }+});++test('check-griffel-styles CLI: a file with no default export is not a page, so only the Griffel check speaks', () => {+ withPage(`${SCROLL_HEAD}export function Panel() {\n return <div style={{ display: 'flex' }} />;\n}\n`, (file) => {+ const res = runCli('--file', file);+ assert.equal(res.status, 0, res.stdout);+ assert.deepEqual(JSON.parse(res.stdout), { ok: true, filePath: path.resolve(file), calls: 0, problems: [] });+ });+});+// ─── Real pages ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────function walk(dir, suffix, out = []) {diff --git a/plugins/model-apps/scripts/tests/helpers/page-swap-crash-child.js b/plugins/model-apps/scripts/tests/helpers/page-swap-crash-child.jsnew file mode 100644index 000000000..f96536f64--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/page-swap-crash-child.js@@ -0,0 +1,49 @@+'use strict';+// A child process for the page-tree crash tests (download-model-app.test.js): it downloads into <out> as tests/helpers/page-swap.js does+// and STOPS DEAD (process.exit: no catch, no finally, no clean-up runs, as for a kill) at one boundary of writePageTree's swap:+// partial while the second page of the new tree is being written;+// staged with the new tree whole, just before pages/ is moved aside;+// aside just after pages/ is moved aside, before the new tree is moved in;+// in just after the new tree is moved to pages/, before the swap folder is removed;+// removed just after the swap folder is removed.+// It exits 86 at that point; any other exit means the point was never reached.+// node page-swap-crash-child.js <out> <direct|managed> <point>+const fs = require('node:fs');+const path = require('node:path');+const { SWAP_B, swapDownload } = require('./page-swap.js');++const [out, mode, point] = process.argv.slice(2);+// The download moves and writes through the real path of <out> (an 8.3 short name names the same folder).+const realOut = fs.realpathSync.native(out);+const pagesDir = path.join(realOut, 'pages');+// The swap folder of the publish to <out> (`<out>/.pages-replace.*`), not the one the managed download stages its tree with.+const inSwap = (p) => {+ const rel = path.relative(realOut, String(p));+ return !rel.startsWith('..') && rel.split(path.sep)[0].startsWith('.pages-replace.');+};+const stop = () => process.exit(86);++const rename = fs.renameSync;+fs.renameSync = function (from, to) {+ if (point === 'staged' && from === pagesDir) stop();+ const result = rename.apply(this, arguments);+ if (point === 'aside' && from === pagesDir) stop();+ if (point === 'in' && to === pagesDir && inSwap(from)) stop();+ return result;+};+const rm = fs.rmSync;+fs.rmSync = function (p) {+ const result = rm.apply(this, arguments);+ if (point === 'removed' && path.dirname(String(p)) === realOut && inSwap(p)) stop();+ return result;+};+const open = fs.openSync;+fs.openSync = function (p) {+ if (point === 'partial' && inSwap(p) && path.relative(realOut, String(p)).split(path.sep).includes(SWAP_B)) stop();+ return open.apply(this, arguments);+};++swapDownload(out, mode === 'managed').then(+ () => { process.exitCode = 0; },+ (e) => { process.stderr.write(`${(e && e.stack) || e}\n`); process.exitCode = 1; },+);diff --git a/plugins/model-apps/scripts/tests/helpers/page-swap.js b/plugins/model-apps/scripts/tests/helpers/page-swap.jsnew file mode 100644index 000000000..a4e5e8b2f--- /dev/null+++ b/plugins/model-apps/scripts/tests/helpers/page-swap.js@@ -0,0 +1,84 @@+'use strict';+// The app and the download the page-tree tests run (download-model-app.test.js, and the child process its crash tests stop part-way):+// an app whose navigation names generative pages, served through the stand-in SDK the other runDownload tests use, and a pages/ folder+// a maker has worked in.+const fs = require('node:fs');+const path = require('node:path');+const { runDownload } = require('../../download-model-app.js');+const { currentReadSdk } = require('./app-membership-sdk.js');+const { fakeGenpage } = require('./fake-genpage.js');++// An app with the given pages in its navigation, served through the stand-in SDK the other runDownload tests use.+function pagesApp(pageIds) {+ const APP_ID = 'a1b2c3d4-0000-4000-8000-000000000001';+ const LAYER = 'c0ffee00-0000-4000-8000-00000000dddd';+ const xml = `<SiteMap><Area><Group>${pageIds.map((id, i) => `<SubArea GenPageId="${id}" Title="Title ${i}"/>`).join('')}<SubArea Entity="contoso_item"/></Group></Area></SiteMap>`;+ const sdk = {+ fetchArtifact: async () => ({+ name: 'Pages App', description: '',+ siteMap: { areas: [{ title: 'M', groups: [{ title: 'G', subAreas: [+ ...pageIds.map((id, i) => ({ type: 'GenPage', genPageId: id, title: `Title ${i}` })),+ { type: 'Entity', entity: 'contoso_item' },+ ] }] }] },+ }),+ queryRecords: async (logical, opts) => {+ const filter = (opts && opts.filter) || '';+ if (logical === 'appmodule') {+ const m = filter.match(/uniquename eq '([^']+)'/);+ if (m) return m[1] === 'test_pages' ? [{ appmoduleid: APP_ID, appmoduleidunique: LAYER }] : [];+ return [{ appmoduleid: APP_ID, appmoduleidunique: LAYER, uniquename: 'test_pages' }];+ }+ if (logical === 'appmodulecomponent') return [{ objectid: '5111e0f2-0000-4000-8000-0000000000aa', componenttype: 62 }];+ if (logical === 'sitemap') return [{ sitemapxml: xml }];+ return [];+ },+ fetchEntityMetadata: async (logical) => ({ schemaName: logical, displayName: 'Item', primaryNameAttribute: `${String(logical).split('_')[0]}_name` }),+ };+ return { sdk: currentReadSdk(sdk, { appId: APP_ID, layerId: LAYER, sitemapXml: xml }), appId: APP_ID, appUnique: 'test_pages' };+}++const SWAP_A = '13ecbc57-a3a4-4132-b0a2-a6c6b12691e8';+const SWAP_B = '5c0a4889-45fd-46ea-91a8-ff876914d644';+const MAKER_ONLY = '77777777-7777-4777-8777-777777777777';+const DOWNLOADED_A = 'export default () => "downloaded";\n';++// A pages/ the maker has worked in: a page the app still has, edited, and a page only the maker has.+function seedEditedPages(out) {+ const write = (rel, text) => {+ fs.mkdirSync(path.dirname(path.join(out, rel)), { recursive: true });+ fs.writeFileSync(path.join(out, rel), text);+ };+ write(`pages/${SWAP_A}/page.tsx`, 'export default () => "edited by the maker";\n');+ write(`pages/${SWAP_A}/config.json`, '{"dataSources":["contoso_item"]}');+ write(`pages/${MAKER_ONLY}/page.tsx`, 'export default () => "not uploaded yet";\n');+}++// Every file under `dir` as { 'relative/path': hex bytes }, so two trees compare byte for byte.+function treeBytes(dir) {+ const files = {};+ const walk = (d) => {+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {+ const p = path.join(d, e.name);+ if (e.isDirectory()) walk(p);+ else files[path.relative(dir, p).split(path.sep).join('/')] = fs.readFileSync(p).toString('hex');+ }+ };+ if (fs.existsSync(dir)) walk(dir);+ return files;+}++const swapGenpage = () => fakeGenpage({ pages: [{ pageId: SWAP_A, name: 'Alpha', source: DOWNLOADED_A }, { pageId: SWAP_B, name: 'Beta' }] });++// Downloads the two-page app into `out`, as a direct download (pages/ written by the download itself) or as the managed download does+// (`managed`: the tree is staged, then checked and published).+async function swapDownload(out, managed) {+ const result = await runDownload({ ...pagesApp([SWAP_A, SWAP_B]), genpage: swapGenpage(), outDir: out, ...(managed ? { stagePages: true } : {}) });+ if (!result.ok) throw new Error(`download failed: ${JSON.stringify(result)}`);+ if (managed) {+ result.stagedPages.check();+ result.stagedPages.publish();+ }+ return result;+}++module.exports = { pagesApp, SWAP_A, SWAP_B, MAKER_ONLY, DOWNLOADED_A, seedEditedPages, treeBytes, swapGenpage, swapDownload };diff --git a/plugins/model-apps/scripts/tests/page-scroll.test.js b/plugins/model-apps/scripts/tests/page-scroll.test.jsnew file mode 100644index 000000000..d39e3a339--- /dev/null+++ b/plugins/model-apps/scripts/tests/page-scroll.test.js@@ -0,0 +1,415 @@+'use strict';+// Does a generated page establish its own scroll context? (AB#6793599) — lib/page-scroll.js, which check-griffel-styles.js runs on every page.+//+// The host shows a page in a container of fixed height and never scrolls it, so a page in which nothing both has a bounded height and+// scrolls is cut off below the fold, silently. Measured on the host for each root shape: a root with `height: "100%"` and `overflowY: "auto"`+// scrolls (P2, P3); the same root in an `overflow: "hidden"` wrapper scrolls (P7); a fixed header over a `flex: 1`, `minHeight: 0`,+// `overflowY: "auto"` body scrolls (P6); a bare root (P1), `height` alone (P4), `overflowY` alone (P5), a wrapper round a bare root (P8) and+// `minHeight: "100%"` (P9) clip; and a box that fills its container with vertical padding in the content-box model overhangs it by the+// padding, so its end stays cut off, until `boxSizing: "border-box"` (P10, P11). The P-numbers below are those shapes.+// The CLI's output contract is pinned in griffel-styles.test.js; that the flows run it in each mode, in genpage-dispatch-contract.test.js.++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { execFileSync } = require('node:child_process');++const { analyzePageScroll, pageScrollProblems, REMEDY_KEYS } = require('../lib/page-scroll.js');+const { loadVendoredTypeScript } = require('../lib/typescript-compiler.js');+const { griffelStyleProblems } = require('../lib/griffel-styles.js');++const ts = loadVendoredTypeScript();+const PLUGIN = path.join(__dirname, '..', '..');+const REPO = path.join(PLUGIN, '..', '..');++const HEAD = "import * as React from 'react';\nimport { makeStyles, mergeClasses, shorthands, tokens, Spinner, MessageBar, Card, Text } from '@fluentui/react-components';\n";++// A page: `slots` is the body of its one makeStyles object, `body` the statements of its default export (which binds `styles`).+const page = (slots, body, extra = '') => `${HEAD}const useStyles = makeStyles({\n${slots}\n});\n${extra}export default function Page(props: any) {\n const styles = useStyles();\n${body}\n}\n`;+// The same, returning one element with className={styles.root} and three rows.+const rooted = (rootKeys, otherSlots = '', attrs = '') => page(` root: { ${rootKeys} },\n row: { padding: '8px' },\n${otherSlots}`, ` return (\n <div className={styles.root}${attrs}>\n {[1, 2, 3].map((n) => <div key={n} className={styles.row}><Text>Row {n}</Text></div>)}\n </div>\n );`);++// One word for a result: pass, fail, unproven:<reason>, padding, or not judged.+function verdict(source) {+ const r = analyzePageScroll(source);+ if (!r.judged) return `not judged: ${r.why}`;+ const codes = new Set(r.problems.map((p) => p.code));+ if (codes.has('no-scroll-context')) return 'fail';+ const unproven = r.problems.find((p) => p.code === 'scroll-context-unproven');+ if (unproven) return `unproven:${unproven.reason}`;+ if (codes.has('scroll-context-padding')) return 'padding';+ return 'pass';+}++const SCROLLS = "height: '100%', overflowY: 'auto', boxSizing: 'border-box'";+const FLEX_COLUMN = "display: 'flex', flexDirection: 'column'";+// Content taller than any host.+const TALL = '<div style={{ height: 2000 }}><Text>end</Text></div>';++// [name, source, verdict]. Every case that is not a pass is also a case of the remedy invariant below.+const CASES = [+ // The measured shapes.+ ['P1 a bare root', rooted(FLEX_COLUMN), 'fail'],+ ['P2 height 100%, overflowY auto and vertical padding, content-box', rooted("height: '100%', overflowY: 'auto', padding: '16px'"), 'padding'],+ ['P2b the same with boxSizing border-box', rooted("height: '100%', overflowY: 'auto', padding: '16px', boxSizing: 'border-box'"), 'pass'],+ ['P3 the overflow shorthand', rooted("height: '100%', overflow: 'auto'"), 'pass'],+ ['P4 height alone', rooted("height: '100%'"), 'fail'],+ ['P5 overflowY alone', rooted("overflowY: 'auto'"), 'fail'],+ ['P6 a fixed header over a flex body that scrolls', page(` root: { height: '100%', overflow: 'hidden', ${FLEX_COLUMN} },\n header: { flexShrink: 0 },\n body: { flex: 1, minHeight: 0, overflowY: 'auto' },`, ' return (\n <div className={styles.root}>\n <div className={styles.header}><Text>Title</Text></div>\n <div className={styles.body}>{props.rows}</div>\n </div>\n );'), 'pass'],+ ['P6 with vertical padding on the root around the body', page(` root: { height: '100%', overflow: 'hidden', padding: tokens.spacingVerticalL, ${FLEX_COLUMN} },\n body: { flex: 1, minHeight: 0, overflowY: 'auto' },`, ' return (\n <div className={styles.root}>\n <Text>Title</Text>\n <div className={styles.body}>{props.rows}</div>\n </div>\n );'), 'padding'],+ ['P6 a body that scrolls needs no minHeight 0 (a scroll container\'s automatic minimum is 0)', page(` root: { height: '100%', ${FLEX_COLUMN} },\n body: { flexGrow: 1, overflowY: 'auto' },`, ' return (\n <div className={styles.root}>\n <Text>Title</Text>\n <div className={styles.body}>{props.rows}</div>\n </div>\n );'), 'pass'],+ ['P6 a flex body that does not scroll and holds nothing that does', page(` root: { height: '100%', overflow: 'hidden', ${FLEX_COLUMN} },\n body: { flex: 1, minHeight: 0 },`, ' return (\n <div className={styles.root}>\n <div className={styles.body}><Text>Rows</Text></div>\n </div>\n );'), 'fail'],+ ['P7 the two-div wrapper round a root that scrolls', page(` root: { ${SCROLLS} },`, " return (\n <div style={{ height: '100%', overflow: 'hidden' }}>\n <div className={styles.root}><Text>Rows</Text></div>\n </div>\n );"), 'pass'],+ ['P7 the wrapper round a padded content-box root', page(" root: { height: '100%', overflowY: 'auto', ...shorthands.padding('16px') },", " return (\n <div style={{ height: '100%', overflow: 'hidden' }}>\n <div className={styles.root}><Text>Rows</Text></div>\n </div>\n );"), 'padding'],+ ['P8 the wrapper round a bare root (the reported failure)', page(` root: { ${FLEX_COLUMN} },`, " return (\n <div style={{ height: '100%', overflow: 'hidden' }}>\n <div className={styles.root}><Text>Rows</Text></div>\n </div>\n );"), 'fail'],+ ['P9 minHeight 100%', rooted("minHeight: '100%', overflowY: 'auto'"), 'fail'],+ ['a viewport height is taller than the host\'s container', rooted("height: '100vh', overflowY: 'auto'"), 'fail'],+ ['a maxHeight region under a bounded root', page(` root: { height: '100%', ${FLEX_COLUMN} },\n region: { maxHeight: 'calc(100% - 100px)', overflow: 'auto' },`, ' return (\n <div className={styles.root}>\n <Text>Title</Text>\n <div className={styles.region}>{props.rows}</div>\n </div>\n );'), 'pass'],+ ['a maxHeight region under a root that grows', page(` root: { ${FLEX_COLUMN} },\n region: { maxHeight: '400px', overflow: 'auto' },`, ' return (\n <div className={styles.root}>\n <Text>Title</Text>\n <div className={styles.region}>{props.rows}</div>\n </div>\n );'), 'fail'],+ // Padding: only a box that fills its container, and only vertical padding that is not zero.+ ['horizontal padding only', rooted("height: '100%', overflowY: 'auto', padding: '0 16px'"), 'pass'],+ ['paddingTop 0', rooted("height: '100%', overflowY: 'auto', paddingTop: 0"), 'pass'],+ ['shorthands.padding with a vertical 0', rooted("height: '100%', overflowY: 'auto', ...shorthands.padding('0', '16px')"), 'pass'],+ ['paddingBlock given a token', rooted("height: '100%', overflowY: 'auto', paddingBlock: tokens.spacingVerticalM"), 'padding'],+ ['a region of fixed height with padding', page(` root: { height: '100%', ${FLEX_COLUMN} },\n region: { maxHeight: '300px', overflowY: 'auto', padding: '16px' },`, ' return (\n <div className={styles.root}>\n <div className={styles.region}>{props.rows}</div>\n </div>\n );'), 'pass'],+ ['boxSizing set inline', rooted("height: '100%', overflowY: 'auto', padding: '16px'", '', " style={{ boxSizing: 'border-box' }}"), 'pass'],+ // Reading styles.+ ['overflowX auto makes overflow-y compute to auto', rooted("height: '100%', overflowX: 'auto'"), 'pass'],+ ['shorthands.overflow(x, y)', rooted("height: '100%', ...shorthands.overflow('hidden', 'auto')"), 'pass'],+ ['shorthands.flex(1) on a body', page(` root: { height: '100%', ${FLEX_COLUMN} },\n body: { ...shorthands.flex(1), minHeight: 0, overflowY: 'auto' },`, ' return (\n <div className={styles.root}>\n <div className={styles.body}>{props.rows}</div>\n </div>\n );'), 'pass'],+ ['mergeClasses: the later class wins', page(" base: { height: '100%' },\n scroll: { overflowY: 'auto' },\n clip: { overflowY: 'hidden' },", ' return <div className={mergeClasses(styles.base, styles.scroll, styles.clip)}><Text>Rows</Text></div>;'), 'fail'],+ ['mergeClasses: classes add up', page(" base: { height: '100%' },\n scroll: { overflowY: 'auto' },", ' return <div className={mergeClasses(styles.base, styles.scroll)}><Text>Rows</Text></div>;'), 'pass'],+ ['a destructured slot', page(` root: { ${SCROLLS} },`, ' return <div className={styles.root}><Text>Rows</Text></div>;').replace('const styles = useStyles();\n return <div className={styles.root}>', 'const { root } = useStyles();\n return <div className={root}>'), 'pass'],+ ['the inline style wins over the class', rooted(SCROLLS, '', " style={{ overflowY: 'visible' }}"), 'fail'],+ ['an inline longhand after its shorthand wins', page('', " return <div style={{ height: '100%', overflow: 'hidden', overflowY: 'auto' }}><Text>Rows</Text></div>;"), 'pass'],+ ['an inline shorthand after its longhand wins', page('', " return <div style={{ height: '100%', overflowY: 'auto', overflow: 'hidden' }}><Text>Rows</Text></div>;"), 'fail'],+ ['keys written after a spread are read', page('', " return <div style={{ ...props.extra, height: '100%', overflowY: 'auto', boxSizing: 'border-box', minHeight: 0 }}><Text>Rows</Text></div>;"), 'pass'],+ // A spread before the keys may carry a minHeight, and a minimum wins over a height.+ ['a spread before the keys may carry a minHeight', page('', " return <div style={{ ...props.extra, height: '100%', overflowY: 'auto', boxSizing: 'border-box' }}><Text>Rows</Text></div>;"), 'unproven:unread-spread'],+ ['a spread before the keys may carry padding', page('', " return <div style={{ ...props.extra, height: '100%', overflowY: 'auto', minHeight: 0 }}><Text>Rows</Text></div>;"), 'padding'],+ ['a spread after the keys may replace them', page('', " return <div style={{ height: '100%', overflowY: 'auto', ...props.extra }}><Text>Rows</Text></div>;"), 'unproven:unread-spread'],+ ['a spread of attributes after className', rooted(SCROLLS, '', ' {...props.attrs}'), 'unproven:spread-attributes'],+ ['a conditional class that sets overflow', rooted(SCROLLS, " dense: { overflowY: 'hidden' },", '').replace('className={styles.root}', 'className={mergeClasses(styles.root, props.dense && styles.dense)}'), 'unproven:conditional-class'],+ ['a conditional class that sets only a colour', rooted(SCROLLS, ' dense: { color: tokens.colorNeutralForeground2 },', '').replace('className={styles.root}', 'className={mergeClasses(styles.root, props.dense && styles.dense)}'), 'pass'],+ ['a template-string className', rooted(SCROLLS).replace('className={styles.root}', 'className={`${styles.root} page`}'), 'unproven:string-class'],+ ['a string className', page('', ' return <div className="page-root"><Text>Rows</Text></div>;'), 'unproven:string-class'],+ ['a slot the hook does not have', rooted(SCROLLS).replace('className={styles.root}', 'className={styles.missing}'), 'unproven:unknown-slot'],+ ['a height given a token', rooted("height: tokens.spacingVerticalXXXL, overflowY: 'auto'"), 'unproven:unread-value'],+ ['a shorthand and its longhand on classes, to different effect', rooted("height: '100%', overflow: 'hidden', overflowY: 'auto'"), 'unproven:conflicting-keys'],+ ['an inline style computed by code', rooted(SCROLLS, '', ' style={props.style}'), 'unproven:style-expression'],+ // Following the page.+ ['an early return of a spinner is not judged', page(` root: { ${SCROLLS} },`, " if (props.loading) return <div><Spinner /></div>;\n return <div className={styles.root}><Text>Rows</Text></div>;"), 'pass'],+ ['when the final return is a library state view, the earlier returns are judged', page(` root: { ${SCROLLS} },`, ' if (props.data) return <div className={styles.root}><Text>Rows</Text></div>;\n return <Spinner />;'), 'pass'],+ ['a library arm beside an element is a state view', page(` root: { ${SCROLLS} },`, ' return props.error ? <MessageBar>{props.error}</MessageBar> : <div className={styles.root}><Text>Rows</Text></div>;'), 'pass'],+ ['both arms of a condition are judged', page(` root: { ${SCROLLS} },\n other: { ${FLEX_COLUMN} },`, ' return props.wide ? <div className={styles.root}><Text>A</Text></div> : <div className={styles.other}><Text>B</Text></div>;'), 'fail'],+ ['transparent components pass through', page(` root: { ${SCROLLS} },`, ' return <React.StrictMode><React.Suspense fallback={null}><Ctx.Provider value={1}><div className={styles.root}><Text>Rows</Text></div></Ctx.Provider></React.Suspense></React.StrictMode>;', 'const Ctx = React.createContext(0);\n'), 'pass'],+ ['a fragment with one element is that element', page(` root: { ${SCROLLS} },`, ' return <><div className={styles.root}><Text>Rows</Text></div></>;'), 'pass'],+ ['a fragment of several elements side by side', page(` root: { ${SCROLLS} },`, ' return <><Text>Title</Text><div className={styles.root}><Text>Rows</Text></div></>;'), 'unproven:fragment-top'],+ ['a portal at the top', page('', ' return ReactDOM.createPortal(<div />, document.body);', "import * as ReactDOM from 'react-dom';\n"), 'unproven:portal'],+ ['a component imported from elsewhere at the top', page('', ' return <Shell />;', "import { Shell } from './shell';\n"), 'unproven:library-top'],+ ['a library component at the top that scrolls', page(` root: { ${SCROLLS} },`, ' return <Card className={styles.root}><Text>Rows</Text></Card>;'), 'pass'],+ ['a return computed by a call', page('', ' return renderBody();', 'declare function renderBody(): any;\n'), 'unproven:unresolved-return'],+ ['content computed by a call inside a root that does not scroll', page(` root: { height: '100%', ${FLEX_COLUMN} },`, ' return <div className={styles.root}>{renderRows()}</div>;', 'declare function renderRows(): any;\n'), 'unproven:unresolved-children'],+ ['components that render each other', page('', ' return <A />;', 'function A(): any { return <B />; }\nfunction B(): any { return <A />; }\n'), 'unproven:recursive'],+ ['a component that returns children it is never given', page('', ' return props.children;'), 'unproven:children-top'],+ // Alternatives: only one of a condition's alternatives is on screen at a time, so each one that renders content must scroll.+ ['only one alternative of a condition scrolls', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <div>${TALL}</div>}</div>);`), 'unproven:partial-alternatives'],+ ['every alternative of a condition scrolls', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <div style={{ ${SCROLLS} }}>${TALL}</div>}</div>);`), 'pass'],+ ['a nested condition with one alternative that does not scroll', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.a ? <div style={{ ${SCROLLS} }}>${TALL}</div> : props.b ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <div>${TALL}</div>}</div>);`), 'unproven:partial-alternatives'],+ ['a nested condition in which every alternative scrolls', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.a ? <div style={{ ${SCROLLS} }}>${TALL}</div> : props.b ? <div style={{ ${SCROLLS} }}>${TALL}</div> : null}</div>);`), 'pass'],+ ['a local component whose alternatives do not all scroll', page('', " return (<div style={{ height: '100%', overflow: 'hidden' }}><Body mode={props.mode} /></div>);", `function Body(props: any) {\n return props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <div>${TALL}</div>;\n}\n`), 'unproven:partial-alternatives'],+ ['a loading alternative of a library component', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.loading ? <Spinner /> : <div style={{ ${SCROLLS} }}>${TALL}</div>}</div>);`), 'pass'],+ ['a busy indicator beside a body that scrolls is a sibling', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.busy && <Spinner />}<div style={{ ${SCROLLS} }}>${TALL}</div></div>);`), 'pass'],+ ['an alternative that renders nothing', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.ready && <div style={{ ${SCROLLS} }}>${TALL}</div>}</div>);`), 'pass'],+ // Only a recognised state view (a Spinner, a MessageBar, a line of Text, …) is passed over; any other library component is content.+ ['an error alternative of a MessageBar with a body and an action', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <MessageBar intent="error"><MessageBarBody>{props.error} <b>Retry</b></MessageBarBody></MessageBar>}</div>);`), 'pass'],+ ['an empty alternative of a line of Text', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <Text>No accounts found.</Text>}</div>);`), 'pass'],+ ['an alternative of a Card that holds the rows', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <Card>${TALL}</Card>}</div>);`), 'unproven:partial-alternatives'],+ ['an alternative of a Card that holds a value', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <Card>{props.rows}</Card>}</div>);`), 'unproven:partial-alternatives'],+ ['an alternative of an imported component', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <Rows />}</div>);`, "import { Rows } from './rows';\n"), 'unproven:partial-alternatives'],+ ['an alternative of a MessageBar that holds rows', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.mode ? <div style={{ ${SCROLLS} }}>${TALL}</div> : <MessageBar>${TALL}</MessageBar>}</div>);`), 'unproven:partial-alternatives'],+ // A known limit: an early return is an exit (loading, error, empty), and only the final return is judged when it renders an element.+ ['an early return of a Card beside a final return that scrolls', page('', ` if (props.mode) return <Card>${TALL}</Card>;\n return <div style={{ ${SCROLLS} }}>${TALL}</div>;`), 'pass'],+ ['an early return of a Spinner beside a root that scrolls', page('', ` if (props.loading) return <Spinner />;\n return <div style={{ ${SCROLLS} }}>${TALL}</div>;`), 'pass'],+ // A known false rejection: a loading alternative wrapped in an element of the page's own is judged like content.+ ['a loading alternative inside a box of the page\'s own', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}>{props.loading ? <div><Spinner /></div> : <div style={{ ${SCROLLS} }}>${TALL}</div>}</div>);`), 'unproven:partial-alternatives'],+ ['the remedy on the top element of a loading alternative inside a box of the page\'s own', page('', ` return (<div style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box', minHeight: 0 }}>{props.loading ? <div><Spinner /></div> : <div style={{ ${SCROLLS} }}>${TALL}</div>}</div>);`), 'pass'],+ ['the remedy on the top element of a column whose body has a minHeight of its own', page('', ` return (<div style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box', minHeight: 0, ${FLEX_COLUMN} }}><div style={{ flexShrink: 0, height: 48 }}>Title</div><div style={{ flex: 1, minHeight: 200, overflowY: 'auto' }}>${TALL}</div></div>);`), 'pass'],+ // Definite height: a percentage resolves only against a parent of definite height, not one bounded by maxHeight alone.+ ['height 100% under a parent bounded only by maxHeight', page('', ` return (<div style={{ maxHeight: '100%', overflow: 'hidden' }}><div style={{ ${SCROLLS} }}>${TALL}</div></div>);`), 'fail'],+ ['height 100% under a parent of definite height', page('', ` return (<div style={{ height: '100%', overflow: 'hidden' }}><div style={{ ${SCROLLS} }}>${TALL}</div></div>);`), 'pass'],+ ['a maxHeight 100% region under a parent bounded only by maxHeight', page('', ` return (<div style={{ maxHeight: '100%', overflow: 'hidden' }}><div style={{ maxHeight: '100%', overflowY: 'auto' }}>${TALL}</div></div>);`), 'fail'],+ ['a flex body in a column bounded only by maxHeight', page('', ` return (<div style={{ maxHeight: '100%', overflow: 'hidden', ${FLEX_COLUMN} }}><Text>Title</Text><div style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>${TALL}</div></div>);`), 'pass'],+ ['height 100% inside a flex body that grows in a definite column', page('', ` return (<div style={{ height: '100%', overflow: 'hidden', ${FLEX_COLUMN} }}><Text>Title</Text><div style={{ flex: 1, minHeight: 0 }}><div style={{ ${SCROLLS} }}>${TALL}</div></div></div>);`), 'pass'],+ // minHeight: a minimum wins over a height, so one that may be larger than the bound defeats it.+ ['a minHeight in px under height 100%', page('', ` return (<div style={{ height: '100%', minHeight: 2000, overflowY: 'auto' }}>${TALL}</div>);`), 'unproven:min-height'],+ ['a minHeight larger than a fixed height', page('', ` return (<div style={{ height: 480, minHeight: 2000, overflowY: 'auto' }}>${TALL}</div>);`), 'fail'],+ ['a minHeight not larger than a fixed height', page('', ` return (<div style={{ height: '480px', minHeight: 300, overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],+ ['minHeight 100% under height 100%', rooted(`${SCROLLS}, minHeight: '100%'`), 'pass'],+ ['minHeight 0 under height 100%', rooted(`${SCROLLS}, minHeight: 0`), 'pass'],+ // The same value, or the same unit and not larger, fits; units are never converted.+ ['a minHeight in rem equal to the height', page('', ` return (<div style={{ height: '30rem', minHeight: '30rem', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],+ ['a minHeight in rem smaller than the height', page('', ` return (<div style={{ height: '30rem', minHeight: '10rem', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],+ ['a minHeight in rem larger than the height', page('', ` return (<div style={{ height: '30rem', minHeight: '40rem', overflowY: 'auto' }}>${TALL}</div>);`), 'fail'],+ ['a minHeight that is the same calc() as the height', page('', ` return (<div style={{ height: 'calc(100% - 64px)', minHeight: 'calc(100% - 64px)', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],+ ['a minHeight in % smaller than the height', page('', ` return (<div style={{ height: '50%', minHeight: '25%', overflowY: 'auto' }}>${TALL}</div>);`), 'pass'],+ ['a minHeight in rem under a height in px', page('', ` return (<div style={{ height: '480px', minHeight: '10rem', overflowY: 'auto' }}>${TALL}</div>);`), 'unproven:min-height'],+ ['a minHeight given a token', rooted(`${SCROLLS}, minHeight: tokens.spacingVerticalXXXL`), 'unproven:unread-value'],+ ['a flex body with a minHeight of its own', page(` root: { height: '100%', overflow: 'hidden', ${FLEX_COLUMN} },\n body: { flex: 1, minHeight: '200px', overflowY: 'auto' },`, ' return (\n <div className={styles.root}>\n <Text>Title</Text>\n <div className={styles.body}>{props.rows}</div>\n </div>\n );'), 'unproven:min-height'],+ // Padding is refused only where the box provably fills its container.+ ['height 50% with padding', page('', ` return (<div style={{ height: '50%', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'pass'],+ ['calc(100% - 64px) with 16px padding', page('', ` return (<div style={{ height: 'calc(100% - 64px)', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'pass'],+ ['calc(100% - 8px) with 16px padding', page('', ` return (<div style={{ height: 'calc(100% - 8px)', overflowY: 'auto', padding: '16px' }}>${TALL}</div>);`), 'padding'],+ ['calc(100% - 64px) with a token padding', page('', ` return (<div style={{ height: 'calc(100% - 64px)', overflowY: 'auto', padding: tokens.spacingVerticalL }}>${TALL}</div>);`), 'pass'],+ ['height 100% with 16px padding', page('', ` return (<div style={{ height: '100%', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'padding'],+ ['height 100% capped by maxHeight calc(100% - 64px) with 16px padding', page('', ` return (<div style={{ height: '100%', maxHeight: 'calc(100% - 64px)', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'pass'],+ ['height 100% and maxHeight 100% with 16px padding', page('', ` return (<div style={{ height: '100%', maxHeight: '100%', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'padding'],+ // The used height is max(minHeight, min(height, maxHeight)): a looser maximum, or a minimum that wins over the maximum, leaves it full.+ ['height 100% under a looser maxHeight 150% with 16px padding', page('', ` return (<div style={{ height: '100%', maxHeight: '150%', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'padding'],+ ['height 100% with minHeight 100% over maxHeight calc(100% - 64px) and 16px padding', page('', ` return (<div style={{ height: '100%', minHeight: '100%', maxHeight: 'calc(100% - 64px)', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'padding'],+ ['height 100% with minHeight 0 under maxHeight calc(100% - 64px) and 16px padding', page('', ` return (<div style={{ height: '100%', minHeight: 0, maxHeight: 'calc(100% - 64px)', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'pass'],+ ['height 100% under a fixed maxHeight 400px with 16px padding (not comparable to the host)', page('', ` return (<div style={{ height: '100%', maxHeight: '400px', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'padding'],+ ['height 100% under a looser maxHeight 150% with 16px padding and border-box', page('', ` return (<div style={{ height: '100%', maxHeight: '150%', overflowY: 'auto', padding: 16, boxSizing: 'border-box' }}>${TALL}</div>);`), 'pass'],+ ['maxHeight 100% alone with 16px padding', page('', ` return (<div style={{ maxHeight: '100%', overflowY: 'auto', padding: 16 }}>${TALL}</div>);`), 'padding'],+ // A default export named before the function it names (function declarations are hoisted).+ ['export default of a function declared below it', `${HEAD}export default Page;\nfunction Page() {\n return <div style={{ ${SCROLLS} }}>${TALL}</div>;\n}\n`, 'pass'],+ ['export default of a function declared below it, with a bare root', `${HEAD}export default Page;\nfunction Page() {\n return <div>${TALL}</div>;\n}\n`, 'fail'],+];++for (const [name, source, expected] of CASES) {+ test(`page-scroll: ${name} → ${expected}`, () => {+ assert.equal(verdict(source), expected);+ });+}++test('page-scroll: the work item\'s dashboard — default export → error boundary class → body component → a flex column root — has no scroll context', () => {+ const source = `${HEAD}const useStyles = makeStyles({\n root: { display: 'flex', flexDirection: 'column', gap: tokens.spacingVerticalL, padding: tokens.spacingHorizontalL },\n card: { padding: '8px' },\n});\nclass PageErrorBoundary extends React.Component<{ children: React.ReactNode }> {\n render() { return this.props.children; }\n}\nfunction PageBody() {\n const styles = useStyles();\n return (\n <div className={styles.root}>\n {[1, 2].map((n) => <Card key={n} className={styles.card}><Text>{n}</Text></Card>)}\n </div>\n );\n}\nexport default function GeneratedComponent() {\n return <PageErrorBoundary><PageBody /></PageErrorBoundary>;\n}\n`;+ const problems = pageScrollProblems(source);+ assert.deepEqual(problems.map(({ code, line, column, element, fix }) => ({ code, line, column, element, fix })), [+ { code: 'no-scroll-context', line: 13, column: 5, element: 'div', fix: { kind: 'class', hook: 'useStyles', slot: 'root', flexColumn: true } },+ ]);+ assert.equal(problems[0].message, 'the page has no scroll context: nothing from its top <div> at line 13 down both has a bounded height and scrolls. The host shows a page in a container of fixed height and does not scroll it, so whatever does not fit is cut off with no scrollbar. Add height: "100%", overflowY: "auto", boxSizing: "border-box" to the "root" slot of useStyles (the class of the page\'s top <div> at line 13), and delete any overflow key or shorthands.overflow(…) from that slot (references/rules.md, "Page Layout"). That element is a flex column, which shrinks its items to fit once its height is bounded: give flexShrink: 0 to each of its items that clips its own content (a Card, or a box with an overflow key), or they are squeezed and cut off inside.');+});++test('page-scroll: a component that renders its children inside a box of its own passes them the bounded height', () => {+ const layout = 'function Layout({ children }: { children: React.ReactNode }) {\n const styles = useStyles();\n return <div className={styles.shell}>{children}</div>;\n}\n';+ const slots = ` shell: { height: '100%', overflow: 'hidden', ${FLEX_COLUMN} },\n body: { flex: 1, minHeight: 0, overflowY: 'auto' },`;+ assert.equal(verdict(page(slots, ' return <Layout><div className={styles.body}>{props.rows}</div></Layout>;', layout)), 'pass');+ assert.equal(verdict(page(slots, ' return <Layout><div>{props.rows}</div></Layout>;', layout)), 'fail');+});++test('page-scroll: every way to name the default export is read — memo, forwardRef, an alias, `export { X as default }`, a class', () => {+ const body = `const useStyles = makeStyles({ root: { ${FLEX_COLUMN} } });\nfunction Page() {\n const styles = useStyles();\n return <div className={styles.root} />;\n}\n`;+ for (const tail of ['export default React.memo(Page);', 'export default React.forwardRef(Page);', 'const Alias = Page;\nexport default Alias;', 'export { Page as default };']) {+ assert.equal(verdict(`${HEAD}${body}${tail}\n`), 'fail', tail);+ }+ // A className the check cannot read may carry a minHeight, which the inline style must then also set.+ assert.equal(verdict(`${HEAD}const useStyles = makeStyles({ root: { ${SCROLLS} } });\nexport default class Page extends React.Component {\n render() { return <div className="x" style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box', minHeight: 0 }} />; }\n}\n`), 'pass');+ // makeStyles and mergeClasses under another name or through a namespace.+ assert.equal(verdict(`import * as React from 'react';\nimport * as F from '@fluentui/react-components';\nconst useStyles = F.makeStyles({ root: { ${SCROLLS} } });\nexport default function Page() {\n const s = useStyles();\n return <div className={F.mergeClasses(s.root)} />;\n}\n`), 'pass');+ assert.equal(verdict(`import * as React from 'react';\nimport { makeStyles as ms } from '@griffel/react';\nconst useStyles = ms({ root: { ${SCROLLS} } });\nexport default function Page() {\n return <div className={useStyles().root} />;\n}\n`), 'unproven:computed-class');+});++test('page-scroll: what is not a page is not judged, so its result is what it was before this check — a fragment, a parse error, a page that renders nothing', () => {+ assert.equal(verdict(`${HEAD}export function Part() { return <div />; }\n`), 'not judged: no default export');+ assert.equal(verdict(`${HEAD}export default function Page() { return <div className= />; }\n`), 'not judged: parse error');+ assert.equal(verdict(`${HEAD}export default function Page() { return null; }\n`), 'not judged: renders nothing');+ assert.equal(verdict(''), 'not judged: no default export');+ // The pre-filter is a cheap regex, so a default export written in a comment only gets the parser to say "no default export".+ assert.equal(verdict(`${HEAD}// export default\nexport const x = 1;\n`), 'not judged: no default export');+});++test('page-scroll: one problem for each top element that fails, and one for each padded box on the path, in source order', () => {+ // The line and column an editor shows for the n-th `needle` in `source`.+ const at = (source, needle, n = 0) => {+ let i = -1;+ for (let k = 0; k <= n; k += 1) i = source.indexOf(needle, i + 1);+ const before = source.slice(0, i).split('\n');+ return `${before.length}:${before[before.length - 1].length + 1}`;+ };+ const source = page(` a: { ${FLEX_COLUMN} },\n b: { height: '100%' },`, ' return props.wide ? <div className={styles.a} /> : <div className={styles.b} />;');+ assert.deepEqual(pageScrollProblems(source).map((p) => `${p.code}@${p.line}:${p.column}`), [`no-scroll-context@${at(source, '<div')}`, `no-scroll-context@${at(source, '<div', 1)}`]);+ const padded = page(" wrap: { height: '100%', overflow: 'hidden', padding: '8px' },\n root: { height: '100%', overflowY: 'auto', padding: '16px' },", ' return <div className={styles.wrap}><div className={styles.root} /></div>;');+ assert.deepEqual(pageScrollProblems(padded).map((p) => `${p.code}@${p.line}:${p.column}:${p.fix.kind}`), [`scroll-context-padding@${at(padded, '<div')}:class`, `scroll-context-padding@${at(padded, '<div', 1)}:class`]);+ assert.match(pageScrollProblems(padded)[0].message, /^the page scrolls, but its <div> at line \d+ fills its container .* Add boxSizing: "border-box" to the "wrap" slot of useStyles/);+});++// ─── The remedy invariant: the edit each problem gives is one the check then accepts ────────────────────────────────────────────────────++// Applies each problem's `fix` the way its message tells an agent to, with the TypeScript parser (not a regex), and returns the new source.+function applyFixes(source, problems) {+ const sf = ts.createSourceFile('page.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+ const edits = [];+ const offset = (line, column) => sf.getPositionOfLineAndCharacter(line - 1, column - 1);+ const find = (pred) => {+ let hit = null;+ const visit = (n) => {+ if (!hit && pred(n)) hit = n;+ if (!hit) ts.forEachChild(n, visit);+ };+ visit(sf);+ return hit;+ };+ for (const p of problems) {+ const keys = p.code === 'scroll-context-padding' ? 'boxSizing: "border-box"' : p.fix.minHeight ? `${REMEDY_KEYS}, minHeight: 0` : REMEDY_KEYS;+ const at = offset(p.line, p.column);+ if (p.fix.kind === 'class') {+ const hook = find((n) => ts.isVariableDeclaration(n) && n.name.getText(sf) === p.fix.hook);+ const slot = hook.initializer.arguments[0].properties.find((x) => x.name && x.name.getText(sf).replace(/['"]/g, '') === p.fix.slot).initializer;+ // "… and delete any overflow key or shorthands.overflow(…) from that slot"+ const kept = slot.properties.map((x) => x.getText(sf)).filter((text) => p.code === 'scroll-context-padding' || !/^(?:['"]?overflow['"]?\s*:|\.\.\.shorthands\.overflow\()/.test(text));+ edits.push({ start: slot.getStart(sf), end: slot.getEnd(), text: `{ ${[...kept, keys].join(', ')} }` });+ } else if (p.fix.kind === 'style') {+ const element = find((n) => (ts.isJsxElement(n) || ts.isJsxSelfClosingElement(n)) && n.getStart(sf) === at);+ const open = ts.isJsxElement(element) ? element.openingElement : element;+ const style = open.attributes.properties.find((a) => ts.isJsxAttribute(a) && a.name.getText(sf) === 'style');+ let inner = '';+ if (style) {+ const e = style.initializer.expression;+ inner = ts.isObjectLiteralExpression(e) ? e.properties.map((x) => x.getText(sf)).join(', ') : `...(${e.getText(sf)})`;+ edits.push({ start: style.getFullStart(), end: style.getEnd(), text: '' });+ }+ // "make style its last attribute"+ edits.push({ start: open.attributes.getEnd(), end: open.attributes.getEnd(), text: ` style={{ ${inner ? `${inner}, ` : ''}${keys} }}` });+ } else {+ // The outermost expression that starts where the problem points (a pre-order walk meets it first): what the component returns.+ const outer = find((n) => ts.isExpression(n) && n.getStart(sf) === at);+ const jsx = ts.isJsxElement(outer) || ts.isJsxSelfClosingElement(outer) || ts.isJsxFragment(outer);+ edits.push({ start: outer.getStart(sf), end: outer.getEnd(), text: `<div style={{ ${REMEDY_KEYS} }}>${jsx ? outer.getText(sf) : `{${outer.getText(sf)}}`}</div>` });+ }+ }+ let out = source;+ for (const e of edits.sort((a, b) => b.start - a.start || b.end - a.end)) out = out.slice(0, e.start) + e.text + out.slice(e.end);+ return out;+}++test('page-scroll: the remedy each problem gives is accepted — on the class, as the last inline style, or as a wrapper — for every shape the check does not pass', () => {+ let fixed = 0;+ const kinds = new Set();+ for (const [name, source, expected] of CASES) {+ if (expected === 'pass') continue;+ const problems = pageScrollProblems(source);+ assert.ok(problems.length, name);+ for (const p of problems) kinds.add(`${p.code}/${p.fix.kind}`);+ const after = applyFixes(source, problems);+ assert.equal(verdict(after), 'pass', `${name}\n${after}`);+ // The remedy must not trade a scroll problem for a Griffel one.+ assert.deepEqual(griffelStyleProblems(after).problems, [], name);+ fixed += 1;+ }+ assert.ok(fixed >= 30, `${fixed} shapes fixed`);+ for (const kind of ['no-scroll-context/class', 'no-scroll-context/style', 'scroll-context-unproven/class', 'scroll-context-unproven/style', 'scroll-context-unproven/wrap', 'scroll-context-padding/class']) {+ assert.ok(kinds.has(kind), `${kind} is exercised (${[...kinds].join(', ')})`);+ }+});++test('page-scroll: the remedy works where the className cannot be read — a template string, a spread of attributes after it, a class that is not this page\'s', () => {+ for (const [source, reason] of [+ [rooted(FLEX_COLUMN).replace('className={styles.root}', 'className={`${styles.root} page`}'), 'string-class'],+ [rooted(FLEX_COLUMN, '', ' {...props.attrs}'), 'spread-attributes'],+ [rooted(FLEX_COLUMN, '', ' {...props.attrs} style={props.style}'), 'style-expression'],+ [rooted(FLEX_COLUMN).replace('className={styles.root}', 'className={props.cls}'), 'computed-class'],+ [rooted(FLEX_COLUMN).replace('className={styles.root}', 'className={mergeClasses(...props.classes)}'), 'computed-class'],+ [page('', " return <div className=\"page\" style={{ height: '100%', overflow: 'hidden', padding: '16px' }}><Text>Rows</Text></div>;"), null],+ ]) {+ const problems = pageScrollProblems(source);+ // An inline style is read even on an element whose classes are not: an inline overflow of hidden is known not to scroll.+ assert.deepEqual(problems.map((p) => [p.code, p.reason, p.fix.kind]), [[reason ? 'scroll-context-unproven' : 'no-scroll-context', reason || undefined, 'style']], source);+ assert.ok(problems[0].message.includes('make style its last attribute: an inline style wins over every class'), problems[0].message);+ assert.equal(verdict(applyFixes(source, problems)), 'pass', applyFixes(source, problems));+ }+});++test('page-scroll: the remedy also writes minHeight: 0 where a minHeight may be larger than the container, and only there', () => {+ for (const source of [rooted(`${FLEX_COLUMN}, minHeight: 2000`), page('', ` return (<div style={{ height: '100%', minHeight: 2000, overflowY: 'auto' }}>${TALL}</div>);`)]) {+ const problems = pageScrollProblems(source);+ assert.equal(problems.length, 1, source);+ assert.equal(problems[0].fix.minHeight, true);+ assert.ok(problems[0].message.includes(`${REMEDY_KEYS}, minHeight: 0`), problems[0].message);+ assert.equal(verdict(applyFixes(source, problems)), 'pass');+ }+ const plain = pageScrollProblems(rooted(`${FLEX_COLUMN}, minHeight: '100%'`));+ assert.equal(plain[0].fix.minHeight, undefined);+ assert.ok(!plain[0].message.includes('minHeight: 0'), plain[0].message);+});++test('page-scroll: the class is the fix only when the slot provably wins — another class with an overflow key, or an inline key the remedy writes, moves it inline', () => {+ const fixOf = (source) => pageScrollProblems(source).map((p) => p.fix.kind).join();+ assert.equal(fixOf(rooted(FLEX_COLUMN)), 'class');+ assert.equal(fixOf(page(` base: { overflowY: 'hidden' },\n root: { ${FLEX_COLUMN} },`, ' return <div className={mergeClasses(styles.base, styles.root)} />;')), 'style');+ assert.equal(fixOf(rooted(FLEX_COLUMN, '', " style={{ height: 'auto' }}")), 'style');+ assert.equal(fixOf(rooted(FLEX_COLUMN, '', " style={{ boxSizing: 'content-box' }}")), 'style');+ assert.equal(fixOf(rooted(FLEX_COLUMN, " on: { display: 'block' },").replace('className={styles.root}', 'className={mergeClasses(styles.root, props.on && styles.on)}')), 'style');+ assert.equal(fixOf(rooted(FLEX_COLUMN, ' on: { color: tokens.colorBrandForeground1 },').replace('className={styles.root}', 'className={mergeClasses(styles.root, props.on && styles.on)}')), 'class');+});++// ─── The committed pages ───────────────────────────────────────────────────────────────────────────────────────────────────────────────++function committedPages(t) {+ try {+ // Through `git ls-files`, not a directory walk: capture-fixture.test.js creates and deletes transient fixture folders while the suite runs.+ return execFileSync('git', ['ls-files', '-z', '*.tsx'], { cwd: REPO, encoding: 'utf8' }).split('\0').filter(Boolean);+ } catch {+ t.skip('not a git checkout');+ return null;+ }+}++test('page-scroll: every sample the page builder learns from establishes a scroll context with no padding overhang', (t) => {+ const pages = committedPages(t);+ if (!pages) return;+ const samples = pages.filter((p) => p.startsWith('plugins/model-apps/samples/'));+ assert.ok(samples.length >= 13, `${samples.length} samples`);+ for (const sample of samples) assert.equal(verdict(fs.readFileSync(path.join(REPO, sample), 'utf8')), 'pass', sample);+});++test('page-scroll: the captured eval pages keep the verdicts they were measured with — a parser change that flips one shows here', (t) => {+ const pages = committedPages(t);+ if (!pages) return;+ const { CAPTURED_BEFORE_THE_RULE } = require('../../../../evals/model-apps/genpage/lib/scroll-context.js');+ const captured = pages.filter((p) => p.startsWith('evals/model-apps/genpage/fixtures/'));+ const seen = {};+ for (const p of captured) seen[p.slice('evals/model-apps/genpage/fixtures/'.length)] = verdict(fs.readFileSync(path.join(REPO, p), 'utf8'));+ for (const [file, expected] of Object.entries(CAPTURED_BEFORE_THE_RULE)) assert.equal(seen[file], expected, file);+ // A captured page not in the list is graded by the eval, so it must pass.+ for (const [file, v] of Object.entries(seen)) if (!(file in CAPTURED_BEFORE_THE_RULE)) assert.equal(v, 'pass', `${file} is graded by the eval and must pass`);+});++test('page-scroll: every code sample in the plugin\'s instructions that is a whole page establishes a scroll context, but for the excerpts listed', () => {+ // A fenced block with a default export is a page the builder may copy; one without is a fragment and is not judged. The blocks that+ // do not pass are excerpts about something other than layout, each listed with why it is left as it is.+ const EXCERPTS = [+ // The page error wrapper as a three-line excerpt: PageErrorBoundary and PageBody are defined in rules.md, not in the block.+ 'agents/genpage-page-builder.md unproven:library-top',+ 'agents/genpage-page-builder.md unproven:library-top',+ 'references/dataverse-operations.md unproven:library-top',+ 'references/rules.md unproven:library-top',+ // The canonical page error block of "Missing Error Handling": its PageBody shows the error bar, not a page layout, and the+ // block is executed as written by page-error-reference.test.js and the eval's page-error teaching test.+ 'references/rules.md fail',+ ];+ const seen = [];+ for (const dir of ['references', 'skills', 'agents']) {+ const walk = (d) => {+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {+ const full = path.join(d, entry.name);+ if (entry.isDirectory()) walk(full);+ else if (entry.name.endsWith('.md')) {+ const lines = fs.readFileSync(full, 'utf8').replace(/\r\n/g, '\n').split('\n');+ for (let i = 0; i < lines.length; i += 1) {+ const open = /^\s*(`{3,}|~{3,})(?:tsx|typescript|ts)\s*$/.exec(lines[i]);+ if (!open) continue;+ let end = i + 1;+ while (end < lines.length && !lines[end].trimStart().startsWith(open[1])) end += 1;+ const body = lines.slice(i + 1, end).join('\n');+ if (analyzePageScroll(body).judged) seen.push(`${path.relative(PLUGIN, full).replace(/\\/g, '/')} ${verdict(body)}`);+ i = end;+ }+ }+ }+ };+ walk(path.join(PLUGIN, dir));+ }+ assert.deepEqual(seen.filter((s) => !s.endsWith(' pass')).sort(), [...EXCERPTS].sort());+});diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.jsindex 3af9d299d..56ffc7b30 100644--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js@@ -1250,6 +1250,8 @@ test('deploy: a page already deployed with a dropped key and sent again UNCHANGEassert.ok(warning.includes('detail.tsx:7:24: `borderColor` is not supported by Griffel'), 'and the second');assert.ok(warning.includes(BOTH_WAYS_OUT), 'both ways out');assert.match(warning, /lists every one\); once the page's source changes, the build holds it to the check and stops on anything the check still reports\.$/);+ // The page is deployed already, so the checker it suggests is the one for an existing page: its scroll findings are notes (Styling gotchas 6).+ assert.ok(warning.includes('`node scripts/check-griffel-styles.js --file <page.tsx> --existing`'), warning);// A caller that does not listen (no `warn`) goes on all the same: the warning is advice, never a condition.await app.rebuild({ baselineSpec, warn: undefined }).run();} finally { app.cleanup(); }@@ -1301,6 +1303,7 @@ test('deploy: a page that is UPDATED with a changed source is held to the checkassert.ok(e.message.includes('detail.tsx:4:5: `borderWidth`') && e.message.includes('detail.tsx:7:24: `borderColor`'), 'each key, where it is');assert.ok(e.message.includes(BOTH_WAYS_OUT), 'both ways out');assert.ok(e.message.includes('Its source changed since the last build recorded for it, so it is held to the check as a new page is; left as it was, it would only be warned about. Fix them in the page\'s source'), 'and why this page is held to it');+ assert.ok(e.message.includes('`node scripts/check-griffel-styles.js --file <page.tsx> --existing` lists every one'), 'a changed page is still a deployed one: the checker it suggests reports scroll findings as notes');return true;});assert.deepStrictEqual(r.genpageCli.uploads, [], 'neither page was written');@@ -1342,6 +1345,7 @@ test('deploy: a page that exists but has no record in this workspace is warned aassert.strictEqual(r.warnings.length, 1, what);assert.ok(r.warnings[0].startsWith('page "Detail" is already deployed, and this workspace holds no record of what the last build sent for it, so the build cannot tell whether this send changes it; it goes on, as builds did before this check. '), `${what}: ${r.warnings[0]}`);assert.ok(r.warnings[0].includes('detail.tsx:4:5: `borderWidth`') && r.warnings[0].includes(BOTH_WAYS_OUT), what);+ assert.ok(r.warnings[0].includes('`node scripts/check-griffel-styles.js --file <page.tsx> --existing`'), `${what}: the checker for a deployed page`);assert.ok(r.warnings[0].endsWith('once a build has recorded this page, a change to its source is held to the check, and the build stops on anything the check still reports.'), `${what}: what happens from then on`);}} finally { app.cleanup(); }@@ -1354,6 +1358,7 @@ test('deploy: a page that exists but has no record in this workspace is warned aawait assert.rejects(runSdkBuild(fresh.spec, { sdk: mockSdk().sdk, apply: true, env: 'https://x', appDir: fresh.appDir, genpageCli, phases: PHASES, baselineSpec }),(e) => e.code === 'pages-griffel-shorthand' && /page "Detail" writes CSS/.test(e.message) && !/Its source changed/.test(e.message)+ && e.message.includes('`node scripts/check-griffel-styles.js --file <page.tsx>` lists every one'));assert.deepStrictEqual(genpageCli.uploads, []);} finally { fs.rmSync(fresh.appDir, { recursive: true, force: true }); }@@ -1399,7 +1404,7 @@ test('deploy: a makeStyles call the checker cannot read is reported as that —assert.ok(e.message.startsWith('page "Detail" has makeStyles calls the Griffel check could not read, so it cannot tell whether the page writes CSS that Griffel drops at runtime — detail.tsx:3:19: the makeStyles call here cannot be checked for certain'), e.message);assert.doesNotMatch(e.message, /writes CSS that Griffel drops at runtime, so the page would deploy without it/, 'it is not said to write any');assert.match(e.message, /put an operand in parentheses, \(\{ … \}\) \/ 2 or \(\/re\/\)\.test\(text\), or end the statement with a ";" — or move the makeStyles call above it\./);- assert.match(e.message, /Its source changed since the last build recorded for it, so it is held to the check as a new page is; left as it was, it would only be warned about\. Change the page's source as that says \(`node scripts\/check-griffel-styles\.js --file <page\.tsx>` shows what it cannot read\), then re-run\.$/);+ assert.match(e.message, /Its source changed since the last build recorded for it, so it is held to the check as a new page is; left as it was, it would only be warned about\. Change the page's source as that says \(`node scripts\/check-griffel-styles\.js --file <page\.tsx> --existing` shows what it cannot read\), then re-run\.$/);return true;});assert.deepStrictEqual(held.genpageCli.uploads, []);diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.mdindex 35cffa8df..27084afa6 100644--- a/plugins/model-apps/skills/app-builder/SKILL.md+++ b/plugins/model-apps/skills/app-builder/SKILL.md@@ -573,6 +573,12 @@ After plan-mode approval (before the full build):that starts with `--`, `&`, `:` or `@` is read); Fluent's `...shorthands.*(…)` and`...typographyStyles.*` may be spread as they are.+ The same command checks that each page establishes a scroll context (`references/rules.md`,+ **Page Layout**): the host shows a page in a container of fixed height and never scrolls it, so a+ page with none is cut off below the fold. `no-scroll-context`, `scroll-context-unproven` and+ `scroll-context-padding` are problems like any other, each with the edit that fixes it: apply it+ and run the check again.+Review every generated page for iteration that another page compiler can lose as well:Pages this plugin uploads are compiled with iterator support (ES5 with `downlevelIteration`), so a@@ -1039,9 +1045,10 @@ Then:the folder that pins `languageCode` needs neither). Do not guess it: a spec whose titles were read in thewrong language writes them over the right ones on the next build.2. Edit `app-spec.json` (and any page `.tsx`) for the requested change. A page you edit by hand is- checked like a generated one: run `node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file <page.tsx>`+ checked like a generated one: run `node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file <page.tsx> --existing`on it before you rebuild (the rule and the ten shorthands are in Phase 1.5, step 5) and fix what it- reports. A key the page already had when it was downloaded is reported too: the deployed page renders+ reports. `--existing` reports the page's scroll context (`references/rules.md`, **Page Layout**) in+ `notes` without changing the exit code: tell the user about each note and offer the edit it gives. A key the page already had when it was downloaded is reported too: the deployed page renderswithout it today, so deleting it keeps the page looking as it does, while writing the longhands makesthe style start to render — delete it unless the user wants that change. The build runs the samecheck on every page it uploads that is new or that you changed since the last successful apply of this app, and halts asdiff --git a/plugins/model-apps/skills/genpage/SKILL.md b/plugins/model-apps/skills/genpage/SKILL.mdindex 06f595d9c..127a664c5 100644--- a/plugins/model-apps/skills/genpage/SKILL.md+++ b/plugins/model-apps/skills/genpage/SKILL.md@@ -886,7 +886,7 @@ subagent. Inline the page-builder workflow directly in the orchestrator:Rewrite any unverified names with the closest verified alternative; do notload the full icon list into context9. Check the generated file for the Griffel shorthands that `makeStyles` drops at- runtime:+ runtime, and for a scroll context:```powershellnode "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<filename>.tsx'@@ -919,6 +919,13 @@ subagent. Inline the page-builder workflow directly in the orchestrator:cannot see (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's`...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.+ The same command checks that the page establishes a scroll context+ (`references/rules.md`, **Page Layout**): the host shows a page in a container of+ fixed height and never scrolls it, so a page with none is cut off below the fold.+ `no-scroll-context`, `scroll-context-unproven` and `scroll-context-padding` are+ problems like any other, each with the edit that fixes it: apply it and run the+ check again.+Then review the page for iteration that another page compiler can lose:Pages this plugin uploads are compiled with iterator support (ES5 with@@ -1039,7 +1046,8 @@ check themselves; run it on every generated page, exactly as in step 9 of Phasenode "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<filename>.tsx'```-and fix what it reports in the page yourself before Phase 6. A page that has not+and fix what it reports in the page yourself before Phase 6, its scroll context+included (step 9). A page that has notexited 0 is not deployed. Review every generated page for iteration that another pagecompiler can lose as well, and fix it yourself: the workers follow the same rule(`references/rules.md`, **Common Errors > 5. Iteration that another page compiler can lose**).@@ -1194,7 +1202,8 @@ did not already have (below). The result is `"code":"griffel-shorthand"`, with eand what each way out does in `error` (and the same list in `problems`). That is the same check as`check-griffel-styles.js`, held at the one place every upload passes, so a page that skipped the earlier gate still cannotship a key it added without its border. Fix the page and run the upload again; no flag skips it, and-`--overwrite-deployed` does not. The upload reads the code file once and writes exactly the text it checked, so a change saved+`--overwrite-deployed` does not. The upload does not check a page's scroll context: only `check-griffel-styles.js`+does (Phase 5b step 9). The upload reads the code file once and writes exactly the text it checked, so a change savedto the file after the upload started is not sent — run the upload again to send it. It does not take `--compiled-code-file`: the SDKcompiles the checked file itself.diff --git a/plugins/model-apps/skills/genpage/edit-flow.md b/plugins/model-apps/skills/genpage/edit-flow.mdindex 01f180ace..8c86e17b1 100644--- a/plugins/model-apps/skills/genpage/edit-flow.md+++ b/plugins/model-apps/skills/genpage/edit-flow.md@@ -519,7 +519,7 @@ Before Edit Phase 6, check the edited page for the Griffel shorthands that`makeStyles` drops at runtime:```powershell-node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<page-id>/page.tsx'+node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<page-id>/page.tsx' --existing```Griffel does not support ten CSS shorthands, and `makeStyles` drops them at@@ -549,6 +549,19 @@ keys, and so is a key computed from an expression (`[key]: …`), whose name itsee (a template that starts with `--`, `&`, `:` or `@` is read); Fluent's`...shorthands.*(…)` and `...typographyStyles.*` may be spread as they are.+`--existing` is there because this page was not generated in this run: the check+also reads its scroll context (`references/rules.md`, **Page Layout**), and reports+what it finds in `notes` without changing the exit code, so a maker's layout never+blocks their edit.++When the maker's requested edit itself rewrites the page's top-level layout, that+layout is new code written in this run and must follow the scroll rule: apply the+remedy as part of that edit, and tell the maker in one sentence that you did. Any+other scroll note on a downloaded page is offer-only: tell the maker that content+below the fold may be cut off, offer the edit its message gives, and apply it only+if they agree. A note is never a reason to change a layout the maker did not ask+to change.+A page that was deployed before this check existed can already hold such a key, so thechecker may report one that your edit did not add. The deployed page renders without ittoday, which is why there are two ways out: **delete the key** — nothing changes on@@ -698,6 +711,8 @@ Log the marker, the check result (`code`, `lines`, `deployedCopy`) and that `Cho## Edit Phase 7: Verify (Optional)Offer browser verification via `AskUserQuestion` (same flow as Phase 7 in the create flow — see SKILL.md).+The page is still an existing one: if 7.5 in `verify-flow.md` fixes it, check the fix with the+`--existing` command that 7.5 gives for the edit flow, not the command for a generated page.## Edit Phase 8: Summarydiff --git a/plugins/model-apps/skills/genpage/verify-flow.md b/plugins/model-apps/skills/genpage/verify-flow.mdindex 4d4f2b1f6..f6872e041 100644--- a/plugins/model-apps/skills/genpage/verify-flow.md+++ b/plugins/model-apps/skills/genpage/verify-flow.md@@ -22,29 +22,123 @@ https://<env>.crm.dynamics.com/main.aspx?appid=<app-id>&pagetype=genux&id=<page-Take an initial `browser_snapshot` to capture above-the-fold content.-**Check whether the page extends beyond the viewport:**+The host gives the page a fixed-height container, and nothing above the page+scrolls: the window stays at the top, so `window.scrollTo` moves nothing. A page+shows content below the fold only by scrolling an element of its own+(`references/rules.md`, **Page Layout**). A `browser_snapshot` is not proof that+content can be seen: it lists elements that are cut off as well.++**Find the page's scroller.** It is an element that scrolls (`overflow-y` is+`auto` or `scroll`) and holds more than it shows. The script marks the largest+one and lists up to three:```javascript-browser_evaluate(() => ({- scrollHeight: document.documentElement.scrollHeight,- clientHeight: document.documentElement.clientHeight-}))+browser_evaluate(() => {+ const pick = 0; // the index of the entry that holds the page's content+ const found = [...document.querySelectorAll('body *')]+ .filter((el) => /^(auto|scroll|overlay)$/.test(getComputedStyle(el).overflowY)+ && el.clientHeight > 0 && el.scrollHeight > el.clientHeight + 1)+ .sort((a, b) => b.clientWidth * b.clientHeight - a.clientWidth * a.clientHeight);+ document.querySelectorAll('[data-verify-scroller]').forEach((el) => el.removeAttribute('data-verify-scroller'));+ if (found[pick]) found[pick].setAttribute('data-verify-scroller', '');+ return found.slice(0, 3).map((el) => ({ tag: el.tagName, scrollHeight: el.scrollHeight,+ clientHeight: el.clientHeight, text: el.innerText.slice(0, 60) }));+})```-**If `scrollHeight > clientHeight`, the page has content below the fold.**-Scroll through to verify all sections render:+Check that the marked entry (`pick`) shows the page's own text, not the app's+navigation. If another entry does, run the script again with `pick` set to its+index.-1. Scroll to the bottom:- ```javascript- browser_evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight))- ```-2. Take a fresh `browser_snapshot` to capture below-the-fold content.-3. For very tall pages (long lists, multi-section dashboards), scroll- incrementally and snapshot each section:+**If no entry holds the page's content, check whether the page is cut off:**++```javascript+browser_evaluate(() => [...document.querySelectorAll('body *')]+ .filter((el) => { const r = el.getBoundingClientRect();+ return r.width > 1 && r.height > 1 && r.bottom > window.innerHeight + 1+ && getComputedStyle(el).visibility !== 'hidden'; })+ .slice(0, 5).map((el) => ({ tag: el.tagName, bottom: el.getBoundingClientRect().bottom,+ text: (el.innerText || '').slice(0, 60) })))+```++An empty list means the whole page fits on the screen. Any entry is content+below the visible area that nothing can scroll to: the page has no scroll+context. Fix it in 7.5.++**If the page has a scroller, scroll it to the end and prove the last content+is visible:**++```javascript+browser_evaluate(() => {+ const el = document.querySelector('[data-verify-scroller]');+ el.scrollTop = el.scrollHeight;+ const scrolls = (a) => /^(auto|scroll|overlay)$/.test(getComputedStyle(a).overflowY);+ // Content inside a scroll region of its own (a list in a panel) is checked in the next step.+ const own = (d) => { for (let a = d.parentElement; a && a !== el; a = a.parentElement) if (scrolls(a)) return false; return true; };+ // The lowest visible point: the scroller and each ancestor that clips cut off what is below them.+ let visibleBottom = window.innerHeight;+ for (let a = el; a && a !== document.documentElement; a = a.parentElement)+ if (a === el || getComputedStyle(a).overflowY !== 'visible')+ visibleBottom = Math.min(visibleBottom, a.getBoundingClientRect().bottom);+ const lastContentBottom = Math.max(...[...el.querySelectorAll('*')].filter(own)+ .map((d) => d.getBoundingClientRect()).filter((r) => r.width > 1 && r.height > 1)+ .map((r) => r.bottom));+ const regions = [...el.querySelectorAll('*')]+ .filter((d) => scrolls(d) && d.clientHeight > 0 && d.scrollHeight > d.clientHeight + 1).length;+ return { atEnd: Math.ceil(el.scrollTop + el.clientHeight) >= el.scrollHeight,+ lastContentBottom, visibleBottom, lastContentVisible: lastContentBottom <= visibleBottom + 1, regions };+})+```++`lastContentVisible` must be `true`. If it is `false`, the end of the page is cut+off even at the end of the scroll. Usually the scroller is taller than the+host's container because its padding is added to `height: "100%"`. Fix it in 7.5.++**If `regions` is more than 0, check each scroll region inside the scroller the+same way.** A region of its own (a list in a fixed-height panel) is not a defect+of the page's layout until its own end is proven cut off, so scroll each one to+its end too:++```javascript+browser_evaluate(() => {+ const root = document.querySelector('[data-verify-scroller]');+ const scrolls = (a) => /^(auto|scroll|overlay)$/.test(getComputedStyle(a).overflowY);+ const regions = [...root.querySelectorAll('*')]+ .filter((d) => scrolls(d) && d.clientHeight > 0 && d.scrollHeight > d.clientHeight + 1);+ return regions.map((el) => {+ el.scrollTop = el.scrollHeight;+ const own = (d) => { for (let a = d.parentElement; a && a !== el; a = a.parentElement) if (scrolls(a)) return false; return true; };+ let visibleBottom = window.innerHeight;+ for (let a = el; a && a !== document.documentElement; a = a.parentElement)+ if (a === el || getComputedStyle(a).overflowY !== 'visible')+ visibleBottom = Math.min(visibleBottom, a.getBoundingClientRect().bottom);+ const lastContentBottom = Math.max(...[...el.querySelectorAll('*')].filter(own)+ .map((d) => d.getBoundingClientRect()).filter((r) => r.width > 1 && r.height > 1)+ .map((r) => r.bottom));+ return { tag: el.tagName, text: (el.innerText || '').slice(0, 60), lastContentBottom, visibleBottom,+ lastContentVisible: lastContentBottom <= visibleBottom + 1 };+ });+})+```++Every entry's `lastContentVisible` must be `true`; one that is `false` names the+region whose end is cut off (usually its own padding on `height: "100%"`). Fix+it in 7.5.++Then verify that all sections render:++1. Take a fresh `browser_snapshot` and a `browser_take_screenshot` at the end+ of the scroll.+2. For very tall pages (long lists, multi-section dashboards), start at the top+ and scroll one screen at a time. Take a snapshot and a screenshot at each+ position:```javascript- browser_evaluate(() => window.scrollBy(0, window.innerHeight))+ browser_evaluate(() => {+ const el = document.querySelector('[data-verify-scroller]');+ el.scrollTop += el.clientHeight;+ return { scrollTop: el.scrollTop, atEnd: Math.ceil(el.scrollTop + el.clientHeight) >= el.scrollHeight };+ })```-4. Use `browser_take_screenshot` at each scroll position to capture visuals.Verify expected DOM elements are present somewhere on the page (not justabove-the-fold):@@ -59,9 +153,11 @@ above-the-fold):| File Upload | File input or drop zone element || Navigation Sidebar | Nav element with menu items |-**Scroll back to the top before interactive testing:**+**Scroll back to the top before interactive testing** (when the page has a+scroller):```javascript-browser_evaluate(() => window.scrollTo(0, 0))+browser_evaluate(() => { document.querySelector('[data-verify-scroller]').scrollTop = 0;+ document.querySelectorAll('[data-verify-scroller] *').forEach((el) => { if (el.scrollTop) el.scrollTop = 0; }); })```## 7.3 Interactive Testing@@ -86,11 +182,14 @@ validation, pagination.Use `browser_take_screenshot` to capture the page in its final verified state.-For pages taller than the viewport, capture multiple screenshots by scrolling:-top (`window.scrollTo(0, 0)`), one or more intermediate positions for long-pages, and bottom-(`window.scrollTo(0, document.documentElement.scrollHeight)`). This gives a-complete visual record for the deployment summary.+For pages taller than the viewport, capture multiple screenshots by scrolling+the page's scroller (7.2), not the window: the top+(`document.querySelector('[data-verify-scroller]').scrollTop = 0`), one or more+intermediate positions for long pages (`scrollTop += clientHeight`, as in 7.2),+and the end (`scrollTop = scrollHeight`). A scroll region inside it (7.2) is+captured at its end too, after the script that checks the regions. Run the 7.2 scripts again first if+the marker is gone (the page was reloaded). This gives a complete visual record+for the deployment summary.## 7.5 Fix and Re-deploy@@ -105,8 +204,28 @@ fixed page before the re-deploy:node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<file>.tsx'```+That command is for a page generated in this run (you came here from Phase 7 of+the create flow). If you came from **Edit Phase 7**, the page was downloaded, not+generated, so check it as Edit Phase 5 does — with `--existing`:++```powershell+node "${PLUGIN_ROOT}/scripts/check-griffel-styles.js" --file '<working-dir>/<page-id>/page.tsx' --existing+```++With `--existing`, the page's scroll context is reported in `notes` and does not+change the exit code. Handle each note as Edit Phase 5 says:++When the maker's requested edit itself rewrites the page's top-level layout, that+layout is new code written in this run and must follow the scroll rule: apply the+remedy as part of that edit, and tell the maker in one sentence that you did. Any+other scroll note on a downloaded page is offer-only: tell the maker that content+below the fold may be cut off, offer the edit its message gives, and apply it only+if they agree. A note is never a reason to change a layout the maker did not ask+to change.+Do not upload until it exits 0: fix what it reports (each key's line, column and longhands)-and run it again. `genpage-upload.js` makes the same check and refuses a page that adds a key the+and run it again. The same command checks that the fixed page still establishes a scroll context+(`references/rules.md`, **Page Layout**); a scroll problem is fixed with the edit its message gives. `genpage-upload.js` makes the same check and refuses a page that adds a key thedeployed page did not already have, or gives one it had another value (`griffel-shorthand`), so skipping this step costs a refusedupload, not a shipped defect. A key the page already had before your fix, set the same, is reported as well:delete it to keep the page looking as it does, or write the longhands to make the style start to