Skip to content

packages/core/src/lib/layout/flex.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import { allocationCheckpointPhaseOwner, retainAllocationCheckpointPhases } from './allocation-checkpoint-owner.js';
2 import { withAllocationCheckpoint, recordAllocationStyle, allocationMeasurement, declineUnrecordedAllocationMeasurement } from './allocation-checkpoint.js';
3 import { contentBoxStyle } from './box-sizing.js';
4 import { canvasMeasurementService, isCurrentCanvasMeasurementService, isGenericCanvasFont } from './canvas-measurement.js';
5 import { Grid } from './grid.js';
6 import { Flow } from './flow.js';
7 import type { PreparedFlexLayoutPlan, PreparedLayoutPlan, PreparedLayoutSlot } from './prepared-root.js';
8 import { currentPreparedReceiverSlot, isKnownLayoutType, registerKnownLayoutPreflight, stagePreparedChildStyle, claimPreparedFlexPlan, peekPreparedLayoutPlan, peekPreparedFlexPlan, stagePreparedLayoutPlan, preflightKnownLayout, attachPreparedLayoutSlot, stagePreparedIntrinsicMain, peekPreparedIntrinsicMain, takePreparedIntrinsicMain, type PreparedIntrinsicMainStage } from './prepared-root.js';
9 import { isLayoutComponent, prepareLayoutComponent } from './define-layout-component.js';
10 import { allocationInputRevision, allocationStructuralRevision } from './allocation-revision.js';
11 import { FLEX_BASELINE_GROUP, FLEX_LAST_BASELINE } from './flex-baseline-mode.js';
12 import type { CachedFlexPlacement } from './flex-allocation-cache.js';
13 import { nativeLayout, LayoutRegion, mountedLayoutRegion, solveTransientFlexMain, prepareTransientIntrinsicMainQueries, resolveTransientIntrinsicMain, resolveTransientKnownOwnerMain, type NumericFlexMainInput, recordWasmMeasurement, recordWasmAllocationPass, recordWasmAllocationItem, recordWasmAllocationCacheHit } from './wasm/region.js';
14 import { Rectangle } from '../components/rect.js';
15 import { Text, prepareLayoutTextContent as readLayoutTextContent, measureLayoutTextMinimumWidth, measureLayoutTextNaturalRun } from '../components/text.js';
16 
17 const unsupportedProperties = ['order'] as const;
18 
19 import { ResponsiveStylePreparation, UnsupportedResponsiveMeasurement, withStyleMeasurement, preparedStyleValue, preparedStyleQuery, type PreparedQuery } from '../style/responsive.js';
20 import { definePrimitive } from '../define-primitive.js';
21 import { clonePibblElement } from '../element/create-element.js';
22 import { getChildPrimitiveReceiverToken, getPrimitiveReceiverToken, getPrimitiveDefinition, getPrimitiveProgramProps, getElementMetadata, setElementMetadata } from '../element/metadata.js';
23 import type { PibblElement } from '../element/types.js';
24 import { GLOBAL_STATE } from '../global-state.js';
25 import { LayoutDiagnostic, layoutDiagnostic } from '../style/diagnostics.js';
26 import {
27   type PibblStructuralEventProps,
28   wireStructuralEvents,
29 } from '../components/structural-events.js';
30 import { normalizeBoxInsets, hasPercentageBoxPadding, resolveAllocatedInsets } from './box-insets.js';
31 import { resolveScalarSizingLength } from '../style/sizing-length.js';
32 import { parsePercentage } from '../style/resolve-length.js';
33 import { isIntrinsicSizingValue, normalizeSizingLength, type NormalizedSizingLength } from '../style/sizing-length.js';
34 import { setPreNormalizedStyle, peekPreNormalizedStyle } from '../style/resolve-dispatch.js';
35 import type {
36   BoxStyle,
37   TextStyle,
38   Percentage,
39   FlexItemStyle,
40   LayoutItemStyle,
41   ResolvedBoxStyle,
42 } from '../style/types.js';
43 import type {
44   CanvasMeasurementService,
45   PibblNodeInput,
46   MeasureInput,
47   MeasureResult,
48   IntrinsicMeasureInput,
49   IntrinsicSizesResult,
50   RenderingContext2D,
51   SystemStyle,
52 } from '../types.js';
53 import {
54   childWithUsedSize,
55   prepareDirectChildStyle,
56   materializeLayoutChildren,
57   placeDirectChildren,
58   prepareLayoutChildren,
59   resolveContainerBox,
60   resolveDirectChildBox,
61 } from './absolute.js';
62 import { getLayoutDirection, getLogicalContainingBox, pushLayoutBox } from './context.js';
63 import { recordLayoutEvaluation } from './diagnostics.js';
64 import { assertSupportedChildPosition } from './positioning-diagnostics.js';
65 import { markDerivedAbsoluteAxes } from '../style/positioning.js';
66 import { measureElement, measureConstrainedLayoutChild, measureIntrinsicElement, measureConstrainedIntrinsicElement, measurePreparedLayoutElement, measureBaselineElement, setPreparedBaselineOwner, type BaselineMeasurementOptions, withIsolatedRenderState } from './measure.js';
67 import { isSignal, withSignalWriteForbidden } from '../signals/graph.js';
68 import type { Constraints, LayoutBox } from './types.js';
69 
70 type FlexDirection = 'row' | 'column' | 'row-reverse' | 'column-reverse';
71 type FlexWrap = 'nowrap' | 'wrap' | 'wrap-reverse';
72 type MainAlignment =
73   | 'flex-start'
74   | 'flex-end'
75   | 'center'
76   | 'space-between'
77   | 'space-around'
78   | 'space-evenly';
79 type CrossAlignment = 'stretch' | 'flex-start' | 'flex-end' | 'center';
80 type ItemCrossAlignment = CrossAlignment | 'first-baseline' | 'last-baseline';
81 
82 /**
83  * Supported geometry and presentation properties for Flex.
84  *
85  * @see {@link BoxStyle}
86  * @see {@link LayoutItemStyle}
87  * @see {@link Flex}
88  */
89 export interface FlexStyle extends BoxStyle, LayoutItemStyle {
90   /** Inherited inline direction. Roots default to LTR. See {@link Flex}. */
91   layoutDirection?: 'ltr' | 'rtl';
92   /** The main axis along which flex children are placed. See {@link FlexDirection}. */
93   flexDirection?: FlexDirection;
94   /** Whether children may wrap onto additional flex lines. See {@link FlexWrap}. */
95   flexWrap?: FlexWrap;
96   /** Distribution along the main axis. start/end follow layout direction independently of axis reversal. See {@link MainAlignment}. */
97   justifyContent?: MainAlignment | 'start' | 'end';
98   /** Cross alignment. start/end follow layout direction independently of wrap reversal. See {@link CrossAlignment}. */
99   alignItems?: ItemCrossAlignment | 'start' | 'end';
100   /**
101    * Distribution of wrapped flex lines within the available cross-axis space. See
102    * {@link CrossAlignment}, {@link MainAlignment}.
103    */
104   alignContent?: CrossAlignment | MainAlignment | 'start' | 'end';
105   /** Numeric spacing, or experimental allocated-axis percentages. See {@link Percentage}, {@link FlexStyle}. */
106   gap?: number | Percentage;
107   /** Physical row spacing; experimental percentages use content height. See {@link Percentage}, {@link FlexStyle}. */
108   rowGap?: number | Percentage;
109   /** Physical column spacing; experimental percentages use content width. See {@link Percentage}, {@link FlexStyle}. */
110   columnGap?: number | Percentage;
111 }
112 
113 /**
114  * Authored inputs for Flex, including the declared data and presentation options.
115  *
116  * @see {@link PibblNodeInput}
117  * @see {@link Flex}
118  */
119 export interface FlexProps extends PibblStructuralEventProps {
120   /** Descendant content or the callback that supplies it. See {@link PibblNodeInput}. */
121   children: PibblNodeInput;
122 }
123 
124 export interface FlexMeasurementInput {
125   service: CanvasMeasurementService;
126   measureElement(
127     element: PibblElement<any>,
128     constraints: Readonly<Constraints>,
129   ): MeasureResult;
130 }
131 
132 // Parent input is private metadata, not a recursively validated resolved value.
133 const FLEX_ABSOLUTE_BOX_STYLE = Symbol('pibbl.flex-absolute-box-style');
134 const FLEX_INHERITED_CONTAINING_BOX = Symbol('pibbl.flex-inherited-containing-box');
135 
136 interface ResolvedFlexStyle extends SystemStyle {
137   layoutDirection: 'ltr' | 'rtl';
138   box: ResolvedBoxStyle;
139   overflow: 'visible' | 'clip';
140   flexDirection: FlexDirection;
141   flexWrap: FlexWrap;
142   justifyContent: MainAlignment;
143   alignItems: CrossAlignment;
144   /** True when first/last baseline requires a horizontal measured group. */
145   [FLEX_BASELINE_GROUP]: boolean;
146   [FLEX_LAST_BASELINE]: boolean;
147   alignContent: CrossAlignment | MainAlignment;
148   rowGap: number;
149   columnGap: number;
150   /** Original container input retained for lazy absolute padding-box derivation. */
151   [FLEX_ABSOLUTE_BOX_STYLE]: Readonly<FlexStyle>;
152   [FLEX_INHERITED_CONTAINING_BOX]?: Readonly<LayoutBox>;
153 }
154 
155 interface FlexItem {
156   child: PibblElement<any>;
157   normalized: Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle>;
158   baseMain: number;
159   targetMain: number;
160   paddingMain: number;
161   marginMainBefore: number;
162   marginMainAfter: number;
163   autoMainBefore: boolean;
164   autoMainAfter: boolean;
165   marginCrossBefore: number;
166   marginCrossAfter: number;
167   autoCrossBefore: boolean;
168   autoCrossAfter: boolean;
169   preferredCross: number;
170   paddingCross: number;
171   paddingCrossBefore: number;
172   minMain: number;
173   maxMain: number;
174   minCross: number;
175   maxCross: number;
176   grow: number;
177   shrink: number;
178   crossAuto: boolean;
179   aspectRatio?: number;
180   alignSelf: CrossAlignment | 'auto';
181   receiverToken: object;
182   layoutToken?: object;
183   query?: PreparedQuery;
184   relativeX: number;
185   relativeY: number;
186   /** Signed selected baseline offset resolved after final main allocation. */
187   firstBaseline?: number;
188   /** Current transaction root of a transparent layout description. */
189   baselineRoot?: PibblElement<any>;
190   /** Existing known-Flex slot prepared before this outer baseline pass. */
191   structuralBaselineSlot?: PreparedLayoutSlot;
192   /** Unkeyed source-type occurrence, shared with known descendant preparation. */
193   layoutOccurrence: number;
194   /** Column natural cross size is measured only after native main allocation. */
195   deferredColumnAutoCross: boolean;
196   ordinaryColumnAutoCross: boolean;
197   sourceIndex: number;
198 }
199 
200 interface FlexLine {
201   items: FlexItem[];
202   crossSize: number;
203   crossOffset: number;
204 }
205 
206 /** One current known-Flex baseline result, without claiming its staged region. */
207 interface PreparedKnownBaseline {
208   readonly slot: PreparedLayoutSlot;
209   readonly offset: number;
210 }
211 
212 export interface FlexPlacement extends CachedFlexPlacement {
213   box: LayoutBox;
214   element: PibblElement<any>;
215 }
216 interface DeferredStaticAbsolutePlacement {
217   readonly sourceIndex: number;
218   readonly child: PibblElement<any>;
219   readonly style: Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle>;
220   readonly receiverToken: object;
221   readonly query: PreparedQuery | undefined;
222   readonly measurement: FlexMeasurementInput | undefined;
223   readonly measurementToken: object | undefined;
224 }
225 interface DeferredStaticPlacementState {
226   /** Source-indexed descriptors keep source ordering without scanning pending entries. */
227   readonly slots: Array<DeferredStaticAbsolutePlacement | undefined>;
228   readonly style: Readonly<ResolvedFlexStyle>;
229 }
230 const deferredStaticPlans = new WeakMap<PreparedFlexLayoutPlan, DeferredStaticPlacementState>();
231 function deferredStaticPlacementSentinel(): FlexPlacement {
232   const fail = (): never => { throw new Error('Deferred static Flex absolute placement was read before finalization.'); };
233   return { get box() { return fail(); }, get layoutY() { return fail(); }, get usedWidth() { return fail(); }, get usedHeight() { return fail(); }, get element() { return fail(); } };
234 }
235 
236 function renderFlex(
237   props: FlexProps,
238   style: Readonly<ResolvedFlexStyle>,
239   ctx: RenderingContext2D,
240 ) {
241   wireStructuralEvents(props);
242   recordLayoutEvaluation();
243   const content = style.box.contentBox;
244   ctx.translate(content.x, content.y);
245   const localContent = Object.freeze({
246     x: 0,
247     y: 0,
248     width: content.width,
249     height: content.height,
250   });
251   const specified = style[FLEX_ABSOLUTE_BOX_STYLE];
252   const releaseLayout = pushLayoutBox(localContent, {
253     layoutDirection: style.layoutDirection,
254     logicalOffset: content,
255     containingBlock: nativeLayout && specified?.position !== 'static'
256       ? resolveFlexAbsolutePaddingBox(specified ?? {}, localContent) : undefined,
257   });
258   GLOBAL_STATE.componentRefs!.onAfterRender = releaseLayout;
259   const service = flexMeasurementService(ctx);
260   const prepared = nativeLayout ? claimPreparedFlexPlan(GLOBAL_STATE.componentRefs!.element, localContent) : undefined;
261   const region = nativeLayout ? mountedLayoutRegion() : undefined;
262   const plan = prepared ?? prepareFlexAllocation(props, style, localContent, service, region);
263   if (nativeLayout && !prepared) prepareFlexDescendants(plan, style);
264   const { children, placements } = plan;
265   let index = 0;
266   return placeDirectChildren(
267     children,
268     localContent,
269     () => placements[index++],
270     style.overflow,
271   );
272 }
273 
274 function flexMeasurementService(ctx: RenderingContext2D): CanvasMeasurementService {
275   return canvasMeasurementService(ctx);
276 }
277 function prepareFlexAllocation(props: FlexProps, style: Readonly<ResolvedFlexStyle>, localContent: Readonly<LayoutBox>, service: CanvasMeasurementService, region?: LayoutRegion, parentSlot?: PreparedLayoutSlot, deferStaticAbsolute?: Array<DeferredStaticAbsolutePlacement | undefined>) {
278   const revision = allocationInputRevision();
279   const children = prepareLayoutChildren(props.children, 'Flex');
280   const axis = isRowDirection(style.flexDirection) ? 'row' : 'column';
281   const staged = takePreparedIntrinsicMain(
282     GLOBAL_STATE.primitiveReceiverToken,
283     children,
284     axis,
285     axis === 'row' ? localContent.width : localContent.height,
286     revision,
287   );
288   const placements = withAllocationCheckpoint(region, {
289     children, content: localContent, settings: { style, deferred: !!deferStaticAbsolute }, flexMargins: true,
290     continuation: staged && { axis: staged.axis, contentMain: staged.contentMain, items: staged.items, autoMarginFreeMain: staged.autoMarginFreeMain },
291     pending: deferStaticAbsolute && {
292       read: index => {
293         const entry = deferStaticAbsolute[index];
294         return entry && { style: entry.style, data: { measured: !!entry.measurement, token: entry.measurementToken } };
295       },
296       replay: (index, normalized, receiverToken, query, data) => {
297         const { measured, token } = data as { measured: boolean; token: object | undefined };
298         deferStaticAbsolute[index] = { sourceIndex: index, child: children[index], style: normalized, receiverToken, query,
299           measurement: measured ? { service, measureElement: (element, constraints) => measureElement(element, constraints, service) } : undefined,
300           measurementToken: token };
301         return deferredStaticPlacementSentinel();
302       },
303     },
304     onHit: recordWasmAllocationCacheHit,
305     calculate: () => resolveFlexPlacements(localContent, children, style, {
306       service,
307       measureElement: (element, constraints) => measureElement(element, constraints, service),
308     }, region, staged, parentSlot, deferStaticAbsolute),
309   });
310   for (let index = 0; index < placements.length; index++) {
311     if (deferStaticAbsolute?.[index]) continue;
312     const placement = placements[index];
313     attachPreparedLayoutSlot(placement.element, currentPreparedReceiverSlot(getPrimitiveReceiverToken(placement.element)));
314   }
315   if (region) retainAllocationCheckpointPhases(region, deferStaticAbsolute?.flatMap((entry, index) => entry ? [index] : []) ?? []);
316   return { children, placements, revision, content: localContent, cached: false };
317 }
318 
319 /**
320  * Describes the supported Flexbox subset for JSX or createElement authoring.
321  * Text automatic heights use the final allocated width in rows and nowrap columns
322  * before dependent sibling placement. See {@link Text}.
323  *
324  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
325  * props and style types.
326  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
327  *
328  * @see {@link FlexProps}
329  * @see {@link FlexStyle}
330  */
331 export const Flex = definePrimitive<
332   FlexProps,
333   FlexStyle,
334   FlexStyle,
335   ResolvedFlexStyle
336 >(renderFlex, {
337   childInput: 'structural',
338   resolveStyle: (style, context) => {
339     const box = resolveContainerBox(style, context, 'Flex', 'flex');
340     return {
341       box,
342       [FLEX_ABSOLUTE_BOX_STYLE]: style,
343       [FLEX_INHERITED_CONTAINING_BOX]: nativeLayout ? getElementMetadata(GLOBAL_STATE.componentRefs!.element)?.absoluteContainingBlock : undefined,
344       overflow: style.overflow ?? 'visible',
345       ...normalizeFlexOptions(style, box.contentBox),
346     };
347   },
348   measure: input => measureFlex(input),
349   measureIntrinsic: input => measureFlexIntrinsic(input),
350 });
351 
352 // A known Absolute sibling boundary resolves these receiver inputs before any
353 // sibling's opaque component executes. Geometry still solves in normal traversal.
354 let allocatedIntrinsicMain: { receiver: object; main: number; rootMin?: number; rootMax?: number } | undefined;
355 
356 // A known Flex contributes its native adjusted line size while its parent is
357 // measuring the same main axis. The scope is receiver-bound and only exists
358 // through the immediate child measurement; ordinary public queries retain the
359 // resolved outer size.
360 let requestedIntrinsicContribution: { receiver: object; axis: 'row' | 'column'; normalOwner?: boolean } | undefined;
361 if (nativeLayout) registerKnownLayoutPreflight(Flex, (element, style, content, receiver, slot, parentMainAxis, preflightOptions) => {
362   const options = normalizeFlexOptions(style as Readonly<FlexStyle>, content);
363   const releaseLayout = pushLayoutBox(content, options);
364   const previous = GLOBAL_STATE.primitiveReceiverToken;
365   GLOBAL_STATE.primitiveReceiverToken = receiver;
366   try {
367     const children = prepareLayoutChildren(element.props.children, 'Flex');
368     const axis = isRowDirection(options.flexDirection) ? 'row' : 'column';
369     const main = axis === 'row' ? content.width : content.height;
370     const contribution = parentMainAxis === axis ? peekPreparedIntrinsicMain(
371       receiver, children, axis, main, allocationInputRevision(),
372     ) : undefined;
373     if (contribution && !contribution.normalOwner) {
374       // A main-axis contribution sizes this owner, not its final descendants.
375       // Rebind those descendants through native exact mode at the allocated main.
376       const ctx = GLOBAL_STATE.renderContext;
377       if (!ctx) throw new Error('Known layout preparation requires a Canvas measurement context.');
378       const measuredRoot = clonePibblElement(element);
379       setPreNormalizedStyle(measuredRoot, contribution.style, element, receiver);
380       const previousPhase = allocatedIntrinsicMain;
381       allocatedIntrinsicMain = { receiver, main, rootMin: contribution.rootMin, rootMax: contribution.rootMax };
382       try {
383         const result = measureConstrainedIntrinsicElement(measuredRoot, {
384           minWidth: 0, maxWidth: content.width, minHeight: 0, maxHeight: content.height,
385         }, flexMeasurementService(ctx));
386         if (result.status !== 'measured') throw new Error(`Known Flex allocated-owner measurement is unsupported: ${result.reason}`);
387       } finally { allocatedIntrinsicMain = previousPhase; }
388     }
389     for (let index = 0; index < children.length; index++) {
390       const child = children[index];
391       const token = getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, receiver, index);
392       let prepared = prepareDirectChildStyle(child, token, content, true);
393       const specified = preparedStyleValue(prepared) as Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle & Record<string, unknown>>;
394       const normalized = resolveAllocatedInsets(specified, { width: content.width, layoutDirection: options.layoutDirection, context: childContext(child, content) });
395       if (normalized !== specified) {
396         if (prepared instanceof ResponsiveStylePreparation) prepared.style = normalized;
397         else prepared = normalized;
398       }
399       assertSupportedChildPosition('Flex', child, normalized, true);
400       rejectUnsupportedItemFields(child, normalized, content);
401       nonnegativeFactor(normalized.flexGrow ?? 0, 'flexGrow', child, content);
402       nonnegativeFactor(normalized.flexShrink ?? 1, 'flexShrink', child, content);
403       stagePreparedChildStyle(child, token, content, prepared);
404     }
405     const ctx = GLOBAL_STATE.renderContext;
406     if (!ctx) throw new Error('Known layout preparation requires a Canvas measurement context.');
407     const region = slot.acquire();
408     const resolved = {
409       box: { contentBox: content },
410       [FLEX_ABSOLUTE_BOX_STYLE]: style as Readonly<FlexStyle>,
411       [FLEX_INHERITED_CONTAINING_BOX]: getElementMetadata(element)?.absoluteContainingBlock,
412       overflow: (style as Readonly<FlexStyle>).overflow ?? 'visible',
413       ...normalizeFlexOptions(style as Readonly<FlexStyle>, content),
414     } as Readonly<ResolvedFlexStyle>;
415     const deferred = preflightOptions?.deferStaticContainingDescendants ? [] as Array<DeferredStaticAbsolutePlacement | undefined> : undefined;
416     const plan = prepareFlexAllocation(element.props as FlexProps, resolved, content, flexMeasurementService(ctx), region, slot, deferred);
417     const staged = { ...plan, region } as PreparedFlexLayoutPlan;
418     if (deferred) {
419       // Count represents the unresolved origin phase, even if this owner has no direct absolute child.
420       staged.pending = { kind: 'static-flex-containing-origin', count: 1 };
421       deferredStaticPlans.set(staged, { slots: deferred, style: resolved });
422       // Prepare in-flow known descendants now; static descendants inherit this pending origin.
423       prepareFlexDescendants(staged, resolved, slot, true);
424     } else prepareFlexDescendants(staged, resolved, slot);
425     stagePreparedLayoutPlan(slot, staged);
426   } finally { GLOBAL_STATE.primitiveReceiverToken = previous; releaseLayout(); }
427 });
428 
429 function deferredStaticState(plan: PreparedFlexLayoutPlan): DeferredStaticPlacementState | undefined {
430   return deferredStaticPlans.get(plan);
431 }
432 function finalizeDeferredStaticAbsolutePlacements(plan: PreparedFlexLayoutPlan, style: Readonly<ResolvedFlexStyle>): void {
433   const state = deferredStaticState(plan as PreparedFlexLayoutPlan);
434   if (!state) return;
435   let paddingBox: Readonly<LayoutBox> | undefined;
436   for (let sourceIndex = 0; sourceIndex < state.slots.length; sourceIndex++) {
437     const entry = state.slots[sourceIndex];
438     if (!entry) continue;
439     if (entry.sourceIndex !== sourceIndex || sourceIndex >= plan.placements.length) throw new Error('Deferred static absolute placement lost source ordering.');
440     const containing = paddingBox ??= resolveFlexContainingBox(style, plan.content);
441     const owner = plan.region && allocationCheckpointPhaseOwner(plan.region, sourceIndex);
442     plan.placements[sourceIndex] = withAllocationCheckpoint(owner, {
443       children: [entry.child], receiverTokens: [entry.receiverToken], content: plan.content,
444       settings: { style, containing }, flexMargins: true, onHit: recordWasmAllocationCacheHit,
445       calculate: () => {
446         // This is a distinct numerical phase, after the containing origin settles.
447         if (plan.region) { recordWasmAllocationPass(); recordWasmAllocationItem(); }
448         recordAllocationStyle(entry.receiverToken, entry.query ? new ResponsiveStylePreparation(entry.style, entry.query) : entry.style);
449         return [resolveAbsoluteFlexPlacement(containing, entry.child, entry.style, entry.receiverToken, entry.query,
450           plan.content, style, entry.measurement, plan.region, entry.measurementToken)];
451       },
452     })[0];
453     state.slots[sourceIndex] = undefined;
454   }
455 }
456 
457 /** Known descendants prepare only after this boundary's own allocation settles. */
458 function prepareFlexDescendants(plan: Pick<PreparedFlexLayoutPlan, 'children' | 'placements' | 'content'> & { region?: LayoutRegion }, style: Readonly<ResolvedFlexStyle>, parentSlot?: PreparedLayoutSlot, unresolvedStaticOrigin = false): void {
459   if (!unresolvedStaticOrigin) finalizeDeferredStaticAbsolutePlacements(plan as PreparedFlexLayoutPlan, style);
460   let containingBox: Readonly<LayoutBox> | undefined;
461   let flexOccurrence = 0;
462   let descriptionOccurrences: Map<Function, number> | undefined;
463     for (let index = 0; index < plan.children.length; index++) {
464       const child = plan.children[index];
465       if (!isKnownLayoutType(child.type) && !isLayoutComponent(child.type)) continue;
466       let occurrence = 0;
467       if (child.key === undefined) {
468         if (child.type === Flex) occurrence = flexOccurrence++;
469         else {
470           descriptionOccurrences ??= new Map();
471           occurrence = descriptionOccurrences.get(child.type) ?? 0;
472           descriptionOccurrences.set(child.type, occurrence + 1);
473         }
474       }
475       // A static owner has not received its containing origin yet. Its direct
476       // absolute entries are descriptors, never settled placement objects.
477       if (deferredStaticState(plan as PreparedFlexLayoutPlan)?.slots[index]) continue;
478       const placement = plan.placements[index];
479       const prepared = peekPreNormalizedStyle(placement.element);
480       if (!prepared) throw new Error('Known layout preparation requires settled receiver inputs.');
481       const receiver = getPrimitiveReceiverToken(placement.element);
482       if (!receiver) throw new Error('Known layout preparation requires the current child receiver.');
483       const preparedRoot = isLayoutComponent(child.type) ? prepareLayoutComponent(child, { receiverToken: receiver }) : child;
484       const staticFlexRoot = preparedRoot.type === Flex && (prepared.style as FlexStyle).position === 'static';
485       let preparationChild = child;
486       // Declarative static Flex boxes pass the nearest owner's padding box through
487       // existing placement metadata. Nothing is attached to authored props/styles.
488       const unresolvedStaticChild = unresolvedStaticOrigin && staticFlexRoot;
489       if (staticFlexRoot && !unresolvedStaticChild) {
490         containingBox ??= resolveFlexContainingBox(style, plan.content);
491         const insets = normalizeBoxInsets(prepared.style as FlexStyle, childContext(child, plan.content));
492         const x = finiteRelativePlacement(containingBox.x - placement.box.x - insets.left, 'left', child, plan.content);
493         const y = finiteRelativePlacement(containingBox.y - placement.box.y - insets.top, 'top', child, plan.content);
494         setElementMetadata(placement.element, {
495           ...getElementMetadata(placement.element),
496           layoutDescriptionSource: getElementMetadata(child)?.layoutDescriptionSource ?? child,
497           absoluteContainingBlock: Object.freeze({ x, y, width: containingBox.width, height: containingBox.height }),
498         });
499         preparationChild = placement.element;
500       }
501       const content = { x: 0, y: 0, width: placement.usedWidth, height: placement.usedHeight };
502       const staged = getElementMetadata(placement.element)?.preparedLayoutSlot as PreparedLayoutSlot | undefined;
503       // A baseline pass may have already staged this exact settled child. Retain
504       // static containing-box metadata above, but never stage the slot twice.
505       const current = staged && peekPreparedLayoutPlan(staged, content, (prepared.style as FlexStyle).layoutDirection ?? style.layoutDirection);
506       if (current) {
507         if (preparedRoot.type === Flex) {
508           const stagedFlex = current as PreparedFlexLayoutPlan;
509           const state = deferredStaticState(stagedFlex);
510           if (state && !unresolvedStaticOrigin) {
511             const inherited = getElementMetadata(placement.element)?.absoluteContainingBlock;
512             if (!inherited) throw new Error('Static structural descendants require the settled containing box before finalization.');
513             const nestedStyle = { ...state.style, [FLEX_INHERITED_CONTAINING_BOX]: inherited } as Readonly<ResolvedFlexStyle>;
514             finalizeDeferredStaticAbsolutePlacements(stagedFlex, nestedStyle);
515             prepareFlexDescendants(stagedFlex, nestedStyle, staged);
516             stagedFlex.pending!.count = 0;
517             deferredStaticPlans.delete(stagedFlex);
518           }
519         }
520         continue;
521       }
522       const nested = preflightKnownLayout(preparationChild, prepared.style, content, receiver, occurrence, parentSlot, isRowDirection(style.flexDirection) ? 'row' : 'column',
523         unresolvedStaticChild ? { deferStaticContainingDescendants: true } : undefined);
524       attachPreparedLayoutSlot(placement.element, nested);
525     }
526 }
527 
528 
529 /** Pure content contributions; final allocation still belongs to the native solver. */
530 function measureFlexIntrinsic(input: IntrinsicMeasureInput<FlexProps, FlexStyle>): IntrinsicSizesResult {
531   const width = input.constraints.width.kind === 'bounded' ? input.constraints.width.max : Number.POSITIVE_INFINITY;
532   const height = input.constraints.height.kind === 'bounded' ? input.constraints.height.max : Number.POSITIVE_INFINITY;
533   const owner = { x: 0, y: 0, width: Number.isFinite(width) ? width : 0, height: Number.isFinite(height) ? height : 0 };
534   const row = isRowDirection(input.style.flexDirection);
535   const wrap = (input.style.flexWrap ?? 'nowrap') !== 'nowrap';
536   if (isPercentage(input.style.gap) || isPercentage(input.style.columnGap) || isPercentage(input.style.rowGap)) return { status: 'unsupported', reason: 'Flex intrinsic percentage gaps require a definite owning axis' };
537   const options = normalizeFlexOptions(input.style, owner);
538   const children = materializeLayoutChildren(input.props.children, 'Flex');
539   let minMain = 0, maxMain = 0, minCross = 0, maxCross = 0, count = 0;
540   for (let index = 0; index < children.length; index++) {
541     const child = children[index];
542     const receiver = getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, index);
543     const prepared = prepareDirectChildStyle(child, receiver, owner, true);
544     let style = preparedStyleValue(prepared) as Readonly<BoxStyle & FlexItemStyle>;
545     if (style.position === 'absolute') continue;
546     if (style.boxSizing !== undefined) style = contentBoxStyle(style, { width: owner.width, height: owner.height, mainAxis: row ? 'width' : 'height', context: childContext(child, owner) });
547     if (hasPercentageBoxPadding(style) || isPercentage(style.width) || isPercentage(style.height) ||
548       isPercentage(style.flexBasis) || hasPercentageBounds(style)) return { status: 'unsupported', reason: 'Flex intrinsic percentage child sizes require a definite owning axis' };
549     const measuredChild = clonePibblElement(child);
550     setPreNormalizedStyle(measuredChild, style, child, receiver, preparedStyleQuery(prepared));
551     const measured = typeof style.width === 'number' && typeof style.height === 'number' ? {
552       status: 'measured' as const, minContent: { width: style.width, height: style.height }, maxContent: { width: style.width, height: style.height },
553     } : measureIntrinsicElement(measuredChild, { minWidth: 0, maxWidth: width, minHeight: 0, maxHeight: height }, input.service);
554     if (measured.status !== 'measured') return measured;
555     const padding = normalizeBoxInsets(style, childContext(child, owner));
556     const horizontal = padding.left + padding.right, vertical = padding.top + padding.bottom;
557     const marginLeft = style.marginLeft ?? style.margin, marginRight = style.marginRight ?? style.margin;
558     const marginTop = style.marginTop ?? style.margin, marginBottom = style.marginBottom ?? style.margin;
559     const marginsX = allocatedMargin(marginLeft === 'auto' ? 0 : marginLeft, 'marginLeft', child, owner) + allocatedMargin(marginRight === 'auto' ? 0 : marginRight, 'marginRight', child, owner);
560     const marginsY = allocatedMargin(marginTop === 'auto' ? 0 : marginTop, 'marginTop', child, owner) + allocatedMargin(marginBottom === 'auto' ? 0 : marginBottom, 'marginBottom', child, owner);
561     const lowerWidth = intrinsicOptionalNumber(style.minWidth, 0, 'minWidth');
562     const upperWidth = intrinsicOptionalNumber(style.maxWidth, Number.POSITIVE_INFINITY, 'maxWidth');
563     const lowerHeight = intrinsicOptionalNumber(style.minHeight, 0, 'minHeight');
564     const upperHeight = intrinsicOptionalNumber(style.maxHeight, Number.POSITIVE_INFINITY, 'maxHeight');
565     if (lowerWidth > upperWidth) throw childDiagnostic(child, 'minWidth', lowerWidth, owner, 'minimum must not exceed maximum');
566     if (lowerHeight > upperHeight) throw childDiagnostic(child, 'minHeight', lowerHeight, owner, 'minimum must not exceed maximum');
567     const minimumWidth = clamp(typeof style.width === 'number' ? style.width : measured.minContent.width, lowerWidth, upperWidth) + horizontal + marginsX;
568     const maximumWidth = clamp(typeof style.width === 'number' ? style.width : measured.maxContent.width, lowerWidth, upperWidth) + horizontal + marginsX;
569     const minimumHeight = clamp(typeof style.height === 'number' ? style.height : measured.minContent.height, lowerHeight, upperHeight) + vertical + marginsY;
570     const maximumHeight = clamp(typeof style.height === 'number' ? style.height : measured.maxContent.height, lowerHeight, upperHeight) + vertical + marginsY;
571     const childMinMain = row ? minimumWidth : minimumHeight, childMaxMain = row ? maximumWidth : maximumHeight;
572     const childMinCross = row ? minimumHeight : minimumWidth, childMaxCross = row ? maximumHeight : maximumWidth;
573     minMain = wrap ? Math.max(minMain, childMinMain) : minMain + childMinMain;
574     maxMain += childMaxMain;
575     minCross = wrap ? minCross + childMinCross : Math.max(minCross, childMinCross);
576     maxCross = Math.max(maxCross, childMaxCross);
577     count++;
578   }
579   const mainGaps = Math.max(0, count - 1) * (row ? options.columnGap : options.rowGap);
580   const crossGaps = Math.max(0, count - 1) * (row ? options.rowGap : options.columnGap);
581   if (!wrap) minMain += mainGaps; else minCross += crossGaps;
582   maxMain += mainGaps;
583   return { status: 'measured', minContent: { width: Math.max(0, row ? minMain : minCross), height: Math.max(0, row ? minCross : minMain) }, maxContent: { width: Math.max(0, row ? maxMain : maxCross), height: Math.max(0, row ? maxCross : maxMain) } };
584 }
585 
586 /** Finite-main native continuation for general intrinsic children. */
587 function measureAllocatedFlex(input: MeasureInput<FlexProps, FlexStyle>, children: readonly PibblElement<any>[], measuredWidth: NonNullable<FlexStyle['width']>): MeasureResult {
588     const width = resolveMeasuredContainerLength(measuredWidth, input.constraints.maxWidth, 'width', input.constraints);
589     const height = Number.isFinite(input.constraints.maxHeight) ? input.constraints.maxHeight : 0;
590     const region = new LayoutRegion();
591     let placements: FlexPlacement[];
592     try {
593       placements = resolveFlexPlacements({ x: 0, y: 0, width, height }, children, {
594         ...input.style, alignContent: 'flex-start',
595         alignItems: input.style.alignItems === undefined || input.style.alignItems === 'stretch' ? 'flex-start' : input.style.alignItems,
596       }, input, region);
597     } catch (error) {
598       if (error instanceof LayoutDiagnostic && error.message.includes('measurement is required but unsupported:')) return { status: 'unsupported', reason: error.message };
599       throw error;
600     } finally { region.dispose(); }
601     let first = Number.POSITIVE_INFINITY, last = Number.NEGATIVE_INFINITY;
602     const owner = { x: 0, y: 0, width, height };
603     for (let index = 0; index < placements.length; index++) {
604       const placement = placements[index];
605       const style = peekPreNormalizedStyle(placement.element)?.style as Readonly<FlexItemStyle & BoxStyle>;
606       if (style.position === 'absolute') continue;
607       const top = style.marginTop ?? style.margin, bottom = style.marginBottom ?? style.margin;
608       const before = top === 'auto' ? 0 : allocatedMargin(top, 'marginTop', placement.element, owner);
609       const after = bottom === 'auto' ? 0 : allocatedMargin(bottom, 'marginBottom', placement.element, owner);
610       first = Math.min(first, placement.layoutY - before);
611       last = Math.max(last, placement.layoutY + placement.box.height + after);
612     }
613     return { status: 'measured', size: { width, height: Number.isFinite(first) ? Math.max(0, last - first) : 0 } };
614 }
615 
616 interface IntrinsicRowItem extends NumericFlexMainInput {
617   readonly sourceIndex: number;
618   readonly child: PibblElement<any>;
619   /** Prepared direct paired root when the source child is a layout description. */
620   readonly measuredChild: PibblElement<any>;
621   readonly style: Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle & Record<string, unknown>>;
622   readonly receiverToken: object;
623   readonly measureCross: boolean;
624   readonly baseCross: number;
625   readonly minCross: number;
626   readonly maxCross: number;
627   readonly paddingCross: number;
628   readonly marginCross: number;
629 }
630 
631 function measureFlex(
632   input: MeasureInput<FlexProps, FlexStyle>,
633 ): MeasureResult {
634   const children = prepareLayoutChildren(input.props.children, 'Flex');
635   const phase = allocatedIntrinsicMain;
636   if (phase && phase.receiver === GLOBAL_STATE.primitiveReceiverToken) {
637     allocatedIntrinsicMain = undefined;
638     try {
639       const diagnosticBox = { x: 0, y: 0, width: input.constraints.maxWidth, height: input.constraints.maxHeight };
640       const result = measureStagedNonexactMain(input, children, normalizeFlexOptions(input.style, diagnosticBox), diagnosticBox, phase);
641       if (result) return result;
642       return unsupportedIntrinsic('allocated known-owner continuation no longer matches its measured profile');
643     } finally { allocatedIntrinsicMain = phase; }
644   }
645   // Exact caller availability supplies a definite main axis. A finite maximum
646   // alone remains an availability limit, never a percentage containing size.
647   const automaticWidth = input.style.width === undefined || input.style.width === 'auto';
648   const exactRowWidth = nativeLayout && automaticWidth &&
649     (input.style.flexDirection ?? 'row') === 'row' &&
650     (input.style.flexWrap ?? 'nowrap') === 'nowrap' &&
651     (input.style.layoutDirection ?? getLayoutDirection()) === 'ltr' &&
652     input.constraints.minWidth === input.constraints.maxWidth &&
653     Number.isFinite(input.constraints.maxWidth) && input.constraints.maxWidth >= 0 ?
654     input.constraints.maxWidth : undefined;
655   const automaticHeight = input.style.height === undefined || input.style.height === 'auto';
656   const exactColumnHeight = nativeLayout && automaticHeight &&
657     input.style.flexDirection === 'column' &&
658     (input.style.flexWrap ?? 'nowrap') === 'nowrap' &&
659     (input.style.layoutDirection ?? getLayoutDirection()) === 'ltr' &&
660     input.constraints.minHeight === input.constraints.maxHeight &&
661     Number.isFinite(input.constraints.maxHeight) && input.constraints.maxHeight >= 0 ?
662     input.constraints.maxHeight : undefined;
663   const measuredHeight = exactColumnHeight ?? input.style.height;
664   const measuredWidth = exactRowWidth ?? input.style.width;
665   const widthDefinite = measuredWidth !== undefined && measuredWidth !== 'auto';
666   const heightDefinite = measuredHeight !== undefined && measuredHeight !== 'auto';
667   if (widthDefinite && heightDefinite) {
668     return { status: 'measured', size: {
669       width: resolveMeasuredContainerLength(
670         measuredWidth!,
671         input.constraints.maxWidth,
672         'width',
673         input.constraints,
674       ),
675       height: resolveMeasuredContainerLength(
676         measuredHeight!,
677         input.constraints.maxHeight,
678         'height',
679         input.constraints,
680       ),
681     } };
682   }
683   const wrappedIntrinsic = (input.style.flexWrap ?? 'nowrap') !== 'nowrap';
684   if (wrappedIntrinsic && !nativeLayout) return unsupportedIntrinsic('requires nowrap because wrapped intrinsic sizing is deferred');
685   if (isPercentage(input.style.gap) || isPercentage(input.style.rowGap) || isPercentage(input.style.columnGap)) return unsupportedIntrinsic('does not support percentage gaps without an actual finite content allocation');
686   const row = isRowDirection(input.style.flexDirection);
687   const diagnosticBox = {
688     x: 0,
689     y: 0,
690     width: Number.isFinite(input.constraints.maxWidth) ?
691       input.constraints.maxWidth : 0,
692     height: Number.isFinite(input.constraints.maxHeight) ?
693       input.constraints.maxHeight : 0,
694   };
695   const options = normalizeFlexOptions(input.style, diagnosticBox);
696   const stagedNonexact = measureStagedNonexactMain(input, children, options, diagnosticBox);
697   if (stagedNonexact) return stagedNonexact;
698   if (wrappedIntrinsic && !(nativeLayout && options.flexDirection === 'row' && options.flexWrap === 'wrap' && options.layoutDirection === 'ltr' && typeof input.style.width === 'number' && !heightDefinite)) {
699     if (nativeLayout && row && widthDefinite && !heightDefinite) return measureAllocatedFlex(input, children, measuredWidth!);
700     return unsupportedIntrinsic('wrapped intrinsic height requires a finite main allocation');
701   }
702   const wrapWidth = wrappedIntrinsic ? resolveMeasuredContainerLength(measuredWidth!, input.constraints.maxWidth, 'width', input.constraints) : 0;
703   const mainGap = row ? options.columnGap : options.rowGap;
704   // An exact width makes this dependency acyclic: main allocation precedes each
705   // paired leaf's height query. Metadata inspection never evaluates components.
706   const measuredRowWidth = nativeLayout && options.flexDirection === 'row' &&
707     options.flexWrap === 'nowrap' && options.layoutDirection === 'ltr' && !heightDefinite &&
708     typeof measuredWidth === 'number' ?
709     resolveMeasuredContainerLength(measuredWidth, input.constraints.maxWidth, 'width', input.constraints) : undefined;
710   let rowItems: IntrinsicRowItem[] | undefined;
711   if (measuredRowWidth !== undefined) for (let index = 0; index < children.length; index++) {
712     const candidate = children[index];
713     // A layout description is inspectable only through its prepared root. Keep
714     // the same receiver that the item pass will use, so description ownership
715     // and cycle metadata stay on the source wrapper.
716     const root = isLayoutComponent(candidate.type) ?
717       prepareLayoutComponent(candidate, { receiverToken: getChildPrimitiveReceiverToken(
718         GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, index,
719       ) }) : candidate;
720     const definition = getPrimitiveDefinition(root.type);
721     if (root.type !== Text && definition?.measureIntrinsic && definition.measure) { rowItems = []; break; }
722   }
723   let requiresSolvedCross = false;
724   let lineMain = 0, lineCross = 0, lineItems = 0, wrappedHeight = 0;
725   let intrinsicMain = 0;
726   let intrinsicCross = 0;
727   let count = 0;
728   for (let sourceIndex = 0; sourceIndex < children.length; sourceIndex++) {
729     const child = children[sourceIndex];
730     const receiverToken = getChildPrimitiveReceiverToken(
731       GLOBAL_STATE.renderTransaction,
732       GLOBAL_STATE.primitiveReceiverToken,
733       sourceIndex,
734     );
735     const prepared = prepareDirectChildStyle(child, receiverToken, diagnosticBox, true);
736     let style = preparedStyleValue(prepared) as Readonly<
737       BoxStyle & FlexItemStyle & LayoutItemStyle & Record<string, unknown>
738     >;
739     if (nativeLayout) {
740       validateIntrinsicBound(style.minWidth, 'minWidth', child, diagnosticBox);
741       validateIntrinsicBound(style.maxWidth, 'maxWidth', child, diagnosticBox);
742       validateIntrinsicBound(style.minHeight, 'minHeight', child, diagnosticBox);
743       validateIntrinsicBound(style.maxHeight, 'maxHeight', child, diagnosticBox);
744     }
745     if (hasPercentageBoxPadding(style, options.layoutDirection)) return unsupportedIntrinsic('does not support percentage padding without an actual finite Flex allocation');
746     // Absolute children have no flow contribution. This first slice does not
747     // define an intrinsic containing-block cascade, so fail before a child can
748     // be measured into the owner size.
749     if (style.position === 'absolute') {
750       if (nativeLayout && wrappedIntrinsic && row && widthDefinite && !heightDefinite) return measureAllocatedFlex(input, children, measuredWidth!);
751       return unsupportedIntrinsic('does not support absolute children during intrinsic Flex measurement');
752     }
753     if (nativeLayout && (style.paddingStart !== undefined || style.paddingEnd !== undefined || style.borderStartWidth !== undefined || style.borderEndWidth !== undefined)) style = resolveAllocatedInsets(style, { width: diagnosticBox.width, layoutDirection: options.layoutDirection, context: childContext(child, diagnosticBox) });
754     const layoutChild = isLayoutComponent(child.type) ? prepareLayoutComponent(child, { receiverToken }) : child;
755     const layoutReceiverToken = getPrimitiveReceiverToken(layoutChild) ?? receiverToken;
756     const settledColumnChild = nativeLayout && !row && typeof input.style.width === 'number' && !heightDefinite &&
757       (child.type === Text || layoutChild.type === Flow || layoutChild.type === Grid || layoutChild.type === Flex && isColumnDirection(style.flexDirection) && (style.flexWrap ?? 'nowrap') === 'nowrap');
758     if (settledColumnChild && (isPercentage(style.width) || isPercentage(style.minWidth) || isPercentage(style.maxWidth))) {
759       if (isPercentage(style.height) || isPercentage(style.flexBasis) || isPercentage(style.minHeight) || isPercentage(style.maxHeight)) return unsupportedIntrinsic('does not support percentage child main sizes or bounds');
760       const reference = resolveMeasuredContainerLength(measuredWidth!, input.constraints.maxWidth, 'width', input.constraints);
761       const context = childContext(child, diagnosticBox);
762       // Resolve only against an explicit owner, before converting outer box inputs.
763       // Keep numeric hot paths allocation-free and leave indefinite owners unsupported.
764       style = { ...style,
765         width: isPercentage(style.width) ? resolveScalarSizingLength(style.width!, reference, 'width', context) : style.width,
766         minWidth: isPercentage(style.minWidth) ? resolveScalarSizingLength(style.minWidth!, reference, 'minWidth', context) : style.minWidth,
767         maxWidth: isPercentage(style.maxWidth) ? resolveScalarSizingLength(style.maxWidth!, reference, 'maxWidth', context) : style.maxWidth,
768       };
769     }
770     if (nativeLayout && automaticWidth && options.flexDirection === 'row' &&
771       options.flexWrap === 'nowrap' && options.layoutDirection === 'ltr' &&
772       (isPercentage(style.minWidth) || isPercentage(style.maxWidth))) {
773       if (exactRowWidth === undefined) return unsupportedIntrinsic('requires an exact finite row width to resolve percentage main bounds');
774       const context = childContext(child, diagnosticBox);
775       style = { ...style,
776         minWidth: isPercentage(style.minWidth) ? resolveScalarSizingLength(style.minWidth!, exactRowWidth, 'minWidth', context) : style.minWidth,
777         maxWidth: isPercentage(style.maxWidth) ? resolveScalarSizingLength(style.maxWidth!, exactRowWidth, 'maxWidth', context) : style.maxWidth,
778       };
779       if (typeof style.minWidth === 'number' && typeof style.maxWidth === 'number' && style.minWidth > style.maxWidth) {
780         throw childDiagnostic(child, 'minWidth', style.minWidth, diagnosticBox, 'minimum must not exceed maximum');
781       }
782     }
783     if (nativeLayout && automaticHeight && options.flexDirection === 'column' &&
784       options.flexWrap === 'nowrap' && options.layoutDirection === 'ltr' &&
785       (isPercentage(style.minHeight) || isPercentage(style.maxHeight))) {
786       if (exactColumnHeight === undefined) return unsupportedIntrinsic('requires an exact finite column height to resolve percentage main bounds');
787       const context = childContext(child, diagnosticBox);
788       style = { ...style,
789         minHeight: isPercentage(style.minHeight) ? resolveScalarSizingLength(style.minHeight!, exactColumnHeight, 'minHeight', context) : style.minHeight,
790         maxHeight: isPercentage(style.maxHeight) ? resolveScalarSizingLength(style.maxHeight!, exactColumnHeight, 'maxHeight', context) : style.maxHeight,
791       };
792       if (typeof style.minHeight === 'number' && typeof style.maxHeight === 'number' && style.minHeight > style.maxHeight) {
793         throw childDiagnostic(child, 'minHeight', style.minHeight, diagnosticBox, 'minimum must not exceed maximum');
794       }
795     }
796     if (style.boxSizing !== undefined) style = contentBoxStyle(style, { width: diagnosticBox.width, height: diagnosticBox.height, mainAxis: row ? 'width' : 'height', context: childContext(child, diagnosticBox) });
797     rejectUnsupportedItemFields(child, style, diagnosticBox);
798     if (style.aspectRatio !== undefined) return unsupportedIntrinsic('does not support aspectRatio during intrinsic measurement');
799     const marginDirection = layoutChild.type === Flex ? style.layoutDirection ?? options.layoutDirection : options.layoutDirection;
800     const logicalLeft = marginDirection === 'rtl' ? style.marginEnd : style.marginStart;
801     const logicalRight = marginDirection === 'rtl' ? style.marginStart : style.marginEnd;
802     const leftValue = logicalLeft !== undefined ? logicalLeft : style.marginLeft === undefined ? style.margin : style.marginLeft;
803     const rightValue = logicalRight !== undefined ? logicalRight : style.marginRight === undefined ? style.margin : style.marginRight;
804     const topValue = style.marginTop === undefined ? style.margin : style.marginTop;
805     const bottomValue = style.marginBottom === undefined ? style.margin : style.marginBottom;
806     const hasLogicalMargin = style.marginStart !== undefined || style.marginEnd !== undefined;
807     if ((!hasLogicalMargin && isPercentage(style.margin)) || isPercentage(topValue) || isPercentage(rightValue) || isPercentage(bottomValue) || isPercentage(leftValue)) return unsupportedIntrinsic('does not support percentage margins without an actual finite Flex allocation');
808     const autoTop = topValue === 'auto', autoRight = rightValue === 'auto';
809     const autoBottom = bottomValue === 'auto', autoLeft = leftValue === 'auto';
810     if (!nativeLayout && (autoTop || autoRight || autoBottom || autoLeft)) return unsupportedIntrinsic('automatic margins require the experimental layout engine');
811     // Physical-only paths retain their existing shorthand validation.
812     if (!hasLogicalMargin) numericMargin(nativeLayout && style.margin === 'auto' ? 0 : style.margin, 'margin', child, diagnosticBox);
813     // Final allocation already represents automatic margins as zero until the
814     // native placement pass divides free space. The intrinsic contribution uses
815     // the same zero contribution; each measurement path retains its sizing guards.
816     const marginTop = numericMargin(autoTop ? 0 : topValue, 'marginTop', child, diagnosticBox);
817     const marginRight = numericMargin(autoRight ? 0 : rightValue, logicalRight !== undefined ? marginDirection === 'rtl' ? 'marginStart' : 'marginEnd' : 'marginRight', child, diagnosticBox);
818     const marginBottom = numericMargin(autoBottom ? 0 : bottomValue, 'marginBottom', child, diagnosticBox);
819     const marginLeft = numericMargin(autoLeft ? 0 : leftValue, logicalLeft !== undefined ? marginDirection === 'rtl' ? 'marginEnd' : 'marginStart' : 'marginLeft', child, diagnosticBox);
820     const marginMain = row ? marginLeft + marginRight : marginTop + marginBottom;
821     const marginCross = row ? marginTop + marginBottom : marginLeft + marginRight;
822     const grow = nonnegativeFactor(
823       style.flexGrow ?? 0,
824       'flexGrow',
825       child,
826       diagnosticBox,
827     );
828     if (grow !== 0) {
829       if (nativeLayout && wrappedIntrinsic && row && widthDefinite && !heightDefinite) return measureAllocatedFlex(input, children, measuredWidth!);
830       return unsupportedIntrinsic('does not support flexGrow during intrinsic measurement');
831     }
832     const shrink = nonnegativeFactor(
833       style.flexShrink ?? 1,
834       'flexShrink',
835       child,
836       diagnosticBox,
837     );
838     const basis = style.flexBasis ?? 'auto';
839     if (wrappedIntrinsic && (!hasEmptyRectangleMinimum(child, style, preparedStyleQuery(prepared)) || shrink !== 0 || basis !== 'auto')) return measureAllocatedFlex(input, children, measuredWidth!);
840     const mainProperty = row ? 'width' : 'height';
841     const crossProperty = row ? 'height' : 'width';
842     const minimumProperty = row ? 'minWidth' : 'minHeight';
843     if ((shrink > 0 || basis === 'auto') && style[minimumProperty] === undefined &&
844       !hasEmptyRectangleMinimum(child, style, preparedStyleQuery(prepared))) {
845       if (nativeLayout && row && widthDefinite && !heightDefinite && getPrimitiveDefinition(layoutChild.type)?.measureIntrinsic) return measureAllocatedFlex(input, children, measuredWidth!);
846       throw childDiagnostic(
847         child,
848         minimumProperty,
849         style[minimumProperty],
850         diagnosticBox,
851         'an explicit main-axis minimum is required for shrink or auto basis',
852       );
853     }
854     const mainValue = basis === 'auto' ? style[mainProperty] : basis;
855     const crossValue = style[crossProperty];
856     if (isPercentage(mainValue) || isPercentage(crossValue) ||
857       hasPercentageBounds(style)) {
858       return unsupportedIntrinsic('does not support percentage child sizes or bounds');
859     }
860     let baseMain: number;
861     let baseCross: number;
862     const provider = rowItems && layoutChild.type !== Text ? getPrimitiveDefinition(layoutChild.type) : undefined;
863     const measureCross = !!rowItems && !!provider?.measureIntrinsic && !!provider.measure &&
864       (crossValue === undefined || crossValue === 'auto');
865     if (rowItems && preparedStyleQuery(prepared)) return unsupportedIntrinsic('does not support responsive child queries during solved row measurement');
866     if (nativeLayout && layoutChild.type === Flex &&
867       (style.flexDirection ?? 'row') === options.flexDirection &&
868       options.flexWrap === 'nowrap' && (style.flexWrap ?? 'nowrap') === 'nowrap' &&
869       options.layoutDirection === 'ltr' && (style.layoutDirection ?? 'ltr') === 'ltr' &&
870       (mainValue === undefined || mainValue === 'auto') &&
871       typeof crossValue === 'number' && Number.isFinite(crossValue) && crossValue >= 0 &&
872       grow === 0 && shrink === 0) {
873       // A declared same-axis owner can contribute its natural main size through
874       // the shared pure context. Its finite cross size makes this descent acyclic.
875       const measuredChild = clonePibblElement(layoutChild);
876       setPreNormalizedStyle(measuredChild, style, layoutChild, layoutReceiverToken, preparedStyleQuery(prepared));
877       const previousContribution = requestedIntrinsicContribution;
878       requestedIntrinsicContribution = { receiver: layoutReceiverToken, axis: row ? 'row' : 'column' };
879       let result: MeasureResult;
880       try {
881         result = input.measureElement(measuredChild, row ? {
882           minWidth: 0, maxWidth: input.constraints.maxWidth, minHeight: crossValue, maxHeight: crossValue,
883         } : {
884           minWidth: crossValue, maxWidth: crossValue, minHeight: 0, maxHeight: input.constraints.maxHeight,
885         });
886       } finally {
887         requestedIntrinsicContribution = previousContribution;
888       }
889       if (result.status !== 'measured') return result;
890       baseMain = row ? result.size.width : result.size.height;
891       baseCross = crossValue;
892     } else if (nativeLayout && !row && widthDefinite && !heightDefinite &&
893       (child.type === Text || layoutChild.type === Flow || layoutChild.type === Grid || layoutChild.type === Flex && isColumnDirection(style.flexDirection) && (style.flexWrap ?? 'nowrap') === 'nowrap') &&
894       (mainValue === undefined || mainValue === 'auto' || crossValue === undefined || crossValue === 'auto')) {
895       // Descend only through known built-in columns at settled content widths.
896       // The shared measurement context detects descriptor cycles; there is no
897       // speculative component execution, percentage feedback or fixed-point loop.
898       const padding = normalizeBoxInsets(style, childContext(child, diagnosticBox));
899       const automaticWidth = crossValue === undefined || crossValue === 'auto';
900       if (automaticWidth && effectiveAlignment(normalizeItemAlignment(style.alignSelf, child, diagnosticBox), options.alignItems) !== 'stretch') {
901         return unsupportedIntrinsic('requires stretch or a definite child width in an auto-height column');
902       }
903       const availableWidth = resolveMeasuredContainerLength(measuredWidth!, input.constraints.maxWidth, 'width', input.constraints);
904       const minWidth = intrinsicOptionalNumber(style.minWidth, 0, 'minWidth');
905       const maxWidth = intrinsicOptionalNumber(style.maxWidth, Number.POSITIVE_INFINITY, 'maxWidth');
906       if (minWidth > maxWidth) throw childDiagnostic(child, 'minWidth', minWidth, diagnosticBox, 'minimum must not exceed maximum');
907       const usedWidth = clamp(automaticWidth ? Math.max(0, availableWidth-padding.left-padding.right-marginCross) : intrinsicNumber(crossValue, 'width'), minWidth, maxWidth);
908       const measuredChild = clonePibblElement(layoutChild);
909       const measuredStyle = { ...style, width: usedWidth };
910       setPreNormalizedStyle(measuredChild, measuredStyle, layoutChild, getPrimitiveReceiverToken(layoutChild) ?? receiverToken, preparedStyleQuery(prepared));
911       const result = input.measureElement(measuredChild, { minWidth: 0, maxWidth: usedWidth, minHeight: 0, maxHeight: input.constraints.maxHeight });
912       if (result.status !== 'measured') return result;
913       baseMain = mainValue === undefined || mainValue === 'auto' ? result.size.height : intrinsicNumber(mainValue, 'flexBasis');
914       baseCross = usedWidth;
915     } else {
916       if (mainValue === undefined || mainValue === 'auto') {
917         return unsupportedIntrinsic('requires a definite child basis; measured auto basis is deferred');
918       }
919       if ((crossValue === undefined || crossValue === 'auto') && !measureCross) {
920         return unsupportedIntrinsic('requires a definite child cross size');
921       }
922       baseMain = intrinsicNumber(mainValue, 'flexBasis');
923       baseCross = measureCross ? 0 : intrinsicNumber(crossValue, crossProperty);
924     }
925     const minMain = intrinsicOptionalNumber(style[minimumProperty], 0, minimumProperty);
926     const maxMainProperty = row ? 'maxWidth' : 'maxHeight';
927     const maxMain = intrinsicOptionalNumber(
928       style[maxMainProperty],
929       Number.POSITIVE_INFINITY,
930       maxMainProperty,
931     );
932     const minCrossProperty = row ? 'minHeight' : 'minWidth';
933     const maxCrossProperty = row ? 'maxHeight' : 'maxWidth';
934     const minCross = intrinsicOptionalNumber(style[minCrossProperty], 0, minCrossProperty);
935     const maxCross = intrinsicOptionalNumber(
936       style[maxCrossProperty],
937       Number.POSITIVE_INFINITY,
938       maxCrossProperty,
939     );
940     const padding = normalizeBoxInsets(style, childContext(child, diagnosticBox));
941     const paddingMain = row ? padding.left + padding.right :
942       padding.top + padding.bottom;
943     const paddingCross = row ? padding.top + padding.bottom :
944       padding.left + padding.right;
945     if (wrappedIntrinsic) {
946       const outerMain = clamp(baseMain, minMain, maxMain) + paddingMain + marginLeft + marginRight;
947       const crossExtent = clamp(baseCross, minCross, maxCross) + paddingCross + marginTop + marginBottom;
948       const nextMain = lineMain + (lineItems > 0 ? mainGap : 0) + outerMain;
949       if (!Number.isFinite(outerMain) || !Number.isFinite(crossExtent)) throw childDiagnostic(child, 'intrinsicLine', nextMain, diagnosticBox, 'wrapped intrinsic outer extents and line widths must remain finite');
950       const outerCross = Math.max(0, crossExtent);
951       if (lineItems > 0 && nextMain > wrapWidth) {
952         wrappedHeight += lineCross + options.rowGap;
953         if (!Number.isFinite(wrappedHeight)) throw childDiagnostic(child, 'intrinsicLine', wrappedHeight, diagnosticBox, 'wrapped intrinsic accumulated height must remain finite');
954         lineCross = 0; lineItems = 0;
955       }
956       lineMain = lineItems > 0 ? nextMain : outerMain;
957       if (!Number.isFinite(lineMain)) throw childDiagnostic(child, 'intrinsicLine', lineMain, diagnosticBox, 'wrapped intrinsic accumulated line width must remain finite');
958       lineCross = Math.max(lineCross, outerCross);
959       lineItems++;
960     }
961     if (rowItems) {
962       rowItems.push({ sourceIndex, child, measuredChild: layoutChild, style, receiverToken: layoutReceiverToken, measureCross, baseMain, minMain, maxMain,
963         paddingMain, grow, shrink, marginMainBefore: marginLeft, marginMainAfter: marginRight,
964         baseCross, minCross, maxCross, paddingCross, marginCross });
965       if (measureCross) requiresSolvedCross = true;
966     } else {
967       intrinsicMain += clamp(baseMain, minMain, maxMain) + paddingMain + marginMain;
968       intrinsicCross = Math.max(intrinsicCross,
969         clamp(baseCross, minCross, maxCross) + paddingCross + marginCross);
970     }
971     count++;
972   }
973   if (rowItems) {
974     const targets = requiresSolvedCross ? solveTransientFlexMain(rowItems, measuredRowWidth!, mainGap) : undefined;
975     for (let index = 0; index < rowItems.length; index++) {
976       const item = rowItems[index];
977       const main = targets ? targets[index] : clamp(item.baseMain, item.minMain, item.maxMain);
978       let cross = item.baseCross;
979       if (item.measureCross) {
980         const measuredChild = clonePibblElement(item.measuredChild);
981         const measuredStyle = { ...item.style, width: main };
982         // The root clone keeps its layout-description source metadata, while
983         // the style handoff still names the authored wrapper and uses the
984         // prepared leaf receiver for provider input ownership.
985         setPreNormalizedStyle(measuredChild, measuredStyle, item.child, item.receiverToken);
986         const result = measureConstrainedLayoutChild(measuredChild, {
987           minWidth: main, maxWidth: main, minHeight: 0, maxHeight: Number.POSITIVE_INFINITY,
988         }, item.sourceIndex);
989         if (result.status !== 'measured') return result;
990         cross = result.size.height;
991       }
992       intrinsicMain += main + item.paddingMain + item.marginMainBefore! + item.marginMainAfter!;
993       intrinsicCross = Math.max(intrinsicCross,
994         clamp(cross, item.minCross, item.maxCross) + item.paddingCross + item.marginCross);
995     }
996   }
997   intrinsicMain = Math.max(0, intrinsicMain + Math.max(0, count - 1) * mainGap);
998   return { status: 'measured', size: {
999     width: widthDefinite ? resolveMeasuredContainerLength(
1000       measuredWidth!,
1001       input.constraints.maxWidth,
1002       'width',
1003       input.constraints,
1004     ) : row ? intrinsicMain : intrinsicCross,
1005     height: heightDefinite ? resolveMeasuredContainerLength(
1006       measuredHeight!,
1007       input.constraints.maxHeight,
1008       'height',
1009       input.constraints,
1010     ) : row ? wrappedIntrinsic ? wrappedHeight + lineCross : intrinsicCross : intrinsicMain,
1011   } };
1012 }
1013 
1014 function intrinsicMainLength(value: unknown, property: string, child: PibblElement<any>, box: Readonly<LayoutBox>): { value?: number; unit: 'none' | 'point' | 'percent' } | undefined {
1015   if (value === undefined) return { unit: 'none' };
1016   if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return { value, unit: 'point' };
1017   if (isPercentage(value)) return { value: parsePercentage(value, property, childContext(child, box)), unit: 'percent' };
1018   return undefined;
1019 }
1020 
1021 /**
1022  * The native query retains Yoga's two main-axis phases. It returns final numeric
1023  * child bounds, which are staged only for the matching normal placement; raw
1024  * percentage styles are deliberately left untouched for forwarding.
1025  */
1026 function measureStagedNonexactMain(
1027   input: MeasureInput<FlexProps, FlexStyle>,
1028   children: readonly PibblElement<any>[],
1029   options: Readonly<ReturnType<typeof normalizeFlexOptions>>,
1030   diagnosticBox: Readonly<LayoutBox>,
1031   allocated?: Readonly<{ main: number; rootMin?: number; rootMax?: number }>,
1032 ): MeasureResult | undefined {
1033   if (!nativeLayout || options.flexWrap !== 'nowrap' || options.layoutDirection !== 'ltr') return;
1034   if (options.flexDirection !== 'row' && options.flexDirection !== 'column') return;
1035   const row = options.flexDirection === 'row';
1036   const automaticMain = row ? input.style.width === undefined || input.style.width === 'auto' : input.style.height === undefined || input.style.height === 'auto';
1037   const cross = row ? input.style.height : input.style.width;
1038   const available = row ? input.constraints.maxWidth : input.constraints.maxHeight;
1039   const ownerReference = Number.isFinite(available) ? available : undefined;
1040   const rootMin = allocated ? allocated.rootMin : intrinsicOwnerBound(
1041     row ? input.style.minWidth : input.style.minHeight, ownerReference, row ? 'minWidth' : 'minHeight', input.constraints,
1042   );
1043   const rootMax = allocated ? allocated.rootMax : intrinsicOwnerBound(
1044     row ? input.style.maxWidth : input.style.maxHeight, ownerReference, row ? 'maxWidth' : 'maxHeight', input.constraints,
1045   );
1046   if (input.style.padding !== undefined || input.style.paddingStart !== undefined || input.style.paddingEnd !== undefined ||
1047       input.style.borderWidth !== undefined || input.style.borderStartWidth !== undefined || input.style.borderEndWidth !== undefined ||
1048       input.style.boxSizing !== undefined || input.style.aspectRatio !== undefined ||
1049       (row ? input.style.minHeight !== undefined && input.style.minHeight !== 0 || input.style.maxHeight !== undefined : input.style.minWidth !== undefined && input.style.minWidth !== 0 || input.style.maxWidth !== undefined)) return;
1050   if (!automaticMain || typeof cross !== 'number' || !Number.isFinite(cross) || cross < 0 ||
1051       (rootMin !== undefined && (typeof rootMin !== 'number' || !Number.isFinite(rootMin) || rootMin < 0)) ||
1052       (rootMax !== undefined && (typeof rootMax !== 'number' || !Number.isFinite(rootMax) || rootMax < 0)) ||
1053       typeof input.style.gap === 'number' && input.style.gap !== 0 ||
1054       input.style.rowGap !== undefined || input.style.columnGap !== undefined) return;
1055   if (typeof rootMin === 'number' && typeof rootMax === 'number' && rootMin > rootMax) {
1056     throw layoutDiagnostic({ component: 'Flex', property: row ? 'minWidth' : 'minHeight', value: rootMin, algorithm: 'measurement', constraints: input.constraints, reason: 'minimum must not exceed maximum' });
1057   }
1058   const externalOwner = allocated?.main ?? ownerReference;
1059   // An authored maximum retains its own initial envelope. Otherwise a finite
1060   // caller maximum is fit-content availability, still distinct from exact size.
1061   const initialAvailable = allocated?.main ?? (typeof rootMax === 'number' ? rootMax : externalOwner);
1062   const mode = allocated !== undefined ? 'exact' as const : initialAvailable === undefined ? 'max-content' as const : 'fit-content' as const;
1063   let hasPercentageBound = false;
1064   const items: { base: number; min: { value?: number; unit: 'none' | 'point' | 'percent' }; max: { value?: number; unit: 'none' | 'point' | 'percent' }; measured?: boolean; queryMaximum?: number }[] = [];
1065   const measuredLeaves: { readonly sourceIndex: number; readonly child: PibblElement<any>; readonly normalized: Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle>; readonly receiver: object; readonly query: PreparedQuery | undefined }[] = [];
1066   for (let sourceIndex = 0; sourceIndex < children.length; sourceIndex++) {
1067     const child = children[sourceIndex];
1068     const definition = getPrimitiveDefinition(child.type);
1069     const pairedMeasuredLeaf = child.type !== Rectangle && child.type !== Text && !isKnownLayoutType(child.type) &&
1070       !Object.hasOwn(child.props, 'children') && !!definition?.measureIntrinsic && !!definition.measure;
1071     if ((!pairedMeasuredLeaf && (child.type !== Rectangle || Object.hasOwn(child.props, 'children'))) ||
1072         !child.props.style || typeof child.props.style !== 'object' || isSignal(child.props.style)) return;
1073     const receiver = getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, sourceIndex);
1074     const prepared = prepareDirectChildStyle(child, receiver, diagnosticBox, true);
1075     const style = preparedStyleValue(prepared) as Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle>;
1076     validateIntrinsicBound(style.minWidth, 'minWidth', child, diagnosticBox);
1077     validateIntrinsicBound(style.maxWidth, 'maxWidth', child, diagnosticBox);
1078     validateIntrinsicBound(style.minHeight, 'minHeight', child, diagnosticBox);
1079     validateIntrinsicBound(style.maxHeight, 'maxHeight', child, diagnosticBox);
1080     const main = row ? style.width : style.height;
1081     const basis = style.flexBasis ?? 'auto';
1082     const childCross = row ? style.height : style.width;
1083     const min = row ? style.minWidth : style.minHeight;
1084     const max = row ? style.maxWidth : style.maxHeight;
1085     const automaticMeasuredMain = main === undefined || main === 'auto';
1086     if (preparedStyleQuery(prepared) || style.position !== undefined || style.aspectRatio !== undefined ||
1087         (pairedMeasuredLeaf && (row ? style.minHeight !== undefined && style.minHeight !== 0 || style.maxHeight !== undefined : style.minWidth !== undefined && style.minWidth !== 0 || style.maxWidth !== undefined)) ||
1088         typeof childCross !== 'number' || !Number.isFinite(childCross) || childCross < 0 ||
1089         (style.flexGrow ?? 0) !== 0 || (style.flexShrink ?? 1) !== 0 ||
1090         !zeroIntrinsicMargin(style.margin) || !zeroIntrinsicMargin(style.marginTop) || !zeroIntrinsicMargin(style.marginRight) ||
1091         !zeroIntrinsicMargin(style.marginBottom) || !zeroIntrinsicMargin(style.marginLeft) ||
1092         !zeroIntrinsicMargin(style.marginStart) || !zeroIntrinsicMargin(style.marginEnd) ||
1093         style.padding !== undefined || style.paddingStart !== undefined || style.paddingEnd !== undefined ||
1094         style.borderWidth !== undefined || style.borderStartWidth !== undefined || style.borderEndWidth !== undefined ||
1095         (pairedMeasuredLeaf ? !automaticMeasuredMain || basis !== 'auto' :
1096           typeof main !== 'number' || !Number.isFinite(main) || main < 0 ||
1097           typeof basis !== 'number' || !Number.isFinite(basis) || basis < 0 || main !== basis)) return;
1098     const intrinsicMin = intrinsicMainLength(min, row ? 'minWidth' : 'minHeight', child, diagnosticBox);
1099     const intrinsicMax = intrinsicMainLength(max, row ? 'maxWidth' : 'maxHeight', child, diagnosticBox);
1100     if (!intrinsicMin || !intrinsicMax) return;
1101     if (intrinsicMin.unit === 'percent' || intrinsicMax.unit === 'percent') hasPercentageBound = true;
1102     items.push({ base: pairedMeasuredLeaf ? 0 : basis as number, min: intrinsicMin, max: intrinsicMax, measured: pairedMeasuredLeaf || undefined });
1103     if (pairedMeasuredLeaf) measuredLeaves.push({ sourceIndex, child, normalized: style, receiver, query: preparedStyleQuery(prepared) });
1104   }
1105   if (!items.length || !hasPercentageBound) return;
1106   const intrinsicQuery = { externalOwner, initialAvailable, rootMin: rootMin as number | undefined,
1107     rootMax: rootMax as number | undefined, mode, gap: 0 };
1108   if (measuredLeaves.length) {
1109     const preparedQueries = prepareTransientIntrinsicMainQueries(items, intrinsicQuery);
1110     for (let index = 0; index < measuredLeaves.length; index++) {
1111       const leaf = measuredLeaves[index];
1112       const queryMaximum = preparedQueries.maximums[leaf.sourceIndex];
1113       const measurementChild = clonePibblElement(leaf.child);
1114       setPreNormalizedStyle(measurementChild, leaf.normalized, leaf.child, leaf.receiver, leaf.query);
1115       const leafCross = (row ? leaf.normalized.height : leaf.normalized.width) as number;
1116       const constraints = row ? { minWidth: 0, maxWidth: queryMaximum, minHeight: leafCross, maxHeight: leafCross } :
1117         { minWidth: leafCross, maxWidth: leafCross, minHeight: 0, maxHeight: queryMaximum };
1118       const result = measureConstrainedLayoutChild(measurementChild, constraints);
1119       if (result.status === 'unsupported') return result;
1120       const natural = row ? result.size.width : result.size.height;
1121       if (!Number.isFinite(natural) || natural < 0) throw new Error('Experimental staged intrinsic Flex provider returned an invalid main size.');
1122       items[leaf.sourceIndex] = { ...items[leaf.sourceIndex], base: natural, measured: true, queryMaximum };
1123     }
1124   }
1125   const receiver = GLOBAL_STATE.primitiveReceiverToken;
1126   const axis = row ? 'row' : 'column';
1127   // A same-axis known Flex is contributing to a parent's intrinsic line. Its
1128   // parent needs the adjusted native contribution, while standalone queries
1129   // deliberately continue to report the full resolved size.
1130   const contribution = allocated === undefined && requestedIntrinsicContribution !== undefined && requestedIntrinsicContribution.receiver === receiver &&
1131     requestedIntrinsicContribution.axis === axis;
1132   const normalOwner = contribution && requestedIntrinsicContribution?.normalOwner === true && !measuredLeaves.length &&
1133     externalOwner !== undefined && Number.isFinite(externalOwner) && initialAvailable !== undefined && Number.isFinite(initialAvailable);
1134   const resolved = normalOwner ? resolveTransientKnownOwnerMain(items, intrinsicQuery) : resolveTransientIntrinsicMain(items, intrinsicQuery);
1135   const stagedMain = allocated?.main ?? (contribution ? resolved.contributionMain : resolved.main);
1136   stagePreparedIntrinsicMain(receiver, {
1137     elements: children, axis, style: input.style, rootMin, rootMax, contentMain: stagedMain,
1138     normalOwner, autoMarginFreeMain: resolved.autoMarginFreeMain,
1139     revision: allocationInputRevision(),
1140     items: resolved.targets.map((target, sourceIndex) => ({
1141       sourceIndex, target, min: resolved.effectiveMins[sourceIndex], max: resolved.effectiveMaxes[sourceIndex],
1142       measured: items[sourceIndex].measured,
1143     })),
1144   });
1145   const reportedMain = contribution ? resolved.contributionMain : resolved.main;
1146   return { status: 'measured', size: row ? { width: reportedMain, height: cross } : { width: cross, height: reportedMain } };
1147 }
1148 
1149 /** Auto edges contribute zero; positive numeric edges need a separate phase profile. */
1150 function zeroIntrinsicMargin(value: FlexItemStyle['margin']): boolean {
1151   return value === undefined || value === 0 || value === 'auto';
1152 }
1153 
1154 /** Own bounds use the caller reference, never the eventual auto-owner size. */
1155 function intrinsicOwnerBound(
1156   value: BoxStyle['minWidth'], reference: number | undefined,
1157   property: string, constraints: Readonly<Constraints>,
1158 ): number | undefined {
1159   if (value === undefined) return;
1160   if (typeof value === 'number') {
1161     if (Number.isFinite(value) && value >= 0) return value;
1162     throw layoutDiagnostic({ component: 'Flex', property, value, algorithm: 'measurement', constraints, reason: 'must be finite and nonnegative' });
1163   }
1164   const percentage = parsePercentage(value, property, { component: 'Flex', algorithm: 'measurement', constraints });
1165   if (percentage < 0) throw layoutDiagnostic({ component: 'Flex', property, value, algorithm: 'measurement', constraints, reason: 'must be nonnegative' });
1166   if (reference === undefined) return;
1167   const resolved = percentage / 100 * reference;
1168   if (!Number.isFinite(resolved)) throw layoutDiagnostic({ component: 'Flex', property, value, algorithm: 'measurement', constraints, reason: 'resolved percentage arithmetic must remain finite' });
1169   return resolved;
1170 }
1171 
1172 function resolveMeasuredContainerLength(
1173   value: Exclude<BoxStyle['width'], undefined>,
1174   reference: number,
1175   property: string,
1176   constraints: Readonly<Constraints>,
1177 ): number {
1178   const resolved = resolveScalarSizingLength(value, reference, property, {
1179     component: 'Flex',
1180     algorithm: 'measurement',
1181     constraints,
1182   });
1183   if (resolved === undefined || resolved < 0) {
1184     throw layoutDiagnostic({
1185       component: 'Flex',
1186       property,
1187       value,
1188       algorithm: 'measurement',
1189       constraints,
1190       reason: 'requires a definite nonnegative container size',
1191     });
1192   }
1193   return resolved;
1194 }
1195 
1196 function intrinsicNumber(
1197   value: unknown,
1198   property: string,
1199 ): number {
1200   if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
1201     throw layoutDiagnostic({
1202       component: 'Flex',
1203       property,
1204       value,
1205       algorithm: 'measurement',
1206       reason: 'intrinsic measurement requires finite nonnegative numeric sizes',
1207     });
1208   }
1209   return value;
1210 }
1211 
1212 function validateIntrinsicBound(value: unknown, property: string, child: PibblElement<any>, container: Readonly<LayoutBox>): void {
1213   if (value === undefined) return;
1214   if (typeof value === 'number') {
1215     if (!Number.isFinite(value) || value < 0) throw childDiagnostic(child, property, value, container, 'must be finite and nonnegative');
1216     return;
1217   }
1218   const percentage = parsePercentage(value, property, childContext(child, container));
1219   if (percentage < 0) throw childDiagnostic(child, property, value, container, 'must be nonnegative');
1220 }
1221 
1222 function intrinsicOptionalNumber(
1223   value: unknown,
1224   fallback: number,
1225   property: string,
1226 ): number {
1227   return value === undefined ? fallback : intrinsicNumber(value, property);
1228 }
1229 
1230 function isPercentage(value: unknown): boolean {
1231   return typeof value === 'string' && value.endsWith('%');
1232 }
1233 
1234 function hasPercentageBounds(style: Readonly<BoxStyle>): boolean {
1235   return isPercentage(style.minWidth) || isPercentage(style.maxWidth) ||
1236     isPercentage(style.minHeight) || isPercentage(style.maxHeight);
1237 }
1238 
1239 function unsupportedIntrinsic(reason: string): MeasureResult {
1240   return {
1241     status: 'unsupported',
1242     reason: `Flex intrinsic measurement ${reason}`,
1243   };
1244 }
1245 
1246 export function layoutFlex(
1247   container: Readonly<LayoutBox>,
1248   children: PibblNodeInput,
1249   style: Readonly<FlexStyle>,
1250   measurement: FlexMeasurementInput,
1251 ): LayoutBox[] {
1252   const prepared = materializeLayoutChildren(children, 'Flex');
1253   const region = nativeLayout ? new LayoutRegion() : undefined;
1254   try {
1255     return resolveFlexPlacements(
1256       container,
1257       prepared,
1258       style,
1259       measurement,
1260       region,
1261     ).map(placement => placement.box);
1262   } finally { region?.dispose(); }
1263 }
1264 
1265 function resolveFlexPlacements(
1266   container: Readonly<LayoutBox>,
1267   children: readonly PibblElement<any>[],
1268   style: Readonly<FlexStyle>,
1269   measurement: FlexMeasurementInput,
1270   region?: LayoutRegion,
1271   stagedIntrinsic?: PreparedIntrinsicMainStage,
1272   parentSlot?: PreparedLayoutSlot,
1273   deferStaticAbsolute?: Array<DeferredStaticAbsolutePlacement | undefined>,
1274 ): FlexPlacement[] {
1275   if (region) recordWasmAllocationPass();
1276   assertFiniteBox(container);
1277   const options = normalizeFlexOptions(style, container);
1278   const row = isRowDirection(options.flexDirection);
1279   const authoredReverse = options.flexDirection === 'row-reverse' || options.flexDirection === 'column-reverse';
1280   const reverse = authoredReverse !== (row && options.layoutDirection === 'rtl');
1281   const authoredWrapReverse = options.flexWrap === 'wrap-reverse';
1282   const wrapReverse = authoredWrapReverse !== (!row && options.layoutDirection === 'rtl');
1283   const mainSize = row ? container.width : container.height;
1284   const crossSize = row ? container.height : container.width;
1285   const mainGap = row ? options.columnGap : options.rowGap;
1286   const crossGap = row ? options.rowGap : options.columnGap;
1287   const items: FlexItem[] = [];
1288   const placementsBySource: Array<FlexPlacement | undefined> = new Array(children.length);
1289   let hasAspectRatio = false;
1290   let hasAutoMainMargins = false;
1291   let absolutePaddingBox: Readonly<LayoutBox> | undefined;
1292   let absoluteMeasurementTokens: Set<object> | undefined;
1293 
1294   const occurrences = new Map<object, number>();
1295   for (let sourceIndex = 0; sourceIndex < children.length; sourceIndex++) {
1296     const child = children[sourceIndex];
1297     if (region) recordWasmAllocationItem();
1298     const receiverToken = getChildPrimitiveReceiverToken(
1299       GLOBAL_STATE.renderTransaction,
1300       GLOBAL_STATE.primitiveReceiverToken,
1301       sourceIndex,
1302     );
1303     const occurrence = occurrences.get(child.type) ?? 0;
1304     if (child.key === undefined) occurrences.set(child.type, occurrence + 1);
1305     const prepared = prepareDirectChildStyle(child, receiverToken, container, true);
1306     const declared = preparedStyleValue(prepared) as Readonly<
1307       BoxStyle & FlexItemStyle & LayoutItemStyle & Record<string, unknown>
1308     >;
1309     let normalized = declared;
1310     if (nativeLayout) normalized = resolveAllocatedInsets(normalized, { width: container.width, layoutDirection: options.layoutDirection, context: childContext(child, container) });
1311     if (normalized.boxSizing !== undefined) normalized = contentBoxStyle(normalized, { width: container.width, height: container.height, mainAxis: row ? 'width' : 'height', context: childContext(child, container) });
1312     const stagedItem = stagedIntrinsic?.items[sourceIndex];
1313     if (stagedItem && stagedItem.sourceIndex !== sourceIndex) throw new Error('Staged intrinsic Flex children are out of source order.');
1314     const stagedMeasured = stagedItem?.measured === true;
1315     const aspectRatio = normalized.aspectRatio;
1316     if (aspectRatio !== undefined && (typeof aspectRatio !== 'number' || !Number.isFinite(aspectRatio) || aspectRatio <= 0)) {
1317       throw childDiagnostic(child, 'aspectRatio', aspectRatio, container, 'must be a positive finite outer width/height ratio');
1318     }
1319     if (nativeLayout && aspectRatio !== undefined && normalized.position !== 'absolute' &&
1320       (normalized.flexBasis === undefined || normalized.flexBasis === 'auto')) {
1321       const main = normalized[row ? 'width' : 'height'], cross = normalized[row ? 'height' : 'width'];
1322       if ((main === undefined || main === 'auto') && typeof cross === 'number') {
1323         const insets = normalizeBoxInsets(normalized, childContext(child, container));
1324         const crossInsets = row ? insets.top + insets.bottom : insets.left + insets.right;
1325         const mainInsets = row ? insets.left + insets.right : insets.top + insets.bottom;
1326         const outer = row ? (cross + crossInsets) * aspectRatio : (cross + crossInsets) / aspectRatio;
1327         normalized = { ...normalized, [row ? 'width' : 'height']: Math.max(0, outer - mainInsets) };
1328       }
1329     }
1330     assertSupportedChildPosition('Flex', child, normalized, true);
1331     rejectUnsupportedItemFields(child, normalized, container);
1332     if (options[FLEX_BASELINE_GROUP] && normalized.position === 'absolute') {
1333       throw childDiagnostic(child, 'position', 'absolute', container, 'PIBBL_LAYOUT_UNSUPPORTED_BASELINE: absolute children are outside first-baseline composition');
1334     }
1335     if (normalized.position === 'absolute') {
1336       const definition = getPrimitiveDefinition(child.type);
1337       const hasPairedMeasurement = child.type !== Text && !!definition?.measureIntrinsic && !!definition.measure;
1338       const measurableText = child.type === Text &&
1339         (normalized.wrap === undefined || typeof normalized.wrap === 'boolean') &&
1340         (normalized.fit === undefined || normalized.fit === 'visible') &&
1341         (normalized.overflow === undefined || normalized.overflow === 'visible' || normalized.overflow === 'clip') && genericTextFont(normalized);
1342       const unwrappedText = measurableText && normalized.wrap !== true;
1343       const automaticWidth = normalized.width === undefined || normalized.width === 'auto';
1344       const automaticHeight = normalized.height === undefined || normalized.height === 'auto';
1345       const naturalBoth = unwrappedText && automaticWidth && automaticHeight && normalized.aspectRatio === undefined &&
1346         (absoluteLeftInset(normalized, options.layoutDirection) === undefined || absoluteRightInset(normalized, options.layoutDirection) === undefined) &&
1347         (normalized.top === undefined || normalized.bottom === undefined);
1348       const naturalWidth = naturalBoth || automaticWidth &&
1349         isAbsoluteSizeInput(normalized.height) &&
1350         normalized.aspectRatio === undefined && (absoluteLeftInset(normalized, options.layoutDirection) === undefined || absoluteRightInset(normalized, options.layoutDirection) === undefined) &&
1351         (hasPairedMeasurement || unwrappedText);
1352       const naturalHeight = naturalBoth || automaticHeight &&
1353         isAbsoluteSizeInput(normalized.width) &&
1354         normalized.aspectRatio === undefined && (normalized.top === undefined || normalized.bottom === undefined) &&
1355         (hasPairedMeasurement || measurableText);
1356       assertSupportedAbsoluteFlexPosition(child, normalized, container, options.layoutDirection, preparedStyleQuery(prepared), naturalWidth, naturalHeight);
1357       const measurementToken = naturalWidth || naturalHeight ? region?.absoluteMeasurementIdentity(child.type,
1358         child.key === undefined ? `occurrence:${occurrence}` : `key:${typeof child.key}:${child.key}`) : undefined;
1359       if (measurementToken) (absoluteMeasurementTokens ??= new Set()).add(measurementToken);
1360       const absoluteMeasurement = naturalWidth || naturalHeight ? measurement : undefined;
1361       if (deferStaticAbsolute) {
1362         deferStaticAbsolute[sourceIndex] = { sourceIndex, child, style: normalized, receiverToken,
1363           query: preparedStyleQuery(prepared), measurement: absoluteMeasurement, measurementToken };
1364         placementsBySource[sourceIndex] = deferredStaticPlacementSentinel();
1365       } else placementsBySource[sourceIndex] = resolveAbsoluteFlexPlacement(
1366         absolutePaddingBox ??= resolveFlexContainingBox(style, container), child, normalized, receiverToken,
1367         preparedStyleQuery(prepared), container, options, absoluteMeasurement, region, measurementToken,
1368       );
1369       continue;
1370     }
1371     if (aspectRatio !== undefined) hasAspectRatio = true;
1372     const layoutChild = isLayoutComponent(child.type) ? prepareLayoutComponent(child, { receiverToken }) : child;
1373     const pairedLayoutDefinition = getPrimitiveDefinition(layoutChild.type);
1374     const knownIntrinsicLayout = child.type === Flex || layoutChild.type === Flow || layoutChild.type === Grid || layoutChild.type === Flex &&
1375       isColumnDirection(normalized.flexDirection) && (normalized.flexWrap ?? 'nowrap') === 'nowrap';
1376     const layoutToken = region?.identity(child.type, child.key === undefined ? `occurrence:${occurrence}` : `key:${typeof child.key}:${child.key}`);
1377     let relativeX = 0;
1378     let relativeY = 0;
1379     const position = normalized.position;
1380     if (position !== undefined) {
1381       assertSupportedRelativeFlexPosition(child, normalized, options, container);
1382       const left = resolveFlexInset(normalized.left, 'left', child, container);
1383       const right = resolveFlexInset(normalized.right, 'right', child, container);
1384       const top = resolveFlexInset(normalized.top, 'top', child, container);
1385       const bottom = resolveFlexInset(normalized.bottom, 'bottom', child, container);
1386       if (position === 'relative') {
1387         if (options.layoutDirection === 'rtl') relativeX = right === undefined ? left ?? 0 : -right;
1388         else relativeX = left === undefined ? right === undefined ? 0 : -right : left;
1389         relativeY = top === undefined ? bottom === undefined ? 0 : -bottom : top;
1390       }
1391     }
1392     const allMargin = normalized.margin === 'auto' ? 'auto' : allocatedMargin(normalized.margin, 'margin', child, container);
1393     const marginDirection = layoutChild.type === Flex ? normalized.layoutDirection ?? options.layoutDirection : options.layoutDirection;
1394     const logicalLeft = marginDirection === 'rtl' ? normalized.marginEnd : normalized.marginStart;
1395     const logicalRight = marginDirection === 'rtl' ? normalized.marginStart : normalized.marginEnd;
1396     const marginLeftProperty = logicalLeft !== undefined ? marginDirection === 'rtl' ? 'marginEnd' : 'marginStart' : 'marginLeft';
1397     const marginRightProperty = logicalRight !== undefined ? marginDirection === 'rtl' ? 'marginStart' : 'marginEnd' : 'marginRight';
1398     const marginTopValue = normalized.marginTop === undefined ? allMargin : normalized.marginTop;
1399     const marginBottomValue = normalized.marginBottom === undefined ? allMargin : normalized.marginBottom;
1400     const marginRightValue = logicalRight !== undefined ? logicalRight : normalized.marginRight === undefined ? allMargin : normalized.marginRight;
1401     const marginLeftValue = logicalLeft !== undefined ? logicalLeft : normalized.marginLeft === undefined ? allMargin : normalized.marginLeft;
1402     const autoTop = marginTopValue === 'auto', autoRight = marginRightValue === 'auto';
1403     const autoBottom = marginBottomValue === 'auto', autoLeft = marginLeftValue === 'auto';
1404     const declaredCrossSize = row ? normalized.height : normalized.width;
1405     const hasAutoCrossMargin = row ? autoTop || autoBottom : autoLeft || autoRight;
1406     const measuredCrossContext = hasAutoCrossMargin && nativeLayout && row &&
1407       (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1408       !preparedStyleQuery(prepared) && aspectRatio === undefined;
1409     const columnNaturalWrappedTextCross = nativeLayout && !row &&
1410       options.flexWrap === 'nowrap' &&
1411       child.type === Text && (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1412       typeof declared.height === 'number' && typeof normalized.height === 'number' &&
1413       Number.isFinite(normalized.height) && normalized.height >= 0 &&
1414       (normalized.flexBasis === undefined || normalized.flexBasis === 'auto') &&
1415       (normalized.flexGrow ?? 0) === 0 && normalized.flexShrink === 0 && normalized.minHeight === 0 &&
1416       normalized.maxHeight === undefined && (normalized.minWidth === undefined || normalized.minWidth === 0) && normalized.maxWidth === undefined &&
1417       normalized.wrap === true &&
1418       (normalized.fit === undefined || normalized.fit === 'visible') &&
1419       (normalized.overflow === undefined || normalized.overflow === 'visible' || normalized.overflow === 'clip') &&
1420       !preparedStyleQuery(prepared) && aspectRatio === undefined && genericTextFont(normalized);
1421     const measuredColumnTextCross = hasAutoCrossMargin && nativeLayout && !row &&
1422       options.flexWrap === 'nowrap' &&
1423       child.type === Text && (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1424       (normalized.height === undefined || normalized.height === 'auto' ||
1425         typeof normalized.height === 'number' && Number.isFinite(normalized.height) && normalized.height >= 0) &&
1426       (normalized.flexBasis === undefined || normalized.flexBasis === 'auto' ||
1427         typeof normalized.flexBasis === 'number' && Number.isFinite(normalized.flexBasis) && normalized.flexBasis >= 0) &&
1428       (normalized.flexGrow ?? 0) === 0 && normalized.flexShrink === 0 && normalized.minHeight === 0 &&
1429       normalized.maxHeight === undefined && normalized.minWidth === undefined && normalized.maxWidth === undefined &&
1430       (normalized.wrap === undefined || normalized.wrap === false) &&
1431       !preparedStyleQuery(prepared) && aspectRatio === undefined;
1432     const measuredColumnProviderCrossDefinition = hasAutoCrossMargin && nativeLayout && !row &&
1433       options.flexWrap === 'nowrap' &&
1434       (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1435       typeof declared.height === 'number' && typeof normalized.height === 'number' &&
1436       Number.isFinite(normalized.height) && normalized.height >= 0 &&
1437       (normalized.flexBasis === undefined || normalized.flexBasis === 'auto') &&
1438       (normalized.flexGrow ?? 0) === 0 && normalized.flexShrink === 0 && normalized.minHeight === 0 &&
1439       normalized.maxHeight === undefined && normalized.minWidth === undefined && normalized.maxWidth === undefined &&
1440       !preparedStyleQuery(prepared) && aspectRatio === undefined && child.type !== Text ?
1441       getPrimitiveDefinition(child.type) : undefined;
1442     const measuredColumnProviderCross = !!measuredColumnProviderCrossDefinition?.measureIntrinsic &&
1443       !!measuredColumnProviderCrossDefinition.measure;
1444     const measuredColumnKnownCrossAuto = hasAutoCrossMargin && nativeLayout && !row &&
1445       options.flexWrap === 'nowrap' &&
1446       isKnownLayoutType(layoutChild.type) && (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1447       typeof declared.height === 'number' && typeof normalized.height === 'number' &&
1448       Number.isFinite(normalized.height) && normalized.height >= 0 &&
1449       (normalized.flexBasis === undefined || normalized.flexBasis === 'auto') &&
1450       (normalized.flexGrow ?? 0) === 0 && normalized.flexShrink === 0 && normalized.minHeight === 0 &&
1451       normalized.maxHeight === undefined && (normalized.minWidth === undefined || normalized.minWidth === 0) && normalized.maxWidth === undefined &&
1452       !preparedStyleQuery(prepared) && aspectRatio === undefined;
1453     // In a finite column the main allocation is authoritative. For these
1454     // measured children, wait until the kernel settles height, then obtain the
1455     // natural width under that exact height before cross placement.
1456     const deferredColumnAutoCross = hasAutoCrossMargin && nativeLayout && !row &&
1457       options.flexWrap === 'nowrap' &&
1458       (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1459       !preparedStyleQuery(prepared) && aspectRatio === undefined && (
1460         child.type === Text &&
1461           (normalized.wrap === undefined || normalized.wrap === false) ||
1462         layoutChild.type !== Text && !!pairedLayoutDefinition?.measureIntrinsic && !!pairedLayoutDefinition.measure ||
1463         layoutChild.type === Flex || layoutChild.type === Flow || layoutChild.type === Grid
1464       );
1465     // Main sizing remains authoritative. The existing Text resolver uses
1466     // the shared settled-width pass before a row cross-auto margin is placed.
1467     const measuredTextCrossAuto = hasAutoCrossMargin && nativeLayout && row &&
1468       child.type === Text && (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1469       !preparedStyleQuery(prepared) && aspectRatio === undefined;
1470     const autoCrossDefinition = measuredCrossContext && !measuredTextCrossAuto ? pairedLayoutDefinition : undefined;
1471     const measuredPrimitiveCrossAuto = !!autoCrossDefinition?.measureIntrinsic && !!autoCrossDefinition.measure;
1472     const measuredKnownCrossAuto = measuredCrossContext && (layoutChild.type === Flex || layoutChild.type === Flow || layoutChild.type === Grid);
1473     // Remaining ordinary providers keep the same finite-availability query as
1474     // non-stretch sizing; an intrinsic callback is not a cross-size prerequisite.
1475     const ordinaryCrossAuto = hasAutoCrossMargin && nativeLayout &&
1476       (row || options.flexWrap === 'nowrap') &&
1477       (declaredCrossSize === undefined || declaredCrossSize === 'auto') &&
1478       !preparedStyleQuery(prepared) && aspectRatio === undefined && !!pairedLayoutDefinition?.measure;
1479     if (hasAutoCrossMargin && !measuredTextCrossAuto && !measuredColumnTextCross && !columnNaturalWrappedTextCross && !measuredColumnProviderCross && !measuredColumnKnownCrossAuto && !deferredColumnAutoCross && !measuredPrimitiveCrossAuto && !measuredKnownCrossAuto && !ordinaryCrossAuto &&
1480         aspectRatio === undefined && (declaredCrossSize === undefined || declaredCrossSize === 'auto')) {
1481       throw childDiagnostic(child, row ? autoTop ? 'marginTop' : 'marginBottom' : autoLeft ? marginLeftProperty : marginRightProperty, 'auto', container, 'auto cross-axis margins require a finite numeric child cross size or supported measurement');
1482     }
1483     const autoCrossBefore = row ? wrapReverse ? autoBottom : autoTop : wrapReverse ? autoRight : autoLeft;
1484     const autoCrossAfter = row ? wrapReverse ? autoTop : autoBottom : wrapReverse ? autoLeft : autoRight;
1485     const autoMainBefore = row ? reverse ? autoRight : autoLeft : reverse ? autoBottom : autoTop;
1486     const autoMainAfter = row ? reverse ? autoLeft : autoRight : reverse ? autoTop : autoBottom;
1487     if (autoMainBefore || autoMainAfter) hasAutoMainMargins = true;
1488     const marginTop = allocatedMargin(autoTop ? 0 : marginTopValue, 'marginTop', child, container);
1489     const marginRight = allocatedMargin(autoRight ? 0 : marginRightValue, marginRightProperty, child, container);
1490     const marginBottom = allocatedMargin(autoBottom ? 0 : marginBottomValue, 'marginBottom', child, container);
1491     const marginLeft = allocatedMargin(autoLeft ? 0 : marginLeftValue, marginLeftProperty, child, container);
1492     const marginMainBefore = row ? reverse ? marginRight : marginLeft : reverse ? marginBottom : marginTop;
1493     const marginMainAfter = row ? reverse ? marginLeft : marginRight : reverse ? marginTop : marginBottom;
1494     const marginCrossBefore = row ? wrapReverse ? marginBottom : marginTop : wrapReverse ? marginRight : marginLeft;
1495     const marginCrossAfter = row ? wrapReverse ? marginTop : marginBottom : wrapReverse ? marginLeft : marginRight;
1496     const grow = nonnegativeFactor(normalized.flexGrow ?? 0, 'flexGrow', child, container);
1497     const shrink = nonnegativeFactor(
1498       normalized.flexShrink ?? 1,
1499       'flexShrink',
1500       child,
1501       container,
1502     );
1503     const basisValue = normalized.flexBasis ?? 'auto';
1504     const alignment = normalizeItemAlignment(normalized.alignSelf, child, container, authoredWrapReverse);
1505     const padding = normalizeBoxInsets(normalized, childContext(child, container));
1506     const paddingMain = row ? padding.left + padding.right : padding.top + padding.bottom;
1507     const paddingCross = row ? padding.top + padding.bottom : padding.left + padding.right;
1508     const minimumProperty = row ? 'minWidth' : 'minHeight';
1509     // Natural Text contributions are independent of row orientation and line
1510     // direction. Native allocation still owns grow/shrink and line formation.
1511     const intrinsicTextSizing = nativeLayout && row && child.type === Text &&
1512       (normalized.fit === undefined || normalized.fit === 'visible') &&
1513       (normalized.overflow === undefined || normalized.overflow === 'visible' || normalized.overflow === 'clip') &&
1514       !preparedStyleQuery(prepared) && aspectRatio === undefined &&
1515       (normalized.width === undefined || normalized.width === 'auto' || typeof normalized.width === 'number') &&
1516       (normalized.maxWidth === undefined || typeof normalized.maxWidth === 'number');
1517     const automaticTextBasis = intrinsicTextSizing && basisValue === 'auto' &&
1518       (normalized.width === undefined || normalized.width === 'auto') &&
1519       (normalized.minWidth === undefined || typeof normalized.minWidth === 'number');
1520     const automaticTextMinimum = intrinsicTextSizing && normalized[minimumProperty] === undefined && shrink > 0 &&
1521       (typeof basisValue === 'number' || basisValue === 'auto' &&
1522         (typeof normalized.width === 'number' || automaticTextBasis));
1523     // An empty authored rectangle has no intrinsic content contribution. Keep
1524     // opaque/child-bearing primitives conservative without evaluating children.
1525     const aspectMain = basisValue === 'auto' ? normalized[row ? 'width' : 'height'] : basisValue;
1526     const aspectCross = normalized[row ? 'height' : 'width'];
1527     // An empty shape has no content floor. Aspect sizing still derives cross
1528     // size from the solved main allocation; it does not transfer a cross floor.
1529     const automaticAspectRectangleMinimum = nativeLayout && aspectRatio !== undefined &&
1530       child.type === Rectangle && !Object.hasOwn(child.props, 'children') && !preparedStyleQuery(prepared) &&
1531       typeof aspectMain === 'number' && Number.isFinite(aspectMain) && aspectMain >= 0 &&
1532       (aspectCross === undefined || aspectCross === 'auto' ||
1533         typeof aspectCross === 'number' && Number.isFinite(aspectCross) && aspectCross >= 0);
1534     const automaticRectangleMinimum = automaticAspectRectangleMinimum ||
1535       hasEmptyRectangleMinimum(child, normalized, preparedStyleQuery(prepared), true);
1536     // A selected intrinsic main value reuses the existing direct paired-provider
1537     // transaction. The established numeric grow/shrink/bounds path remains the
1538     // authority after this contribution becomes a number.
1539     const intrinsicMainValue = basisValue === undefined || basisValue === 'auto'
1540       ? normalized[row ? 'width' : 'height']
1541       : basisValue;
1542     const intrinsicMainBounds = isIntrinsicSizingValue(normalized[row ? 'minWidth' : 'minHeight']) || isIntrinsicSizingValue(normalized[row ? 'maxWidth' : 'maxHeight']);
1543     const intrinsicMainRequested = isIntrinsicSizingValue(intrinsicMainValue);
1544     const directIntrinsicTextMain = (intrinsicMainRequested || intrinsicMainBounds) &&
1545       !stagedMeasured && nativeLayout && row &&
1546       child.type === Text && !preparedStyleQuery(prepared);
1547     const directIntrinsicMain = (intrinsicMainRequested || intrinsicMainBounds) &&
1548       !stagedMeasured && nativeLayout &&
1549       row && !preparedStyleQuery(prepared) &&
1550       child.type !== Text && !isLayoutComponent(child.type) &&
1551       !!pairedLayoutDefinition?.measureIntrinsic && !!pairedLayoutDefinition.measure;
1552     const customIntrinsic = child.type !== Text && (!isKnownLayoutType(layoutChild.type) || directIntrinsicMain) && !stagedMeasured && nativeLayout && row &&
1553       !preparedStyleQuery(prepared) && !!pairedLayoutDefinition?.measureIntrinsic &&
1554       (!isLayoutComponent(child.type) || aspectRatio === undefined && !!pairedLayoutDefinition.measure) &&
1555       (directIntrinsicMain || basisValue === 'auto' && (normalized.width === undefined || normalized.width === 'auto') || shrink > 0 && normalized.minWidth === undefined);
1556     let intrinsicMainRequest: NormalizedSizingLength | undefined;
1557     if (intrinsicMainRequested && (directIntrinsicMain || directIntrinsicTextMain)) {
1558       intrinsicMainRequest = normalizeSizingLength(intrinsicMainValue, {
1559         reference: mainSize, property: basisValue === undefined || basisValue === 'auto' ? 'width' : 'flexBasis',
1560         context: childContext(child, container), allowAuto: false, allowIntrinsic: true,
1561       });
1562     }
1563     let intrinsicTextMinimum: number | undefined;
1564     let intrinsicTextBasis: number | undefined;
1565     let intrinsicTextMaximum: number | undefined;
1566     if (directIntrinsicTextMain) {
1567       const intrinsic = measureTextIntrinsicWidths(child, normalized, receiverToken, measurement, region);
1568       const maximum = intrinsic.maximum;
1569       if (!Number.isFinite(maximum) || maximum < 0) {
1570         throw childDiagnostic(child, 'width', intrinsicMainValue, container, 'Text intrinsic run width must be finite and nonnegative');
1571       }
1572       // An unwrapped run has no soft break opportunities in Text's public policy.
1573       intrinsicTextMinimum = intrinsic.minimum;
1574       intrinsicTextMaximum = maximum;
1575       if (intrinsicMainRequest) {
1576         intrinsicTextBasis = resolveIntrinsicMainBasis(intrinsicMainRequest, intrinsicTextMinimum, maximum, child, container);
1577       } else if (basisValue === 'auto' && (normalized.width === undefined || normalized.width === 'auto')) {
1578         intrinsicTextBasis = maximum;
1579       }
1580     }
1581     let intrinsicSizes: Extract<import('../types.js').IntrinsicSizesResult, { status: 'measured' }> | undefined;
1582     if (customIntrinsic) {
1583       const measurementChild = clonePibblElement(child);
1584       setPreNormalizedStyle(measurementChild, normalized, child, receiverToken);
1585       const result = measureIntrinsicElement(measurementChild, { minWidth: 0, maxWidth: container.width, minHeight: 0, maxHeight: container.height }, measurement.service, region ? { cache: region, token: layoutToken ?? receiverToken, recordMeasurement: recordWasmMeasurement, key: JSON.stringify([allocationStructuralRevision(), measurementStyle(normalized), container.width, container.height]) } : undefined);
1586       if (result.status === 'unsupported') throw childDiagnostic(child, 'measureIntrinsic', 'unsupported', container, `intrinsic measurement is required but unsupported: ${result.reason}; supply a definite basis and explicit minWidth: 0 to avoid the query`);
1587       intrinsicSizes = result;
1588     }
1589 
1590     // Intrinsic-pair heights belong to their respective widths. A column floor
1591     // instead needs natural content height measured at its declared exact width.
1592     const columnExactWidth = !row && typeof normalized.width === 'number' ? normalized.width :
1593       !row && (normalized.width === undefined || normalized.width === 'auto' || normalized.width === 'stretch') &&
1594       !hasAutoCrossMargin && effectiveAlignment(alignment, options.alignItems) === 'stretch' ?
1595         clamp(Math.max(0, crossSize - paddingCross - marginCrossBefore - marginCrossAfter),
1596           resolveOptionalBound(normalized.minWidth, crossSize, 'minWidth', 0, child, container),
1597           resolveOptionalBound(normalized.maxWidth, crossSize, 'maxWidth', Number.POSITIVE_INFINITY, child, container)) : undefined;
1598     const columnMinimumDefinition = nativeLayout && !row &&
1599       (intrinsicMainRequested || intrinsicMainBounds || shrink > 0 && normalized.minHeight === undefined) &&
1600       (normalized.height === undefined || normalized.height === 'auto' || typeof normalized.height === 'number' || isIntrinsicSizingValue(normalized.height)) &&
1601       columnExactWidth !== undefined && Number.isFinite(columnExactWidth) && columnExactWidth >= 0 && aspectRatio === undefined &&
1602       !preparedStyleQuery(prepared) ? getPrimitiveDefinition(layoutChild.type) : undefined;
1603     let columnMinimumSize: { width: number; height: number } | undefined;
1604     if (columnMinimumDefinition?.measure && (columnMinimumDefinition.measureIntrinsic || child.type === Text || knownIntrinsicLayout)) {
1605       const measurementChild = clonePibblElement(child);
1606       const measurementStyle = { ...normalized, width: columnExactWidth };
1607       setPreNormalizedStyle(measurementChild, measurementStyle, child, receiverToken);
1608       const result = measureFlexChild(measurementChild, {
1609         minWidth: columnExactWidth!, maxWidth: columnExactWidth!,
1610         minHeight: 0, maxHeight: Number.POSITIVE_INFINITY,
1611       }, measurementStyle, layoutToken ?? receiverToken, measurement, region, undefined, true);
1612       if (result.status === 'unsupported') throw childDiagnostic(child, 'minHeight', 'auto', container,
1613         `exact-width automatic minimum measurement is required but unsupported: ${result.reason}`);
1614       columnMinimumSize = result.size;
1615       if (intrinsicMainRequested) intrinsicMainRequest = normalizeSizingLength(intrinsicMainValue, {
1616         reference: mainSize, property: 'height', context: childContext(child, container), allowAuto: false, allowIntrinsic: true,
1617       });
1618     }
1619 
1620     if (!stagedMeasured && (shrink > 0 || basisValue === 'auto') && normalized[minimumProperty] === undefined && !automaticTextMinimum && !automaticTextBasis && !automaticRectangleMinimum && !intrinsicSizes && intrinsicTextMinimum === undefined && !columnMinimumSize) {
1621       throw childDiagnostic(
1622         child,
1623         minimumProperty,
1624         normalized[minimumProperty],
1625         container,
1626         'an explicit main-axis minimum is required for shrink or auto basis',
1627       );
1628     }
1629 
1630     const mainProperty = row ? 'width' : 'height';
1631     const crossProperty = row ? 'height' : 'width';
1632     const mainReference = mainSize;
1633     const crossReference = crossSize;
1634     let measured: { width: number; height: number } | undefined = columnMinimumSize;
1635     const specifiedMain = normalized[mainProperty];
1636     const specifiedCross = normalized[crossProperty];
1637     const needsMeasuredMain = !stagedMeasured && basisValue === 'auto' &&
1638       (specifiedMain === undefined || specifiedMain === 'auto');
1639     if (aspectRatio !== undefined && needsMeasuredMain && !intrinsicSizes && !automaticTextBasis) throw childDiagnostic(child, 'aspectRatio', aspectRatio, container, 'requires a definite main dimension or flexBasis; intrinsic aspect sizing is unsupported');
1640     const crossAuto = specifiedCross === undefined || specifiedCross === 'auto';
1641     const measuredColumnWrapText = nativeLayout && !row && options.flexWrap !== 'nowrap' &&
1642       needsMeasuredMain && child.type === Text && aspectRatio === undefined &&
1643       typeof declared.width === 'number' && typeof normalized.width === 'number' &&
1644       Number.isFinite(normalized.width) && normalized.width >= 0 && declared.minHeight === 0 &&
1645       grow === 0 && shrink === 0 && normalized.wrap === true &&
1646       (normalized.fit === undefined || normalized.fit === 'visible') &&
1647       (normalized.overflow === undefined || normalized.overflow === 'visible' || normalized.overflow === 'clip') &&
1648       (normalized.minWidth === undefined || normalized.minWidth === 0) &&
1649       normalized.maxWidth === undefined && normalized.maxHeight === undefined &&
1650       !preparedStyleQuery(prepared) && genericTextFont(normalized);
1651     const measuredColumnProviderDefinition = nativeLayout && !row && options.flexDirection === 'column' &&
1652       options.flexWrap === 'nowrap' && options.layoutDirection === 'ltr' && needsMeasuredMain &&
1653       aspectRatio === undefined && typeof declared.width === 'number' && typeof normalized.width === 'number' &&
1654       Number.isFinite(normalized.width) && normalized.width >= 0 && declared.minHeight === 0 &&
1655       grow === 0 && shrink === 0 && (normalized.minWidth === undefined || normalized.minWidth === 0) &&
1656       normalized.maxWidth === undefined && !preparedStyleQuery(prepared) ?
1657       getPrimitiveDefinition(child.type) : undefined;
1658     const measuredColumnProvider = child.type !== Text && !isKnownLayoutType(layoutChild.type) && !!measuredColumnProviderDefinition?.measureIntrinsic &&
1659       !!measuredColumnProviderDefinition.measure;
1660     const naturalColumnWrappedTextCross = columnNaturalWrappedTextCross &&
1661       (hasAutoCrossMargin || effectiveAlignment(alignment, options.alignItems) !== 'stretch');
1662     if (nativeLayout && !row && options.flexWrap !== 'nowrap' &&
1663       (needsMeasuredMain && !measuredColumnWrapText || aspectRatio === undefined && crossAuto && effectiveAlignment(alignment, options.alignItems) !== 'stretch')) {
1664       throw childDiagnostic(child, needsMeasuredMain ? mainProperty : crossProperty, 'auto', container,
1665         'Experimental WASM column wrap requires a declared height or flexBasis and a declared width or stretched automatic width; intrinsic item sizes are unsupported.');
1666     }
1667     const needsMeasuredCross = aspectRatio === undefined && crossAuto && alignment !== 'stretch' &&
1668       options.alignItems !== 'stretch';
1669     // A finite column cross allocation determines a stretched built-in child's
1670     // width without measuring its intrinsic height. Resolve bounds/padding first.
1671     const deferredIntrinsicColumn = aspectRatio === undefined && nativeLayout && !row && knownIntrinsicLayout &&
1672       needsMeasuredMain && crossAuto && effectiveAlignment(alignment, options.alignItems) === 'stretch';
1673     if (intrinsicSizes) measured = intrinsicSizes.maxContent;
1674     if (!columnMinimumSize && !directIntrinsicTextMain && !intrinsicSizes && !deferredIntrinsicColumn && !naturalColumnWrappedTextCross && (!deferredColumnAutoCross || needsMeasuredMain) && (needsMeasuredMain || aspectRatio === undefined && (needsMeasuredCross || crossAuto))) {
1675       // A deferred auto-cross child may still need an initial main-size query.
1676       // That provisional query must not borrow the container width: the later
1677       // exact-height query is the only cross-size authority.
1678       const naturalColumnCross = measuredColumnTextCross || measuredColumnProviderCross || measuredColumnKnownCrossAuto || deferredColumnAutoCross;
1679       const exactColumnHeight = naturalColumnCross && typeof normalized.height === 'number' ? normalized.height : undefined;
1680       const constraints = {
1681         minWidth: naturalColumnCross ? 0 : measuredColumnWrapText || measuredColumnProvider ? normalized.width as number : 0,
1682         maxWidth: naturalColumnCross ? Number.POSITIVE_INFINITY : measuredColumnWrapText || measuredColumnProvider ? normalized.width as number : container.width,
1683         minHeight: exactColumnHeight ?? 0,
1684         maxHeight: exactColumnHeight ?? (measuredColumnWrapText || measuredColumnProvider ? Number.POSITIVE_INFINITY : container.height),
1685       };
1686       const measurementChild = clonePibblElement(child);
1687       setPreNormalizedStyle(
1688         measurementChild,
1689         normalized,
1690         child,
1691         receiverToken,
1692         preparedStyleQuery(prepared),
1693       );
1694       const result = measureFlexChild(
1695         measurementChild, constraints, normalized, layoutToken ?? receiverToken, measurement, region,
1696         preparedStyleQuery(prepared),
1697         (nativeLayout && row && options.flexWrap === 'nowrap') || measuredPrimitiveCrossAuto || measuredColumnProvider || measuredColumnProviderCross,
1698         needsMeasuredMain ? (row ? 'row' : 'column') : undefined, ordinaryCrossAuto || !!pairedLayoutDefinition?.measure && !pairedLayoutDefinition.measureIntrinsic && layoutChild.type !== Text && !isKnownLayoutType(layoutChild.type),
1699       );
1700       if (result.status === 'measured') {
1701         measured = result.size;
1702       } else if (measuredTextCrossAuto || measuredColumnTextCross || measuredKnownCrossAuto || measuredColumnProviderCross || measuredColumnKnownCrossAuto || deferredColumnAutoCross || ordinaryCrossAuto || needsMeasuredMain || (crossAuto && effectiveAlignment(
1703         alignment,
1704         options.alignItems,
1705       ) !== 'stretch')) {
1706         throw childDiagnostic(
1707           child,
1708           needsMeasuredMain ? mainProperty : crossProperty,
1709           'auto',
1710           container,
1711           `measurement is required but unsupported: ${result.reason}`,
1712         );
1713       }
1714     }
1715 
1716     const intrinsicMinimum = row ? intrinsicSizes?.minContent.width ?? intrinsicTextMinimum : columnMinimumSize?.height;
1717     const intrinsicMaximum = row ? intrinsicSizes?.maxContent.width ?? intrinsicTextMaximum : columnMinimumSize?.height;
1718     let minMain = stagedItem ? stagedItem.min : isIntrinsicSizingValue(normalized[minimumProperty])
1719       ? resolveIntrinsicMainBound(normalized[minimumProperty]!, intrinsicMinimum, intrinsicMaximum, minimumProperty, mainReference, child, container)
1720       : resolveOptionalBound(
1721       normalized[minimumProperty],
1722       mainReference,
1723       minimumProperty,
1724       0,
1725       child,
1726       container,
1727     );
1728     const maximumProperty = row ? 'maxWidth' : 'maxHeight';
1729     const maxMain = stagedItem ? stagedItem.max : isIntrinsicSizingValue(normalized[maximumProperty])
1730       ? resolveIntrinsicMainBound(normalized[maximumProperty]!, intrinsicMinimum, intrinsicMaximum, maximumProperty, mainReference, child, container)
1731       : resolveOptionalBound(
1732       normalized[maximumProperty],
1733       mainReference,
1734       maximumProperty,
1735       Number.POSITIVE_INFINITY,
1736       child,
1737       container,
1738     );
1739     if (intrinsicSizes && normalized.minWidth === undefined && shrink > 0) {
1740       minMain = Math.min(intrinsicSizes.minContent.width, maxMain,
1741         typeof specifiedMain === 'number' ? specifiedMain : Number.POSITIVE_INFINITY);
1742     }
1743     if (columnMinimumSize) {
1744       minMain = Math.min(columnMinimumSize.height, maxMain,
1745         typeof specifiedMain === 'number' ? specifiedMain : Number.POSITIVE_INFINITY);
1746     }
1747     if (intrinsicTextMinimum !== undefined && normalized.minWidth === undefined && shrink > 0) {
1748       minMain = Math.min(intrinsicTextMinimum, maxMain);
1749     }
1750     const intrinsicMainBasis = intrinsicTextBasis ?? (intrinsicMainRequest && intrinsicMinimum !== undefined && intrinsicMaximum !== undefined
1751       ? resolveIntrinsicMainBasis(intrinsicMainRequest, intrinsicMinimum, intrinsicMaximum, child, container)
1752       : undefined);
1753     if (automaticTextMinimum) {
1754       const contentMinimum = measureTextContentMinimum(child, normalized, receiverToken, measurement, region);
1755       minMain = Math.min(contentMinimum, maxMain,
1756         typeof specifiedMain === 'number' ? specifiedMain : Number.POSITIVE_INFINITY);
1757     }
1758     const minCrossProperty = row ? 'minHeight' : 'minWidth';
1759     const maxCrossProperty = row ? 'maxHeight' : 'maxWidth';
1760     const minCross = resolveOptionalBound(
1761       normalized[minCrossProperty],
1762       crossReference,
1763       minCrossProperty,
1764       0,
1765       child,
1766       container,
1767     );
1768     const maxCross = resolveOptionalBound(
1769       normalized[maxCrossProperty],
1770       crossReference,
1771       maxCrossProperty,
1772       Number.POSITIVE_INFINITY,
1773       child,
1774       container,
1775     );
1776     if (naturalColumnWrappedTextCross) {
1777       const token = layoutToken ?? receiverToken;
1778       const naturalWidth = measureTextNaturalWidth(child, normalized, receiverToken, token, measurement, region);
1779       const chosenWidth = Math.min(naturalWidth, Math.max(0, crossSize - paddingCross - marginCrossBefore - marginCrossAfter));
1780       const measuredStyle = { ...normalized, width: chosenWidth };
1781       const measurementChild = clonePibblElement(child);
1782       setPreNormalizedStyle(measurementChild, measuredStyle, child, receiverToken, preparedStyleQuery(prepared));
1783       const result = measureFlexChild(measurementChild, {
1784         minWidth: chosenWidth, maxWidth: chosenWidth,
1785         minHeight: normalized.height as number, maxHeight: normalized.height as number,
1786       }, measuredStyle, token, measurement, region, preparedStyleQuery(prepared));
1787       if (result.status !== 'measured') {
1788         throw childDiagnostic(child, 'width', 'auto', container,
1789           `measurement is required but unsupported: ${result.reason}`);
1790       }
1791       measured = result.size;
1792     }
1793     if (minMain > maxMain) {
1794       throw childDiagnostic(
1795         child,
1796         minimumProperty,
1797         minMain,
1798         container,
1799         'minimum must not exceed maximum',
1800       );
1801     }
1802     if (minCross > maxCross) {
1803       throw childDiagnostic(
1804         child,
1805         minCrossProperty,
1806         minCross,
1807         container,
1808         'minimum must not exceed maximum',
1809       );
1810     }
1811     // Settle width-dependent height before using an automatic main basis.
1812     // The experimental built-in intrinsic column uses the same final-width rule.
1813     if (!row && options.flexWrap === 'nowrap' && (child.type === Text || nativeLayout && knownIntrinsicLayout) && needsMeasuredMain) {
1814       const preferredWidth = crossAuto ?
1815         effectiveAlignment(alignment, options.alignItems) === 'stretch' && !hasAutoCrossMargin ?
1816           Math.max(0, crossSize - paddingCross - marginCrossBefore - marginCrossAfter) : measured?.width ?? 0 :
1817         resolveItemLength(specifiedCross, crossReference, crossProperty, child, container);
1818       const usedWidth = clamp(preferredWidth, minCross, maxCross);
1819       if (child.type === Text || usedWidth !== measured?.width) {
1820         const measuredStyle = { ...normalized, width: usedWidth };
1821         const measurementChild = clonePibblElement(layoutChild);
1822         setPreNormalizedStyle(measurementChild, measuredStyle, layoutChild, getPrimitiveReceiverToken(layoutChild) ?? receiverToken, preparedStyleQuery(prepared));
1823         const result = measureFlexChild(measurementChild, {
1824           minWidth: 0, maxWidth: usedWidth,
1825           minHeight: 0, maxHeight: container.height,
1826         }, measuredStyle, layoutToken ?? receiverToken, measurement, region, preparedStyleQuery(prepared));
1827         if (result.status === 'measured') measured = result.size;
1828         else throw childDiagnostic(child, mainProperty, 'auto', container,
1829           `measurement is required but unsupported: ${result.reason}`);
1830       }
1831     }
1832 
1833     let naturalTextMain: number | undefined;
1834     if (automaticTextBasis) {
1835       naturalTextMain = measureTextNaturalWidth(child, normalized, receiverToken, layoutToken ?? receiverToken, measurement, region);
1836     }
1837     const stretchMain = (declared.flexBasis === undefined || declared.flexBasis === 'auto' ? declared[mainProperty] : declared.flexBasis) === 'stretch';
1838     const baseMain = stagedMeasured ? stagedItem!.target : stretchMain ? Math.max(0, mainReference - marginMainBefore - marginMainAfter - paddingMain) : intrinsicMainBasis ?? naturalTextMain ?? resolveBasis(
1839       basisValue,
1840       specifiedMain,
1841       measured?.[mainProperty],
1842       mainReference,
1843       mainProperty,
1844       child,
1845       container,
1846     );
1847     const preferredCross = declared[crossProperty] === 'stretch' ? Math.max(0, crossReference - marginCrossBefore - marginCrossAfter - paddingCross) : aspectRatio !== undefined ? 0 : crossAuto ?
1848       measured?.[crossProperty] ?? 0 :
1849       resolveItemLength(
1850         specifiedCross,
1851         crossReference,
1852         crossProperty,
1853         child,
1854         container,
1855       );
1856     items.push({
1857       child,
1858       normalized,
1859       baseMain,
1860       targetMain: baseMain,
1861       paddingMain,
1862       marginMainBefore, marginMainAfter, autoMainBefore, autoMainAfter, marginCrossBefore, marginCrossAfter, autoCrossBefore, autoCrossAfter,
1863       preferredCross: clamp(preferredCross, minCross, maxCross) + paddingCross,
1864       paddingCross,
1865       paddingCrossBefore: row ? padding.top : padding.left,
1866       minMain,
1867       maxMain,
1868       minCross,
1869       maxCross,
1870       grow,
1871       shrink,
1872       crossAuto: aspectRatio === undefined && crossAuto,
1873       aspectRatio,
1874       alignSelf: alignment,
1875       receiverToken,
1876       layoutToken,
1877       query: preparedStyleQuery(prepared),
1878       relativeX,
1879       relativeY,
1880       deferredColumnAutoCross,
1881       ordinaryColumnAutoCross: !row && ordinaryCrossAuto && !deferredColumnAutoCross && !naturalColumnWrappedTextCross,
1882       sourceIndex,
1883       layoutOccurrence: occurrence,
1884     });
1885   }
1886 
1887   const wrappedRegion = region && options.flexWrap !== 'nowrap';
1888   // Rust owns wrapped line boundaries and offsets; JS retains source-order items
1889   // only for host measurement and immediate rendering, never a second line solver.
1890   const lines = region ? items.length ? [{ items, crossSize: 0, crossOffset: 0 }] : [] :
1891     collectLines(items, mainSize, mainGap, options.flexWrap);
1892   if (lines.length === 0) region?.solve([], mainSize, mainGap, !!wrappedRegion);
1893   for (const line of lines) {
1894     if (region) region.solve(line.items, mainSize, mainGap, !!wrappedRegion);
1895     else resolveFlexibleLengths(line, mainSize, mainGap);
1896     if (hasAspectRatio) for (const item of line.items) {
1897       if (item.aspectRatio === undefined) continue;
1898       const outerMain = item.targetMain + item.paddingMain;
1899       const outerCross = row ? outerMain / item.aspectRatio : outerMain * item.aspectRatio;
1900       if (!Number.isFinite(outerCross)) throw childDiagnostic(item.child, 'aspectRatio', item.aspectRatio, container, 'derived cross size must be finite');
1901       item.preferredCross = clamp(Math.max(0, outerCross - item.paddingCross), item.minCross, item.maxCross) + item.paddingCross;
1902     }
1903     // Width-dependent content uses the settled content allocation.
1904     if (row) for (const item of line.items) {
1905       let measuredRoot = item.child;
1906       if (item.crossAuto && nativeLayout && (options.flexWrap === 'nowrap' && options.flexDirection === 'row' && options.layoutDirection === 'ltr' || item.autoCrossBefore || item.autoCrossAfter || options[FLEX_BASELINE_GROUP]) && !item.query && item.aspectRatio === undefined && isLayoutComponent(item.child.type)) {
1907         measuredRoot = prepareLayoutComponent(item.child, { receiverToken: item.receiverToken });
1908       }
1909       const definition = nativeLayout && (options.flexWrap === 'nowrap' || item.autoCrossBefore || item.autoCrossAfter || options[FLEX_BASELINE_GROUP]) && !item.query && item.aspectRatio === undefined ? getPrimitiveDefinition(measuredRoot.type) : undefined;
1910       const constrainedProvider = measuredRoot.type !== Text && !isKnownLayoutType(measuredRoot.type) && !!definition?.measureIntrinsic && !!definition.measure;
1911       const ordinaryProvider = !!definition?.measure && (item.autoCrossBefore || item.autoCrossAfter || options[FLEX_BASELINE_GROUP]);
1912       const requiredKnownCross = nativeLayout && (item.autoCrossBefore || item.autoCrossAfter) && (measuredRoot.type === Flex || measuredRoot.type === Flow || measuredRoot.type === Grid);
1913       if (!item.crossAuto || (item.child.type !== Text && !(nativeLayout && item.child.type === Flex) && !constrainedProvider && !ordinaryProvider && !requiredKnownCross)) continue;
1914       if (item.child.type === Flex && item.normalized.width === item.targetMain) continue;
1915       const measuredStyle = { ...item.normalized, width: item.targetMain };
1916       const child = clonePibblElement(item.child);
1917       setPreNormalizedStyle(child, measuredStyle, item.child, item.receiverToken, item.query);
1918       const result = measureFlexChild(child, {
1919         minWidth: constrainedProvider || ordinaryProvider ? item.targetMain : 0, maxWidth: item.targetMain,
1920         minHeight: 0, maxHeight: container.height,
1921       }, measuredStyle, item.layoutToken ?? item.receiverToken, measurement, region, item.query, constrainedProvider, undefined, ordinaryProvider);
1922       if (result.status === 'measured') {
1923         item.preferredCross = clamp(result.size.height, item.minCross, item.maxCross) + item.paddingCross;
1924         // Baseline grouping consumes this final measured box rather than stretching
1925         // an authored automatic cross size after the provider has been queried.
1926         if (options[FLEX_BASELINE_GROUP] && (item.alignSelf !== 'stretch' || item.autoCrossBefore || item.autoCrossAfter)) item.crossAuto = false;
1927       } else if (constrainedProvider || ordinaryProvider || requiredKnownCross || options[FLEX_BASELINE_GROUP] || nativeLayout && item.child.type === Text && (item.autoCrossBefore || item.autoCrossAfter)) throw childDiagnostic(item.child, 'height', 'auto', container, `final-width measurement is required but unsupported: ${result.reason}`);
1928     }
1929   }
1930   // Defer column natural cross measurement until the kernel has resolved each
1931   // item's final main allocation. The result is still measured through the
1932   // normal transaction/cache path and is required before any placement.
1933   if (!row) for (const item of items) {
1934     if ((!item.deferredColumnAutoCross && !item.ordinaryColumnAutoCross) || !item.crossAuto) continue;
1935     let measuredRoot = item.child;
1936     if (isLayoutComponent(item.child.type)) {
1937       measuredRoot = prepareLayoutComponent(item.child, { receiverToken: item.receiverToken });
1938     }
1939     const definition = getPrimitiveDefinition(measuredRoot.type);
1940     const constrainedProvider = measuredRoot.type !== Text && !!definition?.measureIntrinsic && !!definition.measure;
1941     const ordinaryWidth = Math.max(0, item.preferredCross - item.paddingCross);
1942     const measuredStyle = item.ordinaryColumnAutoCross ?
1943       { ...item.normalized, width: ordinaryWidth, height: item.targetMain } :
1944       { ...item.normalized, height: item.targetMain };
1945     const measurementChild = clonePibblElement(item.child);
1946     setPreNormalizedStyle(measurementChild, measuredStyle, item.child, item.receiverToken, item.query);
1947     const result = measureFlexChild(measurementChild, {
1948       minWidth: 0, maxWidth: item.ordinaryColumnAutoCross ? ordinaryWidth : Number.POSITIVE_INFINITY,
1949       minHeight: item.targetMain, maxHeight: item.targetMain,
1950     }, measuredStyle, item.layoutToken ?? item.receiverToken, measurement, region, item.query, constrainedProvider, undefined, item.ordinaryColumnAutoCross);
1951     if (result.status === 'unsupported') {
1952       throw childDiagnostic(item.child, 'width', 'auto', container,
1953         `final-height measurement is required but unsupported: ${result.reason}`);
1954     }
1955     item.preferredCross = clamp(result.size.width, item.minCross, item.maxCross) + item.paddingCross;
1956   }
1957   if (options[FLEX_BASELINE_GROUP]) {
1958     assertSupportedBaselineFlex(options, items, container, region !== undefined);
1959     for (const item of items) {
1960       // Automatic cross margins replace alignment, so this leaf neither supplies
1961       // nor consumes a shared baseline. Native placement resolves its free space.
1962       if (item.alignSelf !== 'auto' || item.autoCrossBefore || item.autoCrossAfter) { item.firstBaseline = 0; continue; }
1963       const structural = prepareKnownStructuralBaseline(item, container, measurement, parentSlot, options[FLEX_LAST_BASELINE]);
1964       if (structural !== undefined) {
1965         item.structuralBaselineSlot = structural.slot;
1966         item.firstBaseline = item.paddingCrossBefore + structural.offset;
1967         continue;
1968       }
1969       const allocation = { x: 0, y: 0, width: item.targetMain, height: Math.max(0, item.preferredCross - item.paddingCross) };
1970       const baselineRoot = item.baselineRoot ?? item.child;
1971       const definition = getPrimitiveDefinition(baselineRoot.type);
1972       if (!definition?.measureBaselines) {
1973         item.firstBaseline = item.paddingCrossBefore + allocation.height;
1974         continue;
1975       }
1976       const measurementChild = clonePibblElement(baselineRoot);
1977       const measuredStyle: SystemStyle & { width: number; height: number } = { ...item.normalized, width: allocation.width, height: allocation.height };
1978       setPreNormalizedStyle(measurementChild, measuredStyle, baselineRoot, getPrimitiveReceiverToken(baselineRoot) ?? item.receiverToken, item.query);
1979       if (item.query) setPreparedBaselineOwner(measurementChild, container);
1980       // Application-owned fonts can change outside retained layout revisions.
1981       // Query them on each admitted render; only generic Text results are retained.
1982       const cacheOptions: BaselineMeasurementOptions | undefined = region && !item.query && (baselineRoot.type !== Text || genericTextFont(item.normalized)) ? {
1983         cache: region,
1984         token: item.layoutToken ?? item.receiverToken,
1985         key: `${allocationStructuralRevision()}:${allocation.width}:${allocation.height}:${JSON.stringify(measurementStyle(item.normalized))}`,
1986         recordMeasurement: recordWasmMeasurement,
1987       } : undefined;
1988       if (cacheOptions && item.baselineRoot) cacheOptions.source = item.child;
1989       const result = measureBaselineElement(measurementChild, allocation, measurement.service, cacheOptions);
1990       if (result.status === 'unsupported') {
1991         throw childDiagnostic(item.child, 'measureBaselines', 'unsupported', container, `first-baseline alignment requires a baseline result: ${result.reason}`);
1992       }
1993       item.firstBaseline = item.paddingCrossBefore + (options[FLEX_LAST_BASELINE] ? result.last : result.first);
1994     }
1995   }
1996   if (region) {
1997     // Per-item wrapped line cross offsets are produced by the kernel below.
1998     for (const line of lines) { line.crossSize = crossSize; line.crossOffset = 0; }
1999   } else {
2000     resolveLineCrossSizes(lines, crossSize, crossGap, options.alignContent, options.flexWrap === 'wrap');
2001   }
2002 
2003   const crossPlacements = region?.placeCross(items, crossSize, options.alignItems, {
2004     reverse: wrapReverse,
2005     wrap: wrappedRegion ? { gap: crossGap, alignContent: options.alignContent } : undefined,
2006     baseline: options[FLEX_BASELINE_GROUP],
2007     lastBaseline: options[FLEX_LAST_BASELINE],
2008   });
2009   const mainPlacements = region?.placeMain(mainSize, mainGap, options.justifyContent, reverse, hasAutoMainMargins ? items : undefined, stagedIntrinsic?.autoMarginFreeMain);
2010   let mainIndex = 0;
2011   let crossIndex = 0;
2012   for (const line of lines) {
2013     const occupied = mainPlacements ? 0 : line.items.reduce(
2014       (total, item) => total + item.targetMain + item.paddingMain,
2015       Math.max(0, line.items.length - 1) * mainGap,
2016     );
2017     const distribution = mainPlacements ? { start: 0, between: 0 } : distributeAlignment(
2018       options.justifyContent,
2019       mainSize - occupied,
2020       line.items.length,
2021     );
2022     let mainCursor = distribution.start;
2023     for (const item of line.items) {
2024       if (mainPlacements) mainCursor = mainPlacements[mainIndex++];
2025       let outerCross: number;
2026       let crossOffset: number;
2027       if (crossPlacements) {
2028         const placement = crossPlacements[crossIndex++];
2029         outerCross = placement.outerCross;
2030         crossOffset = placement.offset;
2031       } else {
2032         const alignment = effectiveAlignment(item.alignSelf, options.alignItems);
2033         outerCross = item.preferredCross;
2034         if (alignment === 'stretch' && item.crossAuto) {
2035           outerCross = clamp(Math.max(0, line.crossSize - item.paddingCross), item.minCross, item.maxCross) + item.paddingCross;
2036         }
2037         crossOffset = alignmentOffset(alignment, line.crossSize, outerCross);
2038       }
2039       const outerMain = item.targetMain + item.paddingMain;
2040       const x = row ?
2041         container.x + mainCursor + item.relativeX :
2042         container.x + line.crossOffset + crossOffset + item.relativeX;
2043       const layoutY = row ?
2044         container.y + line.crossOffset + crossOffset :
2045         container.y + mainCursor;
2046       const y = layoutY + item.relativeY;
2047       const box = {
2048         x: finiteRelativePlacement(x, 'left', item.child, container),
2049         y: finiteRelativePlacement(y, 'top', item.child, container),
2050         width: row ? outerMain : outerCross,
2051         height: row ? outerCross : outerMain,
2052       };
2053       const usedStyle = {
2054         ...item.normalized,
2055         width: row ? item.targetMain : Math.max(0, outerCross - item.paddingCross),
2056         height: row ? Math.max(0, outerCross - item.paddingCross) : item.targetMain,
2057       };
2058       const element = childWithUsedSize(
2059         item.child,
2060         usedStyle,
2061         usedStyle.width,
2062         usedStyle.height,
2063         item.receiverToken,
2064         item.query,
2065       );
2066       attachPreparedLayoutSlot(element, item.structuralBaselineSlot);
2067       placementsBySource[item.sourceIndex] = {
2068         usedWidth: usedStyle.width,
2069         usedHeight: usedStyle.height,
2070         layoutY: finiteRelativePlacement(layoutY, 'top', item.child, container),
2071         box,
2072         element,
2073       };
2074       mainCursor += outerMain + mainGap + distribution.between;
2075     }
2076   }
2077   for (let sourceIndex = 0; sourceIndex < placementsBySource.length; sourceIndex++) {
2078     if (!placementsBySource[sourceIndex]) throw new Error('Flex placement did not resolve one direct child.');
2079   }
2080   region?.pruneAbsoluteMeasurements(absoluteMeasurementTokens);
2081   return placementsBySource as FlexPlacement[];
2082 }
2083 
2084 function resolveFlexContainingBox(style: Readonly<FlexStyle> | Readonly<ResolvedFlexStyle>, content: Readonly<LayoutBox>): Readonly<LayoutBox> {
2085   const resolved = style as Readonly<Partial<ResolvedFlexStyle>>;
2086   const inherited = resolved[FLEX_INHERITED_CONTAINING_BOX];
2087   if (inherited) return inherited;
2088   const specified = resolved[FLEX_ABSOLUTE_BOX_STYLE] ?? style as Readonly<FlexStyle>;
2089   if (specified.position === 'static') {
2090     return getLogicalContainingBox();
2091   }
2092   return resolveFlexAbsolutePaddingBox(specified, content);
2093 }
2094 
2095 function resolveFlexAbsolutePaddingBox(
2096   style: Readonly<FlexStyle>,
2097   content: Readonly<LayoutBox>,
2098 ): LayoutBox {
2099   const paddingOnly = normalizeBoxInsets({
2100     ...style,
2101     borderWidth: undefined,
2102     borderStartWidth: undefined,
2103     borderEndWidth: undefined,
2104   }, {
2105     component: 'Flex', algorithm: 'flex absolute', constraints: constraintsFor(content),
2106   });
2107   return Object.freeze({
2108     x: content.x - paddingOnly.left,
2109     y: content.y - paddingOnly.top,
2110     width: content.width + paddingOnly.left + paddingOnly.right,
2111     height: content.height + paddingOnly.top + paddingOnly.bottom,
2112   });
2113 }
2114 
2115 export function resolveAbsoluteFlexPlacement(
2116   paddingBox: Readonly<LayoutBox>,
2117   child: PibblElement<any>,
2118   style: Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle>,
2119   receiverToken: object,
2120   query: PreparedQuery | undefined,
2121   content: Readonly<LayoutBox>,
2122   options: Readonly<Pick<ResolvedFlexStyle, 'flexDirection' | 'flexWrap' | 'justifyContent' | 'alignItems' | 'layoutDirection'>>,
2123   measurement?: FlexMeasurementInput,
2124   region?: LayoutRegion,
2125   measurementToken?: object,
2126 ): FlexPlacement {
2127   const left = resolveFlexInset(absoluteLeftInset(style, options.layoutDirection), 'left', child, paddingBox);
2128   const right = resolveFlexInset(absoluteRightInset(style, options.layoutDirection), 'right', child, paddingBox);
2129   const top = resolveFlexInset(style.top, 'top', child, paddingBox);
2130   const bottom = resolveFlexInset(style.bottom, 'bottom', child, paddingBox);
2131   const specifiedWidth = resolveAbsoluteSize(style.width, 'width', paddingBox.width, child, paddingBox);
2132   const specifiedHeight = resolveAbsoluteSize(style.height, 'height', paddingBox.height, child, paddingBox);
2133   const specifiedMinWidth = resolveAbsoluteSize(style.minWidth, 'minWidth', paddingBox.width, child, paddingBox);
2134   const specifiedMaxWidth = resolveAbsoluteSize(style.maxWidth, 'maxWidth', paddingBox.width, child, paddingBox);
2135   const specifiedMinHeight = resolveAbsoluteSize(style.minHeight, 'minHeight', paddingBox.height, child, paddingBox);
2136   const specifiedMaxHeight = resolveAbsoluteSize(style.maxHeight, 'maxHeight', paddingBox.height, child, paddingBox);
2137   const sizingStyle = specifiedWidth === style.width && specifiedHeight === style.height &&
2138     specifiedMinWidth === style.minWidth && specifiedMaxWidth === style.maxWidth &&
2139     specifiedMinHeight === style.minHeight && specifiedMaxHeight === style.maxHeight ? style : {
2140       ...style, width: specifiedWidth, height: specifiedHeight,
2141       minWidth: specifiedMinWidth, maxWidth: specifiedMaxWidth,
2142       minHeight: specifiedMinHeight, maxHeight: specifiedMaxHeight,
2143     };
2144   const automaticWidth = specifiedWidth === undefined || specifiedWidth === 'auto';
2145   const automaticHeight = specifiedHeight === undefined || specifiedHeight === 'auto';
2146   let measuredWidth: number | undefined;
2147   let measuredHeight: number | undefined;
2148   if (measurement) {
2149     const measurementAxis = automaticWidth && automaticHeight ? 'both' : automaticWidth ? 'width' : 'height';
2150     const measuredChild = clonePibblElement(child);
2151     // Text's measure callback uses an omitted natural axis. Keep authored
2152     // automatic dimensions on the original descriptor for final settlement.
2153     const measuredStyle = child.type === Text ? measurementAxis === 'both' ?
2154       { ...sizingStyle, width: undefined, height: undefined } : measurementAxis === 'width' ?
2155         { ...sizingStyle, width: undefined } : { ...sizingStyle, height: undefined } : sizingStyle;
2156     setPreNormalizedStyle(measuredChild, measuredStyle, child, receiverToken, query);
2157     const fixedAxis = measurementAxis === 'both' ? 0 : measurementAxis === 'width' ? specifiedHeight as number : specifiedWidth as number;
2158     const result = measureConstrainedIntrinsicElement(measuredChild, measurementAxis === 'both' ? {
2159       minWidth: 0, maxWidth: Number.POSITIVE_INFINITY, minHeight: 0, maxHeight: Number.POSITIVE_INFINITY,
2160     } : measurementAxis === 'width' ? {
2161       minWidth: 0, maxWidth: Number.POSITIVE_INFINITY, minHeight: fixedAxis, maxHeight: fixedAxis,
2162     } : {
2163       minWidth: fixedAxis, maxWidth: fixedAxis, minHeight: 0, maxHeight: Number.POSITIVE_INFINITY,
2164     }, measurement.service, region && measurementToken ? {
2165       cache: region, token: measurementToken,
2166       key: measurementAxis === 'both' ? `absolute-size:both:${allocationStructuralRevision()}` :
2167         `absolute-size:${measurementAxis}:${allocationStructuralRevision()}:${fixedAxis}`,
2168       recordMeasurement: recordWasmMeasurement,
2169     } : undefined);
2170     if (result.status !== 'measured') {
2171       throw childDiagnostic(child, measurementAxis, 'auto', paddingBox, `absolute natural ${measurementAxis} requires supported pure measurement: ${result.reason}`);
2172     }
2173     if (measurementAxis !== 'height') measuredWidth = result.size.width;
2174     if (measurementAxis !== 'width') measuredHeight = result.size.height;
2175   }
2176   const settledStyle = automaticWidth || automaticHeight ? {
2177     ...sizingStyle,
2178     width: automaticWidth ? measuredWidth ?? resolveAbsoluteAutoSize(left, right, paddingBox.width, 'width', child, paddingBox, sizingStyle.aspectRatio === undefined ? undefined : (specifiedHeight as number) * sizingStyle.aspectRatio) : specifiedWidth,
2179     height: automaticHeight ? measuredHeight ?? resolveAbsoluteAutoSize(top, bottom, paddingBox.height, 'height', child, paddingBox, sizingStyle.aspectRatio === undefined ? undefined : (specifiedWidth as number) / sizingStyle.aspectRatio) : specifiedHeight,
2180   } : sizingStyle;
2181   if (automaticWidth || automaticHeight) markDerivedAbsoluteAxes(settledStyle, automaticWidth, automaticHeight);
2182   const resolved = resolveDirectChildBox(paddingBox, child, 'absolute', settledStyle, undefined, receiverToken);
2183   const width = resolved.borderBox.width;
2184   const height = resolved.borderBox.height;
2185   const row = isRowDirection(options.flexDirection);
2186   const mainReversed = (options.flexDirection === 'row-reverse' || options.flexDirection === 'column-reverse') !==
2187     (row && options.layoutDirection === 'rtl');
2188   const crossReversed = (options.flexWrap === 'wrap-reverse') !== (!row && options.layoutDirection === 'rtl');
2189   const x = left !== undefined || right !== undefined ?
2190     options.layoutDirection === 'rtl'
2191       ? right === undefined ? paddingBox.x + left! : paddingBox.x + paddingBox.width - right - width
2192       : left === undefined ? paddingBox.x + paddingBox.width - right! - width : paddingBox.x + left :
2193     row ? resolveAbsoluteMainAlignment(content, width, options.justifyContent, mainReversed, true) :
2194       resolveAbsoluteCrossAlignment(content, width, options.alignItems, crossReversed, false);
2195   const y = top !== undefined || bottom !== undefined ?
2196     top === undefined ? paddingBox.y + paddingBox.height - bottom! - height : paddingBox.y + top :
2197     row ? resolveAbsoluteCrossAlignment(content, height, options.alignItems, crossReversed, true) :
2198       resolveAbsoluteMainAlignment(content, height, options.justifyContent, mainReversed, false);
2199   const usedWidth = resolved.contentBox.width;
2200   const usedHeight = resolved.contentBox.height;
2201   return {
2202     box: { x: finiteRelativePlacement(x, 'left', child, paddingBox), y: finiteRelativePlacement(y, 'top', child, paddingBox), width, height },
2203     usedWidth,
2204     usedHeight,
2205     layoutY: finiteRelativePlacement(y, 'top', child, paddingBox),
2206     element: childWithUsedSize(child, settledStyle, usedWidth, usedHeight, receiverToken, query),
2207   };
2208 }
2209 
2210 function resolveAbsoluteAutoSize(
2211   start: number | undefined,
2212   end: number | undefined,
2213   available: number,
2214   property: 'width' | 'height',
2215   child: PibblElement<any>,
2216   container: Readonly<LayoutBox>,
2217   aspectSize?: number,
2218 ): number {
2219   if ((start === undefined || end === undefined) && aspectSize === undefined) {
2220     throw childDiagnostic(child, property, 'auto', container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: automatic absolute size requires opposing physical insets or one definite aspect-ratio axis');
2221   }
2222   // Opposing insets win; otherwise use the declared opposite axis before bounds.
2223   const size = start !== undefined && end !== undefined ? available - start - end : aspectSize!;
2224   if (!Number.isFinite(size)) {
2225     throw childDiagnostic(child, property, size, container, 'derived absolute size must remain finite');
2226   }
2227   return Math.max(0, size);
2228 }
2229 
2230 function resolveAbsoluteMainAlignment(
2231   content: Readonly<LayoutBox>,
2232   size: number,
2233   justifyContent: MainAlignment,
2234   reversed: boolean,
2235   horizontal: boolean,
2236 ): number {
2237   let alignment: CrossAlignment = justifyContent === 'flex-end' ? 'flex-end' :
2238     justifyContent === 'flex-start' || justifyContent === 'space-between' ? 'flex-start' : 'center';
2239   if (reversed) {
2240     if (alignment === 'flex-start') alignment = 'flex-end';
2241     else if (alignment === 'flex-end') alignment = 'flex-start';
2242   }
2243   return horizontal ? content.x + alignmentOffset(alignment, content.width, size) :
2244     content.y + alignmentOffset(alignment, content.height, size);
2245 }
2246 
2247 function resolveAbsoluteCrossAlignment(
2248   content: Readonly<LayoutBox>,
2249   size: number,
2250   alignItems: CrossAlignment,
2251   reversed: boolean,
2252   vertical: boolean,
2253 ): number {
2254   let alignment: CrossAlignment = alignItems === 'stretch' ? 'flex-start' : alignItems;
2255   if (reversed) {
2256     if (alignment === 'flex-start') alignment = 'flex-end';
2257     else if (alignment === 'flex-end') alignment = 'flex-start';
2258   }
2259   return vertical ? content.y + alignmentOffset(alignment, content.height, size) :
2260     content.x + alignmentOffset(alignment, content.width, size);
2261 }
2262 
2263 function genericTextFont(style: Readonly<Record<string, unknown>>): boolean {
2264   return isGenericCanvasFont(String(style.font ?? '13px sans-serif'));
2265 }
2266 function measurementStyle(style: Readonly<Record<string, unknown>>) {
2267   const { fill: _fill, stroke: _stroke, opacity: _opacity, cursor: _cursor, filter: _filter, ...metrics } = style;
2268   // Rest construction owns this fresh snapshot; normalize geometry-equivalent axes.
2269   const owned = metrics as Record<string, unknown>;
2270   if (owned.flexDirection === 'row-reverse') owned.flexDirection = 'row';
2271   else if (owned.flexDirection === 'column-reverse') owned.flexDirection = 'column';
2272   return owned;
2273 }
2274 
2275 // Resolve every receiver even on cache hits so normal traversal adopts current
2276 // subscriptions. Retain only scalar snapshots, never descriptors or provisions.
2277 function intrinsicTextSnapshot(child: PibblElement<any>, style: Readonly<BoxStyle & Record<string, unknown>>, constraints: Constraints): unknown[] | undefined {
2278   if (child.type !== Flex || !isColumnDirection(style.flexDirection) || (style.flexWrap ?? 'nowrap') !== 'nowrap' ||
2279     typeof style.width !== 'number' || (style.height !== undefined && style.height !== 'auto')) return;
2280   return withSignalWriteForbidden('Signal writes are forbidden during Pibbl measurement', () => withIsolatedRenderState(() => {
2281     const previous = GLOBAL_STATE.primitiveReceiverToken;
2282     const visiting = new Set<PibblElement<any>>();
2283     function visit(column: PibblElement<any>, columnStyle: Readonly<Record<string, unknown>>, parent: object | undefined, width: number): unknown[] | undefined {
2284       if (visiting.has(column)) return;
2285       visiting.add(column);
2286       GLOBAL_STATE.primitiveReceiverToken = parent;
2287       try {
2288         const snapshot: unknown[] = [];
2289         for (const [index, leaf] of prepareLayoutChildren(column.props.children, 'Flex').entries()) {
2290           const receiver = getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, parent, index);
2291           const prepared = prepareDirectChildStyle(leaf, receiver, { x: 0, y: 0, width, height: constraints.maxHeight });
2292           const leafStyle = preparedStyleValue(prepared) as Readonly<BoxStyle & Record<string, unknown>>;
2293           if (preparedStyleQuery(prepared) || hasPercentageBounds(leafStyle) || isPercentage(leafStyle.width) || isPercentage(leafStyle.height)) return;
2294           let content: unknown;
2295           if (leaf.type === Text) {
2296             if (!genericTextFont(leafStyle)) return;
2297             content = prepareLayoutTextContent(leaf.props, { receiverToken: receiver });
2298           } else if (leaf.type === Flex && isColumnDirection(leafStyle.flexDirection) && (leafStyle.flexWrap ?? 'nowrap') === 'nowrap' && (leafStyle.height === undefined || leafStyle.height === 'auto')) {
2299             const padding = normalizeBoxInsets(leafStyle, childContext(leaf, { x: 0, y: 0, width, height: constraints.maxHeight }));
2300             const available = typeof leafStyle.width === 'number' ? leafStyle.width : Math.max(0, width-padding.left-padding.right);
2301             const usedWidth = clamp(available, typeof leafStyle.minWidth === 'number' ? leafStyle.minWidth : 0, typeof leafStyle.maxWidth === 'number' ? leafStyle.maxWidth : Infinity);
2302             content = visit(leaf, leafStyle, receiver, usedWidth);
2303             if (content === undefined) return;
2304           } else {
2305             // Opaque components participate only by already-declared finite sizes.
2306             if (typeof leafStyle.width !== 'number' || typeof leafStyle.height !== 'number' || !Number.isFinite(leafStyle.width) || !Number.isFinite(leafStyle.height)) return;
2307             content = null;
2308           }
2309           snapshot.push([leaf.key, content, measurementStyle(leafStyle)]);
2310           GLOBAL_STATE.primitiveReceiverToken = parent;
2311         }
2312         return [measurementStyle(columnStyle), snapshot];
2313       } finally { visiting.delete(column); GLOBAL_STATE.primitiveReceiverToken = parent; }
2314     }
2315     try { return visit(child, style, getPrimitiveReceiverToken(child), style.width as number); }
2316     finally { GLOBAL_STATE.primitiveReceiverToken = previous; }
2317   }));
2318 }
2319 
2320 interface PreparedRowMeasurement {
2321   readonly snapshot: readonly unknown[];
2322   readonly receivers: readonly object[];
2323 }
2324 
2325 // This snapshot is intentionally stricter than the ordinary primitive snapshot:
2326 // a layout description can otherwise hide mutable leaf props behind its own stable
2327 // descriptor. It records every direct leaf's identity and resolved full style, so
2328 // cache reuse never bypasses a provider-visible paint/style or program input.
2329 function preparedRowMeasurement(
2330   child: PibblElement<any>,
2331   style: Readonly<BoxStyle & Record<string, unknown>>,
2332 ): PreparedRowMeasurement | undefined {
2333   try { return withSignalWriteForbidden('Signal writes are forbidden during Pibbl measurement', () =>
2334     withStyleMeasurement('recursive', () => withIsolatedRenderState(() => {
2335       const previous = GLOBAL_STATE.primitiveReceiverToken;
2336       try {
2337         const root = prepareLayoutComponent(child);
2338         if (root.type !== Flex) return;
2339         const rootReceiver = getPrimitiveReceiverToken(root);
2340         if (!rootReceiver) return;
2341         GLOBAL_STATE.primitiveReceiverToken = rootReceiver;
2342         const rootStyle = style as Readonly<FlexStyle & Record<string, unknown>>;
2343         if ((rootStyle.flexDirection ?? 'row') !== 'row' ||
2344           (rootStyle.flexWrap ?? 'nowrap') !== 'nowrap' ||
2345           (rootStyle.layoutDirection ?? getLayoutDirection()) !== 'ltr' ||
2346           typeof rootStyle.width !== 'number' || !Number.isFinite(rootStyle.width) || rootStyle.width < 0 ||
2347           rootStyle.height !== undefined && rootStyle.height !== 'auto') return;
2348         const snapshot: unknown[] = ['prepared-row', root.type, root.key];
2349         if (!appendPreparedProgramSnapshot(snapshot, getPrimitiveProgramProps(child))) return;
2350         if (!appendPreparedProgramSnapshot(snapshot, getPrimitiveProgramProps(root), true)) return;
2351         if (!appendPreparedStyleSnapshot(snapshot, rootStyle)) return;
2352         const children = prepareLayoutChildren(root.props.children, 'Flex');
2353         snapshot.push(children.length);
2354         const receivers: object[] = [];
2355         for (let index = 0; index < children.length; index++) {
2356           const leaf = children[index];
2357           const directReceiver = getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, rootReceiver, index);
2358           const directPrepared = prepareDirectChildStyle(leaf, directReceiver, undefined, true);
2359           if (preparedStyleQuery(directPrepared)) return;
2360           const directStyle = preparedStyleValue(directPrepared) as Readonly<
2361             BoxStyle & FlexItemStyle & LayoutItemStyle & Record<string, unknown>
2362           >;
2363           let measuredLeaf = leaf;
2364           let receiver = directReceiver;
2365           let wrapped = false;
2366           if (isLayoutComponent(leaf.type)) {
2367             // One transparent known description is enough for the 164 receipt:
2368             // snapshot both layers and replay the paired root's current receiver.
2369             // A second description would need a recursive receipt path.
2370             measuredLeaf = prepareLayoutComponent(leaf, { receiverToken: directReceiver });
2371             if (isLayoutComponent(measuredLeaf.type)) return;
2372             const preparedReceiver = getPrimitiveReceiverToken(measuredLeaf);
2373             if (!preparedReceiver) return;
2374             receiver = preparedReceiver;
2375             wrapped = true;
2376           }
2377           const paired = getPrimitiveDefinition(measuredLeaf.type);
2378           const emptyRectangle = !wrapped && measuredLeaf.type === Rectangle &&
2379             !Object.hasOwn(measuredLeaf.props, 'children');
2380           if (!emptyRectangle && !(paired?.measureIntrinsic && paired.measure)) return;
2381           if (!appendPreparedProgramSnapshot(snapshot, getPrimitiveProgramProps(leaf)) ||
2382             !appendPreparedStyleSnapshot(snapshot, directStyle) ||
2383             wrapped && !appendPreparedProgramSnapshot(snapshot, getPrimitiveProgramProps(measuredLeaf))) return;
2384           snapshot.push(index, leaf.type, leaf.key, wrapped, measuredLeaf.type, measuredLeaf.key);
2385           receivers.push(receiver);
2386         }
2387         return { snapshot, receivers };
2388       } finally {
2389         GLOBAL_STATE.primitiveReceiverToken = previous;
2390       }
2391     })),
2392   ); } catch (error) {
2393     if (error instanceof UnsupportedResponsiveMeasurement) return undefined;
2394     throw error;
2395   }
2396 }
2397 
2398 function appendPreparedProgramSnapshot(
2399   snapshot: unknown[],
2400   props: Readonly<Record<PropertyKey, unknown>>,
2401   omitChildren = false,
2402 ): boolean {
2403   const keys = Reflect.ownKeys(props);
2404   let count = 0;
2405   for (let index = 0; index < keys.length; index++) if (!omitChildren || keys[index] !== 'children') count++;
2406   snapshot.push(count);
2407   for (let index = 0; index < keys.length; index++) {
2408     const key = keys[index];
2409     if (omitChildren && key === 'children') continue;
2410     const value = props[key];
2411     if (typeof value === 'function' || value !== null && typeof value === 'object' && !isSignal(value)) return false;
2412     snapshot.push(key, value);
2413   }
2414   return true;
2415 }
2416 
2417 function appendPreparedStyleSnapshot(snapshot: unknown[], style: Readonly<Record<PropertyKey, unknown>>): boolean {
2418   const keys = Reflect.ownKeys(style);
2419   snapshot.push(keys.length);
2420   for (let index = 0; index < keys.length; index++) {
2421     const key = keys[index];
2422     const value = style[key];
2423     if (typeof value === 'function' || value !== null && typeof value === 'object') return false;
2424     snapshot.push(key, value);
2425   }
2426   return true;
2427 }
2428 
2429 function currentFlexMeasurementInput(): FlexMeasurementInput {
2430   const context = GLOBAL_STATE.renderContext;
2431   if (!context) throw new Error('A mounted Flex query requires its current Canvas context.');
2432   const service = canvasMeasurementService(context);
2433   return { service, measureElement: (element, constraints) => measureElement(element, constraints, service) };
2434 }
2435 function bindFlexMeasurementInput(input: FlexMeasurementInput): () => FlexMeasurementInput {
2436   return isCurrentCanvasMeasurementService(input.service) ? currentFlexMeasurementInput : () => input;
2437 }
2438 
2439 function measureTextIntrinsicWidths(child: PibblElement<any>, style: Readonly<SystemStyle>, receiver: object, measurement: FlexMeasurementInput, region?: LayoutRegion): { minimum: number; maximum: number } {
2440   const resolveMeasurement = bindFlexMeasurementInput(measurement);
2441   const element = clonePibblElement(child);
2442   setPreNormalizedStyle(element, style, child, receiver);
2443   return allocationMeasurement(element, current => {
2444     const measurement = resolveMeasurement();
2445     const normalized = peekPreNormalizedStyle(current)!.style as Readonly<TextStyle>;
2446     const receiverToken = getPrimitiveReceiverToken(current);
2447     const font = normalized.font ?? '13px sans-serif';
2448     const content = prepareLayoutTextContent(current.props, { receiverToken });
2449     if (region) recordWasmMeasurement();
2450     const maximum = normalized.wrap === true ? measureLayoutTextNaturalRun(content, { font, service: measurement.service }) : measurement.service.measureText(content, font).width;
2451     const minimum = normalized.wrap === true ? measureLayoutTextMinimumWidth(current.props, { font, service: measurement.service, receiverToken }) : maximum;
2452     return { minimum, maximum };
2453   });
2454 }
2455 function measureTextContentMinimum(child: PibblElement<any>, style: Readonly<SystemStyle>, receiver: object, measurement: FlexMeasurementInput, region?: LayoutRegion): number {
2456   const resolveMeasurement = bindFlexMeasurementInput(measurement);
2457   const element = clonePibblElement(child);
2458   setPreNormalizedStyle(element, style, child, receiver);
2459   return allocationMeasurement(element, current => {
2460     const measurement = resolveMeasurement();
2461     const normalized = peekPreNormalizedStyle(current)!.style as Readonly<TextStyle>;
2462     const receiverToken = getPrimitiveReceiverToken(current);
2463     const font = normalized.font ?? '13px sans-serif';
2464     if (region) recordWasmMeasurement();
2465     return normalized.wrap === true ? measureLayoutTextMinimumWidth(current.props, { font, service: measurement.service, receiverToken }) :
2466       measurement.service.measureText(prepareLayoutTextContent(current.props, { receiverToken }), font).width;
2467   });
2468 }
2469 function measureTextNaturalWidth(child: PibblElement<any>, style: Readonly<SystemStyle>, receiver: object, token: object, measurement: FlexMeasurementInput, region?: LayoutRegion): number {
2470   const resolveMeasurement = bindFlexMeasurementInput(measurement);
2471   const element = clonePibblElement(child);
2472   setPreNormalizedStyle(element, style, child, receiver);
2473   return allocationMeasurement(element, current => {
2474     const measurement = resolveMeasurement();
2475     const normalized = peekPreNormalizedStyle(current)!.style as Readonly<TextStyle>;
2476     const receiverToken = getPrimitiveReceiverToken(current);
2477     const font = normalized.font ?? '13px sans-serif';
2478     const content = prepareLayoutTextContent(current.props, { receiverToken });
2479     let width = genericTextFont(normalized) ? region?.readTextMaximum(token, content, font) : undefined;
2480     if (width === undefined) {
2481       if (region) recordWasmMeasurement();
2482       width = normalized.wrap === true ? measureLayoutTextNaturalRun(content, { font, service: measurement.service }) : measurement.service.measureText(content, font).width;
2483       if (genericTextFont(normalized)) region?.writeTextMaximum(token, content, font, width);
2484     }
2485     return width;
2486   });
2487 }
2488 
2489 function prepareLayoutTextContent(props: Parameters<typeof readLayoutTextContent>[0], options: Parameters<typeof readLayoutTextContent>[1]): string {
2490   declineUnrecordedAllocationMeasurement();
2491   return readLayoutTextContent(props, options);
2492 }
2493 
2494 function measureFlexChild(
2495   child: PibblElement<any>, constraints: Constraints,
2496   style: Readonly<BoxStyle & Record<string, unknown>>, token: object,
2497   measurement: FlexMeasurementInput, region?: LayoutRegion, query?: PreparedQuery, constrainedProvider = false,
2498   parentMainAxis?: 'row' | 'column', ordinaryProvider = false,
2499 ): MeasureResult {
2500   const resolveMeasurement = bindFlexMeasurementInput(measurement);
2501   return allocationMeasurement(child, current => measureFlexChildUncached(current, constraints,
2502     (peekPreNormalizedStyle(current)?.style ?? style) as Readonly<BoxStyle & Record<string, unknown>>,
2503     token, resolveMeasurement(), region, query, constrainedProvider, parentMainAxis, ordinaryProvider));
2504 }
2505 
2506 function measureFlexChildUncached(
2507   child: PibblElement<any>, constraints: Constraints,
2508   style: Readonly<BoxStyle & Record<string, unknown>>, token: object,
2509   measurement: FlexMeasurementInput, region?: LayoutRegion, query?: PreparedQuery, constrainedProvider = false,
2510   parentMainAxis?: 'row' | 'column', ordinaryProvider = false,
2511 ): MeasureResult {
2512   const measuredRoot = !query && isLayoutComponent(child.type) && (constrainedProvider || ordinaryProvider || parentMainAxis !== undefined) ?
2513     prepareLayoutComponent(child) : child;
2514   // `style` is the direct-placement normalized style, including the described
2515   // Flex root's forwarded values. Do not reread authored component props here:
2516   // signals or callbacks there would describe a different phase.
2517   const rootAxis = style.flexDirection === 'column' || style.flexDirection === 'column-reverse' ? 'column' : 'row';
2518   const contributionReceiver = parentMainAxis !== undefined && measuredRoot.type === Flex && rootAxis === parentMainAxis ?
2519     getPrimitiveReceiverToken(measuredRoot) : undefined;
2520   // The prepared-row cache is a normal final-size result. A same-axis
2521   // contribution has a distinct native result contract and must bypass it.
2522   if (contributionReceiver) {
2523     const previousContribution = requestedIntrinsicContribution;
2524     requestedIntrinsicContribution = { receiver: contributionReceiver, axis: parentMainAxis!, normalOwner: true };
2525     try {
2526       if (region) recordWasmMeasurement();
2527       return measurement.measureElement(child, constraints);
2528     } finally {
2529       requestedIntrinsicContribution = previousContribution;
2530     }
2531   }
2532   // A direct paired primitive keeps the original descriptor as the receiver
2533   // boundary. A described row uses the same parent-region entry, but only after a
2534   // conservative structural snapshot has established fresh direct-child receiver
2535   // paths for receipt replay on a later transaction.
2536   if (region && !query && isLayoutComponent(child.type)) {
2537     const prepared = preparedRowMeasurement(child, style);
2538     if (prepared) {
2539       return measurePreparedLayoutElement(child, constraints, measurement.service, {
2540         cache: region,
2541         token,
2542         key: JSON.stringify(['prepared-row', allocationStructuralRevision(), measurementStyle(style), constraints]),
2543         recordMeasurement: recordWasmMeasurement,
2544       }, prepared.snapshot, prepared.receivers);
2545     }
2546   }
2547   const definition = (constrainedProvider || ordinaryProvider) && !query ? getPrimitiveDefinition(measuredRoot.type) : undefined;
2548   if (measuredRoot.type !== Text && !isKnownLayoutType(measuredRoot.type) && definition?.measure && (definition.measureIntrinsic || ordinaryProvider)) return measureConstrainedIntrinsicElement(child, constraints, measurement.service, region ? { cache: region, token, key: JSON.stringify([allocationStructuralRevision(), measurementStyle(style), constraints]), recordMeasurement: recordWasmMeasurement } : undefined);
2549   const content = region && child.type === Text ? prepareLayoutTextContent(
2550     child.props, { receiverToken: getPrimitiveReceiverToken(child) },
2551   ) : undefined;
2552   const intrinsic = region && !query ? intrinsicTextSnapshot(child, style, constraints) : undefined;
2553   const cacheable = !query && (content !== undefined && genericTextFont(style) || intrinsic !== undefined);
2554   const key = cacheable ? JSON.stringify([content, intrinsic, measurementStyle(style), constraints]) : undefined;
2555   const cached = key ? region!.readMeasurement(token, key) : undefined;
2556   if (cached) return { status: 'measured', size: cached };
2557   if (region) recordWasmMeasurement();
2558   const result = measurement.measureElement(child, constraints);
2559   if (key && result.status === 'measured') region!.writeMeasurement(token, key, result.size);
2560   return result;
2561 }
2562 
2563 function collectLines(
2564   items: readonly FlexItem[],
2565   mainSize: number,
2566   gap: number,
2567   wrap: FlexWrap,
2568 ): FlexLine[] {
2569   const lines: FlexLine[] = [];
2570   let current: FlexItem[] = [];
2571   let occupied = 0;
2572   for (const item of items) {
2573     const hypothetical = clamp(item.baseMain, item.minMain, item.maxMain) +
2574       item.paddingMain;
2575     const next = current.length === 0 ? hypothetical : occupied + gap + hypothetical;
2576     if (wrap === 'wrap' && current.length > 0 && next > mainSize) {
2577       lines.push({ items: current, crossSize: 0, crossOffset: 0 });
2578       current = [];
2579       occupied = 0;
2580     }
2581     occupied = current.length === 0 ? hypothetical : occupied + gap + hypothetical;
2582     current.push(item);
2583   }
2584   if (current.length > 0) {
2585     lines.push({ items: current, crossSize: 0, crossOffset: 0 });
2586   }
2587   return lines;
2588 }
2589 
2590 function resolveFlexibleLengths(
2591   line: FlexLine,
2592   mainSize: number,
2593   gap: number,
2594 ): void {
2595   const gapSpace = Math.max(0, line.items.length - 1) * gap;
2596   const hypotheticalOuter = line.items.reduce(
2597     (total, item) => total +
2598       clamp(item.baseMain, item.minMain, item.maxMain) + item.paddingMain,
2599     0,
2600   );
2601   const growing = hypotheticalOuter + gapSpace < mainSize;
2602   let initialOuter = gapSpace;
2603   const frozen = new Set<FlexItem>();
2604   for (const item of line.items) {
2605     item.targetMain = item.baseMain;
2606     const hypothetical = clamp(item.baseMain, item.minMain, item.maxMain);
2607     if (
2608       (growing ? item.grow : item.shrink) === 0 ||
2609       (growing && item.baseMain > hypothetical) ||
2610       (!growing && item.baseMain < hypothetical)
2611     ) {
2612       item.targetMain = hypothetical;
2613       frozen.add(item);
2614     }
2615     initialOuter += item.targetMain + item.paddingMain;
2616   }
2617   const initialFree = mainSize - initialOuter;
2618   if (!Number.isFinite(initialFree)) throw new Error('Flex numeric overflow during allocation');
2619 
2620   while (frozen.size < line.items.length) {
2621     const fixed = line.items.reduce(
2622       (total, item) => total +
2623         (frozen.has(item) ? item.targetMain : item.baseMain) +
2624         item.paddingMain,
2625       gapSpace,
2626     );
2627     let free = mainSize - fixed;
2628     const unfrozen = line.items.filter(item => !frozen.has(item));
2629     const rawFactor = growing ?
2630       unfrozen.reduce((total, item) => total + item.grow, 0) :
2631       unfrozen.reduce((total, item) => total + item.shrink, 0);
2632     const maxFactor = unfrozen.reduce((max, item) => Math.max(max, growing ? item.grow : item.shrink), 0);
2633     const maxBasis = growing ? 1 : unfrozen.reduce((max, item) => Math.max(max, item.baseMain), 0);
2634     const weight = (item: FlexItem) => maxFactor === 0 || maxBasis === 0 ? 0 :
2635       ((growing ? item.grow : item.shrink) / maxFactor) *
2636       (growing ? 1 : item.baseMain / maxBasis);
2637     const scaledFactor = unfrozen.reduce((total, item) => total + weight(item), 0);
2638     if (scaledFactor === 0) {
2639       for (const item of unfrozen) {
2640         item.targetMain = clamp(item.baseMain, item.minMain, item.maxMain);
2641         frozen.add(item);
2642       }
2643       break;
2644     }
2645     if (rawFactor < 1) {
2646       const partialFree = initialFree * rawFactor;
2647       if (Math.abs(partialFree) < Math.abs(free)) free = partialFree;
2648     }
2649     const violations: { item: FlexItem; amount: number }[] = [];
2650     for (const item of unfrozen) {
2651       const share = weight(item) / scaledFactor;
2652       const candidate = item.baseMain + free * share;
2653       if (!Number.isFinite(candidate)) throw new Error('Flex numeric overflow during allocation');
2654       const clamped = clamp(candidate, item.minMain, item.maxMain);
2655       item.targetMain = clamped;
2656       if (clamped !== candidate) {
2657         violations.push({ item, amount: clamped - candidate });
2658       }
2659     }
2660     if (violations.length === 0) break;
2661     const totalViolation = violations.reduce(
2662       (total, violation) => total + violation.amount,
2663       0,
2664     );
2665     for (const violation of violations) {
2666       if (
2667         totalViolation === 0 ||
2668         (totalViolation > 0 && violation.amount > 0) ||
2669         (totalViolation < 0 && violation.amount < 0)
2670       ) {
2671         frozen.add(violation.item);
2672       }
2673     }
2674   }
2675 }
2676 
2677 function resolveLineCrossSizes(
2678   lines: FlexLine[],
2679   crossSize: number,
2680   gap: number,
2681   alignment: ResolvedFlexStyle['alignContent'],
2682   multiLine: boolean,
2683 ): void {
2684   if (lines.length === 0) return;
2685   for (const line of lines) {
2686     line.crossSize = Math.max(0, ...line.items.map(item => item.preferredCross));
2687   }
2688   if (lines.length === 1 && !multiLine) {
2689     lines[0].crossSize = crossSize;
2690     lines[0].crossOffset = 0;
2691     return;
2692   }
2693   const occupied = lines.reduce(
2694     (total, line) => total + line.crossSize,
2695     Math.max(0, lines.length - 1) * gap,
2696   );
2697   const free = crossSize - occupied;
2698   if (alignment === 'stretch' && free > 0) {
2699     const addition = free / lines.length;
2700     for (const line of lines) line.crossSize += addition;
2701   }
2702   const distribution = alignment === 'stretch' ?
2703     { start: 0, between: 0 } :
2704     distributeAlignment(alignment, free, lines.length);
2705   let cursor = distribution.start;
2706   for (const line of lines) {
2707     line.crossOffset = cursor;
2708     cursor += line.crossSize + gap + distribution.between;
2709   }
2710 }
2711 
2712 function distributeAlignment(
2713   alignment: MainAlignment | CrossAlignment,
2714   free: number,
2715   count: number,
2716 ): { start: number; between: number } {
2717   if (count === 0 || alignment === 'flex-start' || alignment === 'stretch') {
2718     return { start: 0, between: 0 };
2719   }
2720   if (free < 0) {
2721     if (alignment === 'flex-end') return { start: free, between: 0 };
2722     if (alignment === 'center') {
2723       return { start: free / 2, between: 0 };
2724     }
2725     return { start: 0, between: 0 };
2726   }
2727   if (alignment === 'flex-end') return { start: free, between: 0 };
2728   if (alignment === 'center') return { start: free / 2, between: 0 };
2729   if (alignment === 'space-between') {
2730     return count === 1 ? { start: 0, between: 0 } :
2731       { start: 0, between: free / (count - 1) };
2732   }
2733   if (alignment === 'space-around') {
2734     const between = free / count;
2735     return { start: between / 2, between };
2736   }
2737   if (alignment === 'space-evenly') {
2738     const between = free / (count + 1);
2739     return { start: between, between };
2740   }
2741   return { start: 0, between: 0 };
2742 }
2743 
2744 function prepareKnownStructuralBaseline(
2745   item: FlexItem,
2746   container: Readonly<LayoutBox>,
2747   measurement: FlexMeasurementInput,
2748   parentSlot?: PreparedLayoutSlot,
2749   lastSource = false,
2750 ): PreparedKnownBaseline | undefined {
2751   const root = item.baselineRoot ?? item.child;
2752   if (root.type !== Flex && root.type !== Flow && root.type !== Grid) return;
2753   const resolveMeasurement = bindFlexMeasurementInput(measurement);
2754   const { targetMain, preferredCross, paddingCross, layoutOccurrence } = item;
2755   const child = clonePibblElement(item.child);
2756   setPreNormalizedStyle(child, item.normalized, item.child, item.receiverToken, item.query);
2757   const offset = allocationMeasurement(child, current => {
2758     const normalized = peekPreNormalizedStyle(current)!.style;
2759     const receiverToken = getPrimitiveReceiverToken(current);
2760     if (!receiverToken) throw new Error('A structural baseline query requires its current receiver.');
2761     const baselineRoot = isLayoutComponent(current.type) ? prepareLayoutComponent(current, { receiverToken }) : current;
2762     return prepareKnownStructuralBaselineUncached({ child: current, normalized, receiverToken, baselineRoot,
2763       targetMain, preferredCross, paddingCross, layoutOccurrence }, container, resolveMeasurement(), parentSlot, lastSource).offset;
2764   });
2765   const slot = currentPreparedReceiverSlot(item.receiverToken);
2766   if (!slot) throw new Error('A structural baseline demand must stage its current receiver allocation.');
2767   return { slot, offset };
2768 }
2769 
2770 function prepareKnownStructuralBaselineUncached(
2771   item: Pick<FlexItem, 'child' | 'normalized' | 'receiverToken' | 'baselineRoot' | 'targetMain' | 'preferredCross' | 'paddingCross' | 'layoutOccurrence'>,
2772   container: Readonly<LayoutBox>, measurement: FlexMeasurementInput, parentSlot: PreparedLayoutSlot | undefined, lastSource: boolean,
2773 ): PreparedKnownBaseline {
2774   const alignment = lastSource ? 'last-baseline' : 'first-baseline';
2775   const root = item.baselineRoot ?? item.child;
2776   const style = item.normalized as Readonly<FlexStyle>;
2777   const staticOwner = root.type === Flex && style.position === 'static';
2778   const content = { x: 0, y: 0, width: item.targetMain, height: Math.max(0, item.preferredCross - item.paddingCross) };
2779   const direction = style.layoutDirection ?? getLayoutDirection();
2780   const currentSlot = currentPreparedReceiverSlot(item.receiverToken);
2781   const currentPlan = currentSlot && peekPreparedLayoutPlan(currentSlot, content, direction);
2782   // A failed equality comparison may already have prepared this exact demand.
2783   // The ensuing allocator consumes that current plan instead of staging it twice.
2784   const slot = currentPlan ? currentSlot : preflightKnownLayout(item.child, item.normalized, content, item.receiverToken, item.layoutOccurrence, parentSlot, 'row',
2785     staticOwner ? { deferStaticContainingDescendants: true } : undefined);
2786   if (!slot) throw childDiagnostic(item.child, 'alignItems', alignment, container,
2787     'PIBBL_LAYOUT_UNSUPPORTED_BASELINE: the selected known layout root did not prepare its allocation');
2788   const plan = root.type === Flex ?
2789     peekPreparedFlexPlan(slot, content, direction) :
2790     peekPreparedLayoutPlan(slot, content, direction);
2791   if (!plan) throw childDiagnostic(item.child, 'alignItems', alignment, container,
2792     'PIBBL_LAYOUT_UNSUPPORTED_BASELINE: the selected known layout root has no current settled allocation');
2793   return { slot, offset: readPreparedKnownBaseline(plan, root.type === Flex ? 'flex' : root.type === Flow ? 'flow' : 'grid', measurement, direction,
2794     root.type === Flex && (style.flexWrap ?? 'nowrap') !== 'nowrap', lastSource) };
2795 }
2796 
2797 /** Reads current prepared source-order placements without a second layout pass. */
2798 function readPreparedKnownBaseline(
2799   plan: PreparedLayoutPlan,
2800   kind: 'flex' | 'flow' | 'grid',
2801   measurement: FlexMeasurementInput,
2802   direction: 'ltr' | 'rtl',
2803   wrapped: boolean,
2804   lastSource: boolean,
2805 ): number {
2806   const alignment = lastSource ? 'last-baseline' : 'first-baseline';
2807   const content = plan.content;
2808   // Native Flow and Grid retain declared record order. Flex's current native
2809   // first/final-line proof establishes membership without inferring pixel lines.
2810   const flexPlan = kind === 'flex' ? plan as PreparedFlexLayoutPlan : undefined;
2811   const lineCount = wrapped ? lastSource ? flexPlan!.region.lastWrapLineCount() : flexPlan!.region.firstWrapLineCount() : undefined;
2812   const pending = flexPlan ? deferredStaticState(flexPlan) : undefined;
2813   const step = lastSource ? -1 : 1;
2814   for (let index = lastSource ? plan.children.length - 1 : 0; index >= 0 && index < plan.children.length; index += step) {
2815     if (pending?.slots[index]) continue;
2816     const source = plan.children[index];
2817     const placement = plan.placements[index];
2818     const prepared = peekPreNormalizedStyle(placement.element);
2819     if (!prepared) throw new Error('Known Flex baseline selection requires settled child inputs.');
2820     const selectedStyle = prepared.style as Readonly<FlexStyle>;
2821     if (selectedStyle.position === 'absolute') continue;
2822     // Skipping absolute/deferred slots preserves in-flow source order. The
2823     // selected endpoint is native record zero or the final native record, and
2824     // therefore belongs to the validated corresponding endpoint line.
2825     if (lineCount === 0) throw new Error('Structural baseline source has no native endpoint-line membership.');
2826     const receiver = getPrimitiveReceiverToken(placement.element);
2827     const root = isLayoutComponent(source.type) ? prepareLayoutComponent(source, { receiverToken: receiver }) : placement.element;
2828     const usedWidth = 'usedWidth' in placement ? placement.usedWidth : undefined;
2829     const usedHeight = 'usedHeight' in placement ? placement.usedHeight : undefined;
2830     if (typeof usedWidth !== 'number' || !Number.isFinite(usedWidth) || usedWidth < 0 ||
2831         typeof usedHeight !== 'number' || !Number.isFinite(usedHeight) || usedHeight < 0) {
2832       throw new Error('Prepared known baseline placement is missing settled content geometry.');
2833     }
2834     const allocation = { x: 0, y: 0, width: usedWidth, height: usedHeight };
2835     const insets = normalizeBoxInsets(selectedStyle, childContext(source, content));
2836     let offset = allocation.height;
2837     if (root.type === Flex || root.type === Flow || root.type === Grid) {
2838       const slot = getElementMetadata(placement.element)?.preparedLayoutSlot as PreparedLayoutSlot | undefined;
2839       const childDirection = selectedStyle.layoutDirection ?? direction;
2840       const nested = root.type === Flex ?
2841         slot && peekPreparedFlexPlan(slot, allocation, childDirection) :
2842         slot && peekPreparedLayoutPlan(slot, allocation, childDirection);
2843       if (!nested) throw childDiagnostic(source, 'alignItems', alignment, content,
2844         'PIBBL_LAYOUT_UNSUPPORTED_BASELINE: selected known layout root requires its current prepared allocation');
2845       offset = readPreparedKnownBaseline(nested, root.type === Flex ? 'flex' : root.type === Flow ? 'flow' : 'grid', measurement, childDirection,
2846         root.type === Flex && (selectedStyle.flexWrap ?? 'nowrap') !== 'nowrap', lastSource);
2847     } else {
2848       const definition = getPrimitiveDefinition(root.type);
2849       if (!definition || isKnownLayoutType(root.type)) throw childDiagnostic(source, 'alignItems', alignment, content,
2850         'PIBBL_LAYOUT_UNSUPPORTED_BASELINE: selected structural source must resolve to a primitive or prepared known layout root');
2851       if (definition.measureBaselines) {
2852         const measurementChild = clonePibblElement(root);
2853         setPreNormalizedStyle(measurementChild, selectedStyle, root, getPrimitiveReceiverToken(root) ?? receiver, prepared.query);
2854         if (prepared.query) setPreparedBaselineOwner(measurementChild, content);
2855         // Read under the actual current root receiver; retain no aggregate result.
2856         const result = measureBaselineElement(measurementChild, allocation, measurement.service);
2857         if (result.status === 'unsupported') throw childDiagnostic(source, 'measureBaselines', 'unsupported', content,
2858           `${alignment} alignment requires a baseline result: ${result.reason}`);
2859         offset = lastSource ? result.last : result.first;
2860       }
2861     }
2862     const layoutY = kind === 'flex' ? (placement as FlexPlacement).layoutY : placement.box.y;
2863     if (!Number.isFinite(layoutY)) throw new Error('Prepared known baseline placement has no finite physical y origin.');
2864     return layoutY + insets.top + offset;
2865   }
2866   if (lineCount !== undefined && lineCount !== 0) throw new Error('Empty structural baseline source disagrees with native endpoint-line membership.');
2867   return content.height;
2868 }
2869 
2870 function assertSupportedBaselineFlex(
2871   options: Readonly<ReturnType<typeof normalizeFlexOptions>>,
2872   items: readonly FlexItem[],
2873   container: Readonly<LayoutBox>,
2874   mounted: boolean,
2875 ): void {
2876   const alignment = options[FLEX_LAST_BASELINE] ? 'last-baseline' : 'first-baseline';
2877   if (!mounted || !nativeLayout || !isRowDirection(options.flexDirection)) {
2878     throw optionDiagnostic('alignItems', alignment, container, 'requires mounted experimental horizontal Flex');
2879   }
2880   for (const item of items) {
2881     const style = item.normalized;
2882     const baselineRoot = isLayoutComponent(item.child.type) ?
2883       prepareLayoutComponent(item.child, { receiverToken: item.receiverToken }) : item.child;
2884     if (baselineRoot !== item.child) item.baselineRoot = baselineRoot;
2885     if (baselineRoot.type === Flex || baselineRoot.type === Flow || baselineRoot.type === Grid) {
2886       if (item.crossAuto || !Number.isFinite(item.targetMain) || item.targetMain < 0 || !Number.isFinite(item.preferredCross) || item.preferredCross < item.paddingCross) {
2887         throw childDiagnostic(item.child, 'alignItems', alignment, container,
2888           'PIBBL_LAYOUT_UNSUPPORTED_BASELINE: a structural baseline requires settled finite known-layout geometry');
2889       }
2890       continue;
2891     }
2892     const textLeaf = baselineRoot.type === Text;
2893     const textStyle = style as Readonly<TextStyle>;
2894     const fontSize = textLeaf ? /(?:^| )(\d+(?:\.\d+)?)px(?:\s*\/\s*(?:normal|\d+(?:\.\d+)?(?:px|%)?))?\s+\S/.exec(String(textStyle.font ?? '13px sans-serif')) : null;
2895     const supportedTextLeaf = !textLeaf || (
2896       fontSize !== null && Number.isFinite(Number(fontSize[1])) && Number(fontSize[1]) > 0 &&
2897       typeof (textStyle.lineHeight ?? 13) === 'number' &&
2898       Number.isFinite(textStyle.lineHeight ?? 13) &&
2899       (textStyle.lineHeight ?? 13) >= 0 &&
2900       (textStyle.wrap === undefined || typeof textStyle.wrap === 'boolean')
2901     );
2902     const sharesBaseline = item.alignSelf === 'auto' && !item.autoCrossBefore && !item.autoCrossAfter;
2903     if (!getPrimitiveDefinition(baselineRoot.type) || isKnownLayoutType(baselineRoot.type) || isLayoutComponent(baselineRoot.type) || (!supportedTextLeaf && sharesBaseline) ||
2904         (style.position !== undefined && style.position !== 'static' && style.position !== 'relative') || (item.crossAuto && item.alignSelf !== 'stretch') ||
2905         !Number.isFinite(item.targetMain) || item.targetMain < 0 || !Number.isFinite(item.preferredCross) || item.preferredCross < item.paddingCross) {
2906       throw childDiagnostic(item.child, 'alignItems', alignment, container, 'PIBBL_LAYOUT_UNSUPPORTED_BASELINE: requires primitive roots with settled finite content boxes and no absolute position');
2907     }
2908   }
2909 }
2910 
2911 function isRowDirection(direction: unknown): boolean {
2912   return direction === undefined || direction === 'row' || direction === 'row-reverse';
2913 }
2914 function isColumnDirection(direction: unknown): boolean {
2915   return direction === 'column' || direction === 'column-reverse';
2916 }
2917 
2918 function normalizeFlexOptions(
2919   style: Readonly<FlexStyle>,
2920   container: Readonly<LayoutBox>,
2921 ) {
2922   const layoutDirection = style.layoutDirection ?? getLayoutDirection();
2923   if (layoutDirection !== 'ltr' && !(nativeLayout && layoutDirection === 'rtl')) {
2924     throw optionDiagnostic('layoutDirection', layoutDirection, container);
2925   }
2926   const flexDirection = style.flexDirection ?? 'row';
2927   if (flexDirection !== 'row' && flexDirection !== 'column' &&
2928       !(nativeLayout && (flexDirection === 'row-reverse' || flexDirection === 'column-reverse'))) {
2929     throw optionDiagnostic('flexDirection', flexDirection, container, 'uses an unsupported flex direction in this build');
2930   }
2931   const flexWrap = style.flexWrap ?? 'nowrap';
2932   if (flexWrap !== 'nowrap' && flexWrap !== 'wrap' && !(nativeLayout && flexWrap === 'wrap-reverse')) {
2933     throw optionDiagnostic('flexWrap', flexWrap, container, 'uses an unsupported flex wrap in this build');
2934   }
2935   const justifyContent = supported(
2936     normalizeLogicalAlignment(style.justifyContent ?? 'flex-start', flexDirection === 'row-reverse' || flexDirection === 'column-reverse'),
2937     ['flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly'],
2938     'justifyContent',
2939     container,
2940   );
2941   const requestedAlignItems = normalizeLogicalAlignment((style as Readonly<Partial<ResolvedFlexStyle>>)[FLEX_LAST_BASELINE] ? 'last-baseline' : (style as Readonly<Partial<ResolvedFlexStyle>>)[FLEX_BASELINE_GROUP] ? 'first-baseline' : style.alignItems ?? 'stretch', flexWrap === 'wrap-reverse');
2942   const alignItems = supported(
2943     requestedAlignItems,
2944     nativeLayout ? ['stretch', 'flex-start', 'flex-end', 'center', 'first-baseline', 'last-baseline'] : ['stretch', 'flex-start', 'flex-end', 'center'],
2945     'alignItems',
2946     container,
2947   );
2948   const alignContent = supported(
2949     normalizeLogicalAlignment(style.alignContent ?? 'stretch', flexWrap === 'wrap-reverse'),
2950     ['stretch', 'flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly'],
2951     'alignContent',
2952     container,
2953   );
2954   const gap = style.gap ?? 0;
2955   const columnGap = nonnegativeGap(gap, 'gap', container, container.width);
2956   const rowGap = typeof gap === 'number' ? columnGap : nonnegativeGap(gap, 'gap', container, container.height);
2957   return {
2958     layoutDirection,
2959     flexDirection: flexDirection as FlexDirection,
2960     flexWrap: flexWrap as FlexWrap,
2961     justifyContent: justifyContent as MainAlignment,
2962     // Yoga resolves baseline alignment on column axes to logical flex-start
2963     // before placement. It neither measures nor forms a vertical baseline group.
2964     alignItems: alignItems === 'first-baseline' ? 'flex-start' : alignItems === 'last-baseline' ? (isRowDirection(flexDirection) ? 'flex-start' : 'flex-end') : alignItems as CrossAlignment,
2965     [FLEX_BASELINE_GROUP]: (alignItems === 'first-baseline' || alignItems === 'last-baseline') && isRowDirection(flexDirection),
2966     [FLEX_LAST_BASELINE]: alignItems === 'last-baseline' && isRowDirection(flexDirection),
2967     alignContent: alignContent as CrossAlignment | MainAlignment,
2968     rowGap: style.rowGap === undefined ? rowGap : nonnegativeGap(style.rowGap, 'rowGap', container, container.height),
2969     columnGap: style.columnGap === undefined ? columnGap : nonnegativeGap(style.columnGap, 'columnGap', container, container.width),
2970   };
2971 }
2972 
2973 function supported(
2974   value: string,
2975   accepted: readonly string[],
2976   property: string,
2977   container: Readonly<LayoutBox>,
2978 ): string {
2979   if (!accepted.includes(value)) throw optionDiagnostic(property, value, container);
2980   return value;
2981 }
2982 
2983 function nonnegativeGap(
2984   value: unknown,
2985   property: string,
2986   container: Readonly<LayoutBox>,
2987   reference: number,
2988 ): number {
2989   const resolved = nativeLayout && isPercentage(value)
2990     ? resolveScalarSizingLength(value as Percentage, reference, property, { component: 'Flex', algorithm: 'flex', constraints: constraintsFor(container) })
2991     : value;
2992   if (typeof resolved !== 'number' || !Number.isFinite(resolved) || resolved < 0) {
2993     throw optionDiagnostic(property, value, container);
2994   }
2995   return resolved;
2996 }
2997 
2998 function nonnegativeFactor(
2999   value: number,
3000   property: string,
3001   child: PibblElement<any>,
3002   container: Readonly<LayoutBox>,
3003 ): number {
3004   if (!Number.isFinite(value) || value < 0) {
3005     throw childDiagnostic(
3006       child,
3007       property,
3008       value,
3009       container,
3010       'must be finite and nonnegative',
3011     );
3012   }
3013   return value;
3014 }
3015 
3016 function resolveIntrinsicMainBound(
3017   value: NonNullable<BoxStyle['minWidth']>,
3018   minimum: number | undefined,
3019   maximum: number | undefined,
3020   property: 'minWidth' | 'maxWidth' | 'minHeight' | 'maxHeight',
3021   reference: number,
3022   child: PibblElement<any>,
3023   container: Readonly<LayoutBox>,
3024 ): number {
3025   if (minimum === undefined || maximum === undefined) {
3026     throw childDiagnostic(child, property, value, container, 'requires a direct finite horizontal Flex intrinsic-sizing owner');
3027   }
3028   const request = normalizeSizingLength(value, {
3029     reference, property, context: childContext(child, container), allowAuto: false, allowIntrinsic: true,
3030   });
3031   return resolveIntrinsicMainBasis(request!, minimum, maximum, child, container);
3032 }
3033 
3034 function resolveIntrinsicMainBasis(
3035   request: NormalizedSizingLength,
3036   minimum: number,
3037   maximum: number,
3038   child: PibblElement<any>,
3039   container: Readonly<LayoutBox>,
3040 ): number {
3041   if (request.kind === 'min-content') return minimum;
3042   if (request.kind === 'max-content') return maximum;
3043   if (request.kind === 'fit-content') return Math.min(maximum, Math.max(minimum, request.limit));
3044   throw childDiagnostic(child, 'flexBasis', request, container, 'requires min-content, max-content or fit-content');
3045 }
3046 
3047 function resolveBasis(
3048   basis: FlexItemStyle['flexBasis'],
3049   specifiedMain: BoxStyle['width'],
3050   measuredMain: number | undefined,
3051   reference: number,
3052   property: 'width' | 'height',
3053   child: PibblElement<any>,
3054   container: Readonly<LayoutBox>,
3055 ): number {
3056   const value = basis === 'auto' || basis === undefined ? specifiedMain : basis;
3057   if (value === undefined || value === 'auto') {
3058     if (measuredMain === undefined) {
3059       throw childDiagnostic(
3060         child,
3061         property,
3062         value ?? 'auto',
3063         container,
3064         'auto flex basis requires supported pure measurement',
3065       );
3066     }
3067     return measuredMain;
3068   }
3069   return resolveItemLength(value, reference, 'flexBasis', child, container);
3070 }
3071 
3072 function resolveItemLength(
3073   value: Exclude<BoxStyle['width'], undefined>,
3074   reference: number,
3075   property: string,
3076   child: PibblElement<any>,
3077   container: Readonly<LayoutBox>,
3078 ): number {
3079   const resolved = resolveScalarSizingLength(value, reference, property, childContext(child, container));
3080   if (resolved === undefined || resolved < 0) {
3081     throw childDiagnostic(
3082       child,
3083       property,
3084       value,
3085       container,
3086       'must resolve to a finite nonnegative length',
3087     );
3088   }
3089   return resolved;
3090 }
3091 
3092 function resolveOptionalBound(
3093   value: BoxStyle['minWidth'],
3094   reference: number,
3095   property: string,
3096   fallback: number,
3097   child: PibblElement<any>,
3098   container: Readonly<LayoutBox>,
3099 ): number {
3100   if (value === undefined) return fallback;
3101   return resolveItemLength(value, reference, property, child, container);
3102 }
3103 
3104 function normalizeLogicalAlignment(value: string, reversed: boolean): string {
3105   if (value === 'start') return reversed ? 'flex-end' : 'flex-start';
3106   if (value === 'end') return reversed ? 'flex-start' : 'flex-end';
3107   return value;
3108 }
3109 
3110 function normalizeItemAlignment(
3111   value: LayoutItemStyle['alignSelf'],
3112   child: PibblElement<any>,
3113   container: Readonly<LayoutBox>,
3114   reverseCross = false,
3115 ): CrossAlignment | 'auto' {
3116   if (value === undefined || value === 'auto') return 'auto';
3117   if (value === 'start') return reverseCross ? 'flex-end' : 'flex-start';
3118   if (value === 'end') return reverseCross ? 'flex-start' : 'flex-end';
3119   if (value === 'stretch' || value === 'flex-start' ||
3120     value === 'flex-end' || value === 'center') return value;
3121   throw childDiagnostic(
3122     child,
3123     'alignSelf',
3124     value,
3125     container,
3126     'uses an unsupported flex item alignment',
3127   );
3128 }
3129 
3130 function effectiveAlignment(
3131   value: CrossAlignment | 'auto',
3132   fallback: CrossAlignment,
3133 ): CrossAlignment {
3134   return value === 'auto' ? fallback : value;
3135 }
3136 
3137 function alignmentOffset(
3138   alignment: CrossAlignment,
3139   lineSize: number,
3140   itemSize: number,
3141 ): number {
3142   if (alignment === 'center') return (lineSize - itemSize) / 2;
3143   if (alignment === 'flex-end') return lineSize - itemSize;
3144   return 0;
3145 }
3146 
3147 
3148 function finiteRelativePlacement(
3149   value: number,
3150   property: 'left' | 'top',
3151   child: PibblElement<any>,
3152   container: Readonly<LayoutBox>,
3153 ): number {
3154   if (!Number.isFinite(value)) {
3155     throw childDiagnostic(child, property, value, container, 'resolved relative placement arithmetic must remain finite');
3156   }
3157   return value;
3158 }
3159 
3160 function assertSupportedAbsoluteFlexPosition(
3161   child: PibblElement<any>,
3162   style: Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle>,
3163   container: Readonly<LayoutBox>,
3164   direction: 'ltr' | 'rtl',
3165   query: PreparedQuery | undefined,
3166   naturalWidth = false,
3167   naturalHeight = false,
3168 ): void {
3169   if (isKnownLayoutType(child.type) || isLayoutComponent(child.type)) {
3170     throw childDiagnostic(child, 'position', style.position, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: absolute layout children and nested containing blocks are not supported in this slice');
3171   }
3172   if (!nativeLayout) {
3173     throw childDiagnostic(child, 'position', style.position, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: absolute requires experimental Flex');
3174   }
3175   const automaticWidth = style.width === undefined || style.width === 'auto';
3176   const automaticHeight = style.height === undefined || style.height === 'auto';
3177   if ((!automaticWidth && !isAbsoluteSizeInput(style.width)) ||
3178       (!automaticHeight && !isAbsoluteSizeInput(style.height))) {
3179     throw childDiagnostic(child, 'position', style.position, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: absolute currently requires finite nonnegative numeric or percentage dimensions, or admitted automatic dimensions');
3180   }
3181   if (style.aspectRatio !== undefined && automaticWidth === automaticHeight) {
3182     throw childDiagnostic(child, 'aspectRatio', style.aspectRatio, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: absolute aspectRatio currently requires exactly one automatic axis and one finite numeric or percentage axis');
3183   }
3184   if (style.aspectRatio === undefined && ((!naturalWidth && automaticWidth && (absoluteLeftInset(style, direction) === undefined || absoluteRightInset(style, direction) === undefined)) ||
3185       (!naturalHeight && automaticHeight && (style.top === undefined || style.bottom === undefined)))) {
3186     throw childDiagnostic(child, 'position', style.position, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: automatic absolute size requires opposing insets on its axis');
3187   }
3188   if (style.alignSelf !== undefined) {
3189     throw childDiagnostic(child, 'alignSelf', style.alignSelf, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: absolute currently uses parent alignItems only');
3190   }
3191   validateAbsoluteBound(style.minWidth, 'minWidth', child, container);
3192   validateAbsoluteBound(style.maxWidth, 'maxWidth', child, container);
3193   validateAbsoluteBound(style.minHeight, 'minHeight', child, container);
3194   validateAbsoluteBound(style.maxHeight, 'maxHeight', child, container);
3195   if (query || style.flexBasis !== undefined && style.flexBasis !== 'auto' ||
3196       (style.flexGrow !== undefined && style.flexGrow !== 0) || (style.flexShrink !== undefined && style.flexShrink !== 0) ||
3197       style.boxSizing !== undefined || style.padding !== undefined || style.paddingStart !== undefined || style.paddingEnd !== undefined ||
3198       style.borderWidth !== undefined || style.borderStartWidth !== undefined || style.borderEndWidth !== undefined || hasFlexMargin(style)) {
3199     throw childDiagnostic(child, 'position', style.position, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: absolute excludes nonzero flex factors, margins, and child box decoration in this slice');
3200   }
3201 }
3202 
3203 function validateAbsoluteBound(
3204   value: unknown,
3205   property: 'minWidth' | 'maxWidth' | 'minHeight' | 'maxHeight',
3206   child: PibblElement<any>,
3207   container: Readonly<LayoutBox>,
3208 ): void {
3209   if (value === undefined) return;
3210   if (!isAbsoluteSizeInput(value)) {
3211     throw childDiagnostic(child, property, value, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: absolute size bounds currently require nonnegative finite numbers or percentages');
3212   }
3213 }
3214 
3215 function isAbsoluteSizeInput(value: unknown): boolean {
3216   return typeof value === 'number' && Number.isFinite(value) && value >= 0 || isPercentage(value);
3217 }
3218 
3219 function resolveAbsoluteSize(
3220   value: unknown,
3221   property: 'width' | 'height' | 'minWidth' | 'maxWidth' | 'minHeight' | 'maxHeight',
3222   reference: number,
3223   child: PibblElement<any>,
3224   container: Readonly<LayoutBox>,
3225 ): number | 'auto' | undefined {
3226   if (!isPercentage(value)) return value as number | 'auto' | undefined;
3227   const resolved = resolveScalarSizingLength(value as Percentage, reference, property, childContext(child, container))!;
3228   if (resolved < 0) throw childDiagnostic(child, property, value, container, 'absolute sizes must resolve to nonnegative finite numbers');
3229   return resolved;
3230 }
3231 
3232 // Read effective edges without rewriting authored inputs used by exact forwarding.
3233 function absoluteLeftInset(style: Readonly<LayoutItemStyle>, direction: 'ltr' | 'rtl') {
3234   const logical = direction === 'rtl' ? style.insetEnd : style.insetStart;
3235   return logical === undefined ? style.left : logical;
3236 }
3237 
3238 function absoluteRightInset(style: Readonly<LayoutItemStyle>, direction: 'ltr' | 'rtl') {
3239   const logical = direction === 'rtl' ? style.insetStart : style.insetEnd;
3240   return logical === undefined ? style.right : logical;
3241 }
3242 
3243 function resolveFlexInset(
3244   value: unknown,
3245   property: 'left' | 'right' | 'top' | 'bottom',
3246   child: PibblElement<any>,
3247   container: Readonly<LayoutBox>,
3248 ): number | undefined {
3249   if (value === undefined) return;
3250   if (typeof value === 'number' && Number.isFinite(value)) return value;
3251   if (isPercentage(value)) {
3252     return resolveScalarSizingLength(value as Percentage, property === 'left' || property === 'right' ? container.width : container.height,
3253       property, childContext(child, container));
3254   }
3255   throw childDiagnostic(child, property, value, container, 'currently requires a finite numeric inset or a signed decimal percentage');
3256 }
3257 
3258 function assertSupportedRelativeFlexPosition(
3259   child: PibblElement<any>,
3260   style: Readonly<BoxStyle & FlexItemStyle & LayoutItemStyle>,
3261   _options: Readonly<Pick<ResolvedFlexStyle, 'flexDirection' | 'flexWrap' | 'layoutDirection'>>,
3262   container: Readonly<LayoutBox>,
3263 ): void {
3264   const position = style.position;
3265   if (!nativeLayout || (position !== 'static' && position !== 'relative')) {
3266     throw childDiagnostic(child, 'position', position, container, 'PIBBL_LAYOUT_UNSUPPORTED_POSITION: uses an unsupported Flex placement mode');
3267   }
3268 }
3269 
3270 function rejectUnsupportedItemFields(
3271   child: PibblElement<any>,
3272   style: Readonly<Record<string, unknown>>,
3273   container: Readonly<LayoutBox>,
3274 ): void {
3275   if (!nativeLayout && hasFlexMargin(style)) throw childDiagnostic(child, 'margin', style.margin, container, 'margins require the experimental Flex engine');
3276   for (let propertyIndex = 0; propertyIndex < unsupportedProperties.length; propertyIndex++) {
3277     const property = unsupportedProperties[propertyIndex];
3278     if (style[property] !== undefined) {
3279       throw childDiagnostic(
3280         child,
3281         property,
3282         style[property],
3283         container,
3284         'uses an unsupported flex item feature',
3285       );
3286     }
3287   }
3288 }
3289 
3290 function hasFlexMargin(style: Readonly<Record<string, unknown>>): boolean {
3291   return style.margin !== undefined || style.marginTop !== undefined || style.marginRight !== undefined ||
3292     style.marginBottom !== undefined || style.marginLeft !== undefined ||
3293     style.marginStart !== undefined || style.marginEnd !== undefined;
3294 }
3295 function allocatedMargin(value: unknown, property: string, child: PibblElement<any>, container: Readonly<LayoutBox>): number {
3296   if (nativeLayout && isPercentage(value)) {
3297     return resolveScalarSizingLength(value as Percentage, container.width, property, childContext(child, container))!;
3298   }
3299   return numericMargin(value, property, child, container);
3300 }
3301 function numericMargin(value: unknown, property: string, child: PibblElement<any>, container: Readonly<LayoutBox>): number {
3302   if (value === undefined) return 0;
3303   if (typeof value !== 'number' || !Number.isFinite(value)) throw childDiagnostic(child, property, value, container, 'margin must be a finite number in logical Canvas units');
3304   return value;
3305 }
3306 
3307 function hasEmptyRectangleMinimum(
3308   child: PibblElement<any>,
3309   style: Readonly<Record<string, unknown>>,
3310   query: PreparedQuery | undefined,
3311   percentageSizes = false,
3312 ): boolean {
3313   return nativeLayout && child.type === Rectangle &&
3314     !Object.hasOwn(child.props, 'children') && !query &&
3315     (typeof style.width === 'number' && Number.isFinite(style.width) && style.width >= 0 || percentageSizes && isPercentage(style.width)) &&
3316     (typeof style.height === 'number' && Number.isFinite(style.height) && style.height >= 0 || percentageSizes && isPercentage(style.height));
3317 }
3318 
3319 function clamp(value: number, minimum: number, maximum: number): number {
3320   return Math.min(maximum, Math.max(minimum, value));
3321 }
3322 
3323 function assertFiniteBox(container: Readonly<LayoutBox>): void {
3324   for (const [property, value] of Object.entries(container)) {
3325     if (!Number.isFinite(value) ||
3326       ((property === 'width' || property === 'height') && value < 0)) {
3327       throw optionDiagnostic(property, value, container);
3328     }
3329   }
3330 }
3331 
3332 function optionDiagnostic(
3333   property: string,
3334   value: unknown,
3335   container: Readonly<LayoutBox>,
3336   reason = 'uses an unsupported flex value',
3337 ) {
3338   return layoutDiagnostic({
3339     component: 'Flex',
3340     property,
3341     value,
3342     algorithm: 'flex',
3343     constraints: constraintsFor(container),
3344     reason,
3345   });
3346 }
3347 
3348 function childDiagnostic(
3349   child: PibblElement<any>,
3350   property: string,
3351   value: unknown,
3352   container: Readonly<LayoutBox>,
3353   reason: string,
3354 ) {
3355   return layoutDiagnostic({
3356     component: child.type.name || 'Anonymous',
3357     property,
3358     value,
3359     algorithm: 'flex',
3360     constraints: constraintsFor(container),
3361     reason,
3362   });
3363 }
3364 
3365 function childContext(
3366   child: PibblElement<any>,
3367   container: Readonly<LayoutBox>,
3368 ) {
3369   return {
3370     component: child.type.name || 'Anonymous',
3371     algorithm: 'flex',
3372     constraints: constraintsFor(container),
3373   };
3374 }
3375 
3376 function constraintsFor(container: Readonly<LayoutBox>): Constraints {
3377   return {
3378     minWidth: 0,
3379     maxWidth: container.width,
3380     minHeight: 0,
3381     maxHeight: container.height,
3382   };
3383 }
3384 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.