pi-odd-worktree 3.15.0 → 3.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +64 -211
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/lib/user-prompt-card.js +48 -2
  43. package/package.json +3 -2
  44. package/tools/files-bridge.test.js +81 -66
  45. package/tools/fixtures/load-extension.js +40 -18
  46. package/tools/issues-command.test.js +4 -7
  47. package/tools/issues-section.test.js +71 -81
  48. package/tools/odd-rail-wiring.test.js +16 -10
  49. package/tools/package-surface.test.js +42 -13
  50. package/tools/prs-command.test.js +11 -6
  51. package/tools/shell-api/api.test.ts +484 -0
  52. package/tools/shell-api/apply-on-move.test.ts +529 -0
  53. package/tools/shell-api/arm.test.ts +220 -0
  54. package/tools/shell-api/bridge-ready.test.ts +309 -0
  55. package/tools/shell-api/bus.test.ts +194 -0
  56. package/tools/shell-api/button-rows.test.ts +435 -0
  57. package/tools/shell-api/capture.test.ts +583 -0
  58. package/tools/shell-api/card-style-rows.test.ts +493 -0
  59. package/tools/shell-api/card-style-transform.test.ts +379 -0
  60. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  61. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  62. package/tools/shell-api/card-styles.test.ts +324 -0
  63. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  64. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  65. package/tools/shell-api/config.test.ts +93 -0
  66. package/tools/shell-api/docs-coverage.test.ts +82 -0
  67. package/tools/shell-api/e2e.test.ts +562 -0
  68. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  69. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  70. package/tools/shell-api/example-designs.test.ts +737 -0
  71. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  72. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  73. package/tools/shell-api/extension.test.ts +157 -0
  74. package/tools/shell-api/fake-events.ts +58 -0
  75. package/tools/shell-api/fake-host.ts +211 -0
  76. package/tools/shell-api/fake-sidebar.ts +516 -0
  77. package/tools/shell-api/fake-transcript.ts +486 -0
  78. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  79. package/tools/shell-api/hook.test.ts +196 -0
  80. package/tools/shell-api/manifest.test.ts +47 -0
  81. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  82. package/tools/shell-api/message-design-follows.test.ts +361 -0
  83. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  84. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  85. package/tools/shell-api/message-design-rows.test.ts +266 -0
  86. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  87. package/tools/shell-api/message-designs.test.ts +339 -0
  88. package/tools/shell-api/new-category.test.ts +1101 -0
  89. package/tools/shell-api/notices.test.ts +292 -0
  90. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  91. package/tools/shell-api/presence.test.ts +396 -0
  92. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  93. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  94. package/tools/shell-api/rail-width.test.ts +406 -0
  95. package/tools/shell-api/regression.test.ts +434 -0
  96. package/tools/shell-api/repaint-api.test.ts +200 -0
  97. package/tools/shell-api/reserved-categories.test.ts +250 -0
  98. package/tools/shell-api/row-labels.test.ts +261 -0
  99. package/tools/shell-api/row-names.test.ts +407 -0
  100. package/tools/shell-api/row-origin.test.ts +395 -0
  101. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  102. package/tools/shell-api/row-placement.test.ts +410 -0
  103. package/tools/shell-api/section-interaction.test.ts +364 -0
  104. package/tools/shell-api/section-panel.test.ts +430 -0
  105. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  106. package/tools/shell-api/section-placement.test.ts +386 -0
  107. package/tools/shell-api/sections-preview.test.ts +312 -0
  108. package/tools/shell-api/sections-rows.test.ts +293 -0
  109. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  110. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  111. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  112. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  113. package/tools/shell-api/sidebar-render.test.ts +281 -0
  114. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  115. package/tools/shell-api/store.test.ts +192 -0
  116. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  117. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  118. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  119. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  120. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  121. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  122. package/tools/shell-api/tool-designs.test.ts +2412 -0
  123. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  124. package/tools/shell-api/transforms-bus.test.ts +233 -0
  125. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  126. package/tools/shell-api-rpc.test.js +189 -0
  127. package/tools/user-prompt-card.test.js +80 -10
