@powerhousedao/connect 6.2.0-dev.18 → 6.2.0-dev.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/{AddDriveModal-kzL41qdg.js → AddDriveModal-BoKLJyUY.js} +4 -7
  2. package/dist/{AddDriveModal-kzL41qdg.js.map → AddDriveModal-BoKLJyUY.js.map} +1 -1
  3. package/dist/{ClearStorageModal-9qqxbO1y.js → ClearStorageModal-CXoNWmRe.js} +4 -4
  4. package/dist/{ClearStorageModal-9qqxbO1y.js.map → ClearStorageModal-CXoNWmRe.js.map} +1 -1
  5. package/dist/{DebugSettingsModal-Dt-EVIiT.js → DebugSettingsModal-CCwC5vQR.js} +4 -4
  6. package/dist/{DebugSettingsModal-Dt-EVIiT.js.map → DebugSettingsModal-CCwC5vQR.js.map} +1 -1
  7. package/dist/DriveAuthRequiredModal-D1TSn4Vh.js +36 -0
  8. package/dist/DriveAuthRequiredModal-D1TSn4Vh.js.map +1 -0
  9. package/dist/{DriveSettingsModal-Ddmhszv4.js → DriveSettingsModal-CsNFEJ9E.js} +3 -3
  10. package/dist/{DriveSettingsModal-Ddmhszv4.js.map → DriveSettingsModal-CsNFEJ9E.js.map} +1 -1
  11. package/dist/{InspectorModal-v4CyjztA.js → InspectorModal-BsSihzuc.js} +4 -4
  12. package/dist/{InspectorModal-v4CyjztA.js.map → InspectorModal-BsSihzuc.js.map} +1 -1
  13. package/dist/{MissingPackageModal-BqgCNi7N.js → MissingPackageModal-Bn036mWQ.js} +3 -3
  14. package/dist/{MissingPackageModal-BqgCNi7N.js.map → MissingPackageModal-Bn036mWQ.js.map} +1 -1
  15. package/dist/{SettingsModal-CQ7YrCUX.js → SettingsModal-DBMfccv9.js} +5 -5
  16. package/dist/{SettingsModal-CQ7YrCUX.js.map → SettingsModal-DBMfccv9.js.map} +1 -1
  17. package/dist/{UpgradeDriveModal-CyAUDCU7.js → UpgradeDriveModal-C7lV4rAX.js} +3 -3
  18. package/dist/{UpgradeDriveModal-CyAUDCU7.js.map → UpgradeDriveModal-C7lV4rAX.js.map} +1 -1
  19. package/dist/app-loader-BwEatXag.js +4 -0
  20. package/dist/{app-loader-WQF4CBnf.js → app-loader-DVWhjyZt.js} +40 -15
  21. package/dist/app-loader-DVWhjyZt.js.map +1 -0
  22. package/dist/{build-info-Cp9cLhUa.js → build-info-BF8rOJl0.js} +4 -4
  23. package/dist/{build-info-Cp9cLhUa.js.map → build-info-BF8rOJl0.js.map} +1 -1
  24. package/dist/{components-CtpJJ5XZ.js → components-PtdArinE.js} +3 -3
  25. package/dist/{load-D1_uHokU.js → load-DDS7gCLo.js} +5 -5
  26. package/dist/{load-D1_uHokU.js.map → load-DDS7gCLo.js.map} +1 -1
  27. package/dist/main.js +1 -1
  28. package/dist/{package-Doxk1oGT.js → package-CVF5slFr.js} +4 -4
  29. package/dist/package-CVF5slFr.js.map +1 -0
  30. package/dist/{reactor-BAZd7zrS.js → reactor-BxNvHOKC.js} +17 -13
  31. package/dist/reactor-BxNvHOKC.js.map +1 -0
  32. package/dist/start-connect.js +1 -1
  33. package/dist/style.css +63 -0
  34. package/package.json +10 -10
  35. package/dist/app-loader-DH1vM-Ex.js +0 -4
  36. package/dist/app-loader-WQF4CBnf.js.map +0 -1
  37. package/dist/package-Doxk1oGT.js.map +0 -1
  38. package/dist/reactor-BAZd7zrS.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"app-loader-WQF4CBnf.js","sources":["../src/utils/browser.ts","../src/utils/document-editor-debug-tools.ts","../src/components/migration-status.ts","../src/utils/pglite-migration.ts","../src/hooks/useAcceptedCookies.ts","../src/services/openpanel/buffer.ts","../src/services/openpanel/client.ts","../src/services/openpanel/events.json","../src/services/openpanel/events.ts","../src/services/openpanel/processor.ts","../src/services/openpanel/factory.ts","../src/hooks/useIsEmbedded.ts","../src/hooks/useCookieBanner.ts","../src/hooks/useFailedInstallations.ts","../src/hooks/useInitSentry.ts","../src/hooks/usePendingInstallations.ts","../src/hooks/useUndoRedoShortcuts.ts","../src/components/app-skeleton.tsx","../src/components/error-boundary.tsx","../src/components/analytics.tsx","../src/components/openpanel-traits.ts","../src/components/openpanel.tsx","../src/components/document-editor-container.tsx","../src/components/editor-loader.tsx","../src/components/app-container.tsx","../src/context/sentry-provider.tsx","../src/components/missing-model-banner.tsx","../src/components/package-install-prompt.tsx","../src/components/app.tsx","../src/components/cookie-banner.tsx","../src/components/drive-icon.tsx","../src/components/editors.tsx","../src/components/root.tsx","../src/pages/content.tsx","../src/components/router.tsx","../src/components/sidebar.tsx","../src/components/migration-banner.tsx","../src/components/modal/modals-container.tsx","../src/components/app-loader.tsx"],"sourcesContent":["export function getBasePath() {\n if (typeof document === \"undefined\") {\n return \"/\";\n }\n\n const baseEl = document.querySelector(\"base\");\n const href = baseEl?.getAttribute(\"href\");\n return href || \"/\";\n}\n","import type {\n Operation,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\n\nexport class DocumentEditorDebugTools {\n private document: PHDocument | undefined;\n private operations: Operation[] = [];\n\n constructor(document?: PHDocument) {\n if (document) {\n this.document = document;\n }\n }\n\n private operationsToTableObject(operations: Operation[]) {\n return operations.map((op) => ({\n ...op,\n input: JSON.stringify(op.action.input),\n }));\n }\n\n public setDocument(document: PHDocument) {\n this.document = document;\n }\n\n public getDocument() {\n return this.document;\n }\n\n public getOperations() {\n return this.operations;\n }\n\n public pushOperation(operation: Operation) {\n this.operations.push(operation);\n }\n\n public operationsTable() {\n if (!this.document) {\n console.warn(\"No document\");\n }\n const ops = Object.values(this.document?.operations || {})\n .filter((array): array is Operation[] => array !== undefined)\n .flatMap((array) => array)\n .sort((a, b) => a.index - b.index);\n\n console.table(this.operationsToTableObject(ops));\n }\n\n public scopeOperationsTable(scope: string) {\n if (!this.document) {\n console.warn(\"No document\");\n }\n const ops = this.document?.operations[scope] || [];\n console.table(this.operationsToTableObject(ops));\n }\n\n public operationsLog() {\n console.log(this.operations);\n }\n\n public operationsLogTable() {\n console.table(this.operationsToTableObject(this.operations));\n }\n\n public clear() {\n this.operations = [];\n this.document = undefined;\n }\n}\n","export type MigrationPhase = \"clone\" | \"dump\" | \"restore\";\n\nexport type MigrationStatus = {\n idbName: string;\n phase: MigrationPhase;\n};\n\nlet current: MigrationStatus | null = null;\nconst listeners = new Set<() => void>();\n\nexport function setMigrationStatus(status: MigrationStatus | null): void {\n current = status;\n for (const l of listeners) l();\n}\n\nexport function getMigrationStatus(): MigrationStatus | null {\n return current;\n}\n\nexport function subscribeMigrationStatus(cb: () => void): () => void {\n listeners.add(cb);\n return () => {\n listeners.delete(cb);\n };\n}\n","import { PGlite } from \"@electric-sql/pglite\";\nimport {\n setMigrationStatus,\n type MigrationPhase,\n} from \"../components/migration-status.js\";\nimport {\n createFileDataStore,\n IDB_DB_VERSION,\n IDB_STORE_NAME,\n idbError,\n openIdb,\n PRIMARY_IDB_NAMES,\n readPgVersionFile,\n} from \"./pglite-idb.js\";\nimport { CURRENT_PG_MAJOR } from \"./pglite-runtime.js\";\n\nconst BACKUP_PREFIX = \"ph-pglite-backup::\";\nconst BACKUP_INDEX_KEY = \"ph:pglite-backups\";\nconst BACKUP_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;\n\ntype FileDataValue = {\n contents: Uint8Array | number[];\n mode: number;\n timestamp: Date | number;\n};\n\ntype LegacyDumper = (idbName: string) => Promise<string>;\n\nconst LEGACY_DUMPERS: Partial<Record<number, () => Promise<LegacyDumper>>> = {\n 16: async () => {\n const [{ PGlite: LegacyPGlite }, { pgDump }] = await Promise.all([\n import(\"pglite-legacy-02\"),\n import(\"pglite-tools-legacy-02/pg_dump\"),\n ]);\n return async (idbName: string) => {\n const stripped = idbName.replace(/^\\/pglite\\//, \"\");\n const pg = new LegacyPGlite(`idb://${stripped}`);\n try {\n await pg.waitReady;\n const file = await pgDump({ pg });\n return await file.text();\n } finally {\n await pg.close();\n }\n };\n },\n};\n\n// Emscripten IDBFS holds the IDB connection open past pglite's pg.close(),\n// so deleteDatabase can be blocked indefinitely. Callers on the hot path\n// should prefer clearFileData() instead; deleteIdb is only used by the\n// janitor for expired backups, which tolerates the 15s timeout.\nfunction deleteIdb(name: string, timeoutMs = 15_000): Promise<void> {\n return new Promise((resolve, reject) => {\n const req = indexedDB.deleteDatabase(name);\n let settled = false;\n const done = (fn: () => void) => {\n if (settled) return;\n settled = true;\n fn();\n };\n const timer = setTimeout(\n () =>\n done(() =>\n reject(\n new Error(`IDB delete timed out for ${name} after ${timeoutMs}ms`),\n ),\n ),\n timeoutMs,\n );\n req.onsuccess = () =>\n done(() => {\n clearTimeout(timer);\n resolve();\n });\n req.onerror = () =>\n done(() => {\n clearTimeout(timer);\n reject(idbError(req, `IDB delete failed for ${name}`));\n });\n });\n}\n\nasync function clearFileData(name: string): Promise<void> {\n const db = await openIdb(name, IDB_DB_VERSION, createFileDataStore);\n try {\n await new Promise<void>((resolve, reject) => {\n const tx = db.transaction(IDB_STORE_NAME, \"readwrite\");\n tx.oncomplete = () => resolve();\n tx.onerror = () =>\n reject(idbError(tx, `FILE_DATA clear failed for ${name}`));\n tx.onabort = () =>\n reject(idbError(tx, `FILE_DATA clear aborted for ${name}`));\n tx.objectStore(IDB_STORE_NAME).clear();\n });\n } finally {\n db.close();\n }\n}\n\nasync function cloneFileData(\n sourceName: string,\n destName: string,\n): Promise<void> {\n const source = await openIdb(sourceName, IDB_DB_VERSION, createFileDataStore);\n try {\n const dest = await openIdb(destName, IDB_DB_VERSION, createFileDataStore);\n try {\n const readTx = source.transaction(IDB_STORE_NAME, \"readonly\");\n const readStore = readTx.objectStore(IDB_STORE_NAME);\n const entries = await new Promise<\n Array<{ key: IDBValidKey; value: FileDataValue }>\n >((resolve, reject) => {\n const out: Array<{ key: IDBValidKey; value: FileDataValue }> = [];\n const req = readStore.openCursor();\n req.onerror = () =>\n reject(\n idbError(req, `FILE_DATA read cursor failed for ${sourceName}`),\n );\n req.onsuccess = () => {\n const cursor = req.result;\n if (!cursor) return resolve(out);\n out.push({ key: cursor.key, value: cursor.value as FileDataValue });\n cursor.continue();\n };\n });\n\n await new Promise<void>((resolve, reject) => {\n const writeTx = dest.transaction(IDB_STORE_NAME, \"readwrite\");\n writeTx.oncomplete = () => resolve();\n writeTx.onerror = () =>\n reject(idbError(writeTx, `FILE_DATA write failed for ${destName}`));\n writeTx.onabort = () =>\n reject(idbError(writeTx, `FILE_DATA write aborted for ${destName}`));\n const writeStore = writeTx.objectStore(IDB_STORE_NAME);\n writeStore.clear();\n for (const { key, value } of entries) {\n writeStore.put(value, key);\n }\n });\n } finally {\n dest.close();\n }\n } finally {\n source.close();\n }\n}\n\ntype BackupRecord = { name: string; idbName: string; createdAt: number };\n\nfunction readBackupIndex(): BackupRecord[] {\n try {\n const raw = localStorage.getItem(BACKUP_INDEX_KEY);\n if (!raw) return [];\n const parsed: unknown = JSON.parse(raw);\n return Array.isArray(parsed) ? (parsed as BackupRecord[]) : [];\n } catch {\n return [];\n }\n}\n\nfunction writeBackupIndex(records: BackupRecord[]): void {\n try {\n localStorage.setItem(BACKUP_INDEX_KEY, JSON.stringify(records));\n } catch {\n // ignore quota errors — janitor is best-effort\n }\n}\n\nfunction registerBackup(rec: BackupRecord): void {\n writeBackupIndex([...readBackupIndex(), rec]);\n}\n\nfunction forgetBackup(name: string): void {\n writeBackupIndex(readBackupIndex().filter((r) => r.name !== name));\n}\n\nasync function janitor(): Promise<void> {\n const cutoff = Date.now() - BACKUP_RETENTION_MS;\n const keep: BackupRecord[] = [];\n for (const rec of readBackupIndex()) {\n if (rec.createdAt >= cutoff) {\n keep.push(rec);\n continue;\n }\n try {\n await deleteIdb(rec.name);\n } catch (err) {\n console.warn(`Failed to delete expired pglite backup ${rec.name}`, err);\n keep.push(rec);\n }\n }\n writeBackupIndex(keep);\n}\n\nfunction publishPhase(idbName: string, phase: MigrationPhase): void {\n setMigrationStatus({ idbName, phase });\n}\n\nasync function migrateIdbIfNeeded(idbName: string): Promise<void> {\n const major = await readPgVersionFile(idbName);\n if (major === null || major === CURRENT_PG_MAJOR) return;\n\n const loader = LEGACY_DUMPERS[major];\n if (!loader) {\n throw new Error(\n `Unsupported legacy PGlite data dir: PG_VERSION=${major} for ${idbName}`,\n );\n }\n\n const backupName = `${BACKUP_PREFIX}${idbName}::${new Date().toISOString()}`;\n const backupRec: BackupRecord = {\n name: backupName,\n idbName,\n createdAt: Date.now(),\n };\n\n publishPhase(idbName, \"clone\");\n await cloneFileData(idbName, backupName);\n registerBackup(backupRec);\n\n let sql: string;\n try {\n publishPhase(idbName, \"dump\");\n const dump = await loader();\n sql = await dump(idbName);\n } catch (err) {\n await deleteIdb(backupName).catch(() => {});\n forgetBackup(backupName);\n throw err;\n }\n\n try {\n // Can't deleteDatabase here: Emscripten IDBFS from the legacy PGlite\n // keeps its IDB connection open past pg.close(). Clearing the store\n // in-place leaves the IDB handle alone, and the fresh PGlite will\n // initdb into the empty VFS.\n await clearFileData(idbName);\n publishPhase(idbName, \"restore\");\n const stripped = idbName.replace(/^\\/pglite\\//, \"\");\n const pg = new PGlite(`idb://${stripped}`, { relaxedDurability: false });\n try {\n await pg.waitReady;\n // PGlite 0.2.x pg_dump emits SQL literals with doubled backslashes\n // (escape-string form) but does not always emit the matching\n // `SET standard_conforming_strings = off`. PG17 defaults that GUC to on,\n // so '\\\\\"' in the dump is parsed as a literal backslash + end-of-string\n // and JSONB re-parsing fails. Force off at the session level before\n // running the dump so doubled backslashes collapse as intended.\n console.info(\n `[pglite-migration] Dump preamble (first 500 chars):\\n${sql.slice(0, 500)}`,\n );\n try {\n await pg.exec(\"SET standard_conforming_strings = off;\");\n } catch (gucErr) {\n console.warn(\n \"[pglite-migration] Could not force standard_conforming_strings=off\",\n gucErr,\n );\n }\n try {\n await pg.exec(sql);\n } catch (execErr) {\n logRestoreFailure(idbName, sql, execErr);\n throw execErr;\n }\n } finally {\n await pg.close();\n }\n } catch (err) {\n await rollbackFromBackup(idbName, backupName, err);\n throw err;\n }\n}\n\nfunction logRestoreFailure(idbName: string, sql: string, err: unknown): void {\n const errObj = err as {\n message?: string;\n position?: string | number;\n severity?: string;\n code?: string;\n detail?: string;\n where?: string;\n internalQuery?: string;\n };\n const position =\n typeof errObj.position === \"string\"\n ? parseInt(errObj.position, 10)\n : typeof errObj.position === \"number\"\n ? errObj.position\n : NaN;\n\n console.error(`[pglite-migration] Restore failed for ${idbName}`, {\n message: errObj.message,\n code: errObj.code,\n severity: errObj.severity,\n detail: errObj.detail,\n where: errObj.where,\n position: errObj.position,\n sqlLength: sql.length,\n });\n\n if (Number.isFinite(position) && position > 0) {\n const zeroBased = position - 1;\n const start = Math.max(0, zeroBased - 200);\n const end = Math.min(sql.length, zeroBased + 200);\n const before = sql.slice(start, zeroBased);\n const at = sql.slice(zeroBased, zeroBased + 1);\n const after = sql.slice(zeroBased + 1, end);\n console.error(\n `[pglite-migration] SQL context around position ${position}:\\n${before}»${at}«${after}`,\n );\n const lineStart = sql.lastIndexOf(\"\\n\", zeroBased) + 1;\n const lineEnd = sql.indexOf(\"\\n\", zeroBased);\n const line = sql.slice(lineStart, lineEnd === -1 ? sql.length : lineEnd);\n console.error(\n `[pglite-migration] Failing line (truncated to 500 chars):\\n${line.slice(0, 500)}`,\n );\n } else {\n console.error(\n `[pglite-migration] No position info. First 2000 chars of dump:\\n${sql.slice(0, 2000)}`,\n );\n }\n}\n\nasync function rollbackFromBackup(\n idbName: string,\n backupName: string,\n originalError: unknown,\n): Promise<void> {\n try {\n await clearFileData(idbName).catch(() => {});\n await cloneFileData(backupName, idbName);\n } catch (rollbackErr) {\n console.error(\n `PGlite migration failed AND rollback failed for ${idbName}. Primary error:`,\n originalError,\n \"Rollback error:\",\n rollbackErr,\n );\n return;\n }\n await deleteIdb(backupName).catch(() => {});\n forgetBackup(backupName);\n}\n\nasync function migrateAllLocked(): Promise<void> {\n for (const idbName of PRIMARY_IDB_NAMES) {\n await migrateIdbIfNeeded(idbName);\n }\n setMigrationStatus(null);\n}\n\nexport async function migrateAllIfNeeded(): Promise<void> {\n janitor().catch((err) => console.warn(\"PGlite backup janitor failed\", err));\n\n const hasLocks =\n typeof navigator !== \"undefined\" &&\n \"locks\" in navigator &&\n typeof navigator.locks.request === \"function\";\n\n if (!hasLocks) {\n await migrateAllLocked();\n return;\n }\n\n await navigator.locks.request(\n \"ph-pglite-migration\",\n { mode: \"exclusive\" },\n async () => {\n await migrateAllLocked();\n },\n );\n}\n","import { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useSyncExternalStore } from \"react\";\n\nconst namespace = connectConfig.routerBasename;\n\nconst ACCEPTED_COOKIES_KEY_STORAGE = `${namespace}:acceptedCookies`;\n\nexport interface AcceptedCookies {\n analytics: boolean;\n marketing: boolean;\n functional: boolean;\n}\n\nconst listeners = new Set<() => void>();\n\nlet cookies: AcceptedCookies = getInitial();\n\nfunction getInitial(): AcceptedCookies {\n try {\n const value = localStorage.getItem(ACCEPTED_COOKIES_KEY_STORAGE);\n return value\n ? (JSON.parse(value) as AcceptedCookies)\n : { analytics: false, marketing: false, functional: false };\n } catch {\n return { analytics: false, marketing: false, functional: false };\n }\n}\n\nfunction getCookies(): AcceptedCookies {\n return cookies;\n}\n\nfunction setCookies(setter: (prev: AcceptedCookies) => AcceptedCookies) {\n cookies = setter(cookies);\n localStorage.setItem(ACCEPTED_COOKIES_KEY_STORAGE, JSON.stringify(cookies));\n listeners.forEach((fn) => fn());\n}\n\nfunction subscribe(fn: () => void) {\n listeners.add(fn);\n return () => listeners.delete(fn);\n}\n\nexport const useAcceptedCookies = () => {\n const cookies = useSyncExternalStore(subscribe, getCookies, getCookies);\n return [cookies, setCookies] as const;\n};\n","import type { OpenPanelTracker } from \"./processor.js\";\n\n/**\n * Hard cap on pre-init events held in memory. When full, the oldest entry is\n * evicted (drop-oldest) so the most-recent events survive. Bounded, so an\n * uninitialised client never leaks; `resetOpenPanelClient()` discards it\n * entirely so pre-consent events are never replayed.\n */\nconst BUFFER_CAP = 200;\n\ntype BufferEntry = [name: string, props: Record<string, unknown> | undefined];\n\nconst buffer: BufferEntry[] = [];\nlet activeClient: OpenPanelTracker | undefined;\nlet errorHandler: ((err: unknown) => void) | undefined;\n\nfunction defaultOnError(err: unknown): void {\n console.warn(\"[useOpenPanelAnalytics] track failed:\", err);\n}\n\n/**\n * Forward a single event to the active client, swallowing any throw.\n *\n * The outer try/catch handles synchronous throws from `client.track`; the\n * inner `.catch()` handles rejected promises. Both are needed because\n * `Promise.resolve(x).catch()` cannot catch a throw from evaluating `x`.\n */\nfunction forward(\n client: OpenPanelTracker,\n name: string,\n props: Record<string, unknown> | undefined,\n): void {\n try {\n Promise.resolve(client.track(name, props)).catch((err) =>\n (errorHandler ?? defaultOnError)(err),\n );\n } catch (err) {\n (errorHandler ?? defaultOnError)(err);\n }\n}\n\n/**\n * Drain the pre-init buffer in FIFO order through `client.track`, then forward\n * subsequent events directly. Called once from `getOpenPanelClient()`.\n */\nexport function drainOpenPanelBuffer(\n client: OpenPanelTracker,\n onError?: (err: unknown) => void,\n): void {\n activeClient = client;\n errorHandler = onError;\n\n // Splice atomically so any track() during the drain is forwarded directly\n // (activeClient is set) rather than re-buffered.\n const pending = buffer.splice(0, buffer.length);\n for (const [name, props] of pending) {\n forward(client, name, props);\n }\n}\n\n/**\n * Clear the buffer and reset the active client. Buffered pre-consent events\n * are discarded so they are not replayed if the user later re-accepts.\n */\nexport function clearOpenPanelBuffer(): void {\n buffer.length = 0;\n activeClient = undefined;\n errorHandler = undefined;\n}\n\n/**\n * Track an analytics event. Sync, never throws. Forwards immediately when the\n * client is initialised, otherwise buffers (FIFO, cap 200, drop-oldest).\n */\nexport function track(name: string, props?: Record<string, unknown>): void {\n if (activeClient) {\n forward(activeClient, name, props);\n return;\n }\n\n if (buffer.length >= BUFFER_CAP) {\n buffer.shift();\n }\n buffer.push([name, props]);\n}\n","import type { OpenPanel } from \"@openpanel/web\";\n\nimport { clearOpenPanelBuffer, drainOpenPanelBuffer } from \"./buffer.js\";\nimport type { OpenPanelConfig } from \"./types.js\";\n\nlet client: OpenPanel | undefined;\n\n/**\n * Returns the cached `OpenPanel` singleton, building it on first call.\n *\n * When `config.clientId` is empty it returns `undefined` without importing\n * `@openpanel/web`, so the bundler can tree-shake the SDK out of production.\n */\nexport async function getOpenPanelClient(\n config: OpenPanelConfig,\n): Promise<OpenPanel | undefined> {\n if (!config.clientId) {\n return undefined;\n }\n\n if (client) {\n return client;\n }\n\n // Dynamic import keeps @openpanel/web out of the initial chunk.\n const { OpenPanel: OpenPanelClass } = await import(\"@openpanel/web\");\n\n client = new OpenPanelClass({\n clientId: config.clientId,\n ...(config.apiUrl ? { apiUrl: config.apiUrl } : {}),\n trackScreenViews: true,\n trackOutgoingLinks: true,\n });\n\n // The web SDK has no `globalProperties` constructor option.\n client.setGlobalProperties({ app: \"connect\" });\n\n // Runs once (the `if (client)` guard above), so the buffer is never\n // double-drained.\n drainOpenPanelBuffer(client);\n\n return client;\n}\n\n/**\n * Clears the cached singleton and the pre-init buffer. Call on consent\n * revocation or during tests; buffered events are discarded, not replayed.\n */\nexport function resetOpenPanelClient(): void {\n client = undefined;\n clearOpenPanelBuffer();\n}\n","","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport { z } from \"zod\";\n\nimport type { OpenPanelEventMapping } from \"./types.js\";\nimport rawEvents from \"./events.json\" with { type: \"json\" };\n\nconst EventMappingSchema = z\n .object({\n documentType: z.string().min(1),\n actionTypes: z.array(z.string().min(1)).min(1),\n alias: z.string().optional(),\n })\n .strict();\n\nconst EventMappingsSchema = z.array(EventMappingSchema).readonly();\n\n/**\n * Parses and validates the event mapping table, returning the validated array\n * and an O(1) lookup map. Accepts a `raw` override for tests. Throws on zod\n * failures and on duplicate `(documentType, actionType)` pairs.\n */\nexport function loadEvents(raw: unknown = rawEvents): {\n mappings: readonly OpenPanelEventMapping[];\n lookupMap: Map<string, Map<string, OpenPanelEventMapping>>;\n} {\n const result = EventMappingsSchema.safeParse(raw);\n if (!result.success) {\n throw new Error(`Invalid OpenPanel events.json: ${result.error.message}`);\n }\n\n const mappings = result.data as readonly OpenPanelEventMapping[];\n const lookupMap = new Map<string, Map<string, OpenPanelEventMapping>>();\n\n for (const mapping of mappings) {\n let inner = lookupMap.get(mapping.documentType);\n if (!inner) {\n inner = new Map<string, OpenPanelEventMapping>();\n lookupMap.set(mapping.documentType, inner);\n }\n\n for (const actionType of mapping.actionTypes) {\n if (inner.has(actionType)) {\n throw new Error(\n `Duplicate OpenPanel event mapping for ${mapping.documentType}/${actionType}`,\n );\n }\n inner.set(actionType, mapping);\n }\n }\n\n return { mappings, lookupMap };\n}\n\nconst { mappings: defaultMappings, lookupMap: defaultLookupMap } = loadEvents();\n\n/** Validated mapping array from the bundled events.json. */\nexport const eventMappings: readonly OpenPanelEventMapping[] = defaultMappings;\n\n/** O(1) lookup map: documentType → actionType → mapping. */\nexport const eventLookupMap: Map<\n string,\n Map<string, OpenPanelEventMapping>\n> = defaultLookupMap;\n\n/**\n * Normalizes a document type into a safe event-name segment: lowercased, `/`\n * replaced with `.`, and any character outside `[a-z0-9._-]` stripped.\n * e.g. `powerhouse/document-drive` → `powerhouse.document-drive`.\n */\nexport function normalize(documentType: string): string {\n return documentType\n .toLowerCase()\n .replace(/\\//g, \".\")\n .replace(/[^a-z0-9._-]/g, \"\");\n}\n\n/**\n * Derives the OpenPanel event name: `mapping.alias` when present, otherwise\n * `${normalize(documentType)}.${actionType.toLowerCase()}`.\n */\nexport function deriveEventName(\n mapping: OpenPanelEventMapping,\n op: OperationWithContext,\n): string {\n if (mapping.alias) {\n return mapping.alias;\n }\n return `${normalize(op.context.documentType)}.${op.operation.action.type.toLowerCase()}`;\n}\n\n/**\n * Builds the default properties attached to every OpenPanel event. The `app`\n * property is stamped globally by the client, not here.\n */\nexport function buildDefaultProperties(op: OperationWithContext): {\n documentType: string;\n actionType: string;\n documentId: string;\n scope: string;\n branch: string;\n} {\n return {\n documentType: op.context.documentType,\n actionType: op.operation.action.type,\n documentId: op.context.documentId,\n scope: op.context.scope,\n branch: op.context.branch,\n };\n}\n","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport type { IProcessor } from \"@powerhousedao/shared/processors\";\n\nimport { buildDefaultProperties, deriveEventName } from \"./events.js\";\nimport type { OpenPanelEventMapping } from \"./types.js\";\n\n/**\n * Minimal structural type for the injected analytics client. Keeps\n * `@openpanel/web` out of the runtime import graph and makes test fakes\n * trivial; the real `OpenPanel` instance satisfies it structurally.\n */\nexport type OpenPanelTracker = {\n track: (name: string, properties?: Record<string, unknown>) => unknown;\n flush?: () => void;\n};\n\n/**\n * Read-only reactor `IProcessor` that translates matching document operations\n * into OpenPanel analytics events. Operations whose `(documentType, actionType)`\n * pair is absent from the lookup map are skipped; per-operation errors are\n * routed to `onError` and never thrown back to the manager.\n */\nexport class OpenPanelProcessor implements IProcessor {\n constructor(\n private readonly client: OpenPanelTracker,\n private readonly lookupMap: Map<string, Map<string, OpenPanelEventMapping>>,\n private readonly onError: (\n err: unknown,\n op?: OperationWithContext,\n ) => void = (err) =>\n console.warn(\"[OpenPanelProcessor] Error tracking event:\", err),\n ) {}\n\n async onOperations(operations: OperationWithContext[]): Promise<void> {\n for (const op of operations) {\n const inner = this.lookupMap.get(op.context.documentType);\n if (!inner) continue;\n\n const mapping = inner.get(op.operation.action.type);\n if (!mapping) continue;\n\n const name = deriveEventName(mapping, op);\n const payload = buildDefaultProperties(op);\n\n try {\n await this.client.track(name, payload);\n } catch (err) {\n this.onError(err, op);\n }\n }\n }\n\n onDisconnect(): Promise<void> {\n this.client.flush?.();\n return Promise.resolve();\n }\n}\n","import type { OperationWithContext } from \"@powerhousedao/shared/document-model\";\nimport type { PHDocumentHeader } from \"@powerhousedao/shared/document-model\";\nimport type {\n ProcessorFactory,\n ProcessorRecord,\n} from \"@powerhousedao/shared/processors\";\n\nimport { OpenPanelProcessor, type OpenPanelTracker } from \"./processor.js\";\nimport type { OpenPanelEventMapping } from \"./types.js\";\n\nexport type OpenPanelProcessorFactoryConfig = {\n /** The initialized analytics client to forward events to. */\n client: OpenPanelTracker;\n\n /** Loaded event mapping data, as returned by `loadEvents()`. */\n events: {\n mappings: readonly OpenPanelEventMapping[];\n lookupMap: Map<string, Map<string, OpenPanelEventMapping>>;\n };\n\n /** Replay window. Defaults to `\"current\"` (no historical replay). */\n startFrom?: \"current\" | \"beginning\";\n\n /** Error handler; defaults to `console.warn`. */\n onError?: (err: unknown, op?: OperationWithContext) => void;\n};\n\n/**\n * Returns a `ProcessorFactory` that, for each drive, creates a single\n * `OpenPanelProcessor` record whose `filter.documentType` is the union of all\n * document types present in the event mapping table.\n */\nexport function createOpenPanelProcessorFactory(\n config: OpenPanelProcessorFactoryConfig,\n): ProcessorFactory {\n return function openPanelProcessorFactory(\n _driveHeader: PHDocumentHeader,\n ): ProcessorRecord[] {\n const documentType = Array.from(config.events.lookupMap.keys());\n\n const processor = new OpenPanelProcessor(\n config.client,\n config.events.lookupMap,\n config.onError,\n );\n\n const record: ProcessorRecord = {\n processor,\n filter: { documentType },\n startFrom: config.startFrom ?? \"current\",\n };\n\n return [record];\n };\n}\n","/**\n * Detects whether Connect is being rendered inside another app (e.g. inside\n * an iframe in the vetra-cli drive editor). When `?embed=1` is present in the\n * URL, chrome that doesn't make sense in the embedded context — the cookie\n * banner, the outer sidebar — is suppressed.\n */\nexport function getIsEmbedded(): boolean {\n if (typeof window === \"undefined\") return false;\n try {\n const params = new URLSearchParams(window.location.search);\n const value = params.get(\"embed\");\n return value !== null && value !== \"0\" && value !== \"false\";\n } catch {\n return false;\n }\n}\n\nexport function useIsEmbedded(): boolean {\n return getIsEmbedded();\n}\n","import { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useSyncExternalStore } from \"react\";\nimport { getIsEmbedded } from \"./useIsEmbedded.js\";\n\nconst namespace = connectConfig.routerBasename;\n\nexport const COOKIE_BANNER_KEY_STORAGE = `${namespace}:display-cookie-banner`;\n\nconst listeners = new Set<() => void>();\n\nlet bannerShown = getInitial();\n\nfunction getInitial(): boolean {\n if (getIsEmbedded()) return false;\n try {\n const value = localStorage.getItem(COOKIE_BANNER_KEY_STORAGE);\n return value !== \"false\";\n } catch (error) {\n console.error(error);\n return true;\n }\n}\n\nfunction getCookieBannerState(): boolean {\n return bannerShown;\n}\n\nfunction setCookieBannerState(state: boolean) {\n bannerShown = state;\n localStorage.setItem(COOKIE_BANNER_KEY_STORAGE, JSON.stringify(state));\n}\n\nfunction subscribe(fn: () => void) {\n listeners.add(fn);\n return () => listeners.delete(fn);\n}\n\nexport const useCookieBanner = () => {\n const cookieBannerShown = useSyncExternalStore(\n subscribe,\n getCookieBannerState,\n getCookieBannerState,\n );\n return [cookieBannerShown, setCookieBannerState] as const;\n};\n","import {\n usePackageDiscoveryService,\n type FailedInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport { useSyncExternalStore } from \"react\";\n\nconst emptyArray: FailedInstallation[] = [];\n\nexport function useFailedInstallations() {\n const discoveryService = usePackageDiscoveryService();\n return useSyncExternalStore(\n (cb) => discoveryService?.subscribeFailed(cb) ?? (() => {}),\n () => discoveryService?.getFailedInstallations() ?? emptyArray,\n );\n}\n","import { connectConfig } from \"@powerhousedao/connect/config\";\n\nimport type { BrowserOptions } from \"@sentry/react\";\n\nimport { childLogger } from \"document-model\";\nimport React, { useEffect } from \"react\";\nimport {\n createRoutesFromChildren,\n matchRoutes,\n useLocation,\n useNavigationType,\n} from \"react-router-dom\";\nimport { useAcceptedCookies } from \"./useAcceptedCookies.js\";\n\nconst logger = childLogger([\"sentry\"]);\n\nlet clientStarted = false;\n\nasync function getSentry() {\n return await import(\"@sentry/react\");\n}\n\nasync function initSentry() {\n const Sentry = await getSentry();\n const integrations: BrowserOptions[\"integrations\"] = [\n Sentry.httpClientIntegration(),\n Sentry.extraErrorDataIntegration({ depth: 5 }),\n Sentry.replayIntegration(),\n Sentry.captureConsoleIntegration({ levels: [\"error\"] }),\n ];\n if (connectConfig.sentry.tracing) {\n integrations.push(\n Sentry.reactRouterV6BrowserTracingIntegration({\n useEffect: React.useEffect,\n useLocation,\n useNavigationType,\n createRoutesFromChildren,\n matchRoutes,\n }),\n );\n }\n\n Sentry.init({\n release: connectConfig.sentry.release,\n dsn: connectConfig.sentry.dsn ?? undefined,\n environment: connectConfig.sentry.env,\n integrations,\n ignoreErrors: [\n \"User is not allowed to create files\",\n \"User is not allowed to move documents\",\n \"The user aborted a request.\",\n ],\n sendDefaultPii: true,\n tracesSampleRate: 1.0,\n replaysSessionSampleRate: 0.1,\n replaysOnErrorSampleRate: 1.0,\n beforeSend(event, hint) {\n const error = hint.originalException;\n if (\n error instanceof TypeError &&\n error.message.includes(\"Failed to fetch\") &&\n !navigator.onLine\n ) {\n // If fetch fails because user is offline then ignores the error\n return null;\n }\n return event;\n },\n });\n\n clientStarted = true;\n}\n\nasync function closeClient() {\n if (!clientStarted) {\n return;\n }\n const sentry = await getSentry();\n const client = sentry.getClient();\n return client?.close();\n}\n\nexport function useInitSentry() {\n const [acceptedCookies] = useAcceptedCookies();\n const { analytics } = acceptedCookies;\n\n useEffect(() => {\n if (!analytics) {\n closeClient().catch((error: unknown) => logger.error(\"@error\", error));\n return;\n }\n\n // Sentry is disabled when `dsn` is null, undefined, or an empty\n // string — covers both the new schema default (`null`) and any\n // hand-edited config that omits the DSN.\n if (\n clientStarted ||\n connectConfig.sentry.dsn === null ||\n connectConfig.sentry.dsn === undefined ||\n connectConfig.sentry.dsn === \"\"\n ) {\n return;\n }\n\n initSentry().catch((error: unknown) => logger.error(\"@error\", error));\n }, [analytics]);\n}\n","import {\n usePackageDiscoveryService,\n type PendingInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport { useCallback, useRef, useSyncExternalStore } from \"react\";\n\nconst emptyArray: readonly PendingInstallation[] = [];\n\nexport function usePendingInstallations() {\n const discoveryService = usePackageDiscoveryService();\n const cacheRef = useRef<readonly PendingInstallation[]>(emptyArray);\n\n const getSnapshot = useCallback(() => {\n if (!discoveryService) return emptyArray;\n const next = discoveryService.getPendingInstallations() ?? emptyArray;\n const prev = cacheRef.current;\n if (\n next === prev ||\n (next.length === prev.length && next.every((p, i) => p === prev[i]))\n ) {\n return prev;\n }\n cacheRef.current = next;\n return next;\n }, [discoveryService]);\n\n return useSyncExternalStore(\n (cb) => discoveryService?.subscribePending(cb) ?? (() => {}),\n getSnapshot,\n );\n}\n","import { useHotkeys } from \"react-hotkeys-hook\";\n\nexport interface UseUndoRedoShortcutsProps {\n undo: () => void;\n redo: () => void;\n canUndo: boolean;\n canRedo: boolean;\n}\n\nexport const useUndoRedoShortcuts = (props: UseUndoRedoShortcutsProps) => {\n const { undo, redo, canRedo, canUndo } = props;\n const isMac = window.navigator.userAgent.includes(\"Mac\");\n\n let undoShortcut = \"ctrl+z\";\n let redoShortcut = \"ctrl+y\";\n\n if (isMac) {\n undoShortcut = \"mod+z\";\n redoShortcut = \"mod+shift+z\";\n }\n\n // set handler for undo\n useHotkeys(\n undoShortcut,\n (event) => {\n event.preventDefault();\n if (canUndo) {\n undo();\n }\n },\n {},\n [canUndo, undo],\n );\n\n // set handler for redo\n useHotkeys(\n redoShortcut,\n (event) => {\n event.preventDefault();\n if (canRedo) {\n redo();\n }\n },\n {},\n [canRedo, redo],\n );\n};\n","import { getBasePath } from \"@powerhousedao/connect/utils\";\nimport { getIsEmbedded } from \"@powerhousedao/connect/hooks\";\nimport {\n ConnectSidebar,\n HomeScreen,\n LogoAnimation,\n} from \"@powerhousedao/design-system/connect\";\nimport { initTheme } from \"@powerhousedao/reactor-browser\";\nimport {\n useEffect,\n useState,\n useSyncExternalStore,\n type PropsWithChildren,\n} from \"react\";\nimport {\n getMigrationStatus,\n subscribeMigrationStatus,\n type MigrationPhase,\n} from \"./migration-status.js\";\nconst LOADER_DELAY = 250;\n\nconst PHASE_LABEL: Record<MigrationPhase, string> = {\n clone: \"Backing up local database…\",\n dump: \"Exporting data from previous version…\",\n restore: \"Restoring data into the new database…\",\n};\n\nconst MigrationOverlay = () => {\n const status = useSyncExternalStore(\n subscribeMigrationStatus,\n getMigrationStatus,\n () => null,\n );\n if (!status) return null;\n return (\n <div className=\"absolute inset-0 z-20 flex items-center justify-center\">\n <div className=\"rounded-lg bg-white/90 px-6 py-4 text-sm text-gray-900 shadow-lg dark:bg-slate-900/90 dark:text-slate-50\">\n <div className=\"font-medium\">Upgrading local database…</div>\n <div className=\"text-gray-700 dark:text-slate-200\">\n {PHASE_LABEL[status.phase]}\n </div>\n </div>\n </div>\n );\n};\n\nconst Loader = ({ delay = LOADER_DELAY }: { delay?: number }) => {\n const isSSR = typeof window === \"undefined\";\n const showInitialLoader =\n typeof document !== \"undefined\" &&\n document.body.getAttribute(\"data-show-loader\") === \"true\";\n if (!isSSR) {\n initTheme();\n }\n\n const [showLoading, setShowLoading] = useState(!delay || showInitialLoader);\n\n useEffect(() => {\n const id = setTimeout(() => {\n setShowLoading(true);\n }, delay);\n\n return () => clearTimeout(id);\n }, []);\n\n return (\n <div\n className={`skeleton-loader absolute inset-0 z-10 flex items-center justify-center ${showLoading ? \"\" : \"hidden\"}`}\n >\n <div className=\"animate-pulse overflow-hidden rounded-full shadow-lg\">\n <LogoAnimation />\n </div>\n {isSSR ? (\n <script\n dangerouslySetInnerHTML={{\n __html: `setTimeout(() => {\n document.querySelector('.skeleton-loader')?.classList.remove('hidden');\n document.body.setAttribute('data-show-loader', 'true');\n }, ${delay})`,\n }}\n />\n ) : null}\n </div>\n );\n};\n\nexport const AppSkeleton: React.FC<PropsWithChildren> = (props) => {\n const isSSR = typeof window === \"undefined\";\n const isHomeScreen = !isSSR && window.location.pathname === getBasePath();\n /* Match Root's behavior: when Connect is rendered inside an embed (e.g. the\n * vetra-studio BUILD iframe), suppress the sidebar during the Suspense\n * fallback so the loading state matches the loaded state. */\n const isEmbedded = !isSSR && getIsEmbedded();\n return (\n <div className=\"flex h-screen overflow-hidden bg-gray-50 dark:bg-slate-700\">\n {!isEmbedded && (\n <ConnectSidebar\n className=\"animate-pulse\"\n onLogin={undefined}\n onDisconnect={undefined}\n onClickSettings={undefined}\n address={undefined}\n />\n )}\n <HomeScreen\n containerClassName={\n isSSR || !isHomeScreen ? \"hidden home-screen\" : undefined\n }\n children={props.children ?? null}\n />\n {isSSR ? (\n <script\n dangerouslySetInnerHTML={{\n __html: `\n const baseEl = document.querySelector('base');\n const href = baseEl?.getAttribute('href');\n const basePath = href || '/';\n if (window.location.pathname === basePath) {\n document.querySelector('.home-screen')?.classList.remove('hidden')\n }`,\n }}\n />\n ) : null}\n {!props.children ? <Loader /> : null}\n <MigrationOverlay />\n </div>\n );\n};\n\nexport default AppSkeleton;\n","import { Icon, PowerhouseButton } from \"@powerhousedao/design-system\";\nimport { childLogger } from \"document-model\";\nimport type { ReactNode } from \"react\";\nimport {\n ErrorBoundary as ReactErrorBoundary,\n type FallbackProps,\n} from \"react-error-boundary\";\n\nconst logger = childLogger([\"Connect\"]);\n\n/**\n * Available fallback UI variants for the ErrorBoundary component.\n *\n * - `\"silent\"` - Renders nothing when an error occurs (useful for modals)\n * - `\"text\"` - Displays a simple centered text message\n * - `\"detailed\"` - Shows full error details including message and JSON representation\n */\ntype ErrorFallbackVariant = \"silent\" | \"text\" | \"detailed\";\n\n/**\n * Base props shared by all ErrorBoundary configurations.\n */\ntype BaseErrorBoundaryProps = {\n /** Content to wrap with error boundary protection */\n children: ReactNode;\n /** Optional callback invoked when an error is caught (in addition to logging) */\n onError?: (error: Error, info: React.ErrorInfo) => void;\n /** When any value in this array changes, the error boundary resets */\n resetKeys?: unknown[];\n /** Logger context path for error logging (e.g., [\"Connect\", \"Editor\"]) */\n loggerContext?: string[];\n};\n\n/**\n * Props for using a predefined fallback variant.\n */\ntype VariantErrorBoundaryProps = BaseErrorBoundaryProps & {\n /** The fallback UI variant to display on error */\n variant: ErrorFallbackVariant;\n /** Custom message for the \"text\" variant (default: \"Something went wrong\") */\n fallbackMessage?: string;\n};\n\n/**\n * Props for using a custom fallback render function.\n */\ntype CustomFallbackErrorBoundaryProps = BaseErrorBoundaryProps & {\n /** Custom render function for the fallback UI */\n fallbackRender: (props: FallbackProps) => ReactNode;\n};\n\n/**\n * Union type for all ErrorBoundary prop configurations.\n * Use either a variant or a custom fallbackRender, but not both.\n */\ntype ErrorBoundaryProps =\n | VariantErrorBoundaryProps\n | CustomFallbackErrorBoundaryProps;\n\nfunction hasCustomFallback(\n props: ErrorBoundaryProps,\n): props is CustomFallbackErrorBoundaryProps {\n return \"fallbackRender\" in props;\n}\n\nfunction SilentFallback() {\n return null;\n}\n\n/**\n * Simple text-based fallback component.\n * Displays a centered message when an error occurs.\n */\nfunction TextFallback({\n message = \"Something went wrong\",\n}: {\n message?: string;\n}) {\n return <div className=\"text-center\">{message}</div>;\n}\n\n/**\n * Detailed fallback component showing full error information.\n * Displays error message with a collapsible details section.\n * Useful for development and debugging purposes.\n */\nfunction DetailedFallback({ error, resetErrorBoundary }: FallbackProps) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const errorDetails =\n error instanceof Error\n ? (error.stack ?? String(error.cause))\n : JSON.stringify(error, null, 2);\n const hasDetails = errorDetails !== \"{}\";\n\n return (\n <div className=\"z-10 mx-auto flex max-w-[80%] flex-1 items-center justify-center p-6\">\n <div className=\"w-full max-w-lg rounded-lg border border-gray-500 bg-gray-50 p-6 shadow-sm dark:border-slate-400 dark:bg-slate-800\">\n <div className=\"mb-3 flex items-center gap-2\">\n <Icon name=\"Error\" className=\"size-5 shrink-0\" />\n <h1 className=\"text-lg font-semibold\">Something went wrong</h1>\n </div>\n <p className=\"mb-4 text-sm text-gray-700 dark:text-slate-200\">\n {errorMessage}\n </p>\n {hasDetails && (\n <details className=\"group\">\n <summary className=\"cursor-pointer text-sm font-medium text-gray-700 underline select-none hover:text-gray-700 dark:text-slate-200 dark:hover:text-slate-200\">\n Show details\n </summary>\n <pre className=\"mt-2 max-h-48 overflow-auto rounded-sm bg-gray-100 p-3 text-xs dark:bg-slate-700\">\n {errorDetails}\n </pre>\n </details>\n )}\n <PowerhouseButton\n type=\"button\"\n onClick={resetErrorBoundary}\n className=\"mt-4 px-3 py-1.5 text-base font-medium\"\n >\n Try again\n </PowerhouseButton>\n </div>\n </div>\n );\n}\n\n/**\n * Centered error message fallback component.\n * Displays the error message in a centered, full-size container.\n * Suitable for use as a custom fallbackRender when you need simple error display.\n */\nfunction CenteredErrorMessage({ error }: FallbackProps) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return (\n <div className=\"flex size-full items-center justify-center\">\n <h3 className=\"text-lg font-semibold\">{errorMessage}</h3>\n </div>\n );\n}\n\nfunction getFallbackComponent(\n variant: ErrorFallbackVariant,\n fallbackMessage?: string,\n): (props: FallbackProps) => ReactNode {\n switch (variant) {\n case \"silent\":\n return SilentFallback;\n case \"text\":\n return () => <TextFallback message={fallbackMessage} />;\n case \"detailed\":\n return DetailedFallback;\n default:\n return CenteredErrorMessage;\n }\n}\n\n/**\n * Unified error boundary component for catching and handling React errors.\n *\n * Built on top of `react-error-boundary`, this component provides:\n * - Automatic error logging with configurable context\n * - Multiple fallback UI variants (silent, text, detailed)\n * - Support for custom fallback render functions\n * - Reset capability via `resetKeys`\n *\n * @example\n * // Using a predefined variant\n * <ErrorBoundary variant=\"detailed\" loggerContext={[\"Connect\", \"Editor\"]}>\n * <EditorComponent />\n * </ErrorBoundary>\n *\n * @example\n * // Using a custom message with the text variant\n * <ErrorBoundary variant=\"text\" fallbackMessage=\"Failed to load drives\">\n * <DrivesList />\n * </ErrorBoundary>\n *\n * @example\n * // Using a custom fallback render\n * <ErrorBoundary\n * fallbackRender={CenteredErrorMessage}\n * onError={(error) => trackError(error)}\n * >\n * <MyComponent />\n * </ErrorBoundary>\n *\n * @example\n * // Silent mode for modals (renders null on error)\n * <ErrorBoundary variant=\"silent\" loggerContext={[\"Connect\", \"Modals\"]}>\n * <ModalContent />\n * </ErrorBoundary>\n */\nexport function ErrorBoundary(props: ErrorBoundaryProps) {\n const { children, onError, resetKeys, loggerContext } = props;\n\n const handleError = (error: Error, info: React.ErrorInfo) => {\n if (\n error.message.includes(\"Failed to fetch dynamically imported module\") &&\n error.message.includes(\"node_modules/.vite\")\n ) {\n console.error(error);\n console.log(\"Outdated chunk detected, reloading page...\");\n window.location.reload();\n return;\n }\n\n const contextLogger = loggerContext ? childLogger(loggerContext) : logger;\n contextLogger.error(\"@error @info\", error, info);\n onError?.(error, info);\n };\n\n const fallbackRender = hasCustomFallback(props)\n ? props.fallbackRender\n : getFallbackComponent(props.variant, props.fallbackMessage);\n\n return (\n <ReactErrorBoundary\n fallbackRender={fallbackRender}\n onError={handleError}\n resetKeys={resetKeys}\n >\n {children}\n </ReactErrorBoundary>\n );\n}\n\nexport { CenteredErrorMessage, DetailedFallback, TextFallback };\nexport type { FallbackProps };\n","import { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useAcceptedCookies } from \"@powerhousedao/connect/hooks\";\nimport { useEffect } from \"react\";\n\ndeclare global {\n interface Window {\n gtag?: (...args: any[]) => void;\n dataLayer?: any[];\n }\n}\n\nfunction gtag(...args: (string | Date)[]) {\n window.dataLayer?.push(...args);\n}\n\nexport const Analytics = () => {\n const gaTrackingId = connectConfig.gaTrackingId;\n const [{ analytics }] = useAcceptedCookies();\n const useAnalytics = gaTrackingId && analytics;\n\n useEffect(() => {\n if (useAnalytics) {\n // Create the GA script tag\n const script = document.createElement(\"script\");\n script.src = `https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`;\n script.async = true;\n document.head.appendChild(script);\n\n // Initialize GA\n window.dataLayer = window.dataLayer || [];\n\n gtag(\"js\", new Date());\n gtag(\"config\", gaTrackingId);\n\n // Clean up the script if no longer enabled\n return () => {\n document.head.removeChild(script);\n };\n }\n }, [useAnalytics, gaTrackingId]);\n\n return null;\n};\n","import type { User } from \"@renown/sdk\";\n\n/**\n * Builds the OpenPanel identity traits from a renown User.\n *\n * Canonical trait schema (shared with Renown and Vetra — each app sends every\n * field it has data for, under these names):\n * - `address`, `did`, `networkId`, `chainId`, `caip2` — wallet/chain facts.\n * - `ensName`, `ensAvatar` — raw ENS facts.\n * - `username`, `userImage`, `profileDocumentId`, `profileCreatedAt` — raw\n * Renown profile facts.\n * - `accountType` — wallet-adapter concept; only Renown has it.\n *\n * Rules:\n * - `credential` (contains a JWT) is **never** forwarded.\n * - Traits carry raw facts only; resolved presentation values (avatar,\n * display name) go in OpenPanel's native identify fields — see\n * {@link buildIdentifyPayload}.\n * - Optional fields (`ens`, `profile`) are only included when their value is\n * non-nullish (guards against `null` from `RenownProfile` fields as well\n * as plain `undefined`).\n *\n * Mirror the Sentry pattern in `store/user.ts`: destructure off `credential`\n * first, then assemble the trait payload from the remainder.\n */\nexport function buildTraits(user: User): Record<string, unknown> {\n // Destructure credential off so it can never accidentally make it into the\n // returned object.\n const { credential: _credential, ...rest } = user;\n\n const traits: Record<string, unknown> = {\n address: rest.address,\n did: rest.did,\n networkId: rest.networkId,\n chainId: rest.chainId,\n caip2: `${rest.networkId}:${rest.chainId}`,\n };\n\n // ens fields — optional on the User type\n if (rest.ens?.name != null) {\n traits.ensName = rest.ens.name;\n }\n if (rest.ens?.avatarUrl != null) {\n traits.ensAvatar = rest.ens.avatarUrl;\n }\n\n // profile fields — optional on InternalUser; RenownProfile members can be\n // null, so guard with != null (catches both null and undefined)\n if (rest.profile?.username != null) {\n traits.username = rest.profile.username;\n }\n if (rest.profile?.userImage != null) {\n traits.userImage = rest.profile.userImage;\n }\n if (rest.profile?.documentId != null) {\n traits.profileDocumentId = rest.profile.documentId;\n }\n if (rest.profile?.createdAt != null) {\n traits.profileCreatedAt = rest.profile.createdAt;\n }\n\n return traits;\n}\n\n/**\n * Builds the full `identify()` payload:\n * - `profileId` is the wallet address — the cross-app profile key shared with\n * Renown and Vetra.\n * - `avatar` / `firstName` are OpenPanel's native profile fields (they drive\n * the picture and name in the dashboard UI), resolved as\n * `userImage ?? ensAvatar` and `ensName ?? username`.\n * - `properties` are the raw traits from {@link buildTraits}.\n */\nexport function buildIdentifyPayload(user: User): {\n profileId: string;\n avatar?: string;\n firstName?: string;\n properties: Record<string, unknown>;\n} {\n const avatar = user.profile?.userImage ?? user.ens?.avatarUrl;\n const firstName = user.ens?.name ?? user.profile?.username;\n\n return {\n profileId: user.address,\n ...(avatar != null ? { avatar } : {}),\n ...(firstName != null ? { firstName } : {}),\n properties: buildTraits(user),\n };\n}\n","import type { OpenPanel as OpenPanelClient } from \"@openpanel/web\";\nimport { connectConfig } from \"@powerhousedao/connect/config\";\nimport { useAcceptedCookies } from \"@powerhousedao/connect/hooks\";\nimport {\n createOpenPanelProcessorFactory,\n eventLookupMap,\n eventMappings,\n getOpenPanelClient,\n resetOpenPanelClient,\n} from \"@powerhousedao/connect/services\";\nimport {\n useReactorClientModule,\n useUser,\n} from \"@powerhousedao/reactor-browser\";\nimport { useEffect, useRef, useState } from \"react\";\n\nimport { buildIdentifyPayload } from \"./openpanel-traits.js\";\n\ndeclare global {\n interface Window {\n openPanel?: OpenPanelClient;\n }\n}\n\n/**\n * `OpenPanel` is a `null`-rendering component that manages the full lifecycle\n * of the OpenPanel analytics subsystem.\n *\n * Gates:\n * - `useAcceptedCookies().analytics === true` — the existing analytics cookie.\n * - `connectConfig.openPanel.clientId` non-empty — no client ID → no-op.\n *\n * Behaviour when both gates pass:\n * 1. Lazy-imports `@openpanel/web` and builds the singleton via\n * `getOpenPanelClient(connectConfig.openPanel)`.\n * 2. Exposes the client on `window.openPanel` for the card-6\n * `useOpenPanelAnalytics()` hook to consume.\n * 3. If `connectConfig.openPanel.trackOperations`, registers the processor\n * factory against `processorManager` so document operations are forwarded.\n * 4. Calls `client.identify()` when the renown user transitions from\n * `undefined` → defined (login). The profile ID is the wallet address —\n * the cross-app key shared with Renown and Vetra.\n * 5. Calls `client.clear()` when the user transitions from defined →\n * `undefined` (logout).\n *\n * Teardown (unmount **or** consent revocation):\n * - `unregisterFactory(\"openpanel\")` to remove the processor.\n * - `resetOpenPanelClient()` to clear the singleton.\n * - `window.openPanel` is cleared.\n *\n * Mirrors the Sentry pattern in `store/user.ts` for login/logout detection.\n * Analytics failures are caught and forwarded to `console.warn` — they must\n * never throw into the application.\n *\n * Mounted next to `<Analytics />` in `app.tsx`.\n */\nexport function OpenPanel(): null {\n const [{ analytics }] = useAcceptedCookies();\n const user = useUser();\n const reactorClientModule = useReactorClientModule();\n\n const [client, setClient] = useState<OpenPanelClient | undefined>();\n\n /**\n * Tracks the previous `user` value so we can detect the two transitions:\n * undefined → defined (login)\n * defined → undefined (logout)\n */\n const prevUserRef = useRef<ReturnType<typeof useUser>>(undefined);\n\n const enabled = analytics && !!connectConfig.openPanel.clientId;\n const processorManager = reactorClientModule?.reactorModule?.processorManager;\n\n useEffect(() => {\n if (!enabled) return;\n\n let cancelled = false;\n\n // Read via a call — TS would otherwise narrow direct reads to always-false.\n const isCancelled = () => cancelled;\n\n const setup = async () => {\n let builtClient: OpenPanelClient | undefined;\n try {\n builtClient = await getOpenPanelClient(connectConfig.openPanel);\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to build client:\", err);\n return;\n }\n\n if (isCancelled() || !builtClient) return;\n\n setClient(builtClient);\n window.openPanel = builtClient;\n\n if (connectConfig.openPanel.trackOperations && processorManager) {\n try {\n await processorManager.registerFactory(\n \"openpanel\",\n createOpenPanelProcessorFactory({\n client: builtClient,\n events: { mappings: eventMappings, lookupMap: eventLookupMap },\n startFrom: \"current\",\n }),\n );\n // Guard against teardown happening while registerFactory was in flight.\n if (isCancelled()) {\n await processorManager\n .unregisterFactory(\"openpanel\")\n .catch((err: unknown) =>\n console.warn(\n \"[OpenPanel] Failed to unregister factory after cancellation:\",\n err,\n ),\n );\n }\n } catch (err) {\n console.warn(\n \"[OpenPanel] Failed to register processor factory:\",\n err,\n );\n }\n }\n };\n\n void setup();\n\n return () => {\n cancelled = true;\n\n // Reset the user-tracking ref so that when consent is re-granted (and a\n // new client is built) any currently-logged-in user is re-identified.\n prevUserRef.current = undefined;\n\n if (connectConfig.openPanel.trackOperations && processorManager) {\n void processorManager\n .unregisterFactory(\"openpanel\")\n .catch((err: unknown) =>\n console.warn(\n \"[OpenPanel] Failed to unregister processor factory:\",\n err,\n ),\n );\n }\n\n resetOpenPanelClient();\n window.openPanel = undefined;\n setClient(undefined);\n };\n }, [enabled, processorManager]);\n\n // detect login/logout transitions\n useEffect(() => {\n if (!enabled || !client) return;\n\n const prev = prevUserRef.current;\n prevUserRef.current = user;\n\n if (!prev && user) {\n // Login: undefined → defined (or client became available with user\n // already logged in — prevUserRef is undefined in both cases).\n try {\n void client.identify(buildIdentifyPayload(user));\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to identify user:\", err);\n }\n } else if (prev && !user) {\n // Logout: defined → undefined\n try {\n void client.clear();\n } catch (err) {\n console.warn(\"[OpenPanel] Failed to clear user:\", err);\n }\n }\n }, [client, user, enabled]);\n\n return null;\n}\n","import { DocumentEditor } from \"@powerhousedao/connect/components\";\nimport {\n setSelectedNode,\n useNodeParentFolderById,\n useSelectedDocument,\n} from \"@powerhousedao/reactor-browser\";\nimport { useCallback, useMemo } from \"react\";\n\nexport function DocumentEditorContainer() {\n const [selectedDocument] = useSelectedDocument();\n const parentFolder = useNodeParentFolderById(selectedDocument.header.id);\n\n // TODO: unused\n const _onOpenSwitchboardLink = useMemo(() => {\n return async () => {\n //\n };\n }, []);\n\n const _onClose = useCallback(() => {\n setSelectedNode(parentFolder);\n }, [parentFolder]);\n\n return (\n <div\n id=\"document-editor-container\"\n className=\"flex-1\"\n data-document-type={selectedDocument.header.documentType}\n >\n <DocumentEditor document={selectedDocument} />\n </div>\n );\n}\n","import { DefaultEditorLoader } from \"@powerhousedao/design-system/connect\";\nimport type { ComponentProps, ReactNode } from \"react\";\nimport { useEffect, useState } from \"react\";\n\ntype Props = ComponentProps<typeof DefaultEditorLoader> & {\n loadingTimeout?: number;\n customEditorLoader?: ReactNode;\n};\nexport function EditorLoader(props: Props) {\n const [showLoading, setShowLoading] = useState(false);\n\n // only shows the loader after some time has passed\n useEffect(() => {\n setTimeout(() => {\n setShowLoading(true);\n }, props.loadingTimeout ?? 200);\n }, [props]);\n\n if (!showLoading) return null;\n\n const { customEditorLoader, ...defaultProps } = props;\n\n if (customEditorLoader) return <>{customEditorLoader}</>;\n\n return <DefaultEditorLoader {...defaultProps} />;\n}\n","import { DropZoneWrapper } from \"@powerhousedao/design-system/connect\";\nimport { GenericDriveExplorer } from \"@powerhousedao/powerhouse-vetra-packages/editors\";\nimport {\n useAppModuleById,\n useDefaultAppModule,\n useSelectedDocumentId,\n useSelectedDriveSafe,\n} from \"@powerhousedao/reactor-browser\";\nimport { Suspense } from \"react\";\nimport { DocumentEditorContainer } from \"./document-editor-container.js\";\nimport { EditorLoader } from \"./editor-loader.js\";\nimport { ErrorBoundary } from \"./error-boundary.js\";\n\nexport function AppContainer() {\n const [selectedDrive] = useSelectedDriveSafe();\n const selectedDocumentId = useSelectedDocumentId();\n\n const app = useAppModuleById(selectedDrive?.header.meta?.preferredEditor);\n const defaultApp = useDefaultAppModule();\n\n if (!selectedDrive) {\n return <EditorLoader />;\n }\n\n const AppComponent =\n app?.Component ?? defaultApp?.Component ?? GenericDriveExplorer.Component;\n\n if (!AppComponent) {\n throw new Error(\"No app component found\");\n }\n return (\n <ErrorBoundary\n variant=\"detailed\"\n resetKeys={[selectedDrive.header.id]}\n loggerContext={[\"Connect\", \"App\"]}\n >\n <Suspense fallback={<EditorLoader />}>\n <DropZoneWrapper className=\"flex h-full flex-col overflow-auto\">\n <AppComponent>\n {selectedDocumentId ? <DocumentEditorContainer /> : null}\n </AppComponent>\n </DropZoneWrapper>\n </Suspense>\n </ErrorBoundary>\n );\n}\n","import { useInitSentry } from \"@powerhousedao/connect/hooks\";\n\ninterface SentryProviderProps {\n children?: React.ReactNode;\n}\n\nexport const SentryProvider: React.FC<SentryProviderProps> = ({ children }) => {\n useInitSentry();\n\n return children;\n};\n","import { Modal } from \"@powerhousedao/design-system\";\nimport {\n usePackageDiscoveryService,\n type FailedInstallation,\n type FailedInstallationReason,\n} from \"@powerhousedao/reactor-browser\";\nimport { useState } from \"react\";\nimport { twMerge } from \"tailwind-merge\";\nimport { useFailedInstallations } from \"../hooks/useFailedInstallations.js\";\n\nconst reasonLabels: Record<FailedInstallationReason, string> = {\n \"no-registry\": \"No package registry is configured.\",\n \"not-in-registry\": \"No matching package found in the registry.\",\n \"registry-error\": \"Couldn't reach the package registry.\",\n \"install-failed\": \"Package failed to install.\",\n dismissed: \"Installation was dismissed.\",\n};\n\nfunction canRetry(reason: FailedInstallationReason): boolean {\n return reason !== \"no-registry\";\n}\n\nexport function MissingModelBanner() {\n const failed = useFailedInstallations();\n const [open, setOpen] = useState(false);\n\n if (failed.length === 0) return null;\n\n return (\n <>\n <div className=\"flex items-center justify-between gap-3 bg-amber-100 px-4 py-2 text-sm text-amber-900 dark:bg-amber-800 dark:text-amber-100\">\n <span>\n {failed.length === 1\n ? \"1 document type couldn't load (missing model).\"\n : `${failed.length} document types couldn't load (missing models).`}\n </span>\n <button\n type=\"button\"\n onClick={() => setOpen(true)}\n className=\"rounded-md border border-amber-300 bg-gray-50 px-3 py-1 text-amber-900 hover:bg-amber-50 dark:border-amber-600 dark:bg-slate-800 dark:text-amber-100 dark:hover:bg-amber-900\"\n >\n View\n </button>\n </div>\n <MissingModelDetailsModal\n open={open}\n failed={failed}\n onClose={() => setOpen(false)}\n />\n </>\n );\n}\n\ntype DetailsProps = {\n readonly open: boolean;\n readonly failed: FailedInstallation[];\n readonly onClose: () => void;\n};\n\nfunction MissingModelDetailsModal(props: DetailsProps) {\n const { open, failed, onClose } = props;\n const discoveryService = usePackageDiscoveryService();\n const [retrying, setRetrying] = useState<Set<string>>(() => new Set());\n\n async function handleRetry(documentType: string) {\n if (!discoveryService) return;\n setRetrying((prev) => new Set(prev).add(documentType));\n try {\n await discoveryService.retryInstallation(documentType);\n } finally {\n setRetrying((prev) => {\n const next = new Set(prev);\n next.delete(documentType);\n return next;\n });\n }\n }\n\n return (\n <Modal\n open={open}\n onOpenChange={(isOpen) => {\n if (!isOpen) onClose();\n }}\n contentProps={{ className: \"rounded-3xl\" }}\n >\n <div className=\"w-[520px] max-w-[90vw] bg-gray-50 p-6 dark:bg-slate-800\">\n <div className=\"border-b border-gray-100 pb-2 text-2xl font-bold text-gray-900 dark:border-slate-500 dark:bg-slate-600 dark:text-slate-100\">\n Missing document models\n </div>\n <div className=\"my-4 text-sm text-gray-700 dark:text-slate-200\">\n The following document types couldn't be loaded. Documents using them\n won't display until the underlying package is installed.\n </div>\n {failed.length === 0 ? (\n <div className=\"rounded-xl bg-gray-50 p-4 text-sm text-gray-700 dark:bg-slate-800 dark:text-slate-200\">\n No outstanding failures.\n </div>\n ) : (\n <div className=\"flex max-h-[60vh] flex-col gap-3 overflow-y-auto\">\n {failed.map((entry) => {\n const isRetrying = retrying.has(entry.documentType);\n const retryDisabled = !canRetry(entry.reason) || isRetrying;\n return (\n <div\n key={entry.documentType}\n className=\"rounded-xl bg-gray-50 p-4 dark:bg-slate-800\"\n >\n <div className=\"mb-1 font-mono text-sm font-semibold text-gray-900 dark:text-slate-100\">\n {entry.documentType}\n </div>\n <div className=\"mb-2 text-xs text-gray-700 dark:text-slate-200\">\n {reasonLabels[entry.reason]}\n </div>\n {entry.packageNames.length > 0 ? (\n <div className=\"mb-2 text-xs text-gray-500 dark:text-slate-400\">\n Package{entry.packageNames.length > 1 ? \"s\" : \"\"}:{\" \"}\n {entry.packageNames.join(\", \")}\n </div>\n ) : null}\n {entry.error ? (\n <div className=\"mb-2 font-mono text-xs wrap-break-word text-red-700 dark:text-red-100\">\n {entry.error.message}\n </div>\n ) : null}\n <div className=\"flex justify-end\">\n <button\n type=\"button\"\n onClick={() => void handleRetry(entry.documentType)}\n disabled={retryDisabled}\n title={\n canRetry(entry.reason)\n ? undefined\n : \"No registry is configured; nothing to retry against.\"\n }\n className={twMerge(\n \"min-h-[32px] rounded-xl px-3 py-1 text-sm font-semibold text-white transition-all hover:scale-105 dark:text-slate-900\",\n retryDisabled\n ? \"cursor-not-allowed bg-gray-300 hover:scale-100 dark:bg-slate-600 dark:text-slate-100\"\n : \"bg-gray-800 active:opacity-75 dark:bg-slate-100\",\n )}\n >\n {isRetrying ? \"Retrying...\" : \"Try install again\"}\n </button>\n </div>\n </div>\n );\n })}\n </div>\n )}\n <div className=\"mt-4 flex justify-end\">\n <button\n type=\"button\"\n onClick={onClose}\n className=\"min-h-[36px] rounded-xl border border-gray-200 bg-gray-50 px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50 dark:border-slate-500 dark:bg-slate-600 dark:text-slate-100 dark:hover:bg-slate-800\"\n >\n Close\n </button>\n </div>\n </div>\n </Modal>\n );\n}\n","import {\n PackageInstallModal,\n type PendingPackageInstallation,\n} from \"@powerhousedao/design-system/connect\";\nimport { usePackageDiscoveryService } from \"@powerhousedao/reactor-browser\";\nimport { usePendingInstallations } from \"../hooks/usePendingInstallations.js\";\n\nexport function PackageInstallPrompt() {\n const pendingInstallations = usePendingInstallations();\n const discoveryService = usePackageDiscoveryService();\n\n if (!discoveryService || pendingInstallations.length === 0) return null;\n\n const installations: PendingPackageInstallation[] =\n pendingInstallations.flatMap((p) =>\n p.packageNames.map((packageName) => ({\n documentType: p.documentType,\n packageName,\n })),\n );\n\n return (\n <PackageInstallModal\n pendingInstallations={installations}\n onInstall={(packageName) =>\n discoveryService.approveInstallation(packageName)\n }\n onDismiss={(packageName) =>\n discoveryService.dismissInstallation(packageName)\n }\n />\n );\n}\n","import {\n Analytics,\n OpenPanel,\n Router,\n} from \"@powerhousedao/connect/components\";\n\nimport { SentryProvider } from \"@powerhousedao/connect/context\";\nimport {\n DocumentEditorDebugTools,\n serviceWorkerManager,\n} from \"@powerhousedao/connect/utils\";\nimport { useTheme } from \"@powerhousedao/reactor-browser\";\nimport { useEffect } from \"react\";\nimport { ToastContainer } from \"../services/toast.js\";\nimport { MissingModelBanner } from \"./missing-model-banner.js\";\nimport { PackageInstallPrompt } from \"./package-install-prompt.js\";\n\nexport const App = () => {\n useTheme(); // keeps the OS-preference change listener active\n\n // refresh page on vite preload error due to outdated chunks — but only when\n // the failing dynamic import is one of Connect's own chunks. External\n // dynamic imports (e.g. the package manager loading a package from the\n // configured CDN) should let the error propagate so the caller can surface\n // it; reloading here drops any open state and hides the real failure.\n useEffect(() => {\n const handlePreloadError = (event: Event) => {\n const payload = (event as Event & { payload?: unknown }).payload;\n const message =\n payload instanceof Error\n ? payload.message\n : typeof payload === \"string\"\n ? payload\n : \"\";\n const failedUrl = message.match(/https?:\\/\\/[^\\s\"']+/)?.[0];\n\n if (failedUrl && !failedUrl.startsWith(window.location.origin)) {\n console.debug(\n `[Connect] Skipping reload — vite:preloadError for off-origin URL: ${failedUrl}`,\n );\n return;\n }\n\n console.log(\"Outdated chunks detected, reloading page...\");\n window.location.reload();\n };\n\n window.addEventListener(\"vite:preloadError\", handlePreloadError);\n\n return () => {\n window.removeEventListener(\"vite:preloadError\", handlePreloadError);\n };\n }, []);\n\n useEffect(() => {\n if (import.meta.env.MODE === \"development\") {\n window.documentEditorDebugTools = new DocumentEditorDebugTools();\n } else {\n serviceWorkerManager.registerServiceWorker(false);\n }\n }, []);\n\n return (\n <SentryProvider>\n <ToastContainer position=\"bottom-right\" />\n <MissingModelBanner />\n <Router />\n <PackageInstallPrompt />\n <Analytics />\n <OpenPanel />\n </SentryProvider>\n );\n};\n","import {\n useAcceptedCookies,\n useCookieBanner,\n} from \"@powerhousedao/connect/hooks\";\nimport type { CookieInput } from \"@powerhousedao/design-system/connect\";\nimport { CookieBanner as PHCookieBanner } from \"@powerhousedao/design-system/connect\";\nimport { showPHModal } from \"@powerhousedao/reactor-browser\";\nimport { Trans, useTranslation } from \"react-i18next\";\nimport { i18n } from \"@powerhousedao/connect/i18n\";\n\nconst isCookieAccepted = (cookies: CookieInput[], id: string) => {\n return cookies.some((cookie) => cookie.id === id && cookie.value);\n};\n\nexport const CookieBanner = () => {\n const { t } = useTranslation(undefined, {\n useSuspense: true,\n i18n,\n });\n const [showBanner, setShowBanner] = useCookieBanner();\n const [, setAcceptedCookies] = useAcceptedCookies();\n\n const cookiesInput: CookieInput[] = [\n {\n id: \"analytics-cookie\",\n label: t(\"cookieBanner.cookies.analytics\"),\n value: true,\n },\n ];\n\n const handleAccept = (cookies: CookieInput[]) => {\n setShowBanner(false);\n\n if (isCookieAccepted(cookies, \"analytics-cookie\")) {\n setAcceptedCookies((acceptedCookies) => ({\n ...acceptedCookies,\n analytics: true,\n }));\n }\n };\n\n const handleReject = () => {\n setShowBanner(false);\n setAcceptedCookies(() => ({\n analytics: false,\n functional: false,\n marketing: false,\n }));\n };\n\n if (!showBanner) {\n return null;\n }\n\n return (\n <div className=\"absolute inset-0 z-10000 backdrop-blur-sm\">\n <div className=\"absolute inset-0 bg-gray-900 opacity-15 dark:bg-slate-50\" />\n <div className=\"absolute inset-x-0 bottom-0 flex justify-center bg-gray-50 px-10 pt-10 pb-16 shadow-lg dark:bg-slate-800\">\n <PHCookieBanner\n className=\"max-w-[1024px]\"\n cookies={cookiesInput}\n onSubmit={handleAccept}\n onReject={handleReject}\n submitLabel={t(\"cookieBanner.accept\")}\n rejectLabel={t(\"cookieBanner.reject\")}\n >\n <p className=\"font-semibold text-gray-500 dark:text-slate-400\">\n <Trans\n key={\"cookieBanner.message\"}\n i18nKey=\"cookieBanner.message\"\n components={{\n a: (\n <a\n onClick={() => showPHModal({ type: \"cookiesPolicy\" })}\n key={\"cookieBanner.message-link\"}\n className=\"cursor-pointer text-gray-900 hover:underline dark:text-slate-50\"\n />\n ),\n }}\n />\n </p>\n </PHCookieBanner>\n </div>\n </div>\n );\n};\n","import { Icon } from \"@powerhousedao/design-system\";\nimport { DriveCollectionId, useSyncList } from \"@powerhousedao/reactor-browser\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport { useMemo } from \"react\";\n\nexport function DriveIcon({\n drive,\n}: {\n drive: DocumentDriveDocument | undefined;\n}) {\n const remotes = useSyncList();\n const isRemoteDrive = useMemo(() => {\n if (!drive) return false;\n\n return remotes.some((remote) =>\n remote.collectionId.equals(DriveCollectionId.forDrive(drive.header.id)),\n );\n }, [remotes, drive]);\n\n const driveIconSrc = drive?.state.global.icon;\n\n if (driveIconSrc) {\n return (\n <img src={driveIconSrc} alt={drive.header.name} height={32} width={32} />\n );\n }\n\n if (!isRemoteDrive) {\n return <Icon name=\"Hdd\" size={32} />;\n }\n\n return <Icon name=\"Server\" size={32} />;\n}\n","import { EditorLoader } from \"@powerhousedao/connect/components\";\nimport { useUndoRedoShortcuts } from \"@powerhousedao/connect/hooks\";\nimport { toast } from \"@powerhousedao/connect/services\";\nimport { RevisionHistory } from \"@powerhousedao/design-system/connect\";\nimport {\n getRevisionFromDate,\n setRevisionHistoryVisible,\n showPHModal,\n useDocumentById,\n useDocumentModelModuleById,\n useDocumentOperations,\n useEditorModuleById,\n useFallbackEditorModule,\n useRevisionHistoryVisible,\n useSelectedTimelineItem,\n useVetraPackageManager,\n useVetraPackages,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PHDocument } from \"@powerhousedao/shared/document-model\";\nimport { redo, undo } from \"@powerhousedao/shared/document-model\";\nimport { Suspense, useEffect, useState } from \"react\";\nimport { CenteredErrorMessage, ErrorBoundary } from \"./error-boundary.js\";\n\ntype Props<TDocument extends PHDocument = PHDocument> = {\n document: TDocument;\n};\n\nfunction EditorError({ message }: { message: React.ReactNode }) {\n return (\n <div className=\"flex size-full items-center justify-center\">\n <h3 className=\"text-lg font-semibold\">{message}</h3>\n </div>\n );\n}\n\nexport const DocumentEditor: React.FC<Props> = (props) => {\n const { document: initialDocument } = props;\n const selectedTimelineItem = useSelectedTimelineItem();\n const revisionHistoryVisible = useRevisionHistoryVisible();\n const [document, dispatch] = useDocumentById(initialDocument.header.id);\n const documentId = document?.header.id ?? undefined;\n const documentName = document?.header.name ?? undefined;\n const documentType = document?.header.documentType ?? undefined;\n const preferredEditor = document?.header.meta?.preferredEditor ?? undefined;\n const {\n globalOperations,\n localOperations,\n isLoading: isLoadingOperations,\n refetch: refetchOperations,\n } = useDocumentOperations(documentId);\n\n // Refetch operations when revision history panel opens\n useEffect(() => {\n if (revisionHistoryVisible) {\n void refetchOperations();\n }\n }, [revisionHistoryVisible, refetchOperations]);\n\n const globalRevisionNumber = document?.header.revision.global ?? 0;\n const localRevisionNumber = document?.header.revision.local ?? 0;\n const documentModelModule = useDocumentModelModuleById(documentType);\n const preferredEditorModule = useEditorModuleById(preferredEditor);\n const fallbackEditorModule = useFallbackEditorModule(documentType);\n const editorModule = preferredEditorModule ?? fallbackEditorModule;\n const vetraPackages = useVetraPackages();\n const packageManager = useVetraPackageManager();\n const owningPackageName = editorModule\n ? vetraPackages.find((pkg) => pkg.editors.includes(editorModule))?.manifest\n .name\n : undefined;\n const owningPackageVersion =\n owningPackageName && packageManager\n ? packageManager.getPackageVersion(owningPackageName)\n : undefined;\n const editorBundleKey = owningPackageName\n ? `${owningPackageName}@${owningPackageVersion ?? \"unknown\"}`\n : (editorModule?.config.id ?? \"no-editor\");\n const isLoadingDocument = !document;\n const isLoadingEditor =\n editorModule &&\n documentType &&\n !editorModule.documentTypes.includes(documentType) &&\n !editorModule.documentTypes.includes(\"*\");\n\n const canUndo = globalRevisionNumber > 0 || localRevisionNumber > 0;\n const canRedo = !!document?.clipboard.length;\n const addUndoAction = () => dispatch(undo());\n const addRedoAction = () => dispatch(redo());\n useUndoRedoShortcuts({\n undo: addUndoAction,\n redo: addRedoAction,\n canUndo,\n canRedo,\n });\n\n useEffect(() => {\n return () => {\n window.documentEditorDebugTools?.clear();\n };\n }, []);\n\n const [editorError, setEditorError] = useState<\n | {\n error: any;\n info: React.ErrorInfo;\n documentId?: string;\n // clear: () => void;\n }\n | undefined\n >(undefined);\n\n useEffect(() => {\n if (editorError && editorError.documentId !== documentId) {\n // eslint-disable-next-line react-hooks/set-state-in-effect\n setEditorError(undefined);\n }\n }, [editorError, documentId]);\n\n const handleEditorError = (error: Error, info: React.ErrorInfo) => {\n setEditorError({\n error,\n documentId,\n info,\n });\n };\n\n if (isLoadingEditor) {\n return <EditorLoader message=\"Loading editor\" />;\n }\n\n if (isLoadingDocument) {\n return <EditorLoader message=\"Loading document\" />;\n }\n\n if (!documentModelModule) {\n return (\n <EditorError\n message={\n <div className=\"text-center leading-10\">\n <p>\n Unable to open the document because the document model \"\n {documentType}\" is not supported.\n </p>\n <p>\n Go to the{\" \"}\n <button\n type=\"button\"\n className=\"cursor-pointer underline\"\n onClick={() => {\n showPHModal({ type: \"settings\" });\n }}\n >\n package manager\n </button>{\" \"}\n to install this document model\n </p>\n </div>\n }\n />\n );\n }\n\n if (!editorModule) {\n return (\n <EditorError\n message={\n <div className=\"text-center leading-10\">\n <p>Unable to open the document because no editor has been found</p>\n <p>\n Go to the{\" \"}\n <button\n type=\"button\"\n className=\"cursor-pointer underline\"\n onClick={() => {\n showPHModal({ type: \"settings\" });\n }}\n >\n package manager\n </button>{\" \"}\n an editor for the \"${documentType}\" document type\n </p>\n </div>\n }\n />\n );\n }\n const EditorComponent = editorModule.Component;\n\n return (\n <div\n className=\"relative h-full\"\n id=\"document-editor-context\"\n data-editor={editorModule.config.id}\n data-document-type={documentType}\n >\n {revisionHistoryVisible ? (\n isLoadingOperations ? (\n <EditorLoader message=\"Loading operations\" />\n ) : (\n <RevisionHistory\n key={documentId}\n documentTitle={documentName ?? \"\"}\n documentId={documentId ?? \"\"}\n globalOperations={globalOperations}\n localOperations={localOperations}\n onClose={() => setRevisionHistoryVisible(false)}\n documentState={document.state}\n onCopyState={() => {\n toast(\"Copied document state to clipboard\", { type: \"success\" });\n }}\n onCopyDocId={() => {\n toast(\"Copied document ID to clipboard\", { type: \"success\" });\n }}\n />\n )\n ) : (\n <Suspense\n fallback={<EditorLoader message=\"Loading editor\" />}\n name=\"EditorLoader\"\n >\n <ErrorBoundary\n fallbackRender={CenteredErrorMessage}\n resetKeys={[documentId]}\n onError={handleEditorError}\n loggerContext={[\"Connect\", \"DocumentEditor\"]}\n >\n {!editorError?.error && (\n <EditorComponent\n key={`${editorBundleKey}:${documentId}`}\n context={{\n readMode: !!selectedTimelineItem,\n selectedTimelineRevision: getRevisionFromDate(\n selectedTimelineItem?.startDate,\n selectedTimelineItem?.endDate,\n globalOperations,\n ),\n }}\n documentId={document.header.id}\n />\n )}\n </ErrorBoundary>\n </Suspense>\n )}\n </div>\n );\n};\n","import { Sidebar } from \"@powerhousedao/connect/components\";\nimport { useIsEmbedded } from \"@powerhousedao/connect/hooks\";\nimport { Suspense } from \"react\";\nimport { Outlet } from \"react-router-dom\";\n\nexport function Root() {\n const isEmbedded = useIsEmbedded();\n return (\n <div className=\"h-screen bg-gray-50 dark:bg-slate-800\">\n <div\n className={`flex h-screen items-stretch overflow-auto`}\n role=\"presentation\"\n tabIndex={0}\n >\n <Suspense name=\"Root\">\n {!isEmbedded && <Sidebar />}\n <div className=\"relative flex-1 overflow-auto\">\n <Outlet />\n </div>\n </Suspense>\n </div>\n </div>\n );\n}\n","import { AppContainer, DriveIcon } from \"@powerhousedao/connect/components\";\nimport {\n defaultPHAppConfig,\n defaultPHDocumentEditorConfig,\n} from \"@powerhousedao/connect/config\";\nimport {\n HomeScreen,\n HomeScreenAddDriveItem,\n HomeScreenItem,\n} from \"@powerhousedao/design-system/connect\";\nimport {\n setPHAppConfig,\n setPHDocumentEditorConfig,\n setSelectedDrive,\n useAppModuleById,\n useDrives,\n useIsAddDriveEnabled,\n useSelectedDocumentId,\n useSelectedDriveSafe,\n useSelectedFolder,\n} from \"@powerhousedao/reactor-browser\";\nimport type { DocumentDriveDocument } from \"@powerhousedao/shared/document-drive\";\nimport { useEffect } from \"react\";\nimport { getRuntimeConfig } from \"../runtime-config.js\";\n\nexport function Content() {\n const [selectedDrive] = useSelectedDriveSafe();\n const selectedFolder = useSelectedFolder();\n const selectedDocumentId = useSelectedDocumentId();\n\n useEffect(() => {\n if (!selectedDocumentId) {\n setPHDocumentEditorConfig(defaultPHDocumentEditorConfig);\n }\n }, [selectedDocumentId]);\n\n useEffect(() => {\n if (!selectedDrive) {\n setPHAppConfig(defaultPHAppConfig);\n }\n }, [selectedDrive]);\n\n const showHomeScreen =\n !selectedDocumentId && !selectedDrive && !selectedFolder;\n return (\n <ContentContainer>\n {showHomeScreen ? <HomeScreenContainer /> : <AppContainer />}\n </ContentContainer>\n );\n}\n\nfunction ContentContainer({ children }: { children: React.ReactNode }) {\n return (\n <div className=\"flex h-full flex-col overflow-auto\" id=\"content-view\">\n {children}\n </div>\n );\n}\n\nfunction DriveItem({ drive }: { drive: DocumentDriveDocument }) {\n const editorModule = useAppModuleById(drive.header.meta?.preferredEditor);\n const description = editorModule?.config.name || \"Drive Explorer App\";\n return (\n <HomeScreenItem\n key={drive.header.id}\n title={drive.state.global.name || drive.header.name}\n description={description}\n icon={<DriveIcon drive={drive} />}\n onClick={() => setSelectedDrive(drive)}\n />\n );\n}\n\nfunction HomeScreenContainer() {\n const drives = useDrives();\n const isAddDriveEnabled = useIsAddDriveEnabled();\n const runtimeConfig = getRuntimeConfig();\n const homeBackground = runtimeConfig.connect?.branding?.homeBackground;\n return (\n <HomeScreen homeBackground={homeBackground}>\n {drives?.map((drive) => {\n return <DriveItem key={drive.header.id} drive={drive} />;\n })}\n {isAddDriveEnabled && <HomeScreenAddDriveItem />}\n </HomeScreen>\n );\n}\n","import { Root } from \"@powerhousedao/connect/components\";\nimport { connectConfig } from \"@powerhousedao/connect/config\";\nimport { Content } from \"@powerhousedao/connect/pages\";\nimport { Suspense } from \"react\";\nimport type { RouteObject } from \"react-router-dom\";\nimport { RouterProvider, createBrowserRouter } from \"react-router-dom\";\n\nfunction createRouter(routes: RouteObject[]) {\n const routerBasename = connectConfig.routerBasename;\n\n return createBrowserRouter(routes, {\n basename: routerBasename,\n future: {\n v7_fetcherPersist: true,\n v7_relativeSplatPath: true,\n },\n });\n}\n\nfunction createRoutes() {\n const routes: RouteObject[] = [\n {\n index: true,\n path: \"d?/:driveId?/*?\",\n element: (\n <Suspense name=\"Drive\">\n <Content />\n </Suspense>\n ),\n },\n ];\n\n return [\n {\n element: (\n <Suspense name=\"RouteRoot\">\n <Root />\n </Suspense>\n ),\n children: routes,\n },\n ];\n}\n\nconst routes = createRoutes();\nconst router = createRouter(routes);\n\nexport const Router = () => {\n return <RouterProvider router={router} />;\n};\n","import { DriveIcon } from \"@powerhousedao/connect/components\";\nimport {\n ConnectSidebar,\n ConnectTooltipProvider,\n SidebarAddDriveItem,\n SidebarItem,\n useEns,\n} from \"@powerhousedao/design-system/connect\";\n\nimport {\n logout,\n openRenown,\n setSelectedDrive,\n showPHModal,\n useIsAddDriveEnabled,\n useDrives,\n useSelectedDriveSafe,\n useUser,\n} from \"@powerhousedao/reactor-browser\";\nimport { ErrorBoundary } from \"./error-boundary.js\";\n\nexport function Sidebar() {\n const user = useUser();\n const drives = useDrives();\n const isAddDriveEnabled = useIsAddDriveEnabled();\n const [selectedDrive] = useSelectedDriveSafe();\n const connectDebug = localStorage.getItem(\"CONNECT_DEBUG\") === \"true\";\n\n const ensName = user?.ens?.name || user?.profile?.username || undefined;\n const avatarUrl =\n user?.ens?.avatarUrl || user?.profile?.userImage || undefined;\n\n const ensInfo = useEns(!avatarUrl ? user?.address : undefined);\n\n const onClickSettings = () => {\n showPHModal({ type: \"settings\" });\n };\n\n const onAddDriveClick = () => {\n showPHModal({ type: \"addDrive\" });\n };\n\n const etherscanUrl = user?.address\n ? `https://etherscan.io/address/${user.address}`\n : \"\";\n\n return (\n <ConnectTooltipProvider>\n <ConnectSidebar\n id=\"sidebar\"\n onClick={() => setSelectedDrive(undefined)}\n onClickSettings={onClickSettings}\n address={user?.address}\n onLogin={openRenown}\n onDisconnect={() => {\n void logout();\n }}\n ensName={ensName || ensInfo.data?.ens}\n avatarUrl={\n avatarUrl ||\n ensInfo.data?.avatar_small ||\n ensInfo.data?.avatar_url ||\n undefined\n }\n etherscanUrl={etherscanUrl}\n showDebug={connectDebug}\n onDebugClick={() => showPHModal({ type: \"debugSettings\" })}\n >\n <ErrorBoundary\n variant=\"text\"\n fallbackMessage=\"There was an error loading drives\"\n loggerContext={[\"Connect\", \"Sidebar\"]}\n >\n {drives?.map((drive, index) => (\n <SidebarItem\n key={index}\n title={drive.header.name}\n onClick={() => setSelectedDrive(drive)}\n active={selectedDrive?.header.id === drive.header.id}\n icon={<DriveIcon drive={drive} />}\n />\n ))}\n {isAddDriveEnabled && (\n <SidebarAddDriveItem onClick={onAddDriveClick} />\n )}\n </ErrorBoundary>\n </ConnectSidebar>\n </ConnectTooltipProvider>\n );\n}\n","import {\n CURRENT_PG_MAJOR,\n getCachedReactorPgMajor,\n migrateAllIfNeeded,\n subscribeReactorPgMajor,\n} from \"@powerhousedao/connect/utils\";\nimport { useState, useSyncExternalStore } from \"react\";\n\nlet dismissed = false;\nconst listeners = new Set<() => void>();\n\nfunction notify() {\n for (const l of listeners) l();\n}\n\nfunction dismiss() {\n dismissed = true;\n notify();\n}\n\nfunction subscribeDismissed(cb: () => void): () => void {\n listeners.add(cb);\n return () => {\n listeners.delete(cb);\n };\n}\n\nfunction getDismissed(): boolean {\n return dismissed;\n}\n\nexport const MigrationBanner: React.FC = () => {\n const isDismissed = useSyncExternalStore(\n subscribeDismissed,\n getDismissed,\n () => false,\n );\n const major = useSyncExternalStore(\n subscribeReactorPgMajor,\n getCachedReactorPgMajor,\n () => undefined,\n );\n const [migrating, setMigrating] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n if (major === undefined || major === null || major === CURRENT_PG_MAJOR) {\n return null;\n }\n if (isDismissed) return null;\n\n const handleMigrate = () => {\n setError(null);\n setMigrating(true);\n migrateAllIfNeeded()\n .then(() => {\n window.location.reload();\n })\n .catch((err: unknown) => {\n setError(err instanceof Error ? err.message : String(err));\n setMigrating(false);\n });\n };\n\n return (\n <div className=\"absolute inset-x-0 top-0 z-30 flex justify-center p-3\">\n <div className=\"flex max-w-3xl items-center gap-3 rounded-lg border border-yellow-500 bg-yellow-400 px-4 py-3 text-sm text-gray-900 shadow-lg dark:border-yellow-400 dark:bg-yellow-500 dark:text-slate-50\">\n <div className=\"flex-1\">\n <div className=\"font-semibold\">\n Your local database uses Postgres {major}.\n </div>\n <div className=\"text-gray-900 dark:text-slate-100\">\n Migrate to Postgres {CURRENT_PG_MAJOR} to pick up the latest\n features. Your data will be backed up first.\n </div>\n {error && (\n <div className=\"mt-2 font-medium text-red-900 dark:text-red-400\">\n Migration failed: {error}\n </div>\n )}\n </div>\n <button\n type=\"button\"\n disabled={migrating}\n onClick={handleMigrate}\n className=\"rounded-sm bg-gray-900 px-3 py-1 text-sm font-medium text-white hover:bg-gray-800 disabled:opacity-50 dark:bg-slate-50 dark:text-slate-900 dark:hover:bg-slate-100\"\n >\n {migrating ? \"Migrating…\" : \"Migrate now\"}\n </button>\n <button\n type=\"button\"\n disabled={migrating}\n onClick={dismiss}\n className=\"rounded-sm border border-gray-900 bg-transparent px-3 py-1 text-sm font-medium text-gray-900 hover:bg-gray-900/10 disabled:opacity-50 dark:border-slate-50 dark:text-slate-50\"\n >\n Dismiss\n </button>\n </div>\n </div>\n );\n};\n","import { usePHModal } from \"@powerhousedao/reactor-browser\";\nimport { lazy, Suspense } from \"react\";\nimport { ErrorBoundary } from \"../error-boundary.js\";\n\nconst AddDriveModal = lazy(() =>\n import(\"./modals/AddDriveModal.js\").then((m) => ({\n default: m.AddDriveModal,\n })),\n);\nconst ClearStorageModal = lazy(() =>\n import(\"./modals/ClearStorageModal.js\").then((m) => ({\n default: m.ClearStorageModal,\n })),\n);\nconst CookiesPolicyModal = lazy(() =>\n import(\"./modals/CookiesPolicyModal.js\").then((m) => ({\n default: m.CookiesPolicyModal,\n })),\n);\nconst CreateDocumentModal = lazy(() =>\n import(\"./modals/CreateDocumentModal.js\").then((m) => ({\n default: m.CreateDocumentModal,\n })),\n);\nconst DebugSettingsModal = lazy(() =>\n import(\"./modals/DebugSettingsModal.js\").then((m) => ({\n default: m.DebugSettingsModal,\n })),\n);\nconst DeleteDriveModal = lazy(() =>\n import(\"./modals/DeleteDriveModal.js\").then((m) => ({\n default: m.DeleteDriveModal,\n })),\n);\nconst DeleteItemModal = lazy(() =>\n import(\"./modals/DeleteItemModal.js\").then((m) => ({\n default: m.DeleteItemModal,\n })),\n);\nconst DisclaimerModal = lazy(() =>\n import(\"./modals/DisclaimerModal.js\").then((m) => ({\n default: m.DisclaimerModal,\n })),\n);\nconst DriveSettingsModal = lazy(() =>\n import(\"./modals/DriveSettingsModal.js\").then((m) => ({\n default: m.DriveSettingsModal,\n })),\n);\nconst DownloadDocumentWithErrorsModal = lazy(() =>\n import(\"./modals/DownloadDocumentWithErrorsModal.js\").then((m) => ({\n default: m.DownloadDocumentWithErrorsModal,\n })),\n);\nconst SettingsModal = lazy(() =>\n import(\"./modals/SettingsModal.js\").then((m) => ({\n default: m.SettingsModal,\n })),\n);\nconst UpgradeDriveModal = lazy(() =>\n import(\"./modals/UpgradeDriveModal.js\").then((m) => ({\n default: m.UpgradeDriveModal,\n })),\n);\nconst InspectorModal = lazy(() =>\n import(\"./modals/InspectorModal/index.js\").then((m) => ({\n default: m.InspectorModal,\n })),\n);\nconst MissingPackageModal = lazy(() =>\n import(\"./modals/MissingPackageModal.js\").then((m) => ({\n default: m.ConnectMissingPackageModal,\n })),\n);\nconst modalComponents = {\n addDrive: AddDriveModal,\n clearStorage: ClearStorageModal,\n cookiesPolicy: CookiesPolicyModal,\n createDocument: CreateDocumentModal,\n debugSettings: DebugSettingsModal,\n deleteDrive: DeleteDriveModal,\n deleteItem: DeleteItemModal,\n disclaimer: DisclaimerModal,\n driveSettings: DriveSettingsModal,\n downloadDocumentWithErrors: DownloadDocumentWithErrorsModal,\n inspector: InspectorModal,\n settings: SettingsModal,\n upgradeDrive: UpgradeDriveModal,\n missingPackage: MissingPackageModal,\n} as const;\n\nexport const ModalsContainer = lazy(() => {\n return Promise.resolve({\n default: () => {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const phModal = usePHModal();\n\n if (!phModal?.type) return null;\n\n const ModalComponent = modalComponents[phModal.type];\n\n return ModalComponent ? (\n <ErrorBoundary variant=\"silent\" loggerContext={[\"Connect\", \"Modals\"]}>\n <Suspense fallback={null}>\n <ModalComponent />\n </Suspense>\n </ErrorBoundary>\n ) : null;\n },\n });\n});\n","import \"@powerhousedao/connect/i18n\";\nimport type { DocumentModelLib } from \"document-model\";\nimport { lazy, StrictMode, Suspense } from \"react\";\nimport AppSkeleton from \"./app-skeleton.js\";\nimport { DetailedFallback, ErrorBoundary } from \"./error-boundary.js\";\nimport { App, CookieBanner } from \"./index.js\";\nimport { MigrationBanner } from \"./migration-banner.js\";\nimport { ModalsContainer } from \"./modal/modals-container.js\";\n\nexport const AppLoader = (props: { localPackage?: DocumentModelLib }) => {\n const Load = lazy(() =>\n import(\"./load.js\").then((m) => m.loadComponent(props.localPackage)),\n );\n return (\n <StrictMode>\n <ErrorBoundary\n fallbackRender={(props) => (\n <AppSkeleton children={<DetailedFallback {...props} />} />\n )}\n resetKeys={[props.localPackage]}\n loggerContext={[\"Connect\"]}\n >\n <Suspense fallback={<AppSkeleton />} name=\"AppLoader\">\n {/* eslint-disable-next-line react-hooks/static-components */}\n <Load {...props}>\n <App />\n </Load>\n </Suspense>\n <Suspense name=\"CookieBanner\">\n <CookieBanner />\n </Suspense>\n <Suspense name=\"ModalsContainer\">\n <ModalsContainer />\n </Suspense>\n <MigrationBanner />\n </ErrorBoundary>\n </StrictMode>\n );\n};\n"],"names":["listeners","listeners","getInitial","subscribe","rawEvents","listeners","emptyArray","logger","logger","ErrorBoundary","ReactErrorBoundary","ErrorBoundary","CookieBanner","PHCookieBanner","ErrorBoundary","ErrorBoundary","AddDriveModal","CreateDocumentModal","DriveSettingsModal","SettingsModal","ErrorBoundary","ErrorBoundary","CookieBanner"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAgB,cAAc;AAC5B,KAAI,OAAO,aAAa,YACtB,QAAO;AAKT,QAFe,SAAS,cAAc,OAAO,EACxB,aAAa,OAAO,IAC1B;;;;ACFjB,IAAa,2BAAb,MAAsC;CACpC;CACA,aAAkC,EAAE;CAEpC,YAAY,UAAuB;AACjC,MAAI,SACF,MAAK,WAAW;;CAIpB,wBAA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EACE,iBAAiB,UACf,oBAAC,aAAD,EAAa,UAAU,oBAAC,kBAAD,EAAkB,GAAI,OAAS,CAAA,EAAI,CAAA;EAE5D,WAAW,CAAC,MAAM,aAAa;EAC/B,eAAe,CAAC,UAAU;YAL5B;GAOE,oBAAC,UAAD;IAAU,UAAU,oBAAC,aAAD,EAAe,CAAA;IAAE,MAAK;cAExC,oBAAC,MAAD;KAAM,GAAI;eACR,oBAAC,KAAD,EAAO,CAAA;KACF,CAAA;IACE,CAAA;GACX,oBAAC,UAAD;IAAU,MAAK;cACb,oBAACC,gBAAD,EAAgB,CAAA;IACP,CAAA;GACX,oBAAC,UAAD;IAAU,MAAK;cACb,oBAAC,iBAAD,EAAmB,CAAA;IACV,CAAA;GACX,oBAAC,iBAAD,EAAmB,CAAA;GACL;KACL,CAAA","debug_id":"a2462d25-f167-5c28-a4b2-81ce30bf4e13"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"package-Doxk1oGT.js","sources":["../package.json"],"sourcesContent":[""],"names":[],"mappings":"","debug_id":"20fac82a-059d-5835-9693-fd108218d0ae"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"reactor-BAZd7zrS.js","sources":["../src/utils/reactor.ts","../src/feature-flags.ts","../src/no-registry-discovery.ts","../src/package-discovery.ts","../src/package-manager.ts","../src/pglite.db.ts","../src/store/processor-host-module.ts","../src/store/reactor.ts"],"sourcesContent":["import {\n addRemoteDrive,\n ChannelScheme,\n ReactorBuilder,\n ReactorClientBuilder,\n setDriveMetadata,\n waitForDocumentReady,\n type BrowserReactorClientModule,\n type Database,\n type IDocumentModelLoader,\n type JwtHandler,\n type SignerConfig,\n} from \"@powerhousedao/reactor-browser\";\nimport type { PHConnectDefaultDrive } from \"@powerhousedao/shared/clis\";\nimport type { RuntimePowerhouseConfig } from \"@powerhousedao/shared/connect\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { createSignatureVerifier, type IRenown } from \"@renown/sdk\";\nimport { ConsoleLogger } from \"document-model\";\nimport { Kysely } from \"kysely\";\nimport { PGliteDialect } from \"kysely-pglite-dialect\";\nimport {\n detectReactorPgMajor,\n loadPGliteModule,\n resolvePgMajorForRuntime,\n} from \"./pglite-runtime.js\";\nimport { REACTOR_PGLITE_NAME } from \"./storage-namespace.js\";\n\n/**\n * Creates a Reactor that plugs into legacy storage but syncs through the new\n * Reactor GQL API.\n */\nexport async function createBrowserReactor(\n documentModelModules: DocumentModelModule[],\n upgradeManifests: UpgradeManifest<readonly number[]>[],\n renown: IRenown,\n documentModelLoader?: IDocumentModelLoader,\n): Promise<BrowserReactorClientModule> {\n const signerConfig: SignerConfig = {\n signer: renown.signer,\n verifier: createSignatureVerifier(),\n };\n\n const jwtHandler: JwtHandler = async (url: string) => {\n if (!renown.user) {\n return undefined;\n }\n return renown.getBearerToken({ expiresIn: 10, aud: url });\n };\n\n const detected = await detectReactorPgMajor();\n const major = resolvePgMajorForRuntime(detected);\n if (major !== 17) {\n console.warn(\n `[reactor] Running against legacy PGlite data dir (Postgres ${major}). Migrate to PG17 from the banner or the Inspector → Debug tab.`,\n );\n }\n const { PGlite } = await loadPGliteModule(major);\n const pg = new PGlite(`idb://${REACTOR_PGLITE_NAME}`, {\n relaxedDurability: true,\n });\n const logger = new ConsoleLogger([\"reactor-client\"]);\n const builder = new ReactorClientBuilder()\n .withLogger(logger)\n .withSigner(signerConfig)\n .withReactorBuilder(\n new ReactorBuilder()\n .withDocumentModels(documentModelModules)\n .withUpgradeManifests(upgradeManifests)\n .withChannelScheme(ChannelScheme.CONNECT)\n .withJwtHandler(jwtHandler)\n .withKysely(\n new Kysely<Database>({\n dialect: new PGliteDialect(pg),\n }),\n ),\n );\n\n if (documentModelLoader) {\n builder.withDocumentModelLoader(documentModelLoader);\n }\n\n const module = await builder.buildModule();\n return {\n ...module,\n pg,\n } as BrowserReactorClientModule;\n}\n\nexport function getDefaultDrives(\n runtimeConfig: RuntimePowerhouseConfig,\n): PHConnectDefaultDrive[] {\n return runtimeConfig.connect.drives?.defaultDrives ?? [];\n}\n\n/**\n * Add default drives for the new reactor via sync manager.\n *\n * Drives register concurrently so a slow or unreachable drive can't delay the\n * others — in particular the one the URL slug resolves to. Retries with linear\n * backoff to handle the common race where Connect's dev server is ready before\n * the switchboard has finished binding its port.\n *\n * @param drives - Array of drive objects with url, optional name and icon\n */\nexport async function addDefaultDrivesForNewReactor(\n drives: PHConnectDefaultDrive[],\n): Promise<void> {\n const MAX_ATTEMPTS = 3;\n const BACKOFF_MS = 2000;\n\n await Promise.all(\n drives.map(async (drive) => {\n let driveId: string | undefined;\n for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {\n try {\n driveId = await addRemoteDrive(drive.url);\n break;\n } catch (error) {\n if (attempt === MAX_ATTEMPTS) {\n console.error(\n `Failed to add default drive ${drive.url} after ${MAX_ATTEMPTS} attempts:`,\n error,\n );\n } else {\n const delay = BACKOFF_MS * attempt;\n console.warn(\n `Default drive ${drive.url} not reachable (attempt ${attempt}/${MAX_ATTEMPTS}), retrying in ${delay}ms...`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n if (driveId && (drive.name || drive.icon)) {\n try {\n // setDriveMetadata dispatches against the local drive document, which\n // only exists once initial backfill delivers it — wait for it first\n // so the name/icon override isn't lost to a sync race.\n const reactorClient = window.ph?.reactorClient;\n if (reactorClient) {\n await waitForDocumentReady(reactorClient, driveId, {\n timeoutMs: 15_000,\n });\n }\n await setDriveMetadata(driveId, {\n name: drive.name,\n icon: drive.icon,\n });\n } catch (error) {\n console.warn(\n `Default drive ${drive.url} was added but metadata update failed:`,\n error,\n );\n }\n }\n }),\n );\n}\n","import {\n OpenFeature,\n type ErrorCode,\n type JsonValue,\n type Provider,\n type ResolutionDetails,\n} from \"@openfeature/web-sdk\";\nimport { logger, setLogLevel, type ILogger } from \"document-model\";\n\n/**\n * QueryParamProvider reads feature flags from URL query parameters.\n *\n * Usage:\n * const params = new URLSearchParams(window.location.search);\n * const provider = new QueryParamProvider(params);\n * await OpenFeature.setProviderAndWait(provider);\n *\n * Query parameter format:\n * ?FEATURE_DUAL_ACTION_CREATE_ENABLED=true&FEATURE_FOO=false\n */\nexport class QueryParamProvider implements Provider {\n public readonly runsOn = \"client\" as const;\n\n readonly metadata = {\n name: \"QueryParamProvider\",\n } as const;\n\n private flags: Map<string, string>;\n\n constructor(searchParams: URLSearchParams) {\n this.flags = new Map();\n\n // Extract all query parameters that look like feature flags\n for (const [key, value] of searchParams.entries()) {\n this.flags.set(key, value);\n }\n }\n\n resolveBooleanEvaluation(\n flagKey: string,\n defaultValue: boolean,\n ): ResolutionDetails<boolean> {\n const value = this.flags.get(flagKey);\n\n if (value === undefined) {\n return {\n value: defaultValue,\n reason: \"DEFAULT\",\n };\n }\n\n // Parse boolean from string\n const boolValue = value.toLowerCase() === \"true\" || value === \"1\";\n\n return {\n value: boolValue,\n reason: \"STATIC\",\n variant: value,\n };\n }\n\n resolveStringEvaluation(\n flagKey: string,\n defaultValue: string,\n ): ResolutionDetails<string> {\n const value = this.flags.get(flagKey);\n\n if (value === undefined) {\n return {\n value: defaultValue,\n reason: \"DEFAULT\",\n };\n }\n\n return {\n value,\n reason: \"STATIC\",\n variant: value,\n };\n }\n\n resolveNumberEvaluation(\n flagKey: string,\n defaultValue: number,\n ): ResolutionDetails<number> {\n const value = this.flags.get(flagKey);\n\n if (value === undefined) {\n return {\n value: defaultValue,\n reason: \"DEFAULT\",\n };\n }\n\n const numValue = Number(value);\n\n if (isNaN(numValue)) {\n return {\n value: defaultValue,\n reason: \"ERROR\",\n errorCode: \"PARSE_ERROR\" as ErrorCode,\n errorMessage: `Failed to parse \"${value}\" as a number`,\n };\n }\n\n return {\n value: numValue,\n reason: \"STATIC\",\n variant: value,\n };\n }\n\n resolveObjectEvaluation<T extends JsonValue>(\n flagKey: string,\n defaultValue: T,\n ): ResolutionDetails<T> {\n const value = this.flags.get(flagKey);\n\n if (value === undefined) {\n return {\n value: defaultValue,\n reason: \"DEFAULT\",\n };\n }\n\n try {\n const objValue = JSON.parse(value) as T;\n return {\n value: objValue,\n reason: \"STATIC\",\n variant: value,\n };\n } catch (error) {\n return {\n value: defaultValue,\n reason: \"ERROR\",\n errorCode: \"PARSE_ERROR\" as ErrorCode,\n errorMessage: `Failed to parse JSON: ${error instanceof Error ? error.message : String(error)}`,\n };\n }\n }\n}\n\n/**\n * Initialize OpenFeature with the QueryParamProvider.\n * Reads feature flags from query parameters.\n */\nexport async function initFeatureFlags(\n searchParams?: URLSearchParams,\n): Promise<Map<string, boolean>> {\n const params =\n searchParams ??\n (typeof window !== \"undefined\"\n ? new URLSearchParams(window.location.search)\n : new URLSearchParams());\n const provider = new QueryParamProvider(params);\n await OpenFeature.setProviderAndWait(provider);\n\n const features = new Map<string, boolean>();\n\n // Handle LOG_LEVEL query param override\n const logLevelParam = params.get(\"LOG_LEVEL\");\n if (logLevelParam) {\n const validLogLevels = [\"verbose\", \"debug\", \"info\", \"warn\", \"error\"];\n if (validLogLevels.includes(logLevelParam.toLowerCase())) {\n setLogLevel(logLevelParam.toLowerCase() as ILogger[\"level\"]);\n logger.info(\n \"Log level set to @level via query param\",\n logLevelParam.toLowerCase(),\n );\n } else {\n logger.warn(\n \"Invalid LOG_LEVEL query param: @param. Valid values: @validLevels\",\n logLevelParam,\n validLogLevels.join(\", \"),\n );\n }\n }\n\n return features;\n}\n","import {\n type IDocumentModelLoader,\n type IPackageDiscoveryService,\n type DiscoveryEvent,\n type DiscoveryEventListener,\n type FailedInstallation,\n type PendingInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { BrowserPackageManager } from \"./package-manager.js\";\n\n/**\n * Discovery service used when no package registry is configured. Every load\n * for an unknown document type is recorded as a failure with reason\n * \"no-registry\" so the UI can surface the issue; the modal install flow is a\n * no-op because there is no registry to query.\n */\nexport class NoRegistryDiscoveryService\n implements IDocumentModelLoader, IPackageDiscoveryService\n{\n #packageManager: BrowserPackageManager;\n #failed = new Map<string, FailedInstallation>();\n #failedMemo: FailedInstallation[] = [];\n #failedSubscribers = new Set<() => void>();\n #eventSubscribers = new Set<DiscoveryEventListener>();\n\n constructor(packageManager: BrowserPackageManager) {\n this.#packageManager = packageManager;\n }\n\n load(documentType: string): Promise<DocumentModelModule<any>> {\n const existing = this.#findModuleInLoadedPackages(documentType);\n if (existing) {\n this.#clearFailed(documentType);\n return Promise.resolve(existing);\n }\n\n this.#recordFailure(documentType);\n return Promise.reject(\n new Error(\n `No package registry configured; cannot resolve \"${documentType}\"`,\n ),\n );\n }\n\n promptInstallation(): void {\n // no registry to query — nothing to prompt\n }\n\n approveInstallation(): Promise<void> {\n return Promise.resolve();\n }\n\n dismissInstallation(): void {\n // nothing to dismiss\n }\n\n getPendingInstallations(): PendingInstallation[] {\n return [];\n }\n\n subscribePending(): () => void {\n return () => {};\n }\n\n getFailedInstallations(): FailedInstallation[] {\n return this.#failedMemo;\n }\n\n subscribeFailed(listener: () => void): () => void {\n this.#failedSubscribers.add(listener);\n return () => {\n this.#failedSubscribers.delete(listener);\n };\n }\n\n subscribeEvents(listener: DiscoveryEventListener): () => void {\n this.#eventSubscribers.add(listener);\n return () => {\n this.#eventSubscribers.delete(listener);\n };\n }\n\n retryInstallation(documentType: string): Promise<void> {\n // Retry is a no-op without a registry, but re-emitting the failure lets\n // a UI that cleared the row know the underlying condition still holds.\n this.#recordFailure(documentType);\n return Promise.resolve();\n }\n\n #findModuleInLoadedPackages(\n documentType: string,\n ): DocumentModelModule<any> | undefined {\n return this.#packageManager.packages\n .flatMap((p) => p.documentModels)\n .find((m) => m.documentModel.global.id === documentType);\n }\n\n #recordFailure(documentType: string): void {\n this.#failed.set(documentType, {\n documentType,\n reason: \"no-registry\",\n packageNames: [],\n error: null,\n });\n this.#emitEvent({\n type: \"load-failed\",\n documentType,\n reason: \"no-registry\",\n });\n this.#notifyFailedChanged();\n }\n\n #clearFailed(documentType: string): void {\n if (this.#failed.delete(documentType)) {\n this.#notifyFailedChanged();\n }\n }\n\n #notifyFailedChanged(): void {\n this.#failedMemo = Array.from(this.#failed.values());\n for (const listener of this.#failedSubscribers) {\n listener();\n }\n }\n\n #emitEvent(event: DiscoveryEvent): void {\n for (const listener of this.#eventSubscribers) {\n listener(event);\n }\n }\n}\n","import {\n BrowserLocalStorage,\n type IDocumentModelLoader,\n type IPackageDiscoveryService,\n type DiscoveryEvent,\n type DiscoveryEventListener,\n type FailedInstallation,\n type FailedInstallationReason,\n type PendingInstallation,\n} from \"@powerhousedao/reactor-browser\";\nimport type { RegistryClient } from \"@powerhousedao/reactor-browser\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport type { BrowserPackageManager } from \"./package-manager.js\";\n\nexport type DiscoveryMode = \"immediate\" | \"manual\";\n\ntype DeferredEntry = {\n packageNames: string[];\n resolve: (module: DocumentModelModule<any>) => void;\n reject: (reason: unknown) => void;\n promise: Promise<DocumentModelModule<any>>;\n};\n\nexport class PackageDiscoveryService\n implements IDocumentModelLoader, IPackageDiscoveryService\n{\n #packageManager: BrowserPackageManager;\n #registryClient: RegistryClient;\n #mode: DiscoveryMode;\n\n #deferred = new Map<string, DeferredEntry>();\n #pending = new Map<string, PendingInstallation>();\n #pendingMemo: PendingInstallation[] = [];\n #pendingSubscribers = new Set<() => void>();\n #failed = new Map<string, FailedInstallation>();\n #failedMemo: FailedInstallation[] = [];\n #failedSubscribers = new Set<() => void>();\n #eventSubscribers = new Set<DiscoveryEventListener>();\n #dismissedStorage: BrowserLocalStorage<boolean>;\n #discoveredTypes = new Map<string, string[]>();\n\n constructor(\n packageManager: BrowserPackageManager,\n registryClient: RegistryClient,\n options: { mode: DiscoveryMode; storageKey: string },\n ) {\n this.#packageManager = packageManager;\n this.#registryClient = registryClient;\n this.#mode = options.mode;\n this.#dismissedStorage = new BrowserLocalStorage<boolean>(\n options.storageKey + \":PH_DISMISSED_TYPES\",\n );\n }\n\n load(documentType: string): Promise<DocumentModelModule<any>> {\n const existing = this.#findModuleInLoadedPackages(documentType);\n if (existing) {\n this.#clearFailed(documentType);\n return Promise.resolve(existing);\n }\n\n if (this.#dismissedStorage.has(documentType)) {\n this.#recordFailure(documentType, \"dismissed\", [], null);\n return Promise.reject(\n new Error(`Document type \"${documentType}\" was dismissed`),\n );\n }\n\n const tracked = this.#deferred.get(documentType);\n if (tracked) {\n return tracked.promise;\n }\n\n return this.#discover(documentType);\n }\n\n promptInstallation(documentType: string): void {\n const packageNames = this.#discoveredTypes.get(documentType);\n if (!packageNames) return;\n if (this.#pending.has(documentType)) return;\n\n this.#discoveredTypes.delete(documentType);\n this.#addToPending(documentType, packageNames);\n }\n\n async approveInstallation(packageName: string): Promise<void> {\n const affectedTypes = this.#findTypesByPackage(packageName);\n if (affectedTypes.length === 0) return;\n\n const result = await this.#packageManager.addPackage(packageName);\n if (result.type === \"error\") {\n this.#emitEvent({\n type: \"installation-failed\",\n packageName,\n error: result.error,\n });\n for (const documentType of affectedTypes) {\n const entry = this.#deferred.get(documentType);\n if (entry) {\n entry.reject(result.error);\n this.#deferred.delete(documentType);\n this.#pending.delete(documentType);\n }\n this.#recordFailure(\n documentType,\n \"install-failed\",\n [packageName],\n result.error,\n );\n }\n this.#notifyPendingChanged();\n return;\n }\n\n this.#emitEvent({\n type: \"installation-approved\",\n packageName,\n documentTypes: affectedTypes,\n });\n\n for (const documentType of affectedTypes) {\n const entry = this.#deferred.get(documentType);\n if (!entry) continue;\n\n const module = this.#findModuleInLoadedPackages(documentType);\n if (module) {\n entry.resolve(module);\n this.#clearFailed(documentType);\n } else {\n const error = new Error(\n `Package \"${packageName}\" installed but module for \"${documentType}\" not found`,\n );\n entry.reject(error);\n this.#recordFailure(\n documentType,\n \"install-failed\",\n [packageName],\n error,\n );\n }\n this.#deferred.delete(documentType);\n this.#pending.delete(documentType);\n }\n this.#notifyPendingChanged();\n }\n\n dismissInstallation(packageName: string): void {\n const affectedTypes = this.#findTypesByPackage(packageName);\n if (affectedTypes.length === 0) return;\n\n for (const documentType of affectedTypes) {\n this.#dismissedStorage.set(documentType, true);\n const entry = this.#deferred.get(documentType);\n if (entry) {\n entry.reject(\n new Error(`Document type \"${documentType}\" was dismissed`),\n );\n }\n this.#deferred.delete(documentType);\n this.#pending.delete(documentType);\n this.#discoveredTypes.delete(documentType);\n this.#recordFailure(documentType, \"dismissed\", [packageName], null);\n }\n\n this.#emitEvent({\n type: \"installation-dismissed\",\n packageName,\n documentTypes: affectedTypes,\n });\n this.#notifyPendingChanged();\n }\n\n getPendingInstallations(): PendingInstallation[] {\n return this.#pendingMemo;\n }\n\n subscribePending(listener: () => void): () => void {\n this.#pendingSubscribers.add(listener);\n return () => {\n this.#pendingSubscribers.delete(listener);\n };\n }\n\n getFailedInstallations(): FailedInstallation[] {\n return this.#failedMemo;\n }\n\n subscribeFailed(listener: () => void): () => void {\n this.#failedSubscribers.add(listener);\n return () => {\n this.#failedSubscribers.delete(listener);\n };\n }\n\n subscribeEvents(listener: DiscoveryEventListener): () => void {\n this.#eventSubscribers.add(listener);\n return () => {\n this.#eventSubscribers.delete(listener);\n };\n }\n\n async retryInstallation(documentType: string): Promise<void> {\n this.#dismissedStorage.delete(documentType);\n this.#clearFailed(documentType);\n try {\n await this.#discover(documentType);\n } catch {\n // failure has been recorded via #recordFailure; swallow so the\n // caller (UI button) doesn't have to handle the rejection\n }\n }\n\n async #discover(documentType: string): Promise<DocumentModelModule<any>> {\n let packageNames: string[];\n try {\n packageNames =\n await this.#registryClient.getPackagesByDocumentType(documentType);\n } catch (error) {\n const normalized =\n error instanceof Error ? error : new Error(String(error));\n this.#emitEvent({\n type: \"registry-query-failed\",\n documentType,\n error: normalized,\n });\n this.#recordFailure(documentType, \"registry-error\", [], normalized);\n return Promise.reject(normalized);\n }\n\n if (packageNames.length === 0) {\n this.#recordFailure(documentType, \"not-in-registry\", [], null);\n return Promise.reject(\n new Error(`No packages found for document type \"${documentType}\"`),\n );\n }\n\n const entry = this.#createDeferredEntry(documentType, packageNames);\n\n this.#emitEvent({\n type: \"type-discovered\",\n documentType,\n packageNames,\n });\n\n if (this.#mode === \"immediate\") {\n this.#addToPending(documentType, packageNames);\n } else {\n this.#discoveredTypes.set(documentType, packageNames);\n }\n\n return entry.promise;\n }\n\n #createDeferredEntry(\n documentType: string,\n packageNames: string[],\n ): DeferredEntry {\n let resolve!: (module: DocumentModelModule<any>) => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<DocumentModelModule<any>>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n const entry: DeferredEntry = { packageNames, resolve, reject, promise };\n this.#deferred.set(documentType, entry);\n return entry;\n }\n\n #addToPending(documentType: string, packageNames: string[]): void {\n const installation: PendingInstallation = { documentType, packageNames };\n this.#pending.set(documentType, installation);\n this.#emitEvent({\n type: \"installation-prompted\",\n documentType,\n packageNames,\n });\n this.#notifyPendingChanged();\n }\n\n #findModuleInLoadedPackages(\n documentType: string,\n ): DocumentModelModule<any> | undefined {\n return this.#packageManager.packages\n .flatMap((p) => p.documentModels)\n .find((m) => m.documentModel.global.id === documentType);\n }\n\n #findTypesByPackage(packageName: string): string[] {\n const types: string[] = [];\n for (const [documentType, entry] of this.#deferred) {\n if (entry.packageNames.includes(packageName)) {\n types.push(documentType);\n }\n }\n return types;\n }\n\n #notifyPendingChanged(): void {\n this.#pendingMemo = Array.from(this.#pending.values());\n for (const listener of this.#pendingSubscribers) {\n listener();\n }\n }\n\n #notifyFailedChanged(): void {\n this.#failedMemo = Array.from(this.#failed.values());\n for (const listener of this.#failedSubscribers) {\n listener();\n }\n }\n\n #recordFailure(\n documentType: string,\n reason: FailedInstallationReason,\n packageNames: string[],\n error: Error | null,\n ): void {\n this.#failed.set(documentType, {\n documentType,\n reason,\n packageNames,\n error,\n });\n this.#emitEvent({ type: \"load-failed\", documentType, reason });\n this.#notifyFailedChanged();\n }\n\n #clearFailed(documentType: string): void {\n if (this.#failed.delete(documentType)) {\n this.#notifyFailedChanged();\n }\n }\n\n #emitEvent(event: DiscoveryEvent): void {\n for (const listener of this.#eventSubscribers) {\n listener(event);\n }\n }\n}\n","import * as common from \"@powerhousedao/powerhouse-vetra-packages\";\nimport commonPkg from \"@powerhousedao/powerhouse-vetra-packages/package.json\" with { type: \"json\" };\nimport type {\n IPackagesListener,\n PackageManagerInstallResult,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n BrowserLocalStorage,\n type IPackageListerUnsubscribe,\n type IPackageManager,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n type DocumentModelLib,\n type DocumentModelModule,\n} from \"@powerhousedao/shared/document-model\";\nimport * as vetra from \"@powerhousedao/vetra\";\nimport vetraPkg from \"@powerhousedao/vetra/package.json\" with { type: \"json\" };\n\ntype PackageMeta = {\n name: string;\n importUrl: string | null;\n stylesheetUrl: string | null;\n version?: string;\n /**\n * Full spec the user asked for (e.g. `@scope/pkg@2.0.0-beta.2`). Kept so a\n * reload re-installs exactly the tag/version originally picked rather than\n * sliding to `latest`. Absent for legacy entries and local packages.\n */\n spec?: string;\n};\n\n/**\n * Strip any `@tag` / `@version` suffix from a package spec, returning the bare\n * package name. Mirrors `parsePackageSpec` on the UI side.\n */\nfunction parseBareName(spec: string): string {\n const trimmed = spec.trim();\n const at = trimmed.startsWith(\"@\")\n ? trimmed.lastIndexOf(\"@\")\n : trimmed.indexOf(\"@\");\n return at > 0 ? trimmed.slice(0, at) : trimmed;\n}\n\ntype PackageWithMeta = PackageMeta & {\n loadedPackage: DocumentModelLib<any>;\n spec?: string;\n};\n\nasync function fetchPackageJsonVersion(\n baseUrl: string,\n): Promise<string | undefined> {\n try {\n const res = await fetch(baseUrl);\n if (!res.ok) return undefined;\n const pkg = (await res.json()) as { version?: unknown };\n return typeof pkg.version === \"string\" ? pkg.version : undefined;\n } catch {\n return undefined;\n }\n}\n\nconst LOCAL_PACKAGE_NAME = \"Local\" as const;\n\nexport class BrowserPackageManager implements IPackageManager {\n registryUrl: string | null;\n #storage: BrowserLocalStorage<PackageMeta>;\n #packages: Map<string, DocumentModelLib<any>> = new Map();\n #subscribers = new Set<IPackagesListener>();\n #packagesMemo: DocumentModelLib<any>[] = [];\n #stylesheets: Map<string, HTMLStyleElement> = new Map();\n #localPackage: DocumentModelLib<any> | undefined;\n\n #cdnUrl: string | null;\n #localPackageVersion: string | undefined;\n #localPackageNames: Set<string> = new Set([LOCAL_PACKAGE_NAME]);\n\n constructor(namespace: string, registryUrl: string | null) {\n this.#storage = new BrowserLocalStorage<PackageMeta>(\n namespace + \":PH_PACKAGES\",\n );\n this.registryUrl = registryUrl;\n this.#cdnUrl = registryUrl !== null ? this.#toCdnUrl(registryUrl) : null;\n }\n\n #toCdnUrl(baseUrl: string): string {\n if (baseUrl.includes(\"/-/cdn\")) return baseUrl;\n const base = baseUrl.endsWith(\"/\") ? baseUrl.slice(0, -1) : baseUrl;\n return `${base}/-/cdn`;\n }\n\n async init(\n localPackage?: DocumentModelLib<any>,\n localPackageVersion?: string,\n ) {\n this.addLocalPackage(common.manifest.name, common, commonPkg.version);\n this.addLocalPackage(vetra.manifest.name, vetra, vetraPkg.version);\n if (localPackage) {\n this.updateLocalPackage(localPackage, localPackageVersion);\n }\n for (const packageName of this.#storage.keys()) {\n // Re-hydrate with the originally-requested spec so a tag/version pick\n // sticks across reloads. Fall back to the bare key for legacy entries\n // (pre-spec) and for entries that never had a tag.\n const existingMeta = this.#storage.get(packageName);\n const specForReload = existingMeta?.spec ?? packageName;\n console.debug(\n `[Connect][PackageManager] Rehydrating \"${packageName}\" via spec \"${specForReload}\"`,\n );\n const result = await this.addPackage(specForReload);\n // Previously-installed package that no longer resolves (version\n // withdrawn from npm, registry moved, etc.) would otherwise\n // 404-toast on every boot forever. Drop it from persistent storage\n // so the failure is one-shot instead of sticky.\n if (result.type === \"error\") {\n this.#storage.delete(packageName);\n }\n }\n }\n\n addLocalPackage(\n name: string,\n loadedPackage: DocumentModelLib<any>,\n version?: string,\n ) {\n this.#localPackageNames.add(name);\n this.#registerPackage({\n name,\n importUrl: null,\n stylesheetUrl: null,\n loadedPackage,\n version,\n });\n }\n\n updateLocalPackage(pkg: DocumentModelLib<any>, version?: string) {\n console.debug(\"Updating local package:\", pkg);\n this.#localPackage = pkg;\n this.#registerPackage({\n name: LOCAL_PACKAGE_NAME,\n stylesheetUrl: null,\n importUrl: null,\n loadedPackage: pkg,\n });\n if (version) {\n this.#localPackageVersion = version;\n this.#notifyPackagesChanged();\n return;\n }\n fetchPackageJsonVersion(\"/package.json\")\n .then((fetchedVersion) => {\n this.#localPackageVersion = fetchedVersion;\n if (fetchedVersion) this.#notifyPackagesChanged();\n })\n .catch(() => {});\n }\n\n get packages() {\n return this.#packagesMemo;\n }\n\n get cdnUrl(): string | null {\n return this.#cdnUrl;\n }\n\n getPackageSource(packageName: string) {\n // check vs packages registered as local (Common, Vetra, bundled packages...)\n if (this.#localPackageNames.has(packageName)) {\n return \"common\";\n }\n // check if the package has the same name as the local project\n if (packageName === this.#localPackage?.manifest.name) return \"project\";\n const packageMeta = this.#storage.get(packageName);\n // if meta does not exist the package is not installed\n if (!packageMeta) return null;\n // if imported from node_modules then the package is installed locally\n if (packageMeta.importUrl === `/node_modules/${packageName}`)\n return \"local-install\";\n // all other import urls point to a registry\n return \"registry-install\";\n }\n\n /**\n * Return the registry-installed packages keyed by their storage name (which\n * is the registry spec, e.g. \"@powerhousedao/clint-common\"), with the\n * installed version when known. Excludes bundled (common) packages, the\n * local project package, and packages resolved out of `/node_modules/`.\n */\n getRegistryPackages(): { name: string; version: string | undefined }[] {\n const out: { name: string; version: string | undefined }[] = [];\n for (const [name, meta] of this.#storage) {\n if (this.#localPackageNames.has(name)) continue;\n if (name === LOCAL_PACKAGE_NAME) continue;\n if (meta.importUrl === `/node_modules/${name}`) continue;\n out.push({ name, version: meta.version });\n }\n return out;\n }\n\n getPackageVersion(packageName: string): string | undefined {\n if (packageName === this.#localPackage?.manifest.name) {\n return this.#localPackageVersion;\n }\n return this.#storage.get(packageName)?.version;\n }\n\n async addPackage(packageSpec: string): Promise<PackageManagerInstallResult> {\n // `packageSpec` may include a `@tag` / `@version` suffix (e.g. user picked\n // a specific version in the package manager UI, or re-hydrated on reload\n // from the persisted spec). We always register/look up by the bare name so\n // status tracking, version lookups, and uninstall all go through a single\n // canonical key. The spec itself is kept on the meta so reloads re-fetch\n // the same tag.\n const bareName = parseBareName(packageSpec);\n const hasTagOrVersion = bareName !== packageSpec;\n console.debug(\n `[Connect][PackageManager] addPackage spec=\"${packageSpec}\" bareName=\"${bareName}\"`,\n );\n\n const existingPackage = this.#packages.get(bareName);\n if (existingPackage) {\n const requestedVersion = hasTagOrVersion\n ? packageSpec.slice(bareName.length + 1)\n : undefined;\n const currentVersion = this.#storage.get(bareName)?.version;\n const isLocal = this.#localPackageNames.has(bareName);\n const sameVersion =\n !requestedVersion ||\n !currentVersion ||\n requestedVersion === currentVersion;\n if (isLocal || sameVersion) {\n console.debug(\n `[Connect][PackageManager] \"${bareName}\" already loaded; skipping re-fetch`,\n );\n return {\n type: \"success\",\n package: existingPackage,\n };\n }\n console.debug(\n `[Connect][PackageManager] \"${bareName}\" version bump ${currentVersion} → ${requestedVersion}; refetching`,\n );\n }\n try {\n const packageWithMeta = await this.#loadPackage(packageSpec);\n // `#loadPackage*` set `name` to whatever spec it built the URL from.\n // Canonicalize to the bare name for the map/storage keys, and stash the\n // original spec separately so reloads re-use it.\n packageWithMeta.name = bareName;\n if (hasTagOrVersion) {\n packageWithMeta.spec = packageSpec;\n }\n // Swap stylesheets only once the new package is in hand. If `#loadPackage`\n // throws above, the old stylesheet stays mounted and the UI keeps\n // rendering the previous version instead of unstyled markup.\n if (existingPackage) {\n this.#unmountStylesheet(bareName);\n }\n this.#registerPackage(packageWithMeta);\n\n return {\n type: \"success\",\n package: packageWithMeta.loadedPackage,\n };\n } catch (error) {\n const normalized =\n error instanceof Error ? error : new Error(String(error));\n console.error(\n `[Connect][PackageManager] Failed to install package \"${packageSpec}\": ${normalized.message}`,\n normalized,\n );\n return {\n type: \"error\",\n error: normalized,\n };\n }\n }\n\n async addPackages(packageNames: string[]) {\n const results: PackageManagerInstallResult[] = [];\n for (const packageName of packageNames) {\n const result = await this.addPackage(packageName);\n results.push(result);\n }\n return results;\n }\n\n removePackage(name: string) {\n this.#packages.delete(name);\n this.#storage.delete(name);\n this.#unmountStylesheet(name);\n this.#notifyPackagesChanged();\n }\n\n subscribe(handler: IPackagesListener): IPackageListerUnsubscribe {\n this.#subscribers.add(handler);\n return () => {\n this.#subscribers.delete(handler);\n };\n }\n\n load(documentType: string): Promise<DocumentModelModule<any>> {\n const documentModelModule = Array.from(\n this.#packages.values().flatMap((p) => p.documentModels),\n ).find((m) => m.documentModel.global.id === documentType);\n\n if (documentModelModule) return Promise.resolve(documentModelModule);\n return Promise.reject(new Error(\"Model not available\"));\n }\n\n async #loadPackageFromNodeModules(name: string): Promise<PackageWithMeta> {\n const importUrl = `/node_modules/${name}/browser/index.js`;\n const stylesheetUrl = `/node_modules/${name}/style.css`;\n\n const packageWithMeta = await this.#importPackage({\n name,\n importUrl,\n stylesheetUrl,\n });\n packageWithMeta.version = await fetchPackageJsonVersion(\n `/node_modules/${name}/package.json`,\n );\n\n return packageWithMeta;\n }\n\n async #loadPackageFromRegistry(name: string): Promise<PackageWithMeta> {\n const importUrl = `${this.#cdnUrl}/${name}/browser/index.js`;\n const stylesheetUrl = `${this.#cdnUrl}/${name}/style.css`;\n const packageWithMeta = await this.#importPackage({\n name,\n importUrl,\n stylesheetUrl,\n });\n packageWithMeta.version = await fetchPackageJsonVersion(\n `${this.#cdnUrl}/${name}/package.json`,\n );\n\n return packageWithMeta;\n }\n\n async #importPackage(packageMeta: PackageMeta): Promise<PackageWithMeta> {\n const { name, importUrl, stylesheetUrl } = packageMeta;\n if (!importUrl) {\n throw new Error(`Import url not defined for package \"${name}\".`);\n }\n\n const loadedPackage = (await import(\n /* @vite-ignore */ importUrl\n )) as DocumentModelLib<any>;\n\n return {\n name,\n loadedPackage,\n importUrl,\n stylesheetUrl,\n };\n }\n\n async #loadPackage(packageName: string): Promise<PackageWithMeta> {\n if (this.#localPackageNames.has(packageName)) {\n throw new Error(\n `Package \"${packageName}\" is a local package and cannot be loaded dynamically.`,\n );\n }\n\n // only attemp to load from node_modules in dev mode\n if (!import.meta.env.PROD) {\n try {\n const packageWithMeta =\n await this.#loadPackageFromNodeModules(packageName);\n return packageWithMeta;\n } catch (error) {\n console.warn(\n `Failed to load package \"${packageName}\" from node_modules:`,\n error,\n );\n }\n }\n\n if (!this.registryUrl) {\n throw new Error(\"Registry url not defined.\");\n }\n\n return await this.#loadPackageFromRegistry(packageName);\n }\n\n #registerPackage(packageWithMeta: PackageWithMeta) {\n const { name, loadedPackage, importUrl, stylesheetUrl, version, spec } =\n packageWithMeta;\n\n if (stylesheetUrl !== null) {\n this.#mountStylesheet(name, stylesheetUrl);\n }\n this.#packages.set(name, loadedPackage);\n this.#storage.set(name, {\n name,\n importUrl,\n stylesheetUrl,\n version,\n ...(spec ? { spec } : {}),\n });\n console.debug(\n `[Connect][PackageManager] Registered \"${name}\" (version=${version ?? \"?\"}, spec=${spec ?? \"—\"})`,\n );\n\n this.#notifyPackagesChanged();\n }\n\n #mountStylesheet(name: string, href: string) {\n const existing = this.#stylesheets.get(name);\n if (existing) return existing;\n\n const style = document.createElement(\"style\");\n style.textContent = `@import url(\"${href}\") layer(external-packages);`;\n document.head.appendChild(style);\n\n this.#stylesheets.set(name, style);\n }\n\n #unmountStylesheet(name: string): void {\n const style = this.#stylesheets.get(name);\n if (!style) return;\n\n style.remove();\n this.#stylesheets.delete(name);\n }\n\n #notifyPackagesChanged() {\n this.#packagesMemo = Array.from(this.#packages.values());\n const packages = this.packages;\n this.#subscribers.forEach((handler) => {\n handler({ packages });\n });\n }\n}\n","import type { PGliteWorker } from \"@electric-sql/pglite/worker\";\nimport { createRelationalDb } from \"@powerhousedao/shared/processors\";\nimport { Kysely } from \"kysely\";\nimport { PGliteDialect } from \"kysely-pglite-dialect\";\nimport {\n detectRelationalPgMajor,\n resolvePgMajorForRuntime,\n type SupportedPgMajor,\n} from \"./utils/pglite-runtime.js\";\nimport { RELATIONAL_PGLITE_NAME } from \"./utils/storage-namespace.js\";\n\nasync function createPGliteWorkerForMajor(\n major: SupportedPgMajor,\n): Promise<PGliteWorker> {\n // The worker reads the data-dir name from meta so the namespace is owned on\n // the main thread alongside the other origin-scoped stores.\n const meta = { dbName: RELATIONAL_PGLITE_NAME };\n if (major === 16) {\n const [legacyWorker, legacyLive] = await Promise.all([\n import(\"pglite-legacy-02/worker\"),\n import(\"pglite-legacy-02/live\"),\n ]);\n const worker = new Worker(\n new URL(\"./pglite.worker.legacy.js\", import.meta.url),\n { type: \"module\" },\n );\n return legacyWorker.PGliteWorker.create(worker, {\n meta,\n extensions: { live: legacyLive.live },\n }) as unknown as PGliteWorker;\n }\n const [{ PGliteWorker }, { live }] = await Promise.all([\n import(\"@electric-sql/pglite/worker\"),\n import(\"@electric-sql/pglite/live\"),\n ]);\n const worker = new Worker(new URL(\"./pglite.worker.js\", import.meta.url), {\n type: \"module\",\n });\n return PGliteWorker.create(worker, { meta, extensions: { live } });\n}\n\nexport async function getDb() {\n const detected = await detectRelationalPgMajor();\n const major = resolvePgMajorForRuntime(detected);\n if (major !== 17) {\n console.warn(\n `[reactor] Relational worker is opening legacy Postgres ${major} data dir. Migrate to PG17 from the banner or the Inspector → Debug tab.`,\n );\n }\n\n const pgLite = await createPGliteWorkerForMajor(major);\n\n const kysely = new Kysely({\n dialect: new PGliteDialect(pgLite),\n });\n\n const relationalDb = createRelationalDb(kysely);\n\n return { pgLite, relationalDb };\n}\n","import {\n createAttachmentClient,\n type AttachmentHeader,\n type AttachmentResponse,\n type IAttachmentService,\n} from \"@powerhousedao/reactor-attachments/client\";\nimport {\n createAnalyticsStore,\n type IReactorClient,\n type IReactorProcessorHostModule,\n} from \"@powerhousedao/reactor-browser\";\nimport { getDb } from \"../pglite.db.js\";\n\n/** @deprecated Use IReactorClient from @powerhousedao/reactor-browser */\nexport type IReactorDispatch = IReactorClient;\n\nclass NullAttachmentService implements IAttachmentService {\n reserve(): Promise<never> {\n return Promise.reject(\n new Error(\"NullAttachmentService: no attachment service configured\"),\n );\n }\n stat(): Promise<AttachmentHeader> {\n return Promise.reject(\n new Error(\"NullAttachmentService: no attachment service configured\"),\n );\n }\n get(): Promise<AttachmentResponse> {\n return Promise.reject(\n new Error(\"NullAttachmentService: no attachment service configured\"),\n );\n }\n}\n\ninterface INamedReadModel {\n readonly name: string;\n}\n\nexport async function createProcessorHostModule(\n reactorClient: IReactorClient,\n readModels: INamedReadModel[],\n attachmentService?: IAttachmentService,\n): Promise<IReactorProcessorHostModule | undefined> {\n try {\n const { pgLite, relationalDb } = await getDb();\n const { store: analyticsStore } = await createAnalyticsStore({\n pgLite,\n });\n const processorApp = \"connect\" as const;\n return {\n relationalDb,\n analyticsStore,\n processorApp,\n client: reactorClient,\n attachments: createAttachmentClient(\n attachmentService ?? new NullAttachmentService(),\n ),\n dispatch: {\n async execute(docId, branch, actions, signal) {\n const jobInfo = await reactorClient.executeAsync(\n docId,\n branch,\n actions,\n signal,\n );\n return { id: jobInfo.id, status: jobInfo.status };\n },\n },\n getReadModel<T>(name: string): T {\n const model = readModels.find((m) => m.name === name);\n if (!model) {\n throw new Error(`Read model \"${name}\" not found`);\n }\n return model as unknown as T;\n },\n };\n } catch (error) {\n console.error(`Failed to initialize processor host module:`);\n console.error(error);\n }\n}\n","import {\n buildPHGlobalConfig,\n phGlobalConfig,\n} from \"@powerhousedao/connect/config\";\nimport { toast } from \"@powerhousedao/connect/services\";\nimport {\n addDefaultDrivesForNewReactor,\n createBrowserReactor,\n getDefaultDrives,\n} from \"@powerhousedao/connect/utils\";\nimport { createRemoteAttachmentService } from \"@powerhousedao/reactor-attachments/client\";\nimport {\n addPHEventHandlers,\n addRemoteDrive,\n DocumentCache,\n DocumentChangeType,\n extractDriveSlugFromPath,\n extractNodeSlugFromPath,\n getDrives,\n login,\n refreshReactorDataClient,\n RegistryClient,\n setAttachmentService,\n setDefaultPHGlobalConfig,\n setDocumentCache,\n setDrives,\n setFeatures,\n setPackageDiscoveryService,\n setPHToast,\n setReactorClient,\n setReactorClientModule,\n setRenown,\n setSelectedDrive,\n setSelectedNode,\n setVetraPackageManager,\n type IPackageManager,\n type PHToastFn,\n} from \"@powerhousedao/reactor-browser\";\nimport {\n BrowserKeyStorage,\n RenownBuilder,\n RenownCryptoBuilder,\n} from \"@renown/sdk\";\nimport {\n logger,\n type DocumentModelLib,\n type UpgradeManifest,\n} from \"document-model\";\nimport { initFeatureFlags } from \"../feature-flags.js\";\nimport { NoRegistryDiscoveryService } from \"../no-registry-discovery.js\";\nimport { PackageDiscoveryService } from \"../package-discovery.js\";\nimport { BrowserPackageManager } from \"../package-manager.js\";\nimport { getRuntimeConfig } from \"../runtime-config.js\";\nimport { createProcessorHostModule } from \"./processor-host-module.js\";\n\n/**\n * Subscribe to the `/__packages` SSE channel exposed by ph-clint's\n * static-mode `connect-server.js`. On each `packages-changed` event the\n * server sends the full live list; we diff against what the packageManager\n * already has loaded and call `addPackage`/`removePackage` to converge.\n *\n * Best-effort — silently no-ops when the SSE endpoint doesn't exist\n * (e.g. running under vite dev, or hosted somewhere without this protocol).\n */\nfunction subscribeToPackagesChannel(packageManager: IPackageManager): void {\n if (typeof window === \"undefined\" || typeof EventSource === \"undefined\") {\n return;\n }\n let source: EventSource;\n try {\n source = new EventSource(\"/__packages\");\n } catch (err) {\n console.debug(\"[Connect] /__packages subscribe failed:\", err);\n return;\n }\n let firstEvent = true;\n source.addEventListener(\"packages-changed\", (event) => {\n try {\n const payload = JSON.parse((event as MessageEvent<string>).data) as {\n packages?: unknown;\n };\n if (!Array.isArray(payload.packages)) return;\n const next = payload.packages.filter(\n (p): p is string => typeof p === \"string\",\n );\n // Split each incoming spec into (bareName, version). The server may\n // send either bare names (\"@scope/pkg\") or version-qualified specs\n // (\"@scope/pkg@1.2.3\"). parseBareName-style logic: for scoped specs\n // the first `@` belongs to the scope, so version starts after the\n // last `@` only when that `@` is past index 0.\n const parseBare = (\n spec: string,\n ): { bareName: string; version?: string } => {\n const at = spec.startsWith(\"@\")\n ? spec.lastIndexOf(\"@\")\n : spec.indexOf(\"@\");\n if (at > 0) {\n return { bareName: spec.slice(0, at), version: spec.slice(at + 1) };\n }\n return { bareName: spec };\n };\n\n // Diff against the registry-tracked subset only. Bundled \"common\"\n // packages and the project's local package never appear in the\n // server's list and removing them on every event would wipe the\n // drive editors and break the AddDrive modal.\n const currentByName = new Map(\n packageManager\n .getRegistryPackages()\n .map(({ name, version }) => [name, version]),\n );\n const nextByName = new Map<string, string | undefined>();\n for (const spec of next) {\n const { bareName, version } = parseBare(spec);\n nextByName.set(bareName, version);\n }\n\n const isFirst = firstEvent;\n firstEvent = false;\n\n for (const name of currentByName.keys()) {\n if (!nextByName.has(name)) {\n packageManager.removePackage(name);\n if (!isFirst) {\n toast(`Removed package ${name}`, { type: \"connect-deleted\" });\n }\n }\n }\n for (const spec of next) {\n const { bareName, version } = parseBare(spec);\n const currentVersion = currentByName.get(bareName);\n const isKnown = currentByName.has(bareName);\n // Skip when the package is already present at the same version (or\n // when no version info is available on either side to compare).\n if (\n isKnown &&\n (!version || !currentVersion || version === currentVersion)\n ) {\n continue;\n }\n const isUpdate = isKnown;\n Promise.resolve(packageManager.addPackage(spec)).then(\n (result) => {\n if (result.type === \"error\") {\n console.error(\n `[Connect] /__packages addPackage(${spec}) failed:`,\n result.error,\n );\n return;\n }\n if (isFirst) return;\n const name = result.package.manifest.name;\n toast(\n isUpdate\n ? `Updated package ${name}`\n : `Installed package ${name}`,\n { type: \"connect-success\" },\n );\n },\n (err: unknown) => {\n console.error(\n `[Connect] /__packages addPackage(${spec}) threw:`,\n err,\n );\n },\n );\n }\n } catch (err) {\n console.error(\"[Connect] /__packages event parse failed:\", err);\n }\n });\n source.addEventListener(\"error\", () => {\n // EventSource auto-reconnects; nothing to do.\n });\n}\n\nexport async function clearReactorStorage() {\n await window.ph?.reactorClientModule?.pg?.close();\n\n // Dropping tables inside an existing PGlite instance is unreliable with\n // `relaxedDurability: true` followed by an immediate page reload — pending\n // IDB writes can be lost. Deleting the underlying database outright sidesteps\n // flush-timing; the next startup re-creates and re-migrates from scratch.\n const dbs = await indexedDB.databases();\n const targets = dbs\n .map((d) => d.name)\n .filter(\n (n): n is string =>\n !!n && !n.startsWith(\"ph-pglite-backup::\") && /pglite|reactor/i.test(n),\n );\n\n await Promise.all(\n targets.map(\n (name) =>\n new Promise<void>((resolve) => {\n const req = indexedDB.deleteDatabase(name);\n req.onsuccess = req.onerror = req.onblocked = () => resolve();\n }),\n ),\n );\n}\n\nexport async function createReactor(localPackage?: DocumentModelLib) {\n if (!window.ph) {\n window.ph = {};\n }\n if (window.ph.loading) return;\n\n window.ph.loading = true;\n\n // add window event handlers for updates\n addPHEventHandlers();\n\n // register toast function for use in editor components\n setPHToast(toast as PHToastFn);\n\n // initialize feature flags\n const features = await initFeatureFlags();\n\n logger.info(\n \"Features: @features\",\n JSON.stringify(Object.fromEntries(features), null, 2),\n );\n\n // initialize renown crypto\n const keyPairStorage = await BrowserKeyStorage.create();\n const renownCrypto = await new RenownCryptoBuilder()\n .withKeyPairStorage(keyPairStorage)\n .build();\n\n // initialize Renown\n const renown = await new RenownBuilder(\"connect\", {\n basename: phGlobalConfig.routerBasename,\n baseUrl: phGlobalConfig.renownUrl,\n })\n .withCrypto(renownCrypto)\n .build();\n\n // Read the runtime config from cache. loadComponent() awaited\n // loadRuntimeConfig() before calling createReactor, so the cache is warm;\n // using the sync getter matches the convention used by connect.config.ts,\n // useRegistryPackages, and pages/content.tsx — and throws loudly if a\n // future caller violates the boot ordering.\n const runtimeConfig = getRuntimeConfig();\n\n // initialize package manager\n const packageManager = new BrowserPackageManager(\n phGlobalConfig.routerBasename ?? \"\",\n runtimeConfig.packageRegistryUrl ?? null,\n );\n setVetraPackageManager(packageManager);\n await packageManager.init(localPackage, runtimeConfig.localPackage?.version);\n // Register any packages marked as provider: \"local\" in powerhouse.config.json\n // that the vite plugin bundled into this build. The virtual module is only\n // emitted when `phBundledPackagesPlugin` is registered (ph-cli's Connect\n // flow); running `vite dev` against apps/connect's own config has no\n // bundled packages, so a resolution failure here is expected. The\n // indirection + @vite-ignore also keeps Vite's dep scanner from treating\n // the specifier as a real npm package to pre-bundle.\n try {\n const bundledPackagesModule = \"ph-bundled-packages-virtual\";\n const { default: registerBundledPackages } = (await import(\n /* @vite-ignore */ bundledPackagesModule\n )) as { default: (pm: IPackageManager) => void };\n registerBundledPackages(packageManager);\n } catch {\n // no bundled packages in this build\n }\n const remotePackages = runtimeConfig.packages\n .filter((p) => p.provider !== \"local\")\n .map((p) => (p.version ? `${p.packageName}@${p.version}` : p.packageName));\n const packagesResult = await packageManager.addPackages(remotePackages);\n packagesResult.map((r) => {\n if (r.type === \"error\") console.error(r.error);\n });\n\n // Opt-in: subscribe to the static-mode `/__packages` SSE channel so live\n // publishes (e.g. ph-clint's publish-reload trigger pushing a new list) flow\n // into the running tab without a page reload. Enabled via\n // `connect.packages.liveReload`; the channel only exists in static hosting\n // that speaks this protocol.\n if (runtimeConfig.connect?.packages?.liveReload) {\n subscribeToPackagesChannel(packageManager);\n }\n\n // get document models to set in the reactor (all versions)\n const documentModelModules = packageManager.packages\n .flatMap((pkg) => pkg.documentModels)\n .filter(\n (module, index, modules) =>\n // deduplicate by documentType and version\n modules.findIndex(\n (m) =>\n m.documentModel.global.id === module.documentModel.global.id &&\n m.version === module.version,\n ) === index,\n );\n\n // get upgrade manifests from packages\n const upgradeManifests = packageManager.packages\n .flatMap((pkg) => pkg.upgradeManifests)\n .filter(\n (manifest, index, manifests) =>\n // deduplicate by documentType and version\n manifest !== undefined &&\n manifests.findIndex(\n (m) => m && m.documentType === manifest.documentType,\n ) === index,\n ) as UpgradeManifest<readonly number[]>[];\n\n // initialize package discovery service for auto-installing unknown document types\n const discoveryService =\n packageManager.cdnUrl !== null\n ? new PackageDiscoveryService(\n packageManager,\n new RegistryClient(packageManager.cdnUrl),\n {\n mode: \"immediate\",\n storageKey: phGlobalConfig.routerBasename ?? \"\",\n },\n )\n : new NoRegistryDiscoveryService(packageManager);\n\n setPackageDiscoveryService(discoveryService);\n\n // create reactor v2 with all versions and upgrade manifests\n const reactorClientModule = await createBrowserReactor(\n documentModelModules,\n upgradeManifests,\n renown,\n discoveryService,\n );\n\n // get the drives from the reactor\n const drives = await getDrives(reactorClientModule.client);\n\n // initialize user from URL parameter\n const didFromUrl = getDidFromUrl();\n await login(didFromUrl, renown);\n\n const documentCache = new DocumentCache(reactorClientModule.client);\n\n // dispatch the events to set the values in the window object\n const basePath = phGlobalConfig.basePath ?? \"/\";\n const routerBasename = phGlobalConfig.routerBasename ?? \"/\";\n const mergedGlobalConfig = buildPHGlobalConfig(\n basePath,\n routerBasename,\n runtimeConfig.connect ?? {},\n );\n setDefaultPHGlobalConfig(mergedGlobalConfig);\n\n // Slug extraction needs window.ph.basePath, published by\n // setDefaultPHGlobalConfig above.\n const path = window.location.pathname;\n const driveSlug = extractDriveSlugFromPath(path);\n const nodeSlug = extractNodeSlugFromPath(path);\n setReactorClientModule(reactorClientModule);\n setReactorClient(reactorClientModule.client);\n\n const _defaultDrivesUrl = phGlobalConfig.defaultDrivesUrl;\n if (_defaultDrivesUrl) {\n let switchboardOrigin: string | undefined;\n try {\n switchboardOrigin = new URL(_defaultDrivesUrl).origin;\n } catch {\n // malformed URL — skip attachment service construction\n }\n if (switchboardOrigin) {\n const attachmentJwtHandler = async (url: string) => {\n if (!renown.user) return undefined;\n return renown.getBearerToken({ expiresIn: 10, aud: url });\n };\n const attachmentService = createRemoteAttachmentService({\n remoteUrl: switchboardOrigin,\n jwtHandler: attachmentJwtHandler,\n });\n setAttachmentService(attachmentService);\n }\n }\n\n setDocumentCache(documentCache);\n setRenown(renown);\n setDrives(drives);\n setFeatures(features);\n\n // Add default drives and any URL-supplied remote drive in the background so\n // the app renders immediately. setSelectedDrive defers selection until the\n // drive matching the URL slug syncs in (see deferDriveSelection), so we only\n // ever wait for the selected drive, never for unrelated default drives.\n const defaultDrivesConfig = getDefaultDrives(runtimeConfig);\n if (defaultDrivesConfig.length > 0) {\n void addDefaultDrivesForNewReactor(defaultDrivesConfig).catch((error) =>\n console.error(\"Failed to add default drives:\", error),\n );\n }\n\n const remoteUrl = getDriveUrl();\n if (remoteUrl) {\n void addRemoteDrive(remoteUrl, undefined).catch((error) =>\n console.error(`Failed to add remote drive from ${remoteUrl}:`, error),\n );\n }\n\n setSelectedDrive(driveSlug);\n setSelectedNode(nodeSlug);\n\n // Subscribe via ReactorClient interface\n const reactorClient = reactorClientModule.client;\n reactorClient.subscribe({ type: \"powerhouse/document-drive\" }, (event) => {\n logger.verbose(\"ReactorClient subscription event: @event\", event);\n refreshReactorDataClient(reactorClientModule.client).catch((e) =>\n logger.error(\"@error\", e),\n );\n });\n\n // Redirect when a currently-viewed document or drive is deleted remotely\n reactorClient.subscribe({}, (event) => {\n if (event.type !== DocumentChangeType.Deleted) return;\n const deletedId = event.context?.childId;\n if (!deletedId) return;\n\n const selectedDriveId = window.ph?.selectedDriveId;\n const selectedNodeId = window.ph?.selectedNodeId;\n\n if (selectedDriveId && deletedId === selectedDriveId) {\n setSelectedDrive(undefined);\n toast(\"The drive you were viewing has been deleted\");\n return;\n }\n\n if (selectedNodeId && deletedId === selectedNodeId) {\n setSelectedNode(undefined);\n toast(\"The document you were editing has been deleted\");\n }\n });\n\n // Refresh from ReactorClient to pick up any synced drives\n await refreshReactorDataClient(reactorClientModule.client);\n\n // Setup processor factories for packages that have them\n const packagesWithProcessorFactories = packageManager.packages.filter(\n (pkg) => pkg.processorFactory !== undefined,\n );\n\n if (packagesWithProcessorFactories.length > 0) {\n const readModels =\n reactorClientModule.reactorModule?.readModelCoordinator?.readModels ?? [];\n const processorHostModule = await createProcessorHostModule(\n reactorClientModule.client,\n readModels,\n window.ph?.attachmentService,\n );\n if (processorHostModule !== undefined) {\n await Promise.all(\n packagesWithProcessorFactories.map(async (pkg) => {\n const { manifest, processorFactory } = pkg;\n const name = manifest.name;\n const id = manifest.name;\n const version = packageManager.getPackageVersion(name);\n const label = version ? `${name}@${version}` : name;\n logger.info(\"Loading processor factory: @label\", label);\n try {\n const factory = await processorFactory?.(processorHostModule);\n if (!factory) return;\n await reactorClientModule.reactorModule?.processorManager.registerFactory(\n id,\n factory,\n );\n } catch (error) {\n logger.error(`Error registering processor: @label`, label);\n logger.error(\"@error\", error);\n }\n }),\n );\n }\n }\n\n window.ph.loading = false;\n}\n\nfunction getDidFromUrl() {\n const searchParams = new URLSearchParams(window.location.search);\n const didComponent = searchParams.get(\"user\");\n const did = didComponent ? decodeURIComponent(didComponent) : undefined;\n return did;\n}\n\nfunction getDriveUrl() {\n const searchParams = new URLSearchParams(window.location.search);\n const driveUrl = searchParams.get(\"driveUrl\");\n const url = driveUrl ? decodeURIComponent(driveUrl) : undefined;\n return url;\n}\n"],"names":["#packageManager","#findModuleInLoadedPackages","#clearFailed","#recordFailure","#failedMemo","#failedSubscribers","#eventSubscribers","#failed","#emitEvent","#notifyFailedChanged","#packageManager","#registryClient","#mode","#dismissedStorage","#findModuleInLoadedPackages","#clearFailed","#recordFailure","#deferred","#discover","#discoveredTypes","#pending","#addToPending","#findTypesByPackage","#emitEvent","#notifyPendingChanged","#pendingMemo","#pendingSubscribers","#failedMemo","#failedSubscribers","#eventSubscribers","#createDeferredEntry","#failed","#notifyFailedChanged","#storage","#cdnUrl","#toCdnUrl","#localPackageNames","#registerPackage","#localPackage","#localPackageVersion","#notifyPackagesChanged","#packagesMemo","#packages","#loadPackage","#unmountStylesheet","#subscribers","#loadPackageFromNodeModules","#importPackage","#loadPackageFromRegistry","#mountStylesheet","#stylesheets"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkCA,eAAsB,qBACpB,sBACA,kBACA,QACA,qBACqC;CACrC,MAAM,eAA6B;EACjC,QAAQ,OAAO;EACf,UAAU,yBAAyB;EACpC;CAED,MAAM,aAAyB,OAAO,QAAgB;AACpD,MAAI,CAAC,OAAO,K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