diff --git a/src/project.rs b/src/project.rs index e11643e..7c1fd57 100644 --- a/src/project.rs +++ b/src/project.rs @@ -22,7 +22,7 @@ pub(crate) use crate::project_route::{ use crate::project_store::{bind_current_store, prepare_project_store_status}; /// Angular error code for a required input that has no value yet. -const ANGULAR_REQUIRED_INPUT_ERROR: &str = "NG0950"; +pub(crate) const ANGULAR_REQUIRED_INPUT_ERROR: &str = "NG0950"; /// Parameters for `flow_status`. #[derive(Debug, Clone, Deserialize, JsonSchema)] @@ -367,7 +367,8 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { let workspace = project_workspace_url(&url, &project_id); let mut input_pending = false; - for attempt in 0..10 { + let mut store_loading = false; + for attempt in 0..24 { let active_url = engine.current_url().await?; anyhow::ensure!( is_flow_host_url(&active_url) @@ -387,9 +388,12 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { return Ok(()); } if status_err == Some("store_loading") { + store_loading = true; + input_pending = false; tokio::time::sleep(Duration::from_millis(250)).await; continue; } + store_loading = false; input_pending = status_err == Some(ANGULAR_REQUIRED_INPUT_ERROR); let discovery = @@ -401,6 +405,11 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { build_suffix(engine).await ); } + if discovery_err == Some("store_loading") { + store_loading = true; + tokio::time::sleep(Duration::from_millis(250)).await; + continue; + } input_pending |= discovery_err == Some(ANGULAR_REQUIRED_INPUT_ERROR); if discovery["bound"].as_bool() == Some(true) { tokio::time::sleep(Duration::from_millis(250)).await; @@ -425,6 +434,12 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { build_suffix(engine).await ); } + if store_loading { + anyhow::bail!( + "The Flow project store is still loading.{}", + build_suffix(engine).await + ); + } anyhow::bail!( "Failed to bind the Flow project store. Open a Flow project first.{}", build_suffix(engine).await @@ -432,7 +447,7 @@ pub(crate) async fn ensure_flow_store(engine: &ChromeEngine) -> Result<()> { } /// Treats an unset Angular input as a loading result for a project store read. -fn store_loading_result(result: Result) -> Result { +pub(crate) fn store_loading_result(result: Result) -> Result { match result { Err(error) if error.to_string().lines().next().is_some_and(|line| { diff --git a/src/project_store.rs b/src/project_store.rs index 5c97689..a335136 100644 --- a/src/project_store.rs +++ b/src/project_store.rs @@ -11,7 +11,7 @@ use tokio::sync::MutexGuard; use crate::auth::is_signed_in_flow_url; use crate::engine::{ChromeEngine, checked_runtime_result}; -use crate::project::project_id_from_url; +use crate::project::{ANGULAR_REQUIRED_INPUT_ERROR, project_id_from_url, store_loading_result}; /// Holds the browser project store lock and pins the project and runtime session. pub(crate) struct ProjectStoreSession<'a> { @@ -36,20 +36,30 @@ impl<'a> ProjectStoreSession<'a> { .context("Open a Google Flow project before you use this tool")?; let guard = engine.lock_project_store().await; let mut dom_probed = false; - let mut status = bind_current_store(engine, &project_id).await?; - for _ in 0..25 { + let mut status = store_loading_result(bind_current_store(engine, &project_id).await)?; + for _ in 0..30 { let err = status.get("error").and_then(Value::as_str); if err == Some("collection_store_not_bound") && !dom_probed { + let discovery = + store_loading_result(engine.call_flow_async("discoverStore", json!([])).await)?; + if matches!( + discovery.get("error").and_then(Value::as_str), + Some("store_loading" | ANGULAR_REQUIRED_INPUT_ERROR) + ) { + status = json!({ "ok": false, "error": "store_loading" }); + continue; + } dom_probed = true; - let _ = engine.call_flow_async("discoverStore", json!([])).await; - status = engine - .call_flow_js("projectStoreStatus", json!([project_id])) - .await?; + status = store_loading_result( + engine + .call_flow_js("projectStoreStatus", json!([project_id])) + .await, + )?; continue; } - if err == Some("store_loading") { + if matches!(err, Some("store_loading" | ANGULAR_REQUIRED_INPUT_ERROR)) { tokio::time::sleep(Duration::from_millis(200)).await; - status = bind_current_store(engine, &project_id).await?; + status = store_loading_result(bind_current_store(engine, &project_id).await)?; continue; } break; diff --git a/ts/agent_chat.ts b/ts/agent_chat.ts index 13f7e57..b74d73a 100644 --- a/ts/agent_chat.ts +++ b/ts/agent_chat.ts @@ -107,8 +107,12 @@ function liveBinding(projectId: string): Binding | undefined { | undefined; if (life?.[format.destroyed] !== false) return; const project = Reflect.get(page, format.project); - if (typeof project === "function" && project.call(page) === projectId) - return binding; + if (typeof project !== "function") return; + try { + if (project.call(page) === projectId) return binding; + } catch { + return; + } } /** Returns true if the active document has a binding for this project. */ diff --git a/ts/angular.ts b/ts/angular.ts index 6c948c0..b0507c2 100644 --- a/ts/angular.ts +++ b/ts/angular.ts @@ -17,10 +17,12 @@ import type { AngularRouter, FlowStoreHandle, FlowTile, NgLView } from "./types" /** Object with optional Angular Ivy `__ngContext__` or internal `lView` links. */ export interface NgContextCarrier { - /** Angular Ivy LView array or registry slot index. */ + /** Angular Ivy LView array, registry slot index, or upgraded LContext wrapper. */ __ngContext__?: number | NgLView | Record; /** Embedded view LView reference. */ lView?: NgLView; + /** Registry slot ID on an upgraded LContext wrapper. */ + lViewId?: number; } /** Reads an own or prototype property safely without triggering exceptions. */ @@ -53,13 +55,30 @@ export function isNgLViewMap(m: unknown): m is Map { return false; } +/** Reads the Angular `LView` registry slot ID from a host node or context value. */ +export function readLViewSlotId(elOrCtx: unknown): number | null { + const ctxObj = + elOrCtx && typeof elOrCtx === "object" + ? (elOrCtx as NgContextCarrier) + : null; + const raw: unknown = + ctxObj && "__ngContext__" in ctxObj ? ctxObj.__ngContext__ : elOrCtx; + if (typeof raw === "number") return raw; + if (raw && typeof raw === "object" && !(raw instanceof Node)) { + const id = readOwn(raw, "lViewId"); + if (typeof id === "number") return id; + } + const view = resolveLView(elOrCtx); + return typeof view?.[19] === "number" ? view[19] : null; +} + /** Binds the live Angular view registry that contains the selected host context. */ export function bindAngularViews(maps: unknown[], selector: string): boolean { for (const host of document.querySelectorAll(selector)) { - const context = readOwn(host, "__ngContext__"); - if (typeof context !== "number") continue; + const slotId = readLViewSlotId(host); + if (slotId === null) continue; const views = maps.find((map): map is Map => - isNgLViewMap(map) && isLiveLView(map.get(context)), + isNgLViewMap(map) && isLiveLView(map.get(slotId)), ); if (views) { runtimeState.ngLViewMap = views; @@ -83,12 +102,16 @@ export function resolveLView(elOrCtx: unknown): NgLView | null { ? runtimeState.ngLViewMap.get(raw) || null : null; } - if (raw && typeof raw === "object") { + if (raw && typeof raw === "object" && !(raw instanceof Node)) { const lView = readOwn(raw, "lView"); if (Array.isArray(lView)) return lView; const contextField = frontendBuild(readBuildLabel())?.projectStore.lContextView; const verifiedView = contextField ? readOwn(raw, contextField) : undefined; - return Array.isArray(verifiedView) ? verifiedView : null; + if (Array.isArray(verifiedView)) return verifiedView; + const id = readOwn(raw, "lViewId"); + if (typeof id === "number" && runtimeState.ngLViewMap instanceof Map) { + return runtimeState.ngLViewMap.get(id) || null; + } } return null; } diff --git a/ts/character_voices.ts b/ts/character_voices.ts index 8134f6b..0ede6b2 100644 --- a/ts/character_voices.ts +++ b/ts/character_voices.ts @@ -3,7 +3,7 @@ // List and assign Google Flow character voices inside the character editor. -import { readOwn, startMapCapture, type NgContextCarrier } from "./angular"; +import { readLViewSlotId, readOwn, resolveLView, startMapCapture } from "./angular"; import { VOICE_ICON_WORDS, voicePane } from "./character_extra"; import { clickButtonByRegex, @@ -118,14 +118,15 @@ export async function characterVoiceOp( }; return walk(rootLv, 0); }; - const formNg = (form as NgContextCarrier).__ngContext__; + const resolvedLv = resolveLView(form); const direct = - scanLView(formNg, isExactComp) || scanLView(formNg, isFormComp); + scanLView(resolvedLv, isExactComp) || scanLView(resolvedLv, isFormComp); if (direct) { formComponents.set(form, direct); return direct; } - if (typeof formNg !== "number" || probedForms.has(form)) { + const formSlotId = readLViewSlotId(form); + if (formSlotId === null || probedForms.has(form)) { return null; } probedForms.add(form); @@ -181,7 +182,7 @@ export async function characterVoiceOp( } finally { stop(); } - const idx = formNg; + const idx = formSlotId; const findAcrossCaptured = ( predicate: (c: unknown) => c is CharacterFormComponent, ): CharacterFormComponent | null => { diff --git a/ts/discover_store.ts b/ts/discover_store.ts index a6b793e..ef26bb7 100644 --- a/ts/discover_store.ts +++ b/ts/discover_store.ts @@ -7,11 +7,13 @@ import { isNgLViewMap, resolveLView, withLViewMapCapture } from "./angular"; import { delay, hoverProbe } from "./dom"; import { activeProjectStoreFormat } from "./frontend_builds"; import { + STORE_HOST_SELECTORS, clearProjectStore, currentProjectStore, - findProjectStoreInView, + inspectProjectStoreInView, installProjectStore, isCurrent, + isProjectRouteLoading, projectInRoute, selectProjectStoreCandidate, } from "./project_store"; @@ -19,39 +21,25 @@ import type { ProjectStore } from "./project_store"; import { runtimeState } from "./state"; import type { DiscoverStoreResult, NgLView } from "./types"; -/** Component hosts and shell selectors that carry Angular contexts in Google Flow. */ -const STORE_HOST_SELECTORS = [ - "flow-project-shell", - "flow-project-page", - "flow-character-edit-page", - "flow-character-edit-header", - "flow-character-form", - "flow-character-preview-panel", - "flow-character-image-preview", - "flow-edit-character-footer", - "flow-character-header", - "flow-editor-dispatcher", - "flow-editor-page", - "flow-scene-builder", - "flow-scene-timeline", - "flow-grid-tile-container", - 'button[aria-label="Settings trigger"]', - "[mattooltip]", - "button[aria-label]", - "aisandbox-root", - "app-root", - "header", - "main", -] as const; +/** Result of scanning DOM nodes or captured maps for a verified `ProjectStore`. */ +interface StoreProbeOutcome { + /** Selected `ProjectStore` instance when one live candidate matches `projectId`. */ + store: ProjectStore | null; + /** True when a live verified store still waits for its route project input or parameter. */ + inputPending: boolean; +} /** Walks connected DOM elements and parent LViews to find a verified `ProjectStore`. */ -function scanDomStore(projectId: string): ProjectStore | null { +function scanDomStore(projectId: string): StoreProbeOutcome { const seen = new Set(); const candidates: ProjectStore[] = []; + let inputPending = false; const collectFromElement = (el: Element): void => { let view: NgLView | null = resolveLView(el); for (let depth = 0; depth < 6 && Array.isArray(view); depth += 1) { - candidates.push(...findProjectStoreInView(view, projectId, seen)); + const scan = inspectProjectStoreInView(view, projectId, seen); + inputPending ||= scan.inputPending; + candidates.push(...scan.matches); view = Array.isArray(view[3]) ? view[3] : Array.isArray(view[15]) ? view[15] : null; } }; @@ -63,14 +51,14 @@ function scanDomStore(projectId: string): ProjectStore | null { cur = cur.parentElement; } } - if (!candidates.length) { + if (!candidates.length && !inputPending) { const allElements = document.querySelectorAll("*"); const limit = Math.min(allElements.length, 600); for (let i = 0; i < limit; i += 1) { collectFromElement(allElements[i]); } } - return selectProjectStoreCandidate(candidates) ?? null; + return { store: selectProjectStoreCandidate(candidates) ?? null, inputPending }; } /** Captures Angular's LView map via hover probing when not yet recorded in `runtimeState`. */ @@ -92,7 +80,7 @@ async function captureStoreDuring( projectId: string, allMaps: Set>, probe: () => Promise, -): Promise { +): Promise { const seenViews = new Set(); await withLViewMapCapture(probe, (map, value) => { allMaps.add(map); @@ -101,8 +89,11 @@ async function captureStoreDuring( const seen = new Set(); const candidates: ProjectStore[] = []; + let inputPending = false; for (const view of seenViews) { - candidates.push(...findProjectStoreInView(view, projectId, seen)); + const scan = inspectProjectStoreInView(view, projectId, seen); + inputPending ||= scan.inputPending; + candidates.push(...scan.matches); } for (const map of allMaps) { if (!(runtimeState.ngLViewMap instanceof Map) && isNgLViewMap(map)) { @@ -110,13 +101,15 @@ async function captureStoreDuring( } try { for (const value of map.values()) { - candidates.push(...findProjectStoreInView(value, projectId, seen)); + const scan = inspectProjectStoreInView(value, projectId, seen); + inputPending ||= scan.inputPending; + candidates.push(...scan.matches); } } catch { // Skip non-Map prototypes or concurrent map mutations. } } - return selectProjectStoreCandidate(candidates) ?? null; + return { store: selectProjectStoreCandidate(candidates) ?? null, inputPending }; } /** Binds the verified project store from DOM contexts or transient Angular view activity. */ @@ -139,15 +132,24 @@ export async function discoverStore(): Promise { clearProjectStore(); - let found = scanDomStore(projectId); + const initial = scanDomStore(projectId); + let found = initial.store; + let inputPending = initial.inputPending; if (found) { await ensureLViewMap(); - if (!isCurrent(found)) found = scanDomStore(projectId); + if (!isCurrent(found)) { + const recheck = scanDomStore(projectId); + found = recheck.store; + inputPending ||= recheck.inputPending; + } if (found) { installProjectStore(found); return { bound: true, newlyDiscovered: true }; } } + if (inputPending || isProjectRouteLoading(projectId)) { + return { bound: false, newlyDiscovered: false, error: "store_loading" }; + } const allMaps = new Set>(); if (runtimeState.ngLViewMap instanceof Map) { @@ -158,17 +160,23 @@ export async function discoverStore(): Promise { if (found) break; const targets = document.querySelectorAll(selector); if (targets.length === 0) continue; - found = await captureStoreDuring(projectId, allMaps, async () => { + const captured = await captureStoreDuring(projectId, allMaps, async () => { await hoverProbe(Array.from(targets).slice(0, 6), 25); }); - if (!found) found = scanDomStore(projectId); + found = captured.store; + inputPending ||= captured.inputPending; + if (!found) { + const domScan = scanDomStore(projectId); + found = domScan.store; + inputPending ||= domScan.inputPending; + } } - if (!found) { + if (!found && !inputPending) { const scroller = document.querySelector(".page-container, cdk-virtual-scroll-viewport"); if (scroller) { const prev = scroller.scrollTop; - found = await captureStoreDuring(projectId, allMaps, async () => { + const captured = await captureStoreDuring(projectId, allMaps, async () => { scroller.scrollTop = Math.min(scroller.scrollHeight, prev + 200); scroller.dispatchEvent(new Event("scroll")); await delay(50); @@ -176,16 +184,25 @@ export async function discoverStore(): Promise { scroller.dispatchEvent(new Event("scroll")); await delay(50); }); + found = captured.store; + inputPending ||= captured.inputPending; } } if (found) { await ensureLViewMap(); - if (!isCurrent(found)) found = scanDomStore(projectId); + if (!isCurrent(found)) { + const recheck = scanDomStore(projectId); + found = recheck.store; + inputPending ||= recheck.inputPending; + } if (found) { installProjectStore(found); return { bound: true, newlyDiscovered: true }; } } + if (inputPending || isProjectRouteLoading(projectId)) { + return { bound: false, newlyDiscovered: false, error: "store_loading" }; + } return { bound: false, newlyDiscovered: false }; } diff --git a/ts/open_edit_asset.ts b/ts/open_edit_asset.ts index 74e18ad..7779fab 100644 --- a/ts/open_edit_asset.ts +++ b/ts/open_edit_asset.ts @@ -8,7 +8,7 @@ import { findRouter, navigateSpa, readOwn, - type NgContextCarrier, + resolveLView, } from "./angular"; import { delay, elText, isDisabledProp, isVisibleEnabled } from "./dom"; import { clearStore } from "./state"; @@ -119,7 +119,7 @@ export async function openEditAsset( } } } - const ng = (el as NgContextCarrier).__ngContext__; + const ng = resolveLView(el); if (Array.isArray(ng)) { for (let i = 0; i < ng.length; i++) { const item = ng[i]; diff --git a/ts/project_store.ts b/ts/project_store.ts index 983195b..9a0b4c3 100644 --- a/ts/project_store.ts +++ b/ts/project_store.ts @@ -3,13 +3,43 @@ // Bind, validate, read, and mutate the active project store from verified build formats. -import { isNgLViewMap, readOwn } from "./angular"; +import { bindAngularViews, findRouter, isNgLViewMap, readOwn } from "./angular"; import { delay } from "./dom"; import { activeProjectStoreFormat, readBuildLabel, withMutationAliases } from "./frontend_builds"; import type { ProjectStoreFormat } from "./frontend_builds"; import { clearStore, runtimeState } from "./state"; import type { FlowStoreHandle, FlowTile, NgLView, StoreProbeCheck } from "./types"; +/** Angular error code for a required input that has no value yet. */ +const ANGULAR_REQUIRED_INPUT_ERROR = "NG0950"; + +/** Component hosts and shell selectors that carry Angular contexts in Google Flow. */ +export const STORE_HOST_SELECTORS = [ + "flow-project-shell", + "flow-project-page", + "flow-character-page", + "flow-character-edit-page", + "flow-character-edit-header", + "flow-character-form", + "flow-character-preview-panel", + "flow-character-image-preview", + "flow-create-character-footer", + "flow-edit-character-footer", + "flow-character-header", + "flow-editor-dispatcher", + "flow-editor-page", + "flow-scene-builder", + "flow-scene-timeline", + "flow-grid-tile-container", + 'button[aria-label="Settings trigger"]', + "[mattooltip]", + "button[aria-label]", + "aisandbox-root", + "app-root", + "header", + "main", +] as const; + /** A Flow query for the tiles of one project. */ interface ProjectTileQuery { /** Key that includes the project ID. */ @@ -60,13 +90,52 @@ export function projectInRoute(): string | null { return /\/project\/([^/?#]+)/.exec(location.pathname)?.[1] ?? null; } +/** State of the route project signal on a verified `ProjectStore` instance. */ +type StoreProjectState = + | { state: "ready"; projectId: string } + | { state: "loading" } + | { state: "invalid" }; + +/** Result of scanning one Angular `LView` for verified `ProjectStore` instances. */ +export interface StoreViewScan { + /** Verified stores whose route project signal matches the active project. */ + matches: ProjectStore[]; + /** True when a live verified store still waits for its route project input or parameter. */ + inputPending: boolean; +} + +/** Returns true when `error` reports an unset Angular required input (`NG0950`). */ +function isRequiredInputError(error: unknown): boolean { + const text = error instanceof Error ? error.message : String(error ?? ""); + return text.includes(ANGULAR_REQUIRED_INPUT_ERROR); +} + +/** Returns true when `service` has a live Angular `DestroyRef` lifecycle object. */ +function isStoreLifecycleLive(service: object, format: ProjectStoreFormat): boolean { + const lifecycle = readOwn(service, format.lifecycle); + return Boolean(lifecycle) && !readOwn(lifecycle, format.destroyed); +} + +/** Reads the route project signal of `service` and reports whether it is ready or still loading. */ +function readStoreProjectId(service: object, format: ProjectStoreFormat): StoreProjectState { + const currentProject = readOwn(service, format.projectId); + if (typeof currentProject !== "function") return { state: "invalid" }; + try { + const value: unknown = currentProject.call(service); + if (typeof value === "string" && value.length > 0) { + return { state: "ready", projectId: value }; + } + return value === undefined ? { state: "loading" } : { state: "invalid" }; + } catch (error) { + return isRequiredInputError(error) ? { state: "loading" } : { state: "invalid" }; + } +} + /** Checks the active route, lifecycle flag, and project signal of `store`. */ export function isCurrent({ projectId, service, format }: ProjectStore): boolean { - const currentProject = readOwn(service, format.projectId); - const lifecycle = readOwn(service, format.lifecycle); - return projectInRoute() === projectId && - Boolean(lifecycle) && !readOwn(lifecycle, format.destroyed) && - typeof currentProject === "function" && currentProject.call(service) === projectId; + if (projectInRoute() !== projectId || !isStoreLifecycleLive(service, format)) return false; + const current = readStoreProjectId(service, format); + return current.state === "ready" && current.projectId === projectId; } /** Clears both the direct store binding and `runtimeState.store`. */ @@ -105,7 +174,19 @@ function projectQuery({ projectId, service, format }: ProjectStore): ProjectTile if (typeof queryKey !== "function" || typeof find !== "function") return undefined; const key: unknown = queryKey.call(tiles, projectId); if (!isProjectKey(key, projectId)) return undefined; - const query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + let query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + if (!query) { + const signalQuery = readOwn(service, format.tileQuery); + const readStatus = readOwn(signalQuery, "status"); + if (typeof readStatus === "function") { + try { + readStatus.call(signalQuery); + } catch (error) { + if (!isRequiredInputError(error)) throw error; + } + query = find.call(cache, { queryKey: key, exact: true }) as ProjectTileQuery | undefined; + } + } return isProjectKey(query?.queryKey, projectId) ? query : undefined; } @@ -120,7 +201,14 @@ export function isProjectStorePending(store: ProjectStore): boolean { const signalQuery = readOwn(store.service, store.format.tileQuery); if (signalQuery && typeof signalQuery === "object" && "isPending" in signalQuery) { const isPending = readOwn(signalQuery, "isPending"); - if (typeof isPending === "function" ? Boolean(isPending.call(signalQuery)) : isPending === true) { + if (typeof isPending === "function") { + try { + if (Boolean(isPending.call(signalQuery))) return true; + } catch (error) { + if (isRequiredInputError(error)) return true; + throw error; + } + } else if (isPending === true) { return true; } } @@ -157,7 +245,17 @@ export function readProjectStore(store: ProjectStore): Map | n const signalQuery = readOwn(store.service, store.format.tileQuery); if (!signalQuery || typeof signalQuery !== "object" || !("data" in signalQuery)) return null; const readData = readOwn(signalQuery, "data"); - const signalData: unknown = typeof readData === "function" ? readData.call(signalQuery) : readData; + let signalData: unknown; + if (typeof readData === "function") { + try { + signalData = readData.call(signalQuery); + } catch (error) { + if (isRequiredInputError(error)) return null; + throw error; + } + } else { + signalData = readData; + } return indexTileRows(signalData) ?? tileMap(signalData, store.format.rows); } @@ -327,23 +425,30 @@ function verifiedStoreLayout(): { format: ProjectStoreFormat; storeClass: Functi return typeof storeClass === "function" ? { format, storeClass } : null; } -/** Collects live `ProjectStore` candidates from one Angular `LView` array. */ -export function findProjectStoreInView( +/** Scans one Angular `LView` array for live verified `ProjectStore` candidates. */ +export function inspectProjectStoreInView( view: unknown, projectId: string, seen = new Set(), -): ProjectStore[] { - if (!Array.isArray(view)) return []; +): StoreViewScan { + if (!Array.isArray(view)) return { matches: [], inputPending: false }; const layout = verifiedStoreLayout(); - if (!layout) return []; + if (!layout) return { matches: [], inputPending: false }; const { format, storeClass } = layout; const matches: ProjectStore[] = []; + let inputPending = false; const consider = (value: unknown): void => { if (!value || typeof value !== "object" || seen.has(value)) return; seen.add(value); - if (!(value instanceof storeClass)) return; - const candidate: ProjectStore = { projectId, service: value, format }; - if (isCurrent(candidate)) matches.push(candidate); + if (!(value instanceof storeClass) || !isStoreLifecycleLive(value, format)) return; + const projectState = readStoreProjectId(value, format); + if (projectState.state === "loading") { + inputPending = true; + return; + } + if (projectState.state === "ready" && projectState.projectId === projectId) { + matches.push({ projectId, service: value, format }); + } }; for (const slot of view) { @@ -353,7 +458,32 @@ export function findProjectStoreInView( consider(Object.getOwnPropertyDescriptor(slot, key)?.value); } } - return matches; + return { matches, inputPending }; +} + +/** Extracts the normalized `/project/` route suffix from a URL or pathname. */ +function projectRoutePath(urlOrPath: string): string | null { + const pathname = urlOrPath.split(/[?#]/, 1)[0] ?? ""; + const idx = pathname.indexOf("/project/"); + if (idx < 0) return null; + return pathname.slice(idx).replace(/\/+$/, ""); +} + +/** Returns true while the browser document or Angular router still loads `/project/`. */ +export function isProjectRouteLoading(projectId: string): boolean { + if (projectInRoute() !== projectId) return false; + const targetPath = projectRoutePath(location.pathname); + if (!targetPath) return false; + if (document.readyState !== "complete") return true; + if (document.querySelector("flow-loading-page, .projects-loading-container")) return true; + const root = document.querySelector("aisandbox-root, app-root"); + if (root && root.childElementCount === 0 && readOwn(root, "__ngContext__") === undefined) { + return true; + } + const router = findRouter(); + if (!router) return false; + const routerUrl = readOwn(router, "url"); + return typeof routerUrl === "string" && projectRoutePath(routerUrl) !== targetPath; } /** Reports whether the current runtime has a bound and ready store for `projectId`. */ @@ -391,17 +521,25 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto return { ok: false, error: "unsupported_front_end", build }; } if (projectInRoute() !== projectId) return { ok: false, error: "project_changed" }; + if (!(runtimeState.ngLViewMap instanceof Map)) { + bindAngularViews(maps, STORE_HOST_SELECTORS.join(", ")); + } if (!verifiedStoreLayout()) { clearProjectStore(); - return { ok: false, error: "collection_store_not_bound" }; + return isProjectRouteLoading(projectId) + ? { ok: false, error: "store_loading" } + : { ok: false, error: "collection_store_not_bound" }; } const seen = new Set(); const candidates: Array<{ store: ProjectStore; views: Map }> = []; + let inputPending = false; for (const map of maps) { if (!isNgLViewMap(map)) continue; for (const view of map.values()) { - for (const store of findProjectStoreInView(view, projectId, seen)) { + const scan = inspectProjectStoreInView(view, projectId, seen); + inputPending ||= scan.inputPending; + for (const store of scan.matches) { candidates.push({ store, views: map }); } } @@ -411,8 +549,11 @@ export function bindProjectStore(maps: unknown[], projectId: string): ProjectSto const selected = candidates.find(({ store }) => store === selectedStore); if (!selected) { clearProjectStore(); - return candidates.length > 1 - ? { ok: false, error: "ambiguous_collection_store" } + if (candidates.length > 1) { + return { ok: false, error: "ambiguous_collection_store" }; + } + return inputPending || isProjectRouteLoading(projectId) + ? { ok: false, error: "store_loading" } : { ok: false, error: "collection_store_not_bound" }; } installProjectStore(selected.store, selected.views); diff --git a/ts/project_upload.ts b/ts/project_upload.ts index 348b770..ea1a973 100644 --- a/ts/project_upload.ts +++ b/ts/project_upload.ts @@ -428,9 +428,14 @@ function projectWorkspaceRoute(pathname: string): { projectId: string; collectio /** Checks the route and lifecycle of a project workspace component. */ function isCurrentPage(page: object, format: ProjectUploadFormat["page"], projectId: string): boolean { if (projectWorkspaceRoute(location.pathname)?.projectId !== projectId) return false; + if (readOwn(readOwn(page, format.lifecycle), format.destroyed) !== false) return false; const project = readOwn(page, format.project); - return readOwn(readOwn(page, format.lifecycle), format.destroyed) === false && - typeof project === "function" && project.call(page) === projectId; + if (typeof project !== "function") return false; + try { + return project.call(page) === projectId; + } catch { + return false; + } } /** Finds the live project page that owns the upload services. */ diff --git a/ts/projects_ops.ts b/ts/projects_ops.ts index 94104ab..540237a 100644 --- a/ts/projects_ops.ts +++ b/ts/projects_ops.ts @@ -5,10 +5,10 @@ import { buildProjectUrl, + readLViewSlotId, readOwn, resolveLView, withMapCapture, - type NgContextCarrier, } from "./angular"; import { delay, elText, setNativeValue } from "./dom"; import { projectTitleFormat } from "./frontend_builds"; @@ -137,19 +137,22 @@ export async function projectsOp(req: ProjectsOpRequest): Promise { } } if (!pid) { - const ng = (card as NgContextCarrier).__ngContext__; - if (Array.isArray(ng)) { - pid = extractIdFromObject(ng, 0, new Set()); - } else if (typeof ng === "number") { - for (const sm of seenMaps) { - try { - const lv = sm.get(ng); - if (Array.isArray(lv)) { - pid = extractIdFromObject(lv, 0, new Set()); - if (pid) break; + const resolved = resolveLView(card); + if (resolved) { + pid = extractIdFromObject(resolved, 0, new Set()); + } else { + const slotId = readLViewSlotId(card); + if (slotId !== null) { + for (const sm of seenMaps) { + try { + const lv = sm.get(slotId); + if (Array.isArray(lv)) { + pid = extractIdFromObject(lv, 0, new Set()); + if (pid) break; + } + } catch { + // Ignore map read error. } - } catch { - // Ignore map read error. } } }