@@ -0,0 +1,1340 @@
1
+ /**
2
+ * Capture backend (docs/architecture.md §2–§5, docs/contract.md §5, §7).
3
+ *
4
+ * gentle-shell's `ctx.ui.custom` factory returns a plain adapter, not the view, so the rows
5
+ * array is unreachable by duck-typing. The only reachable moment is the view constructor's
6
+ * `options.rows.map(...)` (`lib/visual-customize-view.ts:387`), which runs synchronously inside
7
+ * the factory call. So: swap `Array.prototype.map` for the duration of the outermost factory
8
+ * call, record every row-like array it is invoked on BY REFERENCE, restore the original in
9
+ * `finally`, then push the providers' rows into that captured array and invalidate the adapter.
10
+ *
11
+ * ## Two moments, because the view fixes its page list in the constructor (S18)
12
+ *
13
+ * The view derives `categories` ONCE, in the constructor
14
+ * (`this.categories = [...new Set(options.rows.map(row => row.category ?? "Settings"))]`,
15
+ * `lib/visual-customize-view.ts:387`). `categoryRows()` then filters `options.rows` live
16
+ * (`:391-393`), which is why a row that joins an EXISTING page appears after a late push — and
17
+ * why a row that names a BRAND-NEW page never did: the page list was already fixed, so nothing
18
+ * could select it.
19
+ *
20
+ * So the probe injects at the earlier moment too, for the one array it can PROVE is the menu's,
21
+ * BEFORE that array's `map` reads it. The host's `Set` then contains the new pages, in registry
22
+ * order, after the host's own pages.
23
+ *
24
+ * ## The early step is provisional and is reconciled at the end of the factory (S20)
25
+ *
26
+ * The early step is a GUESS about which array is the menu, made before the factory finished; the
27
+ * late decision is the one that knows (it holds every candidate, the ambiguity rule and the async
28
+ * check). So the early step is provisional, and the late decision has the last word:
29
+ *
30
+ * - every early push is recorded: the array, where the rows were appended, the rows themselves, the
31
+ * `Card style` splice it made, and the marker it set;
32
+ * - when the factory returns a component the late decision runs. If it picks the SAME array, the
33
+ * rows stay and the build is reported `injected`; if it picks ANOTHER array, the session proved
34
+ * several (ambiguous), or the factory returned a promise, the early rows, the splice and the
35
+ * marker are REMOVED from the early array and the previous behaviour applies exactly;
36
+ * - when the factory throws, the same rollback runs in the `finally` that restores
37
+ * `Array.prototype.map`, so a throw leaves no trace — and a session only ever rolls back the
38
+ * array it pushed into, so an inner factory's rollback can never touch the outer session's rows.
39
+ *
40
+ * Net guarantee: after any factory invocation, no array holds bridge rows except the one the late
41
+ * decision chose. The cost, stated honestly: for the duration of the factory an array that
42
+ * satisfies the strict proof can hold bridge rows, visible only to code running inside that
43
+ * factory, and the guess is undone whenever the decision disagrees with it.
44
+ *
45
+ * ## The proof: what makes an array the menu's rows
46
+ *
47
+ * Nothing is written to an array that is not PROVEN at that `map` call, and the proof runs on
48
+ * EVERY call — never once per array, because the host may map its rows to something else first.
49
+ * A `map` call proves the array when the callback, run exactly as `Array.prototype.map` runs it:
50
+ *
51
+ * - derives `row.category ?? "Settings"` for every element of the array;
52
+ * - derives `"Settings"` for a synthetic row with NO category, and a unique sentinel page for a
53
+ * synthetic row naming it — so `row => row.category` and any constant mapper cannot qualify on
54
+ * the host's own rows alone;
55
+ * - does not throw (a throw means "not proven", never a broken host call);
56
+ * - and derives `row.category ?? "Settings"` for every row the bridge is about to append, run over
57
+ * them BEFORE they are pushed, so the host's own `map` can never throw because of a bridge row.
58
+ *
59
+ * Stated cost of the proof: the host's mapper runs over the host's own rows once more per row-like
60
+ * `map` call, and once over each row the bridge appends. It is the host's own
61
+ * `row => row.category ?? "Settings"`, pure by construction in the host; a mapper with side effects
62
+ * sees them once more per element, which is the price of not guessing.
63
+ *
64
+ * Exactly one injection happens per menu build: the early path records what it pushed, the late
65
+ * path reports that and does not repeat it, and the array marker keeps a second build of the same
66
+ * menu from injecting twice.
67
+ *
68
+ * ## Capture-selection rule (why a wrong target can never be silent)
69
+ *
70
+ * Each wrapped `custom` call owns one capture *session* and one candidate list, and the probe
71
+ * records a mapped array into the innermost active session only. The probe is installed around the
72
+ * FACTORY INVOCATION, not around the host call, so a host that resolves its factory in a later
73
+ * microtask (`Promise.resolve().then(factory)`) is still covered; a factory that itself returns a
74
+ * promise stays the documented unsupported case, and the early guess is rolled back for it.
75
+ *
76
+ * - A nested `custom` call — from the host factory or from a provider's own `rows()` — gets its
77
+ * own session, so it can never steal the outer menu's capture, and its menu receives its own
78
+ * injection.
79
+ * - A nested session that throws rolls back only its own array: nothing is left in it, and the
80
+ * outer session continues and resolves its own array.
81
+ * - If ONE session captures more than one row-like array (an incidental row-shaped array before
82
+ * the menu, for example) the bridge does not guess: the outcome is `uncaptured (ambiguous)` and
83
+ * nothing is injected. The one exception is the proof above: when exactly ONE of those arrays
84
+ * derives pages like the menu does, that array is the menu by evidence and is what the late path
85
+ * takes (S18 needs it, or a brand-new page could never be reached); two proven arrays are
86
+ * ambiguous, and so are two unproven ones.
87
+ *
88
+ * Diagnostics never claim an injection into an array that received nothing.
89
+ *
90
+ * Arming is idempotent per target: the non-enumerable marker holds the exact wrapper function it
91
+ * installed, and is read as an OWN property, so a rebind that installs a new `custom` on an
92
+ * instance inheriting an already-wrapped prototype always rearms. Every wrapper also carries the
93
+ * generation it was created in: `disableCaptureBackend()` bumps the generation, so a wrapper that
94
+ * foreign code kept a reference to becomes a plain pass-through instead of injecting later.
95
+ *
96
+ * Shared state lives on `globalThis` behind a `Symbol.for` key, like the bus: a second copy of
97
+ * this package loaded by jiti's `moduleCache: false` must see the same arming, the same sessions
98
+ * and the same diagnostics.
99
+ */
100
+
101
+ import { recordObservedHostCategories, recordRowPlacementLandings } from "./bus.ts";
102
+ import { recordNotice } from "./notices.ts";
103
+ import { extendCardStyleLine } from "./card-style-rows.ts";
104
+ import { findCardStyleLine } from "./card-style-line.ts";
105
+ import {
106
+ applyRowPlacementPlan,
107
+ buildRows,
108
+ createRowContext,
109
+ planRowPlacement,
110
+ rowPlacementLandingsAfterSkippedMove,
111
+ type RowBuildFailure,
112
+ type RowPlacementPlan,
113
+ } from "./rows.ts";
114
+ import {
115
+ patchSharedSections,
116
+ resetSharedSectionsPreviewForTests,
117
+ undoSharedSections,
118
+ type SharedSectionsPatch,
119
+ } from "./sections-preview.ts";
120
+ import type { RowBuildResult } from "./rows.ts";
121
+ import type { CustomizeRow } from "./types.ts";
122
+
123
+ /** Marks a UI target this module wrapped; the value is the wrapper function it installed. */
124
+ const CAPTURE_WRAPPED = Symbol.for("gentle-shell-bridge.capture.wrapped.v1");
125
+ /** Marks a captured rows array that already received an injection. */
126
+ const CAPTURE_INJECTED = Symbol.for("gentle-shell-bridge.capture.injected.v1");
127
+ /** Process-global arming/diagnostics slot. */
128
+ const CAPTURE_STATE = Symbol.for("gentle-shell-bridge.capture.state.v1");
129
+
130
+ /**
131
+ * Minimum length for a mapped array to count as the host's rows array.
132
+ *
133
+ * There is no type or name to key on, so the shape test is structural: an array of at least
134
+ * three objects that each expose a callable `action`. The threshold comes from the probe that
135
+ * proved this technique in the real TUI, where the customize menu builds far more than three
136
+ * rows; three keeps incidental one- and two-element arrays of objects out of the capture without
137
+ * matching anything smaller. The cost is explicit: a host menu with fewer than three rows is
138
+ * below the threshold and would not be captured.
139
+ */
140
+ const MIN_ROW_ARRAY_LENGTH = 3;
141
+
142
+ /**
143
+ * The host's own category for a row that names none, read from the view's page derivation
144
+ * (`row.category ?? "Settings"`, `lib/visual-customize-view.ts:387`). The early injection's proof
145
+ * compares against it, so a host that renames the default falls back to the late path instead of
146
+ * qualifying an array on a guess.
147
+ */
148
+ const HOST_DEFAULT_CATEGORY = "Settings";
149
+
150
+ /**
151
+ * The page name no host row can name, used by the proof's second synthetic row (S20). A mapper that
152
+ * ignores its argument — a constant — cannot return this for one row and `"Settings"` for another,
153
+ * and a mapper that echoes `row.category` cannot return `"Settings"` for the row that has none.
154
+ */
155
+ const SENTINEL_CATEGORY = "gentle-shell-bridge probe sentinel";
156
+
157
+ /**
158
+ * The two rows the host never had. They are the whole difference between "this callback derives
159
+ * pages" and "this callback happens to fit these rows": an incidental array mapped with
160
+ * `row => row.category` fits the host's rows perfectly and returns `undefined` for the first one
161
+ * (JD-A-001).
162
+ */
163
+ const SYNTHETIC_PROOF_ROWS: readonly CustomizeRow[] = [
164
+ { label: "Bridge probe without a category", action: () => {} },
165
+ { category: SENTINEL_CATEGORY, label: "Bridge probe with a sentinel category", action: () => {} },
166
+ ];
167
+
168
+ /** A provider that threw while its rows were built; its rows were dropped. */
169
+ export type CaptureFailure = RowBuildFailure;
170
+
171
+ /** Outcome of the most recent menu build the backend observed. */
172
+ export interface CaptureOutcome {
173
+ kind: "injected" | "uncaptured" | "already-injected";
174
+ /** How many rows this backend pushed into the captured array. */
175
+ injectedRows: number;
176
+ /** Only for `uncaptured`: why nothing was injected. */
177
+ reason?: "async-factory" | "no-capture" | "ambiguous" | "factory-threw";
178
+ }
179
+
180
+ /** What diagnostics (`status`, S6) reads from the capture backend. */
181
+ export interface CaptureDiagnostics {
182
+ /** Number of UI targets currently wrapped in this process. */
183
+ armedTargets: number;
184
+ /** Nesting depth of in-flight `custom` calls; 0 when idle. */
185
+ nestingDepth: number;
186
+ lastOutcome?: CaptureOutcome;
187
+ /** Failures recorded during the most recent menu build. */
188
+ lastFailures: CaptureFailure[];
189
+ }
190
+
191
+ /** Result of one arming attempt, so diagnostics can report why nothing was armed. */
192
+ export interface InstallCaptureResult {
193
+ armed: boolean;
194
+ /** Where the wrapper landed: the instance's own `custom`, the prototype's, or nowhere. */
195
+ target: "instance" | "prototype" | "none";
196
+ outcome: "armed" | "already-armed" | "no-custom";
197
+ }
198
+
199
+ /**
200
+ * What the host's `custom` hands back: the plain adapter component gentle-shell returns
201
+ * (`gentle-shell.ts:3550-3562`), possibly wrapped in a promise (`interactive-mode.ts:3136`).
202
+ * Opaque by design — the bridge only ever calls `invalidate()`, and only on the sync shape.
203
+ */
204
+ export interface HostComponent {
205
+ invalidate?: () => void;
206
+ [key: string]: unknown;
207
+ }
208
+
209
+ export type HostCustomResult = HostComponent | PromiseLike<HostComponent>;
210
+
211
+ type HostCustom = (this: unknown, factory: unknown, ...rest: unknown[]) => HostCustomResult;
212
+ type HostFactory = (ui: unknown, theme: unknown, ...rest: unknown[]) => HostCustomResult;
213
+ /** `Array.prototype.map` with the argument types widened, for the temporary patch only. */
214
+ type LooseMap = (this: unknown, callback: unknown, thisArg?: unknown) => unknown[];
215
+
216
+ /**
217
+ * The callback a `map` call passed, typed the way `Array.prototype.map` calls it — the shape the
218
+ * proof runs it with, so a mapper sees exactly what it would have seen.
219
+ */
220
+ type CategoryMapper = (
221
+ this: unknown,
222
+ row: CustomizeRow,
223
+ index: number,
224
+ rows: readonly CustomizeRow[],
225
+ ) => unknown;
226
+
227
+ type MutableTarget = Record<PropertyKey, unknown> & { custom?: unknown };
228
+
229
+ type CaptureWrapper = (this: unknown, ...args: unknown[]) => HostCustomResult;
230
+
231
+ /** One wrapped `custom` call in flight, with the arrays its factory mapped. */
232
+ interface CaptureSession {
233
+ candidates: CustomizeRow[][];
234
+ /** The candidates that proved themselves to be the menu's rows at a `map` call (S20). */
235
+ proven: CustomizeRow[][];
236
+ /**
237
+ * The theme this factory invocation received, so the rows can be built BEFORE the factory
238
+ * returns — the early path runs inside the view constructor's own `map` call.
239
+ */
240
+ theme: unknown;
241
+ /** True while this session is building/injecting rows, so its own maps are not re-captured. */
242
+ injecting: boolean;
243
+ /** True while a `map` call is being proved, so a mapper that maps again cannot recurse. */
244
+ proving: boolean;
245
+ /**
246
+ * True once the host's own `Card style` line was extended in this build. The splice is not
247
+ * idempotent (`src/card-style-line.ts:94-109`), so exactly one of the two paths may do it — and a
248
+ * rollback clears it again, so the array the late path picks gets its splice.
249
+ */
250
+ extendedCardStyle: boolean;
251
+ /** What the early path pushed and where, so the late decision can keep or undo it (S20). */
252
+ earlyInjection?: EarlyInjection;
253
+ }
254
+
255
+ /** One provisional injection: what landed, where, and how to take it back out. */
256
+ interface EarlyInjection {
257
+ array: CustomizeRow[];
258
+ /** The array exactly as it was before the provider blocks were placed, by identity. */
259
+ original: readonly CustomizeRow[];
260
+ /** Every provider row this build added, by identity, for counting and diagnostics. */
261
+ rows: readonly CustomizeRow[];
262
+ /**
263
+ * S21: the provider rows that went to the TAIL, in order, by identity. `removeInjectedTail` assumes
264
+ * a tail-shaped write, so it is given this and never `rows`.
265
+ */
266
+ tail: readonly CustomizeRow[];
267
+ /**
268
+ * S21: the mid-array insertions, each with the index it was made at and the identities it wrote,
269
+ * in the order they were applied. A rollback removes them in REVERSE, after checking every identity.
270
+ */
271
+ inserts: readonly { index: number; rows: readonly CustomizeRow[] }[];
272
+ /** The plan: where the blocks go once the host's category map has finished. */
273
+ plan: RowPlacementPlan;
274
+ /** The in-place `Card style` splice, when one happened, so a rollback can undo it exactly. */
275
+ cardStyle?: EarlyCardStyleSplice;
276
+ /** The in-place `Sections` preview patch, when one happened, for the same rollback. */
277
+ sectionPreview?: SharedSectionsPatch;
278
+ /** What the build recorded while failing, reported if the injection survives. */
279
+ failures: CaptureFailure[];
280
+ }
281
+
282
+ /** The provisional `Card style` splice, recorded so it can be undone (`spliceCardStyleValues`). */
283
+ interface EarlyCardStyleSplice {
284
+ /** Index of the host's line in the array. */
285
+ start: number;
286
+ /** How many host rows the splice replaced at that index. */
287
+ hostCount: number;
288
+ /** How many bridge value rows it inserted after them. */
289
+ values: number;
290
+ /** The host's own rows, by identity, exactly as they were before the splice. */
291
+ original: readonly CustomizeRow[];
292
+ }
293
+
294
+ interface CaptureState {
295
+ armedTargets: number;
296
+ nestingDepth: number;
297
+ /** Bumped by `disableCaptureBackend()`; a wrapper from an older generation is a pass-through. */
298
+ generation: number;
299
+ /** Innermost last: a mapped array is recorded into the top session only. */
300
+ sessions: CaptureSession[];
301
+ /** The `Array.prototype.map` in force before the probe was installed, while it is installed. */
302
+ savedMap?: typeof Array.prototype.map;
303
+ lastOutcome?: CaptureOutcome;
304
+ lastFailures: CaptureFailure[];
305
+ /** One record per wrapped target, so a backend transition can restore the host's own method. */
306
+ wrappers: Array<{ target: MutableTarget; original: unknown; wrapper: CaptureWrapper }>;
307
+ }
308
+
309
+ function captureHost(): Record<symbol, CaptureState | undefined> {
310
+ // SAFETY: the only writes to this key are the `captureState()` creation below, so if the key
311
+ // holds anything it is a CaptureState from this module. Foreign or partial values are not
312
+ // trusted: `captureState()` checks `armedTargets` and replaces an unusable slot.
313
+ return globalThis as unknown as Record<symbol, CaptureState | undefined>;
314
+ }
315
+
316
+ function captureState(): CaptureState {
317
+ const host = captureHost();
318
+ const existing = host[CAPTURE_STATE];
319
+ if (existing !== undefined && typeof existing.armedTargets === "number") return existing;
320
+ const created: CaptureState = {
321
+ armedTargets: 0,
322
+ nestingDepth: 0,
323
+ generation: 0,
324
+ sessions: [],
325
+ lastOutcome: undefined,
326
+ lastFailures: [],
327
+ wrappers: [],
328
+ };
329
+ host[CAPTURE_STATE] = created;
330
+ return created;
331
+ }
332
+
333
+ /** Diagnostics snapshot for `status` (S6) and for the backend's own tests. */
334
+ export function getCaptureDiagnostics(): CaptureDiagnostics {
335
+ const state = captureState();
336
+ return {
337
+ armedTargets: state.armedTargets,
338
+ nestingDepth: state.nestingDepth,
339
+ lastOutcome: state.lastOutcome,
340
+ lastFailures: [...state.lastFailures],
341
+ };
342
+ }
343
+
344
+ /**
345
+ * Test-only seam: forget arming counts, the last outcome and the last failures. Deliberately not
346
+ * re-exported from `src/index.ts`. Markers live on host objects and arrays and are not cleared;
347
+ * `disableCaptureBackend()` is the seam that unwraps.
348
+ */
349
+ export function resetCaptureStateForTests(): void {
350
+ const state = captureState();
351
+ state.armedTargets = 0;
352
+ state.nestingDepth = 0;
353
+ // Bump so wrappers left in foreign closures from an earlier test become pass-throughs.
354
+ state.generation += 1;
355
+ state.sessions = [];
356
+ state.savedMap = undefined;
357
+ state.lastOutcome = undefined;
358
+ state.lastFailures = [];
359
+ state.wrappers = [];
360
+ // The shared `Sections` preview keeps the last patch, which is how a bridge row finds the host's
361
+ // base list; a new test starts with no patched array to borrow from.
362
+ resetSharedSectionsPreviewForTests();
363
+ }
364
+
365
+ /** The probe records into the innermost session and forwards to the saved original. */
366
+ const probe = function (this: unknown, callback: unknown, thisArg?: unknown): unknown[] {
367
+ const state = captureState();
368
+ const session = state.sessions[state.sessions.length - 1];
369
+ if (session !== undefined) {
370
+ try {
371
+ if (isRowLikeArray(this)) {
372
+ if (!session.candidates.includes(this)) session.candidates.push(this);
373
+ // S18: a brand-new page only exists if the rows are already in the array when the host's
374
+ // own `map` reads it, so the proof and the push happen BEFORE the call is forwarded. S20:
375
+ // the proof is evaluated on EVERY call, and the push is provisional until the factory ends.
376
+ observeRowMap(session, this, callback, thisArg);
377
+ }
378
+ } catch {
379
+ // Never break the host's own `map` call.
380
+ }
381
+ }
382
+
383
+ const original = state.savedMap;
384
+ // Unreachable while the probe is installed (installing saves the original first); returning an
385
+ // empty array keeps the host's call from throwing if a foreign swap cleared the saved value.
386
+ if (original === undefined) return [];
387
+ // SAFETY: `original` is the real `Array.prototype.map` captured in `installProbe()`; `LooseMap`
388
+ // only widens the parameter types so this forwards whatever the host's own call passed.
389
+ return (original as unknown as LooseMap).call(this, callback, thisArg);
390
+ };
391
+
392
+ function installProbe(): void {
393
+ const state = captureState();
394
+ if (state.savedMap !== undefined) return;
395
+ state.savedMap = Array.prototype.map;
396
+ // SAFETY: `probe` forwards the exact (callback, thisArg) pair to the saved original and only
397
+ // observes `this`, so it is a behavioural drop-in for the duration of one outermost call; the
398
+ // original is restored by `removeProbe()` in the wrapper's `finally`.
399
+ Array.prototype.map = probe as unknown as typeof Array.prototype.map;
400
+ }
401
+
402
+ function removeProbe(): void {
403
+ const state = captureState();
404
+ const saved = state.savedMap;
405
+ if (saved === undefined) return;
406
+ Array.prototype.map = saved;
407
+ state.savedMap = undefined;
408
+ }
409
+
410
+ /**
411
+ * Arm the capture backend on a `ctx.ui`-shaped object. Idempotent per target and per function:
412
+ * the marker is an own property holding the exact wrapper installed, so a rebind that gives the
413
+ * instance a new `custom` always rearms instead of reporting a stale `already-armed`.
414
+ *
415
+ * Both shapes Pi can use are covered. When the instance owns `custom`, that own property is
416
+ * wrapped. Otherwise the prototype method that provides `custom` is wrapped once for every
417
+ * instance that inherits it.
418
+ */
419
+ export function installCaptureBackend(ui: unknown): InstallCaptureResult {
420
+ if (ui === null || typeof ui !== "object") {
421
+ return { armed: false, target: "none", outcome: "no-custom" };
422
+ }
423
+ const instance = ui as MutableTarget;
424
+
425
+ if (Object.prototype.hasOwnProperty.call(instance, "custom")) {
426
+ return wrapCustom(instance, "instance");
427
+ }
428
+
429
+ const proto: unknown = Object.getPrototypeOf(instance);
430
+ const protoCustom =
431
+ proto !== null && typeof proto === "object" ? (proto as MutableTarget).custom : undefined;
432
+ if (typeof protoCustom === "function") {
433
+ return wrapCustom(proto as MutableTarget, "prototype");
434
+ }
435
+
436
+ return { armed: false, target: "none", outcome: "no-custom" };
437
+ }
438
+
439
+ function wrapCustom(target: MutableTarget, shape: "instance" | "prototype"): InstallCaptureResult {
440
+ const current = target.custom;
441
+ if (typeof current !== "function") {
442
+ return { armed: false, target: "none", outcome: "no-custom" };
443
+ }
444
+
445
+ // Own-property check plus function identity: an inherited marker describes the prototype's
446
+ // function, not this instance's, so it must never certify this target.
447
+ if (Object.hasOwn(target, CAPTURE_WRAPPED) && target[CAPTURE_WRAPPED] === current) {
448
+ return { armed: false, target: shape, outcome: "already-armed" };
449
+ }
450
+
451
+ const callHost = current as HostCustom;
452
+ // SAFETY: `current` is verified callable above, and the host's `custom` is documented to
453
+ // resolve its factory to a component (or a promise of one) — architecture.md §3. The bridge
454
+ // never inspects the result, it only forwards it, so the return type is not a claim about its
455
+ // shape.
456
+
457
+ const generation = captureState().generation;
458
+ const wrapper = function (this: unknown, ...args: unknown[]): HostCustomResult {
459
+ const state = captureState();
460
+ const factory = args[0];
461
+ const rest = args.slice(1);
462
+ // A wrapper retained by foreign code after a disable must never capture or inject again; it
463
+ // behaves exactly like the host's own method.
464
+ if (state.generation !== generation || typeof factory !== "function") {
465
+ return callHost.apply(this, args as [unknown, ...unknown[]]);
466
+ }
467
+ return callHost.apply(this, [createCaptureFactory(factory as HostFactory), ...rest]);
468
+ };
469
+
470
+ target.custom = wrapper;
471
+ Object.defineProperty(target, CAPTURE_WRAPPED, {
472
+ value: wrapper,
473
+ enumerable: false,
474
+ configurable: true,
475
+ });
476
+ const state = captureState();
477
+ const previous = state.wrappers.findIndex((record) => record.target === target);
478
+ if (previous === -1) state.armedTargets += 1;
479
+ else state.wrappers.splice(previous, 1);
480
+ state.wrappers.push({ target, original: current, wrapper });
481
+ return { armed: true, target: shape, outcome: "armed" };
482
+ }
483
+
484
+ /**
485
+ * Disable every capture wrapper, restoring the host's own `custom` on the exact targets that were
486
+ * wrapped. Used when a different backend becomes active, so one menu cannot receive two copies of
487
+ * the bridge's rows.
488
+ */
489
+ export function disableCaptureBackend(): number {
490
+ const state = captureState();
491
+ let restored = 0;
492
+ for (const record of state.wrappers.splice(0)) {
493
+ try {
494
+ if (record.target.custom === record.wrapper) record.target.custom = record.original;
495
+ if (Object.hasOwn(record.target, CAPTURE_WRAPPED)) delete record.target[CAPTURE_WRAPPED];
496
+ restored += 1;
497
+ } catch {
498
+ // A host object that refuses the assignment keeps its wrapper; the backend is still off.
499
+ }
500
+ }
501
+ state.armedTargets = 0;
502
+ state.generation += 1;
503
+ return restored;
504
+ }
505
+
506
+ /** Wrap exactly one factory invocation, attributing every mapped array to its own session. */
507
+ function createCaptureFactory(factory: HostFactory): HostFactory {
508
+ return (ui, theme, ...rest) => {
509
+ const state = captureState();
510
+ const outermost = state.sessions.length === 0;
511
+ const session: CaptureSession = {
512
+ candidates: [],
513
+ proven: [],
514
+ theme,
515
+ injecting: false,
516
+ proving: false,
517
+ extendedCardStyle: false,
518
+ };
519
+ state.sessions.push(session);
520
+ state.nestingDepth = state.sessions.length;
521
+ // The probe wraps the FACTORY INVOCATION, so a host that calls the factory in a later
522
+ // microtask still runs under it. A factory that returns a promise is handled below.
523
+ if (outermost) installProbe();
524
+
525
+ let component: HostCustomResult;
526
+ let failed = true;
527
+ try {
528
+ component = factory(ui, theme, ...rest);
529
+ failed = false;
530
+ } catch (error) {
531
+ // Nothing was injected into this session: say so rather than leaving the previous outcome.
532
+ state.lastOutcome = {
533
+ kind: "uncaptured",
534
+ injectedRows: 0,
535
+ reason: "factory-threw",
536
+ };
537
+ throw error;
538
+ } finally {
539
+ // A throw leaves no trace (JD-A-004): the early rows and the marker come out of the array in
540
+ // the SAME `finally` that restores `Array.prototype.map`. Only this session's own array is
541
+ // touched, so an inner factory's rollback can never reach the outer session's rows.
542
+ // The stack and the patched `map` are restored FIRST and unconditionally (E10), so nothing the
543
+ // rollback does can leave either installed. `rollbackEarly` never throws.
544
+ state.sessions.pop();
545
+ state.nestingDepth = state.sessions.length;
546
+ if (outermost) removeProbe();
547
+ if (failed) {
548
+ rollbackEarly(session);
549
+ state.lastFailures = [];
550
+ }
551
+ }
552
+ resolveSession(session, component);
553
+ return component;
554
+ };
555
+ }
556
+
557
+ /**
558
+ * Decide what this session's candidates mean and inject once. Never injects into an array it did
559
+ * not capture, and never reports `injected` for a menu that received nothing.
560
+ *
561
+ * S20: this is also where the provisional early injection is reconciled. The early step is a guess;
562
+ * this function is the decision, so it either keeps the guess (same array, sync factory) or takes
563
+ * it back before applying the previous behaviour exactly.
564
+ */
565
+ function resolveSession(session: CaptureSession, component: HostCustomResult): void {
566
+ const state = captureState();
567
+
568
+ // The host may resolve its factory asynchronously (`interactive-mode.ts:3136`). This backend only
569
+ // observes the synchronous shape, so the promise is returned untouched, the early rows are taken
570
+ // back (JD-A-005: no late decision will ever run for them) and the outcome is the previous one.
571
+ if (isThenable(component)) {
572
+ rollbackEarly(session);
573
+ state.lastFailures = [];
574
+ state.lastOutcome = { kind: "uncaptured", injectedRows: 0, reason: "async-factory" };
575
+ return;
576
+ }
577
+
578
+ const picked = pickLateTarget(session);
579
+ if (picked.kind === "none") {
580
+ // No array can be named, or several can (the ambiguity rule). Either way the guess is undone
581
+ // first, so the net guarantee holds whatever the report says.
582
+ rollbackEarly(session);
583
+ state.lastFailures = [];
584
+ state.lastOutcome = { kind: "uncaptured", injectedRows: 0, reason: picked.reason };
585
+ return;
586
+ }
587
+ const captured = picked.array;
588
+ const early = session.earlyInjection;
589
+
590
+ // The early path put the rows in before the view read its page list (S18) and the late decision
591
+ // agrees: report that build and do not build a second time, so the providers run once.
592
+ if (early !== undefined && early.array === captured) {
593
+ // The provisional step APPENDED the blocks so the host's `new Set(...)` could see a new page.
594
+ // The factory has returned, so that map is finished; place the blocks at their slots now. This
595
+ // is also why the provisional step must not splice in the middle: the host's own map captured
596
+ // the length it will iterate, and shifting rows under it would make it read the wrong pages.
597
+ // A frozen/exotic array skips the move; the report then states the landing it really got (S5).
598
+ const problem = early.plan.optsIn ? placeEarlyBlocks(early) : undefined;
599
+ recordRowPlacementLandings(
600
+ problem === undefined
601
+ ? early.plan.landings
602
+ : rowPlacementLandingsAfterSkippedMove(early.plan, problem),
603
+ );
604
+ state.lastFailures = early.failures;
605
+ state.lastOutcome = { kind: "injected", injectedRows: early.rows.length };
606
+ invalidate(component);
607
+ return;
608
+ }
609
+
610
+ // The guess did not survive the decision (another array, or several arrays proved themselves):
611
+ // remove every trace of it before the late path runs.
612
+ rollbackEarly(session);
613
+
614
+ if (Object.hasOwn(captured, CAPTURE_INJECTED)) {
615
+ state.lastOutcome = { kind: "already-injected", injectedRows: 0 };
616
+ return;
617
+ }
618
+ // Non-enumerable marker on the array: the same menu built twice injects once.
619
+ Object.defineProperty(captured as object, CAPTURE_INJECTED, {
620
+ value: true,
621
+ enumerable: false,
622
+ configurable: true,
623
+ });
624
+
625
+ // S1: the host's own `Card style` line is extended IN PLACE here, before the providers' rows are
626
+ // appended — the one moment the array is reachable, and the only place the two could be confused.
627
+ // It never throws: an unreachable line records the `separate` mode and leaves the fallback
628
+ // provider to draw the bridge's own line on this same build. The early path extends the same line
629
+ // at the same point in the array's life; the splice is not idempotent, so only one of them runs.
630
+ if (!session.extendedCardStyle) {
631
+ session.extendedCardStyle = true;
632
+ extendCardStyleLine(captured);
633
+ }
634
+
635
+ // S1/S2: the host's own `Sections` rows now preview the bridge's sections too. Patched after the
636
+ // splice, so the recorded indices describe the array the providers are about to join, and before
637
+ // the rows are built: a bridge row's preview reads the patch lazily, at render time.
638
+ patchSharedSections(captured);
639
+
640
+ const built = buildRows(createRowContext(session.theme));
641
+ state.lastFailures = built.failures;
642
+ // S4/S5: place each provider's block at the slot the ONE resolver names. The plan is computed
643
+ // against the array as it is now and written in one in-place splice, so no insertion index can
644
+ // drift. A host `choice.setting` pair is never split: every insertion point is a block boundary.
645
+ const plan = planRowPlacement(captured, built.providers, built.blocks);
646
+ recordObservedHostCategories(plan.hostCategories);
647
+ if (!plan.optsIn) {
648
+ // No provider opted in: the pre-feature tail append, exactly (S6).
649
+ if (built.rows.length > 0) captured.push(...built.rows);
650
+ recordRowPlacementLandings([]);
651
+ } else {
652
+ const problem = applyRowPlacementPlan(captured, plan.planned);
653
+ if (problem === undefined) {
654
+ recordRowPlacementLandings(plan.landings);
655
+ } else {
656
+ // The planned splice is refused (a read-only index, a frozen array): change nothing, leave
657
+ // the rows where the pre-feature path put them, and report the landing that really happened.
658
+ try {
659
+ if (built.rows.length > 0) captured.push(...built.rows);
660
+ } catch {
661
+ // the host refuses even the tail append; the landing report still says why nothing moved
662
+ }
663
+ recordRowPlacementLandings(rowPlacementLandingsAfterSkippedMove(plan, problem));
664
+ }
665
+ }
666
+ state.lastOutcome = { kind: "injected", injectedRows: built.rows.length };
667
+
668
+ invalidate(component);
669
+ }
670
+
671
+ /** What the late decision chose: one array, or nothing with the reason to report. */
672
+ type LatePick =
673
+ | { kind: "pick"; array: CustomizeRow[] }
674
+ | { kind: "none"; reason: "no-capture" | "ambiguous" };
675
+
676
+ /**
677
+ * The late decision: which array this factory's rows belong in, if any.
678
+ *
679
+ * The rule is the previous one — one row-like candidate is the menu, none means nothing was
680
+ * captured, several are ambiguous and nothing is injected — with one refinement S18 needs: when
681
+ * exactly ONE candidate proved itself the menu's rows at a `map` call (S20's proof), that array is
682
+ * the menu by evidence, so a merely row-LIKE array mapped beside it does not make the target
683
+ * ambiguous. Two proven arrays are ambiguous, and so are two unproven ones: the bridge still never
684
+ * guesses between two arrays that both look like the menu.
685
+ */
686
+ function pickLateTarget(session: CaptureSession): LatePick {
687
+ if (session.proven.length === 1) {
688
+ const proven = session.proven[0];
689
+ if (proven !== undefined) return { kind: "pick", array: proven };
690
+ }
691
+ if (session.proven.length > 1) return { kind: "none", reason: "ambiguous" };
692
+ if (session.candidates.length === 0) return { kind: "none", reason: "no-capture" };
693
+ if (session.candidates.length > 1) return { kind: "none", reason: "ambiguous" };
694
+ const only = session.candidates[0];
695
+ if (only === undefined) return { kind: "none", reason: "no-capture" };
696
+ return { kind: "pick", array: only };
697
+ }
698
+
699
+ /**
700
+ * Put the provisional blocks at the slots the resolver named, once the host's category map has
701
+ * finished. Only the exact `original + inserted rows` shape is reordered: if the host changed its
702
+ * array in the meantime, the appended rows stay where they are rather than losing a host row.
703
+ */
704
+ function placeEarlyBlocks(early: EarlyInjection): string | undefined {
705
+ const { array } = early;
706
+ const inserted = early.inserts.reduce((total, insert) => total + insert.rows.length, 0);
707
+ const expectedLength = early.original.length + early.tail.length + inserted;
708
+ if (array.length !== expectedLength) return "the host array changed before the planned move";
709
+ for (let index = 0; index < early.original.length; index++) {
710
+ if (array[index] !== early.original[index]) return "the host array changed before the planned move";
711
+ }
712
+ // The tail is no longer contiguous from `original.length`: a placed page sits inside the host's
713
+ // own rows. Every row this build wrote must still be at an index this build chose, by identity.
714
+ const written = [...early.inserts.flatMap((insert) => insert.rows), ...early.tail];
715
+ for (const row of written) {
716
+ if (!array.includes(row)) return "the host array changed before the planned move";
717
+ }
718
+ return applyRowPlacementPlan(array, early.plan.planned);
719
+ }
720
+
721
+ /** Describe an error without reading any property off it (a hostile getter can throw). */
722
+ function describeRollbackError(error: unknown): string {
723
+ try {
724
+ if (error === null) return "null";
725
+ if (error === undefined) return "undefined";
726
+ if (typeof error === "string") return "a string";
727
+ if (typeof error === "number") return "a number";
728
+ if (typeof error === "boolean") return "a boolean";
729
+ if (typeof error === "object") return "an object";
730
+ return `a ${typeof error}`;
731
+ } catch {
732
+ return "an unreadable value";
733
+ }
734
+ }
735
+
736
+ /** One truthful rollback count: appended, already removed by the host, removed by the bridge, left. */
737
+ function removalReport(
738
+ appended: number,
739
+ hostRemoved: number,
740
+ bridgeRemoved: number,
741
+ unremovable: number,
742
+ detail?: string,
743
+ ): string {
744
+ const rows = appended === 1 ? "row" : "rows";
745
+ const counts =
746
+ `appended ${appended} ${rows}; ${hostRemoved} already removed by the host; ` +
747
+ `${bridgeRemoved} removed by the bridge; ${unremovable} could not be removed`;
748
+ return detail === undefined ? counts : `${detail}; ${counts}`;
749
+ }
750
+
751
+ /** Why one index cannot receive a write, decided from its own descriptor (S14). */
752
+ function indexWriteProblem(
753
+ array: readonly CustomizeRow[],
754
+ index: number,
755
+ descriptor: PropertyDescriptor | undefined,
756
+ ): string | undefined {
757
+ if (descriptor === undefined) {
758
+ return Object.isExtensible(array) ? undefined : `index ${index} cannot be written`;
759
+ }
760
+ if ("get" in descriptor || "set" in descriptor) {
761
+ // A setter is code, not a write this preflight can verify: it may reject or swallow the value.
762
+ return `index ${index} is read-only`;
763
+ }
764
+ return descriptor.writable === true ? undefined : `index ${index} is read-only`;
765
+ }
766
+
767
+ /** Why the appended range cannot be deleted as one unit, checked before any write. */
768
+ function appendedRangeProblem(
769
+ array: readonly CustomizeRow[],
770
+ start: number,
771
+ count: number,
772
+ ): string | undefined {
773
+ for (let index = start; index < start + count; index += 1) {
774
+ const descriptor = Object.getOwnPropertyDescriptor(array, String(index));
775
+ if (descriptor === undefined) return `index ${index} is missing`;
776
+ if (descriptor.configurable === false) return `index ${index} is non-configurable`;
777
+ const writeProblem = indexWriteProblem(array, index, descriptor);
778
+ if (writeProblem !== undefined) return writeProblem;
779
+ }
780
+ return undefined;
781
+ }
782
+
783
+ /** Match every appended occurrence by identity anywhere in one range, not by suffix position. */
784
+ function matchAppendedRange(
785
+ array: readonly CustomizeRow[],
786
+ start: number,
787
+ count: number,
788
+ rows: readonly CustomizeRow[],
789
+ ): { found: number; reordered: boolean } | undefined {
790
+ const matched = rows.map(() => false);
791
+ let found = 0;
792
+ let reordered = false;
793
+ for (let offset = 0; offset < count; offset += 1) {
794
+ const row = array[start + offset];
795
+ const expected = offset;
796
+ if (expected < rows.length && !matched[expected] && row === rows[expected]) {
797
+ matched[expected] = true;
798
+ found += 1;
799
+ continue;
800
+ }
801
+ const index = rows.findIndex((candidate, candidateIndex) => {
802
+ return !matched[candidateIndex] && candidate === row;
803
+ });
804
+ if (index === -1) return undefined;
805
+ matched[index] = true;
806
+ found += 1;
807
+ reordered = true;
808
+ }
809
+ return { found, reordered };
810
+ }
811
+
812
+ /** Shrink the array to `start` after its appended range was preflighted, writing no element. */
813
+ function removeTailTo(array: CustomizeRow[], start: number): string | undefined {
814
+ const descriptor = Object.getOwnPropertyDescriptor(array, "length");
815
+ if (descriptor !== undefined && descriptor.writable === false) {
816
+ return "the host array's length is read-only";
817
+ }
818
+ try {
819
+ array.length = start;
820
+ } catch {
821
+ return "the host array refused the tail trim";
822
+ }
823
+ return array.length === start ? undefined : "the host array kept a phantom length";
824
+ }
825
+
826
+ /**
827
+ * S21: undo the mid-array insertions a rollback must remove, in reverse order.
828
+ *
829
+ * Every identity is checked before anything is removed: a region the host has since rearranged is
830
+ * left untouched, because removing a row the host wrote would be worse than leaving a bridge row
831
+ * behind. Returns the reason it could not finish, or `undefined`.
832
+ */
833
+ function removeInsertedRows(early: EarlyInjection): string | undefined {
834
+ if (early.inserts.length === 0) return undefined;
835
+ const { array } = early;
836
+ for (const insert of early.inserts) {
837
+ for (let offset = 0; offset < insert.rows.length; offset++) {
838
+ if (array[insert.index + offset] !== insert.rows[offset]) {
839
+ return "the host changed the rows inserted before its own pages";
840
+ }
841
+ }
842
+ }
843
+ for (const insert of early.inserts) {
844
+ // Descending index order was kept when they were applied, so each insertion is still intact.
845
+ try {
846
+ array.splice(insert.index, insert.rows.length);
847
+ } catch {
848
+ return "the host array refused the removal of the inserted rows";
849
+ }
850
+ }
851
+ return undefined;
852
+ }
853
+
854
+ /**
855
+ * Remove exactly the rows this build appended, without writing a retained host index (S10).
856
+ *
857
+ * The normal case is the unchanged array `original + rows`: shrinking `length` removes the tail
858
+ * append and writes no element, so a retained read-only index is never touched and no hole can
859
+ * appear. If the host already removed some appended rows, the remaining tail rows are removed and the
860
+ * notice says who removed what. If the host appended its own rows after ours, only the indices at or
861
+ * after the append point are rewritten, after the whole appended range is preflighted. Anything that
862
+ * cannot be removed as a whole removes nothing, leaves the array as the build left it, and returns the
863
+ * reason and truthful counts for the notice.
864
+ */
865
+ function removeInjectedTail(early: EarlyInjection): string | undefined {
866
+ const { array, original, rows } = early;
867
+ const appended = rows.length;
868
+ if (appended === 0) return undefined;
869
+ const start = original.length;
870
+ try {
871
+ const length = array.length;
872
+ const target = start + appended;
873
+ const tailCount = Math.max(0, length - start);
874
+ if (length <= target) {
875
+ // Everything after `start` must be an appended identity; a foreign row means the host mutated
876
+ // the segment beyond recognition, so remove nothing rather than guess.
877
+ const match = matchAppendedRange(array, start, tailCount, rows);
878
+ if (match === undefined) {
879
+ return removalReport(
880
+ appended,
881
+ 0,
882
+ 0,
883
+ appended,
884
+ "the host changed the appended rows beyond recognition",
885
+ );
886
+ }
887
+ const hostRemoved = appended - match.found;
888
+ if (tailCount > 0) {
889
+ const rangeProblem = appendedRangeProblem(array, start, tailCount);
890
+ if (rangeProblem !== undefined) {
891
+ return removalReport(appended, hostRemoved, 0, match.found, rangeProblem);
892
+ }
893
+ const trimProblem = removeTailTo(array, start);
894
+ if (trimProblem !== undefined) {
895
+ return removalReport(appended, hostRemoved, 0, match.found, trimProblem);
896
+ }
897
+ }
898
+ if (hostRemoved === 0 && !match.reordered) return undefined;
899
+ return removalReport(
900
+ appended,
901
+ hostRemoved,
902
+ match.found,
903
+ 0,
904
+ match.reordered ? "the host changed the appended rows before the rollback" : undefined,
905
+ );
906
+ }
907
+
908
+ // The host appended rows after ours. Only the first `appended` positions may be ours; a host row
909
+ // carrying one of our identities makes the boundary ambiguous, so remove nothing.
910
+ const match = matchAppendedRange(array, start, appended, rows);
911
+ if (match === undefined) {
912
+ return removalReport(
913
+ appended,
914
+ 0,
915
+ 0,
916
+ appended,
917
+ "the host changed the appended rows beyond recognition",
918
+ );
919
+ }
920
+ for (let index = target; index < length; index += 1) {
921
+ if (rows.includes(array[index])) {
922
+ return removalReport(
923
+ appended,
924
+ 0,
925
+ 0,
926
+ appended,
927
+ "the host changed the appended rows beyond recognition",
928
+ );
929
+ }
930
+ }
931
+
932
+ // The removal really touches every index from `start` to the current end while it shifts the
933
+ // host's later rows; preflight that whole range, then the target indices the splice will assign.
934
+ const rangeProblem = appendedRangeProblem(array, start, length - start);
935
+ if (rangeProblem !== undefined) {
936
+ return removalReport(appended, 0, 0, appended, rangeProblem);
937
+ }
938
+ const nextLength = length - appended;
939
+ const lengthDescriptor = Object.getOwnPropertyDescriptor(array, "length");
940
+ if (lengthDescriptor !== undefined && lengthDescriptor.writable === false) {
941
+ return removalReport(appended, 0, 0, appended, "the host array's length is read-only");
942
+ }
943
+ for (let index = start; index < nextLength; index += 1) {
944
+ const descriptor = Object.getOwnPropertyDescriptor(array, String(index));
945
+ const writeProblem = indexWriteProblem(array, index, descriptor);
946
+ if (writeProblem !== undefined) {
947
+ return removalReport(appended, 0, 0, appended, writeProblem);
948
+ }
949
+ }
950
+ try {
951
+ array.splice(start, appended);
952
+ } catch {
953
+ return removalReport(appended, 0, 0, appended, "the host array refused the tail trim");
954
+ }
955
+ if (array.length !== nextLength) {
956
+ return removalReport(appended, 0, 0, appended, "the host array kept a phantom length");
957
+ }
958
+ return match.reordered
959
+ ? removalReport(
960
+ appended,
961
+ 0,
962
+ appended,
963
+ 0,
964
+ "the host changed the appended rows before the rollback",
965
+ )
966
+ : undefined;
967
+ } catch (error) {
968
+ return removalReport(
969
+ appended,
970
+ 0,
971
+ 0,
972
+ appended,
973
+ `the host array could not be inspected or changed (${describeRollbackError(error)})`,
974
+ );
975
+ }
976
+ }
977
+
978
+ /**
979
+ * Take a provisional injection back out, exactly.
980
+ *
981
+ * Three things were written and all three are undone in place, on the SAME array object the host
982
+ * holds: the appended provider rows (removed from their tail segment, never by filtering identities),
983
+ * the `Card style` values the provisional splice inserted into the host's own line, and the injection
984
+ * marker. A retained index the build never changed is never written (S10); if the host moved the
985
+ * appended rows the rollback reports that instead of guessing, but the marker still comes off.
986
+ */
987
+ function rollbackEarly(session: CaptureSession): void {
988
+ const early = session.earlyInjection;
989
+ if (early === undefined) return;
990
+ session.earlyInjection = undefined;
991
+ const { array } = early;
992
+
993
+ // Every step is best effort and none may throw (E10): the host can freeze, seal or proxy its array
994
+ // between our push and this rollback, and a rollback that threw would replace the host's own error
995
+ // and skip the steps after it. An array we cannot restore is left as the host made it.
996
+ const insertProblem = removeInsertedRows(early);
997
+ if (insertProblem !== undefined) {
998
+ recordNotice(
999
+ `gentle-shell-bridge: could not fully roll back the provisional rows: ${insertProblem}. ` +
1000
+ "The host menu was left as consistent as the array allowed.",
1001
+ "error",
1002
+ );
1003
+ }
1004
+ const rollbackProblem = removeInjectedTail({ ...early, rows: early.tail });
1005
+ if (rollbackProblem !== undefined) {
1006
+ recordNotice(
1007
+ `gentle-shell-bridge: could not fully roll back the provisional rows: ${rollbackProblem}. ` +
1008
+ "The host menu was left as consistent as the array allowed.",
1009
+ "error",
1010
+ );
1011
+ }
1012
+ // Reverse order of the writes: the preview patch was applied after the `Card style` splice, so it
1013
+ // goes back FIRST, while its recorded indices still describe the array it edited.
1014
+ try {
1015
+ undoSharedSections(early.sectionPreview);
1016
+ } catch {
1017
+ // same: the host's own previews stay as the host left them
1018
+ }
1019
+ try {
1020
+ undoCardStyleSplice(array, early.cardStyle);
1021
+ } catch {
1022
+ // same: the host's own line stays as the host left it
1023
+ }
1024
+ // The late path may now extend the line of the array IT picks; the splice runs once per build.
1025
+ session.extendedCardStyle = false;
1026
+ try {
1027
+ Reflect.deleteProperty(array as object, CAPTURE_INJECTED);
1028
+ } catch {
1029
+ // A hostile Proxy can refuse even the marker removal; the host's own error still surfaces.
1030
+ }
1031
+ }
1032
+
1033
+ /**
1034
+ * Observe one `map` call on a row-like array (S18, S20).
1035
+ *
1036
+ * The proof runs on EVERY call — never latched to the first one, because the host may map its rows
1037
+ * to labels before the constructor maps them to categories (JD-A-002). An array that proves itself
1038
+ * is remembered as such, and the provisional push happens at most once per build.
1039
+ */
1040
+ function observeRowMap(
1041
+ session: CaptureSession,
1042
+ array: CustomizeRow[],
1043
+ callback: unknown,
1044
+ thisArg: unknown,
1045
+ ): void {
1046
+ // Reentrancy: building the rows itself maps row-like arrays (a provider's own array, a nested
1047
+ // menu's), and those maps belong to the build, not to the host's menu. A mapper that itself maps
1048
+ // is the same case: the callback is proved once, and its own maps prove nothing.
1049
+ if (session.injecting || session.proving) return;
1050
+ session.proving = true;
1051
+ let proven: boolean;
1052
+ try {
1053
+ proven = provesCategoryMap(array, callback, thisArg);
1054
+ } finally {
1055
+ session.proving = false;
1056
+ }
1057
+ if (!proven) return;
1058
+ if (!session.proven.includes(array)) session.proven.push(array);
1059
+ injectProvisionalRows(session, array, callback, thisArg);
1060
+ }
1061
+
1062
+ /** The index right after the LAST row of one category, or -1 when the array has none. */
1063
+ function endOfCategory(array: CustomizeRow[], category: string): number {
1064
+ for (let index = array.length - 1; index >= 0; index -= 1) {
1065
+ if ((array[index]?.category ?? HOST_DEFAULT_CATEGORY) === category) return index + 1;
1066
+ }
1067
+ return -1;
1068
+ }
1069
+
1070
+ /**
1071
+ * S21: put the rows of a page that its provider asked to open where they belong, and return the
1072
+ * writes it made.
1073
+ *
1074
+ * The order of this array is the order of the menu's pages: the host derives `categories` from
1075
+ * `options.rows.map(row => row.category)` (`lib/visual-customize-view.ts:387`), and `new Set(...)`
1076
+ * keeps the FIRST appearance of each category. The injection runs before that `map`, so rows
1077
+ * inserted after another page's rows open their own page right there. "After the anchor page" means
1078
+ * after the LAST row of that page, whatever else follows it.
1079
+ *
1080
+ * Per CATEGORY, never per block: a block's rows may each declare their own `category`
1081
+ * (`src/rows.ts:326-338`), and moving a whole block would drag the first appearance of unrelated
1082
+ * pages to the new index. Only the rows of the page being placed move; the block's other rows keep
1083
+ * the pre-feature tail order.
1084
+ *
1085
+ * A page opened by two providers is placed once, by the lowest provider id — the same tiebreak every
1086
+ * other tie in the contract uses — so the same registrations in any order draw the same menu. A page
1087
+ * the host already lists is not placed: its position inside that page is `placement`'s business.
1088
+ */
1089
+ function insertBuiltRows(
1090
+ array: CustomizeRow[],
1091
+ built: RowBuildResult,
1092
+ ): { tail: CustomizeRow[]; inserts: { index: number; rows: CustomizeRow[] }[] } {
1093
+ const asked = new Map<string, string>();
1094
+ for (const provider of [...built.providers].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))) {
1095
+ const placement = provider.categoryPlacement;
1096
+ if (placement === null || typeof placement !== "object") continue;
1097
+ if (typeof placement.after !== "string" || placement.after.length === 0) continue;
1098
+ if (placement.after === provider.category) continue;
1099
+ if (asked.has(provider.category)) continue;
1100
+ asked.set(provider.category, placement.after);
1101
+ }
1102
+ const hostPages = new Set(array.map((row) => row.category ?? HOST_DEFAULT_CATEGORY));
1103
+ const tail: CustomizeRow[] = [];
1104
+ const inserts: { index: number; rows: CustomizeRow[] }[] = [];
1105
+ for (const block of built.blocks) {
1106
+ const perPage = new Map<string, CustomizeRow[]>();
1107
+ for (const row of block.rows) {
1108
+ const page = row.category ?? block.category;
1109
+ const rows = perPage.get(page);
1110
+ if (rows === undefined) perPage.set(page, [row]);
1111
+ else rows.push(row);
1112
+ }
1113
+ for (const [page, rows] of perPage) {
1114
+ const anchor = asked.get(page);
1115
+ const index = anchor === undefined || hostPages.has(page) ? -1 : endOfCategory(array, anchor);
1116
+ if (index < 0) tail.push(...rows);
1117
+ else inserts.push({ index, rows });
1118
+ }
1119
+ }
1120
+ // Highest index first, so the writes already planned keep their indices.
1121
+ const ordered = [...inserts].sort((a, b) => b.index - a.index);
1122
+ for (const insert of ordered) array.splice(insert.index, 0, ...insert.rows);
1123
+ if (tail.length > 0) array.push(...tail);
1124
+ return { tail, inserts: ordered };
1125
+ }
1126
+
1127
+
1128
+ /**
1129
+ * S18: give a brand-new page to the view before it fixes its page list — provisionally (S20).
1130
+ *
1131
+ * The view computes `categories` once, in its constructor, from `options.rows.map(...)`
1132
+ * (`lib/visual-customize-view.ts:387`). A row that joins an EXISTING page is visible after a late
1133
+ * push because `categoryRows()` filters `options.rows` live (`:391-393`); a row naming a NEW page
1134
+ * is not, because nothing can select a page the list does not hold. So the rows must be in the
1135
+ * array before that `map` reads it.
1136
+ *
1137
+ * Everything here is recorded so `rollbackEarly` can undo it: the append index, the rows by
1138
+ * identity, and the `Card style` splice. The mapper is also run over the rows about to be appended,
1139
+ * before they are pushed, so the host's own `map` can never throw because of a bridge row
1140
+ * (JD-A-003) — if it would, nothing is appended and the late path behaves exactly as before.
1141
+ */
1142
+ function injectProvisionalRows(
1143
+ session: CaptureSession,
1144
+ array: CustomizeRow[],
1145
+ callback: unknown,
1146
+ thisArg: unknown,
1147
+ ): void {
1148
+ // One injection per build, and a menu built twice already received its rows.
1149
+ if (session.earlyInjection !== undefined) return;
1150
+ if (Object.hasOwn(array, CAPTURE_INJECTED)) return;
1151
+
1152
+ session.injecting = true;
1153
+ const state = captureState();
1154
+ let cardStyle: EarlyCardStyleSplice | undefined;
1155
+ let sectionPreview: SharedSectionsPatch | undefined;
1156
+ try {
1157
+ // S1, same ordering as the late path: the host's own line is extended before the providers'
1158
+ // rows are appended (the fallback provider's contribution depends on that order). The splice is
1159
+ // NOT idempotent, so it happens once per menu build.
1160
+ if (!session.extendedCardStyle) {
1161
+ session.extendedCardStyle = true;
1162
+ cardStyle = extendCardStyleProvisional(array);
1163
+ }
1164
+ // S1/S2: the host's `Sections` rows are patched BEFORE the host's own `map` reads this array,
1165
+ // so the list it previews already names the bridge's sections. Undone with everything else.
1166
+ sectionPreview = patchSharedSections(array);
1167
+ const built = buildRows(createRowContext(session.theme));
1168
+ // S4/S5: the provisional placement uses the same plan as the late path, computed against the
1169
+ // array BEFORE the host's own `map` reads it. A brand-new page is already in the array, so the
1170
+ // host's `new Set(...)` sees it; an existing page gets its `start`/`after` slots at the block
1171
+ // boundaries the resolver named.
1172
+ const plan = planRowPlacement(array, built.providers, built.blocks);
1173
+ recordObservedHostCategories(plan.hostCategories);
1174
+ if (
1175
+ plan.rows.length > 0 &&
1176
+ !provesPlannedRows(callback, thisArg, plan.planned, plan.rows)
1177
+ ) {
1178
+ // The host's own `map` would meet a row it cannot derive a page for. Nothing is written: the
1179
+ // splice and the preview patch go back too, and the late path handles this array exactly as it
1180
+ // did before S18.
1181
+ undoSharedSections(sectionPreview);
1182
+ undoCardStyleSplice(array, cardStyle);
1183
+ session.extendedCardStyle = false;
1184
+ return;
1185
+ }
1186
+ const original = [...array];
1187
+ // S21: the rows of a page a provider placed go in BEFORE the host's own `map` reads this array,
1188
+ // so its `new Set(...)` derives the page in the requested position; every other row is appended
1189
+ // in the pre-feature tail order. Both writes are recorded, because the rollback below has to undo
1190
+ // them and a mid-array insert is not a tail.
1191
+ const placed = built.rows.length > 0
1192
+ ? insertBuiltRows(array, built)
1193
+ : { tail: [] as CustomizeRow[], inserts: [] as { index: number; rows: CustomizeRow[] }[] };
1194
+ Object.defineProperty(array as object, CAPTURE_INJECTED, {
1195
+ value: true,
1196
+ enumerable: false,
1197
+ configurable: true,
1198
+ });
1199
+ const injection: EarlyInjection = {
1200
+ array,
1201
+ original,
1202
+ rows: built.rows,
1203
+ tail: placed.tail,
1204
+ inserts: placed.inserts,
1205
+ plan,
1206
+ failures: built.failures,
1207
+ };
1208
+ if (cardStyle !== undefined) injection.cardStyle = cardStyle;
1209
+ if (sectionPreview !== undefined) injection.sectionPreview = sectionPreview;
1210
+ session.earlyInjection = injection;
1211
+ state.lastFailures = built.failures;
1212
+ } catch {
1213
+ // The provider build isolates its own failures, so reaching this means the array refused the
1214
+ // edit. Nothing of the provisional step stays behind.
1215
+ undoSharedSections(sectionPreview);
1216
+ undoCardStyleSplice(array, cardStyle);
1217
+ session.extendedCardStyle = false;
1218
+ } finally {
1219
+ session.injecting = false;
1220
+ }
1221
+ }
1222
+
1223
+ /**
1224
+ * Extend the host's `Card style` line in place, remembering the splice so a rollback can undo it.
1225
+ * Returns `undefined` when nothing was written (no line, nothing registered, or a refusing array).
1226
+ */
1227
+ function extendCardStyleProvisional(array: CustomizeRow[]): EarlyCardStyleSplice | undefined {
1228
+ const line = findCardStyleLine(array);
1229
+ const original = line === undefined ? [] : array.slice(line.start, line.start + line.count);
1230
+ const before = array.length;
1231
+ extendCardStyleLine(array);
1232
+ const values = array.length - before;
1233
+ if (line === undefined || values <= 0) return undefined;
1234
+ return { start: line.start, hostCount: line.count, values, original };
1235
+ }
1236
+
1237
+ /** Put the host's own rows back where the provisional splice replaced them. */
1238
+ function undoCardStyleSplice(array: CustomizeRow[], splice: EarlyCardStyleSplice | undefined): void {
1239
+ if (splice === undefined) return;
1240
+ const total = splice.hostCount + splice.values;
1241
+ if (array.length < splice.start + total) return;
1242
+ array.splice(splice.start, total, ...splice.original);
1243
+ }
1244
+
1245
+ /**
1246
+ * The proof that qualifies an array for the early injection (S20).
1247
+ *
1248
+ * The host's own mapper is run exactly as `Array.prototype.map` would run it — same `this`, element,
1249
+ * index and array, and nothing else — over:
1250
+ *
1251
+ * 1. the array's own elements, each required to derive that element's `category ?? "Settings"`
1252
+ * (the view's page derivation, `lib/visual-customize-view.ts:387`);
1253
+ * 2. two synthetic rows the host never had, required to derive `"Settings"` for the one with no
1254
+ * category and its own unique page for the one naming the sentinel. This is what a mapper that
1255
+ * merely echoes what it is given, or ignores it, can never do;
1256
+ * 3. never a throw: a mapper that throws on any of those rows is simply not proven, so the host's
1257
+ * own call keeps its own behaviour and nothing is mutated.
1258
+ *
1259
+ * Nothing here mutates, runs a provider, or forwards anything to the host.
1260
+ */
1261
+ function provesCategoryMap(
1262
+ array: readonly CustomizeRow[],
1263
+ callback: unknown,
1264
+ thisArg: unknown,
1265
+ ): boolean {
1266
+ if (typeof callback !== "function") return false;
1267
+ const mapper = callback as CategoryMapper;
1268
+ try {
1269
+ for (let index = 0; index < array.length; index++) {
1270
+ const row = array[index];
1271
+ if (mapper.call(thisArg, row, index, array) !== expectedCategory(row)) return false;
1272
+ }
1273
+ for (let index = 0; index < SYNTHETIC_PROOF_ROWS.length; index++) {
1274
+ const row = SYNTHETIC_PROOF_ROWS[index];
1275
+ if (mapper.call(thisArg, row, index, SYNTHETIC_PROOF_ROWS) !== expectedCategory(row)) {
1276
+ return false;
1277
+ }
1278
+ }
1279
+ return true;
1280
+ } catch {
1281
+ return false;
1282
+ }
1283
+ }
1284
+
1285
+ /**
1286
+ * The mapper, run over only the rows this injection inserts — at the index they will have in
1287
+ * `planned`, so a mapper that throws on a bridge row (or would put one in the wrong page) never
1288
+ * meets one in the host's own `map` call (JD-A-003). The host's own rows are already proved.
1289
+ */
1290
+ function provesPlannedRows(
1291
+ callback: unknown,
1292
+ thisArg: unknown,
1293
+ planned: readonly CustomizeRow[],
1294
+ rows: readonly CustomizeRow[],
1295
+ ): boolean {
1296
+ if (typeof callback !== "function") return false;
1297
+ const mapper = callback as CategoryMapper;
1298
+ const inserted = new Set(rows);
1299
+ try {
1300
+ for (let index = 0; index < planned.length; index++) {
1301
+ const row = planned[index];
1302
+ if (!inserted.has(row)) continue;
1303
+ if (mapper.call(thisArg, row, index, planned) !== expectedCategory(row)) return false;
1304
+ }
1305
+ return true;
1306
+ } catch {
1307
+ return false;
1308
+ }
1309
+ }
1310
+
1311
+ /** The page the view would derive for a row: `row.category ?? "Settings"` (`:387`). */
1312
+ function expectedCategory(row: CustomizeRow): string {
1313
+ return row.category ?? HOST_DEFAULT_CATEGORY;
1314
+ }
1315
+
1316
+ /**
1317
+ * Row-like means: an array of at least three objects that each expose a callable `action`.
1318
+ * Deliberately allocation-free and `map`-free, because it runs while `Array.prototype.map` is
1319
+ * patched.
1320
+ */
1321
+ function isRowLikeArray(value: unknown): value is CustomizeRow[] {
1322
+ if (!Array.isArray(value) || value.length < MIN_ROW_ARRAY_LENGTH) return false;
1323
+ for (const element of value) {
1324
+ if (element === null || typeof element !== "object") return false;
1325
+ const action = (element as { action?: unknown }).action;
1326
+ if (typeof action !== "function") return false;
1327
+ }
1328
+ return true;
1329
+ }
1330
+
1331
+ function invalidate(component: HostCustomResult): void {
1332
+ if (component === null || typeof component !== "object") return;
1333
+ const invalidateFn = (component as HostComponent).invalidate;
1334
+ if (typeof invalidateFn === "function") invalidateFn.call(component);
1335
+ }
1336
+
1337
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
1338
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) return false;
1339
+ return typeof (value as { then?: unknown }).then === "function";
1340
+ }