@undefineds.co/xpod 0.3.23 → 0.3.25

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.
@@ -45,6 +45,14 @@ export declare class PodLookupRepository {
45
45
  * not have to match the storage base URL.
46
46
  */
47
47
  findByWebId(webId: string): Promise<PodLookupResult | undefined>;
48
+ /**
49
+ * Find all Pods linked to a WebID.
50
+ *
51
+ * A Cloud WebID can legitimately back both a Cloud Pod and a Local SP Pod.
52
+ * Callers that are scoped to a storage provider must inspect all candidates
53
+ * instead of accepting the first account record returned by CSS storage.
54
+ */
55
+ findAllByWebId(webId: string): Promise<PodLookupResult[]>;
48
56
  /**
49
57
  * Find Pods by linked WebID URLs in one scan.
50
58
  */
@@ -48,29 +48,43 @@ class PodLookupRepository {
48
48
  * not have to match the storage base URL.
49
49
  */
50
50
  async findByWebId(webId) {
51
+ return (await this.findAllByWebId(webId))[0];
52
+ }
53
+ /**
54
+ * Find all Pods linked to a WebID.
55
+ *
56
+ * A Cloud WebID can legitimately back both a Cloud Pod and a Local SP Pod.
57
+ * Callers that are scoped to a storage provider must inspect all candidates
58
+ * instead of accepting the first account record returned by CSS storage.
59
+ */
60
+ async findAllByWebId(webId) {
51
61
  const normalized = normalizeWebId(webId);
52
62
  if (!normalized) {
53
- return undefined;
63
+ return [];
54
64
  }
65
+ const results = [];
55
66
  const pods = await this.getAllPods();
56
67
  for (const pod of pods) {
57
68
  const matchedWebId = getPodWebIds(pod).find((candidate) => normalizeWebId(candidate) === normalized);
58
69
  if (matchedWebId) {
59
- return {
70
+ results.push({
60
71
  ...pod,
61
72
  webId: matchedWebId,
62
- };
73
+ });
63
74
  }
64
75
  }
76
+ if (results.length > 0) {
77
+ return results;
78
+ }
65
79
  const indexed = await this.findByWebIdIndex(normalized);
66
80
  if (!indexed) {
67
- return undefined;
81
+ return [];
68
82
  }
69
83
  const usage = await this.getUsageByPodId();
70
- return {
71
- ...indexed,
72
- storageUrl: indexed.storageUrl ?? usage.get(indexed.podId)?.storageUrl,
73
- };
84
+ return [{
85
+ ...indexed,
86
+ storageUrl: indexed.storageUrl ?? usage.get(indexed.podId)?.storageUrl,
87
+ }];
74
88
  }
75
89
  /**
76
90
  * Find Pods by linked WebID URLs in one scan.
@@ -1 +1 @@
1
- {"version":3,"file":"PodLookupRepository.js","sourceRoot":"","sources":["../../../src/identity/drizzle/PodLookupRepository.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,6BAA6E;AAqC7E;;;;;;GAMG;AACH,MAAa,mBAAmB;IAK9B,YACmB,EAAoB,EACrC,WAAoB;QADH,OAAE,GAAF,EAAE,CAAkB;QAGrC,IAAI,CAAC,WAAW,GAAG,WAAW,IAAI,aAAa,CAAC;QAChD,IAAI,CAAC,qBAAqB,GAAG,gBAAgB,CAAC;QAC9C,IAAI,CAAC,cAAc,GAAG,oBAAoB,CAAC;IAC7C,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,wBAAwB,CAAC,YAAoB;QACxD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QAErC,IAAI,SAAsC,CAAC;QAC3C,IAAI,UAAU,GAAG,CAAC,CAAC;QAEnB,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,aAAa,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC,OAAO,CAAC;YACpD,IAAI,YAAY,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,MAAM,GAAG,UAAU,EAAE,CAAC;gBAChF,SAAS,GAAG,GAAG,CAAC;gBAChB,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC;YACpC,CAAC;QACH,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,QAAQ,CAAC,KAAa;QACjC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QACrC,OAAO,IAAI,CAAC,IAAI,CA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,IAAI,KAAK,EAAE,CAAC;QAC/E,OAAQ,KAAiC,CAAC,OAAO,CAAC;IACpD,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3E,CAAC;AAED,SAAS,cAAc,CAAC,GAA0B,EAAE,GAAW,EAAE,KAAa;IAC5E,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;IAClC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACnB,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import { sql } from 'drizzle-orm';\nimport { type IdentityDatabase, executeQuery, executeStatement } from './db';\n\nexport interface PodLookupResult {\n podId: string;\n accountId: string;\n baseUrl: string;\n storageUrl?: string;\n webId?: string;\n webIds?: string[];\n nodeId?: string;\n edgeNodeId?: string;\n}\n\nexport interface PodMigrationStatus {\n podId: string;\n nodeId?: string;\n migrationStatus?: 'syncing' | 'done' | null;\n migrationTargetNode?: string;\n migrationProgress?: number;\n}\n\ninterface InternalKvRow {\n key?: string;\n value?: string;\n id?: string;\n account_id?: string;\n base_url?: string;\n storage_url?: string;\n node_id?: string;\n edge_node_id?: string;\n}\n\ninterface PodUsageRow {\n pod_id?: string;\n storage_url?: string | null;\n}\n\n/**\n * Repository for Pod lookup operations.\n *\n * Reads Pod data from CSS's internal_kv table where account data is stored.\n * CSS stores account data at key \"accounts/data/{accountId}\" with Pod info\n * nested in the \"**pod**\" field.\n */\nexport class PodLookupRepository {\n private readonly kvTableName: string;\n private readonly indexedStoreTableName: string;\n private readonly usageTableName: string;\n\n public constructor(\n private readonly db: IdentityDatabase,\n kvTableName?: string,\n ) {\n this.kvTableName = kvTableName ?? 'internal_kv';\n this.indexedStoreTableName = 'identity_store';\n this.usageTableName = 'identity_pod_usage';\n }\n\n /**\n * Find Pod by resource path (matches longest canonical storage/base URL prefix).\n */\n public async findByResourceIdentifier(resourcePath: string): Promise<PodLookupResult | undefined> {\n const pods = await this.getAllPods();\n\n let bestMatch: PodLookupResult | undefined;\n let bestLength = 0;\n\n for (const pod of pods) {\n const candidateBase = pod.storageUrl ?? pod.baseUrl;\n if (resourcePath.startsWith(candidateBase) && candidateBase.length > bestLength) {\n bestMatch = pod;\n bestLength = candidateBase.length;\n }\n }\n\n return bestMatch;\n }\n\n /**\n * Get Pod by ID.\n */\n public async findById(podId: string): Promise<PodLookupResult | undefined> {\n const pods = await this.getAllPods();\n return pods.find((p) => p.podId === podId);\n }\n\n /**\n * Find Pod by a linked WebID URL.\n *\n * CSS account data stores WebID links separately from Pod base URLs. This is\n * the precise lookup for IdP/SP split deployments where the WebID path does\n * not have to match the storage base URL.\n */\n public async findByWebId(webId: string): Promise<PodLookupResult | undefined> {\n const normalized = normalizeWebId(webId);\n if (!normalized) {\n return undefined;\n }\n\n const pods = await this.getAllPods();\n for (const pod of pods) {\n const matchedWebId = getPodWebIds(pod).find((candidate) => normalizeWebId(candidate) === normalized);\n if (matchedWebId) {\n return {\n ...pod,\n webId: matchedWebId,\n };\n }\n }\n const indexed = await this.findByWebIdIndex(normalized);\n if (!indexed) {\n return undefined;\n }\n const usage = await this.getUsageByPodId();\n return {\n ...indexed,\n storageUrl: indexed.storageUrl ?? usage.get(indexed.podId)?.storageUrl,\n };\n }\n\n /**\n * Find Pods by linked WebID URLs in one scan.\n */\n public async findByWebIds(webIds: string[]): Promise<PodLookupResult[]> {\n const normalizedTargets = new Set(webIds.map(normalizeWebId).filter((value): value is string => Boolean(value)));\n if (normalizedTargets.size === 0) {\n return [];\n }\n\n const results: PodLookupResult[] = [];\n const pods = await this.getAllPods();\n for (const pod of pods) {\n const matchedWebId = getPodWebIds(pod).find((candidate) => {\n const normalized = normalizeWebId(candidate);\n return normalized ? normalizedTargets.has(normalized) : false;\n });\n if (!matchedWebId) {\n continue;\n }\n results.push({\n ...pod,\n webId: matchedWebId,\n });\n }\n if (results.length < normalizedTargets.size) {\n const seen = new Set(results.map((result) => normalizeWebId(result.webId)).filter(Boolean));\n for (const normalized of normalizedTargets) {\n if (seen.has(normalized)) {\n continue;\n }\n const indexed = await this.findByWebIdIndex(normalized);\n if (indexed) {\n const usage = await this.getUsageByPodId();\n results.push({\n ...indexed,\n storageUrl: indexed.storageUrl ?? usage.get(indexed.podId)?.storageUrl,\n });\n }\n }\n }\n return results;\n }\n\n /**\n * List Pods for a specific account.\n */\n public async listByAccountId(accountId: string): Promise<PodLookupResult[]> {\n const pods = await this.getAllPods();\n return pods.filter((pod) => pod.accountId === accountId);\n }\n\n /**\n * Set the canonical storage URL for a Pod in identity_pod_usage.\n */\n public async setStorageUrl(podId: string, accountId: string, storageUrl: string): Promise<void> {\n const tableId = sql.identifier([this.usageTableName]);\n await executeStatement(this.db, sql`\n INSERT INTO ${tableId} (pod_id, account_id, storage_url)\n VALUES (${podId}, ${accountId}, ${storageUrl})\n ON CONFLICT (pod_id) DO UPDATE SET\n account_id = ${accountId},\n storage_url = ${storageUrl}\n `);\n }\n\n /**\n * Get migration status for a Pod from identity_pod_usage table.\n */\n public async getMigrationStatus(podId: string): Promise<PodMigrationStatus | undefined> {\n try {\n const tableId = sql.identifier([this.usageTableName]);\n const result = await executeQuery<{\n pod_id?: string;\n id?: string;\n node_id?: string | null;\n migration_status?: string | null;\n migration_target_node?: string | null;\n migration_progress?: number | null;\n }>(this.db, sql`\n SELECT pod_id, node_id, migration_status, migration_target_node, migration_progress\n FROM ${tableId}\n WHERE pod_id = ${podId}\n LIMIT 1\n `);\n\n if (result.rows.length === 0) {\n return undefined;\n }\n const row = result.rows[0];\n return {\n podId: row.pod_id ?? row.id ?? podId,\n nodeId: row.node_id ?? undefined,\n migrationStatus: row.migration_status as 'syncing' | 'done' | null | undefined,\n migrationTargetNode: row.migration_target_node ?? undefined,\n migrationProgress: row.migration_progress ?? undefined,\n };\n } catch {\n // Table might not exist.\n return undefined;\n }\n }\n\n /**\n * Set the nodeId for a Pod in identity_pod_usage table.\n */\n public async setNodeId(podId: string, nodeId: string): Promise<void> {\n const tableId = sql.identifier([this.usageTableName]);\n await executeStatement(this.db, sql`\n INSERT INTO ${tableId} (pod_id, account_id, node_id)\n VALUES (${podId}, '', ${nodeId})\n ON CONFLICT (pod_id) DO UPDATE SET node_id = ${nodeId}\n `);\n }\n\n /**\n * Update migration status for a Pod in identity_pod_usage table.\n */\n public async setMigrationStatus(\n podId: string,\n status: 'syncing' | 'done' | null,\n targetNode?: string | null,\n progress?: number | null,\n ): Promise<void> {\n const tableId = sql.identifier([this.usageTableName]);\n await executeStatement(this.db, sql`\n INSERT INTO ${tableId} (pod_id, account_id, migration_status, migration_target_node, migration_progress)\n VALUES (${podId}, '', ${status}, ${targetNode ?? null}, ${progress ?? 0})\n ON CONFLICT (pod_id) DO UPDATE SET\n migration_status = ${status},\n migration_target_node = ${targetNode ?? null},\n migration_progress = ${progress ?? 0}\n `);\n }\n\n /**\n * List all pods.\n */\n public async listAllPods(): Promise<PodLookupResult[]> {\n return this.getAllPods();\n }\n\n /**\n * Extract all pods from CSS's internal_kv storage.\n *\n * It keeps backward compatibility with legacy rows that already expose\n * id/account_id/base_url columns (used by some unit tests and older schemas).\n */\n private async getAllPods(): Promise<PodLookupResult[]> {\n const kvTableId = sql.identifier([this.kvTableName]);\n\n const result = await executeQuery<InternalKvRow>(this.db, sql`\n SELECT key, value FROM ${kvTableId}\n WHERE key LIKE 'accounts/data/%'\n OR key LIKE '/.internal/accounts/data/%'\n `);\n const usageByPodId = await this.getUsageByPodId();\n\n const pods: PodLookupResult[] = [];\n\n for (const row of result?.rows ?? []) {\n if (row.id && row.account_id && row.base_url) {\n pods.push({\n podId: String(row.id),\n accountId: String(row.account_id),\n baseUrl: String(row.base_url),\n storageUrl: row.storage_url ? String(row.storage_url) : undefined,\n nodeId: row.node_id ? String(row.node_id) : undefined,\n edgeNodeId: row.edge_node_id ? String(row.edge_node_id) : undefined,\n });\n continue;\n }\n\n if (!row.key || row.value === undefined) {\n continue;\n }\n\n try {\n const accountId = extractAccountIdFromAccountDataKey(row.key);\n if (!accountId) {\n continue;\n }\n const data = unwrapStoredValue(typeof row.value === 'string' ? JSON.parse(row.value) : row.value);\n\n const podMap = (data as any)['**pod**'] || (data as any).pod || {};\n const webIds = extractAccountWebIds(data);\n\n for (const [podId, podData] of Object.entries(podMap)) {\n const pod = podData as Record<string, unknown>;\n if (pod.baseUrl && typeof pod.baseUrl === 'string') {\n const usage = usageByPodId.get(podId);\n const podWebIds = [\n typeof pod.webId === 'string' ? pod.webId : undefined,\n ...extractPodOwnerWebIds(pod),\n ...webIds,\n ].filter((value): value is string => typeof value === 'string');\n pods.push({\n podId,\n accountId,\n baseUrl: pod.baseUrl,\n storageUrl: stringValue(pod.storageUrl) ?? usage?.storageUrl,\n webId: dedupeStrings(podWebIds)[0],\n ...webIdsProperty(podWebIds),\n nodeId: typeof pod.nodeId === 'string' ? pod.nodeId : undefined,\n edgeNodeId: typeof pod.edgeNodeId === 'string' ? pod.edgeNodeId : undefined,\n });\n }\n }\n } catch {\n // Skip malformed entries.\n }\n }\n\n return mergePodLookupResults([\n ...pods,\n ...await this.getPodsFromIndexedStore(),\n ]);\n }\n\n private async getUsageByPodId(): Promise<Map<string, { storageUrl?: string }>> {\n const tableId = sql.identifier([this.usageTableName]);\n try {\n const result = await executeQuery<PodUsageRow>(this.db, sql`\n SELECT pod_id, storage_url FROM ${tableId}\n `);\n const byPodId = new Map<string, { storageUrl?: string }>();\n for (const row of result.rows) {\n if (!row.pod_id) {\n continue;\n }\n byPodId.set(row.pod_id, {\n storageUrl: row.storage_url ?? undefined,\n });\n }\n return byPodId;\n } catch {\n return new Map();\n }\n }\n\n /**\n * Fast path for CSS WrappedIndexedStorage. WebID indexes point to the root\n * account id, so a single indexed key plus account data row can resolve the\n * profile without scanning all account records.\n */\n private async findByWebIdIndex(webId: string): Promise<PodLookupResult | undefined> {\n const accountIds = await this.readStringArrayFromKv(`accounts/index/webIdLink/webId/${encodeURIComponent(webId)}`);\n for (const accountId of accountIds) {\n const account = await this.readAccountData(accountId);\n if (!account) {\n continue;\n }\n const pods = this.extractPodsFromAccountData(accountId, account);\n const match = pods.find((pod) => getPodWebIds(pod).some((candidate) => normalizeWebId(candidate) === webId));\n if (match) {\n return {\n ...match,\n webId,\n };\n }\n if (pods.length === 1) {\n return {\n ...pods[0],\n webId,\n ...webIdsProperty([webId, ...getPodWebIds(pods[0])]),\n };\n }\n }\n return undefined;\n }\n\n private async readAccountData(accountId: string): Promise<Record<string, unknown> | undefined> {\n for (const key of [`accounts/data/${accountId}`, `/.internal/accounts/data/${accountId}`]) {\n const value = await this.readKvValue(key);\n const record = parsePayloadRecord(value);\n if (record) {\n return record;\n }\n }\n return undefined;\n }\n\n private async readStringArrayFromKv(key: string): Promise<string[]> {\n const value = await this.readKvValue(key);\n return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];\n }\n\n private async readKvValue(key: string): Promise<unknown> {\n const tableId = sql.identifier([this.kvTableName]);\n try {\n const result = await executeQuery<{ value?: unknown }>(this.db, sql`\n SELECT value FROM ${tableId}\n WHERE key = ${key}\n LIMIT 1\n `);\n if (result.rows.length === 0) {\n return undefined;\n }\n return parseStoredValue(result.rows[0].value);\n } catch {\n return undefined;\n }\n }\n\n private extractPodsFromAccountData(accountId: string, data: Record<string, unknown>): PodLookupResult[] {\n const podMap = (data as any)['**pod**'] || (data as any).pod || {};\n const webIds = extractAccountWebIds(data);\n const pods: PodLookupResult[] = [];\n\n for (const [podId, podData] of Object.entries(podMap)) {\n const pod = podData as Record<string, unknown>;\n if (pod.baseUrl && typeof pod.baseUrl === 'string') {\n const podWebIds = [\n typeof pod.webId === 'string' ? pod.webId : undefined,\n ...extractPodOwnerWebIds(pod),\n ...webIds,\n ].filter((value): value is string => typeof value === 'string');\n pods.push({\n podId,\n accountId,\n baseUrl: pod.baseUrl,\n storageUrl: stringValue(pod.storageUrl),\n webId: dedupeStrings(podWebIds)[0],\n ...webIdsProperty(podWebIds),\n nodeId: typeof pod.nodeId === 'string' ? pod.nodeId : undefined,\n edgeNodeId: typeof pod.edgeNodeId === 'string' ? pod.edgeNodeId : undefined,\n });\n }\n }\n\n return pods;\n }\n\n /**\n * Older Xpod/CSS deployments may have used the IndexedStorage-compatible\n * identity_store table instead of CSS's WrappedIndexedStorage JSON tree in\n * internal_kv. Keep this as a read-only compatibility source so hosted WebID\n * profile lookup still works after storage implementation changes.\n */\n private async getPodsFromIndexedStore(): Promise<PodLookupResult[]> {\n const storeTableId = sql.identifier([this.indexedStoreTableName]);\n let result: { rows?: Array<{ container?: string; id?: string; payload?: unknown }> } | undefined;\n try {\n result = await executeQuery(this.db, sql`\n SELECT container, id, payload FROM ${storeTableId}\n WHERE container IN ('pod', 'owner', 'webIdLink')\n `);\n } catch {\n return [];\n }\n\n const podPayloads = new Map<string, Record<string, unknown>>();\n const ownerWebIdsByPodId = new Map<string, string[]>();\n const webIdsByAccountId = new Map<string, string[]>();\n\n for (const row of result?.rows ?? []) {\n if (!row.id || !row.container) {\n continue;\n }\n const payload = parsePayloadRecord(row.payload);\n if (!payload) {\n continue;\n }\n\n if (row.container === 'pod') {\n podPayloads.set(row.id, payload);\n continue;\n }\n\n if (row.container === 'owner') {\n const podId = stringValue(payload.podId);\n const webId = stringValue(payload.webId);\n if (podId && webId) {\n appendMapValue(ownerWebIdsByPodId, podId, webId);\n }\n continue;\n }\n\n if (row.container === 'webIdLink') {\n const accountId = stringValue(payload.accountId);\n const webId = stringValue(payload.webId);\n if (accountId && webId) {\n appendMapValue(webIdsByAccountId, accountId, webId);\n }\n }\n }\n\n const pods: PodLookupResult[] = [];\n for (const [podId, pod] of podPayloads) {\n const baseUrl = stringValue(pod.baseUrl);\n const accountId = stringValue(pod.accountId);\n if (!baseUrl || !accountId) {\n continue;\n }\n const podWebIds = dedupeStrings([\n stringValue(pod.webId),\n ...(ownerWebIdsByPodId.get(podId) ?? []),\n ...(webIdsByAccountId.get(accountId) ?? []),\n ].filter((value): value is string => typeof value === 'string'));\n\n pods.push({\n podId,\n accountId,\n baseUrl,\n storageUrl: stringValue(pod.storageUrl),\n webId: podWebIds[0],\n ...webIdsProperty(podWebIds),\n nodeId: stringValue(pod.nodeId),\n edgeNodeId: stringValue(pod.edgeNodeId),\n });\n }\n\n return pods;\n }\n}\n\nfunction extractAccountIdFromAccountDataKey(key: string): string | undefined {\n const marker = 'accounts/data/';\n const index = key.indexOf(marker);\n if (index < 0) {\n return undefined;\n }\n const accountId = key.slice(index + marker.length).replace(/\\.json$/u, '');\n return accountId || undefined;\n}\n\nfunction extractAccountWebIds(data: unknown): string[] {\n if (!data || typeof data !== 'object') {\n return [];\n }\n\n const record = data as Record<string, unknown>;\n const linkMap = record['**webIdLink**'] || record.webIdLink || {};\n if (!linkMap || typeof linkMap !== 'object') {\n return [];\n }\n\n return Object.values(linkMap as Record<string, unknown>)\n .map((value) => {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n const webId = (value as Record<string, unknown>).webId;\n return typeof webId === 'string' ? webId : undefined;\n })\n .filter((value): value is string => typeof value === 'string');\n}\n\nfunction extractPodOwnerWebIds(pod: Record<string, unknown>): string[] {\n const ownerMap = pod['**owner**'] || pod.owner || {};\n if (!ownerMap || typeof ownerMap !== 'object') {\n return [];\n }\n\n return Object.values(ownerMap as Record<string, unknown>)\n .map((value) => {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n const webId = (value as Record<string, unknown>).webId;\n return typeof webId === 'string' ? webId : undefined;\n })\n .filter((value): value is string => typeof value === 'string');\n}\n\nfunction normalizeWebId(webId: string | undefined): string | undefined {\n if (!webId) {\n return undefined;\n }\n try {\n return new URL(webId).toString();\n } catch {\n return webId;\n }\n}\n\nfunction dedupeStrings(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction getPodWebIds(pod: PodLookupResult): string[] {\n return dedupeStrings([\n pod.webId,\n ...(pod.webIds ?? []),\n ].filter((value): value is string => typeof value === 'string' && value.length > 0));\n}\n\nfunction webIdsProperty(values: string[]): Pick<PodLookupResult, 'webIds'> {\n const webIds = dedupeStrings(values);\n return webIds.length > 1 ? { webIds } : {};\n}\n\nfunction mergePodLookupResults(values: PodLookupResult[]): PodLookupResult[] {\n const byPodId = new Map<string, PodLookupResult>();\n for (const value of values) {\n const existing = byPodId.get(value.podId);\n if (!existing) {\n byPodId.set(value.podId, value);\n continue;\n }\n\n const webIds = dedupeStrings([\n ...getPodWebIds(existing),\n ...getPodWebIds(value),\n ]);\n byPodId.set(value.podId, {\n ...existing,\n baseUrl: existing.baseUrl || value.baseUrl,\n storageUrl: existing.storageUrl ?? value.storageUrl,\n accountId: existing.accountId || value.accountId,\n webId: webIds[0],\n ...webIdsProperty(webIds),\n nodeId: existing.nodeId ?? value.nodeId,\n edgeNodeId: existing.edgeNodeId ?? value.edgeNodeId,\n });\n }\n return [...byPodId.values()];\n}\n\nfunction parsePayloadRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value) {\n return undefined;\n }\n if (typeof value === 'string') {\n try {\n const parsed = JSON.parse(value) as unknown;\n const unwrapped = unwrapStoredValue(parsed);\n return unwrapped && typeof unwrapped === 'object' ? unwrapped as Record<string, unknown> : undefined;\n } catch {\n return undefined;\n }\n }\n const unwrapped = unwrapStoredValue(value);\n return typeof unwrapped === 'object' ? unwrapped as Record<string, unknown> : undefined;\n}\n\nfunction parseStoredValue(value: unknown): unknown {\n if (typeof value === 'string') {\n try {\n return unwrapStoredValue(JSON.parse(value));\n } catch {\n return undefined;\n }\n }\n return unwrapStoredValue(value);\n}\n\nfunction unwrapStoredValue(value: unknown): unknown {\n if (value && typeof value === 'object' && 'key' in value && 'payload' in value) {\n return (value as Record<string, unknown>).payload;\n }\n return value;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction appendMapValue(map: Map<string, string[]>, key: string, value: string): void {\n const values = map.get(key) ?? [];\n values.push(value);\n map.set(key, values);\n}\n"]}
1
+ {"version":3,"file":"PodLookupRepository.js","sourceRoot":"","sources":["../../../src/identity/drizzle/PodLookupRepository.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,6BAA6E;AAqC7E;;;;;;GAMG;AACH,MAAa,mBAAmB;IAK9B,YACmB,EAAoB,EACrC,WAAoB;QADH,OAAE,GAAF,EAAE,CAAkB;QAGrC,IAAI,CAAC,WAAW,GAAG,WAAW,IAAI,aAAa,CAAC;QAChD,IAAI,CAAC,qBAAqB,GAAG,gBAAgB,CAAC;QAC9C,IAAI,CAAC,cAAc,GAAG,oBAAoB,CAAC;IAC7C,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,wBAAwB,CAAC,YAAoB;QACxD,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QAErC,IAAI,SAAsC,CAAC;QAC3C,IAAI,UAAU,GAAG,CAAC,CAAC;QAEnB,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,aAAa,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC,OAAO,CAAC;YACpD,IAAI,YAAY,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,MAAM,GAAG,UAAU,EAAE,CAAC;gBAChF,SAAS,GAAG,GAAG,CAAC;gBAChB,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC;YACpC,CAAC;QACH,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,QAAQ,CAAC,KAAa;QACjC,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QACrC,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,KAAK,KAAK,C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AAC;QAC9C,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,SAAS,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,iBAAiB,CAAC,KAAK,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACvC,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,IAAI,KAAK,IAAI,SAAS,IAAI,KAAK,EAAE,CAAC;QAC/E,OAAQ,KAAiC,CAAC,OAAO,CAAC;IACpD,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,WAAW,CAAC,KAAc;IACjC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3E,CAAC;AAED,SAAS,cAAc,CAAC,GAA0B,EAAE,GAAW,EAAE,KAAa;IAC5E,MAAM,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;IAClC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACnB,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import { sql } from 'drizzle-orm';\nimport { type IdentityDatabase, executeQuery, executeStatement } from './db';\n\nexport interface PodLookupResult {\n podId: string;\n accountId: string;\n baseUrl: string;\n storageUrl?: string;\n webId?: string;\n webIds?: string[];\n nodeId?: string;\n edgeNodeId?: string;\n}\n\nexport interface PodMigrationStatus {\n podId: string;\n nodeId?: string;\n migrationStatus?: 'syncing' | 'done' | null;\n migrationTargetNode?: string;\n migrationProgress?: number;\n}\n\ninterface InternalKvRow {\n key?: string;\n value?: string;\n id?: string;\n account_id?: string;\n base_url?: string;\n storage_url?: string;\n node_id?: string;\n edge_node_id?: string;\n}\n\ninterface PodUsageRow {\n pod_id?: string;\n storage_url?: string | null;\n}\n\n/**\n * Repository for Pod lookup operations.\n *\n * Reads Pod data from CSS's internal_kv table where account data is stored.\n * CSS stores account data at key \"accounts/data/{accountId}\" with Pod info\n * nested in the \"**pod**\" field.\n */\nexport class PodLookupRepository {\n private readonly kvTableName: string;\n private readonly indexedStoreTableName: string;\n private readonly usageTableName: string;\n\n public constructor(\n private readonly db: IdentityDatabase,\n kvTableName?: string,\n ) {\n this.kvTableName = kvTableName ?? 'internal_kv';\n this.indexedStoreTableName = 'identity_store';\n this.usageTableName = 'identity_pod_usage';\n }\n\n /**\n * Find Pod by resource path (matches longest canonical storage/base URL prefix).\n */\n public async findByResourceIdentifier(resourcePath: string): Promise<PodLookupResult | undefined> {\n const pods = await this.getAllPods();\n\n let bestMatch: PodLookupResult | undefined;\n let bestLength = 0;\n\n for (const pod of pods) {\n const candidateBase = pod.storageUrl ?? pod.baseUrl;\n if (resourcePath.startsWith(candidateBase) && candidateBase.length > bestLength) {\n bestMatch = pod;\n bestLength = candidateBase.length;\n }\n }\n\n return bestMatch;\n }\n\n /**\n * Get Pod by ID.\n */\n public async findById(podId: string): Promise<PodLookupResult | undefined> {\n const pods = await this.getAllPods();\n return pods.find((p) => p.podId === podId);\n }\n\n /**\n * Find Pod by a linked WebID URL.\n *\n * CSS account data stores WebID links separately from Pod base URLs. This is\n * the precise lookup for IdP/SP split deployments where the WebID path does\n * not have to match the storage base URL.\n */\n public async findByWebId(webId: string): Promise<PodLookupResult | undefined> {\n return (await this.findAllByWebId(webId))[0];\n }\n\n /**\n * Find all Pods linked to a WebID.\n *\n * A Cloud WebID can legitimately back both a Cloud Pod and a Local SP Pod.\n * Callers that are scoped to a storage provider must inspect all candidates\n * instead of accepting the first account record returned by CSS storage.\n */\n public async findAllByWebId(webId: string): Promise<PodLookupResult[]> {\n const normalized = normalizeWebId(webId);\n if (!normalized) {\n return [];\n }\n\n const results: PodLookupResult[] = [];\n const pods = await this.getAllPods();\n for (const pod of pods) {\n const matchedWebId = getPodWebIds(pod).find((candidate) => normalizeWebId(candidate) === normalized);\n if (matchedWebId) {\n results.push({\n ...pod,\n webId: matchedWebId,\n });\n }\n }\n\n if (results.length > 0) {\n return results;\n }\n\n const indexed = await this.findByWebIdIndex(normalized);\n if (!indexed) {\n return [];\n }\n const usage = await this.getUsageByPodId();\n return [{\n ...indexed,\n storageUrl: indexed.storageUrl ?? usage.get(indexed.podId)?.storageUrl,\n }];\n }\n\n /**\n * Find Pods by linked WebID URLs in one scan.\n */\n public async findByWebIds(webIds: string[]): Promise<PodLookupResult[]> {\n const normalizedTargets = new Set(webIds.map(normalizeWebId).filter((value): value is string => Boolean(value)));\n if (normalizedTargets.size === 0) {\n return [];\n }\n\n const results: PodLookupResult[] = [];\n const pods = await this.getAllPods();\n for (const pod of pods) {\n const matchedWebId = getPodWebIds(pod).find((candidate) => {\n const normalized = normalizeWebId(candidate);\n return normalized ? normalizedTargets.has(normalized) : false;\n });\n if (!matchedWebId) {\n continue;\n }\n results.push({\n ...pod,\n webId: matchedWebId,\n });\n }\n if (results.length < normalizedTargets.size) {\n const seen = new Set(results.map((result) => normalizeWebId(result.webId)).filter(Boolean));\n for (const normalized of normalizedTargets) {\n if (seen.has(normalized)) {\n continue;\n }\n const indexed = await this.findByWebIdIndex(normalized);\n if (indexed) {\n const usage = await this.getUsageByPodId();\n results.push({\n ...indexed,\n storageUrl: indexed.storageUrl ?? usage.get(indexed.podId)?.storageUrl,\n });\n }\n }\n }\n return results;\n }\n\n /**\n * List Pods for a specific account.\n */\n public async listByAccountId(accountId: string): Promise<PodLookupResult[]> {\n const pods = await this.getAllPods();\n return pods.filter((pod) => pod.accountId === accountId);\n }\n\n /**\n * Set the canonical storage URL for a Pod in identity_pod_usage.\n */\n public async setStorageUrl(podId: string, accountId: string, storageUrl: string): Promise<void> {\n const tableId = sql.identifier([this.usageTableName]);\n await executeStatement(this.db, sql`\n INSERT INTO ${tableId} (pod_id, account_id, storage_url)\n VALUES (${podId}, ${accountId}, ${storageUrl})\n ON CONFLICT (pod_id) DO UPDATE SET\n account_id = ${accountId},\n storage_url = ${storageUrl}\n `);\n }\n\n /**\n * Get migration status for a Pod from identity_pod_usage table.\n */\n public async getMigrationStatus(podId: string): Promise<PodMigrationStatus | undefined> {\n try {\n const tableId = sql.identifier([this.usageTableName]);\n const result = await executeQuery<{\n pod_id?: string;\n id?: string;\n node_id?: string | null;\n migration_status?: string | null;\n migration_target_node?: string | null;\n migration_progress?: number | null;\n }>(this.db, sql`\n SELECT pod_id, node_id, migration_status, migration_target_node, migration_progress\n FROM ${tableId}\n WHERE pod_id = ${podId}\n LIMIT 1\n `);\n\n if (result.rows.length === 0) {\n return undefined;\n }\n const row = result.rows[0];\n return {\n podId: row.pod_id ?? row.id ?? podId,\n nodeId: row.node_id ?? undefined,\n migrationStatus: row.migration_status as 'syncing' | 'done' | null | undefined,\n migrationTargetNode: row.migration_target_node ?? undefined,\n migrationProgress: row.migration_progress ?? undefined,\n };\n } catch {\n // Table might not exist.\n return undefined;\n }\n }\n\n /**\n * Set the nodeId for a Pod in identity_pod_usage table.\n */\n public async setNodeId(podId: string, nodeId: string): Promise<void> {\n const tableId = sql.identifier([this.usageTableName]);\n await executeStatement(this.db, sql`\n INSERT INTO ${tableId} (pod_id, account_id, node_id)\n VALUES (${podId}, '', ${nodeId})\n ON CONFLICT (pod_id) DO UPDATE SET node_id = ${nodeId}\n `);\n }\n\n /**\n * Update migration status for a Pod in identity_pod_usage table.\n */\n public async setMigrationStatus(\n podId: string,\n status: 'syncing' | 'done' | null,\n targetNode?: string | null,\n progress?: number | null,\n ): Promise<void> {\n const tableId = sql.identifier([this.usageTableName]);\n await executeStatement(this.db, sql`\n INSERT INTO ${tableId} (pod_id, account_id, migration_status, migration_target_node, migration_progress)\n VALUES (${podId}, '', ${status}, ${targetNode ?? null}, ${progress ?? 0})\n ON CONFLICT (pod_id) DO UPDATE SET\n migration_status = ${status},\n migration_target_node = ${targetNode ?? null},\n migration_progress = ${progress ?? 0}\n `);\n }\n\n /**\n * List all pods.\n */\n public async listAllPods(): Promise<PodLookupResult[]> {\n return this.getAllPods();\n }\n\n /**\n * Extract all pods from CSS's internal_kv storage.\n *\n * It keeps backward compatibility with legacy rows that already expose\n * id/account_id/base_url columns (used by some unit tests and older schemas).\n */\n private async getAllPods(): Promise<PodLookupResult[]> {\n const kvTableId = sql.identifier([this.kvTableName]);\n\n const result = await executeQuery<InternalKvRow>(this.db, sql`\n SELECT key, value FROM ${kvTableId}\n WHERE key LIKE 'accounts/data/%'\n OR key LIKE '/.internal/accounts/data/%'\n `);\n const usageByPodId = await this.getUsageByPodId();\n\n const pods: PodLookupResult[] = [];\n\n for (const row of result?.rows ?? []) {\n if (row.id && row.account_id && row.base_url) {\n pods.push({\n podId: String(row.id),\n accountId: String(row.account_id),\n baseUrl: String(row.base_url),\n storageUrl: row.storage_url ? String(row.storage_url) : undefined,\n nodeId: row.node_id ? String(row.node_id) : undefined,\n edgeNodeId: row.edge_node_id ? String(row.edge_node_id) : undefined,\n });\n continue;\n }\n\n if (!row.key || row.value === undefined) {\n continue;\n }\n\n try {\n const accountId = extractAccountIdFromAccountDataKey(row.key);\n if (!accountId) {\n continue;\n }\n const data = unwrapStoredValue(typeof row.value === 'string' ? JSON.parse(row.value) : row.value);\n\n const podMap = (data as any)['**pod**'] || (data as any).pod || {};\n const webIds = extractAccountWebIds(data);\n\n for (const [podId, podData] of Object.entries(podMap)) {\n const pod = podData as Record<string, unknown>;\n if (pod.baseUrl && typeof pod.baseUrl === 'string') {\n const usage = usageByPodId.get(podId);\n const podWebIds = [\n typeof pod.webId === 'string' ? pod.webId : undefined,\n ...extractPodOwnerWebIds(pod),\n ...webIds,\n ].filter((value): value is string => typeof value === 'string');\n pods.push({\n podId,\n accountId,\n baseUrl: pod.baseUrl,\n storageUrl: stringValue(pod.storageUrl) ?? usage?.storageUrl,\n webId: dedupeStrings(podWebIds)[0],\n ...webIdsProperty(podWebIds),\n nodeId: typeof pod.nodeId === 'string' ? pod.nodeId : undefined,\n edgeNodeId: typeof pod.edgeNodeId === 'string' ? pod.edgeNodeId : undefined,\n });\n }\n }\n } catch {\n // Skip malformed entries.\n }\n }\n\n return mergePodLookupResults([\n ...pods,\n ...await this.getPodsFromIndexedStore(),\n ]);\n }\n\n private async getUsageByPodId(): Promise<Map<string, { storageUrl?: string }>> {\n const tableId = sql.identifier([this.usageTableName]);\n try {\n const result = await executeQuery<PodUsageRow>(this.db, sql`\n SELECT pod_id, storage_url FROM ${tableId}\n `);\n const byPodId = new Map<string, { storageUrl?: string }>();\n for (const row of result.rows) {\n if (!row.pod_id) {\n continue;\n }\n byPodId.set(row.pod_id, {\n storageUrl: row.storage_url ?? undefined,\n });\n }\n return byPodId;\n } catch {\n return new Map();\n }\n }\n\n /**\n * Fast path for CSS WrappedIndexedStorage. WebID indexes point to the root\n * account id, so a single indexed key plus account data row can resolve the\n * profile without scanning all account records.\n */\n private async findByWebIdIndex(webId: string): Promise<PodLookupResult | undefined> {\n const accountIds = await this.readStringArrayFromKv(`accounts/index/webIdLink/webId/${encodeURIComponent(webId)}`);\n for (const accountId of accountIds) {\n const account = await this.readAccountData(accountId);\n if (!account) {\n continue;\n }\n const pods = this.extractPodsFromAccountData(accountId, account);\n const match = pods.find((pod) => getPodWebIds(pod).some((candidate) => normalizeWebId(candidate) === webId));\n if (match) {\n return {\n ...match,\n webId,\n };\n }\n if (pods.length === 1) {\n return {\n ...pods[0],\n webId,\n ...webIdsProperty([webId, ...getPodWebIds(pods[0])]),\n };\n }\n }\n return undefined;\n }\n\n private async readAccountData(accountId: string): Promise<Record<string, unknown> | undefined> {\n for (const key of [`accounts/data/${accountId}`, `/.internal/accounts/data/${accountId}`]) {\n const value = await this.readKvValue(key);\n const record = parsePayloadRecord(value);\n if (record) {\n return record;\n }\n }\n return undefined;\n }\n\n private async readStringArrayFromKv(key: string): Promise<string[]> {\n const value = await this.readKvValue(key);\n return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];\n }\n\n private async readKvValue(key: string): Promise<unknown> {\n const tableId = sql.identifier([this.kvTableName]);\n try {\n const result = await executeQuery<{ value?: unknown }>(this.db, sql`\n SELECT value FROM ${tableId}\n WHERE key = ${key}\n LIMIT 1\n `);\n if (result.rows.length === 0) {\n return undefined;\n }\n return parseStoredValue(result.rows[0].value);\n } catch {\n return undefined;\n }\n }\n\n private extractPodsFromAccountData(accountId: string, data: Record<string, unknown>): PodLookupResult[] {\n const podMap = (data as any)['**pod**'] || (data as any).pod || {};\n const webIds = extractAccountWebIds(data);\n const pods: PodLookupResult[] = [];\n\n for (const [podId, podData] of Object.entries(podMap)) {\n const pod = podData as Record<string, unknown>;\n if (pod.baseUrl && typeof pod.baseUrl === 'string') {\n const podWebIds = [\n typeof pod.webId === 'string' ? pod.webId : undefined,\n ...extractPodOwnerWebIds(pod),\n ...webIds,\n ].filter((value): value is string => typeof value === 'string');\n pods.push({\n podId,\n accountId,\n baseUrl: pod.baseUrl,\n storageUrl: stringValue(pod.storageUrl),\n webId: dedupeStrings(podWebIds)[0],\n ...webIdsProperty(podWebIds),\n nodeId: typeof pod.nodeId === 'string' ? pod.nodeId : undefined,\n edgeNodeId: typeof pod.edgeNodeId === 'string' ? pod.edgeNodeId : undefined,\n });\n }\n }\n\n return pods;\n }\n\n /**\n * Older Xpod/CSS deployments may have used the IndexedStorage-compatible\n * identity_store table instead of CSS's WrappedIndexedStorage JSON tree in\n * internal_kv. Keep this as a read-only compatibility source so hosted WebID\n * profile lookup still works after storage implementation changes.\n */\n private async getPodsFromIndexedStore(): Promise<PodLookupResult[]> {\n const storeTableId = sql.identifier([this.indexedStoreTableName]);\n let result: { rows?: Array<{ container?: string; id?: string; payload?: unknown }> } | undefined;\n try {\n result = await executeQuery(this.db, sql`\n SELECT container, id, payload FROM ${storeTableId}\n WHERE container IN ('pod', 'owner', 'webIdLink')\n `);\n } catch {\n return [];\n }\n\n const podPayloads = new Map<string, Record<string, unknown>>();\n const ownerWebIdsByPodId = new Map<string, string[]>();\n const webIdsByAccountId = new Map<string, string[]>();\n\n for (const row of result?.rows ?? []) {\n if (!row.id || !row.container) {\n continue;\n }\n const payload = parsePayloadRecord(row.payload);\n if (!payload) {\n continue;\n }\n\n if (row.container === 'pod') {\n podPayloads.set(row.id, payload);\n continue;\n }\n\n if (row.container === 'owner') {\n const podId = stringValue(payload.podId);\n const webId = stringValue(payload.webId);\n if (podId && webId) {\n appendMapValue(ownerWebIdsByPodId, podId, webId);\n }\n continue;\n }\n\n if (row.container === 'webIdLink') {\n const accountId = stringValue(payload.accountId);\n const webId = stringValue(payload.webId);\n if (accountId && webId) {\n appendMapValue(webIdsByAccountId, accountId, webId);\n }\n }\n }\n\n const pods: PodLookupResult[] = [];\n for (const [podId, pod] of podPayloads) {\n const baseUrl = stringValue(pod.baseUrl);\n const accountId = stringValue(pod.accountId);\n if (!baseUrl || !accountId) {\n continue;\n }\n const podWebIds = dedupeStrings([\n stringValue(pod.webId),\n ...(ownerWebIdsByPodId.get(podId) ?? []),\n ...(webIdsByAccountId.get(accountId) ?? []),\n ].filter((value): value is string => typeof value === 'string'));\n\n pods.push({\n podId,\n accountId,\n baseUrl,\n storageUrl: stringValue(pod.storageUrl),\n webId: podWebIds[0],\n ...webIdsProperty(podWebIds),\n nodeId: stringValue(pod.nodeId),\n edgeNodeId: stringValue(pod.edgeNodeId),\n });\n }\n\n return pods;\n }\n}\n\nfunction extractAccountIdFromAccountDataKey(key: string): string | undefined {\n const marker = 'accounts/data/';\n const index = key.indexOf(marker);\n if (index < 0) {\n return undefined;\n }\n const accountId = key.slice(index + marker.length).replace(/\\.json$/u, '');\n return accountId || undefined;\n}\n\nfunction extractAccountWebIds(data: unknown): string[] {\n if (!data || typeof data !== 'object') {\n return [];\n }\n\n const record = data as Record<string, unknown>;\n const linkMap = record['**webIdLink**'] || record.webIdLink || {};\n if (!linkMap || typeof linkMap !== 'object') {\n return [];\n }\n\n return Object.values(linkMap as Record<string, unknown>)\n .map((value) => {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n const webId = (value as Record<string, unknown>).webId;\n return typeof webId === 'string' ? webId : undefined;\n })\n .filter((value): value is string => typeof value === 'string');\n}\n\nfunction extractPodOwnerWebIds(pod: Record<string, unknown>): string[] {\n const ownerMap = pod['**owner**'] || pod.owner || {};\n if (!ownerMap || typeof ownerMap !== 'object') {\n return [];\n }\n\n return Object.values(ownerMap as Record<string, unknown>)\n .map((value) => {\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n const webId = (value as Record<string, unknown>).webId;\n return typeof webId === 'string' ? webId : undefined;\n })\n .filter((value): value is string => typeof value === 'string');\n}\n\nfunction normalizeWebId(webId: string | undefined): string | undefined {\n if (!webId) {\n return undefined;\n }\n try {\n return new URL(webId).toString();\n } catch {\n return webId;\n }\n}\n\nfunction dedupeStrings(values: string[]): string[] {\n return [...new Set(values)];\n}\n\nfunction getPodWebIds(pod: PodLookupResult): string[] {\n return dedupeStrings([\n pod.webId,\n ...(pod.webIds ?? []),\n ].filter((value): value is string => typeof value === 'string' && value.length > 0));\n}\n\nfunction webIdsProperty(values: string[]): Pick<PodLookupResult, 'webIds'> {\n const webIds = dedupeStrings(values);\n return webIds.length > 1 ? { webIds } : {};\n}\n\nfunction mergePodLookupResults(values: PodLookupResult[]): PodLookupResult[] {\n const byPodId = new Map<string, PodLookupResult>();\n for (const value of values) {\n const existing = byPodId.get(value.podId);\n if (!existing) {\n byPodId.set(value.podId, value);\n continue;\n }\n\n const webIds = dedupeStrings([\n ...getPodWebIds(existing),\n ...getPodWebIds(value),\n ]);\n byPodId.set(value.podId, {\n ...existing,\n baseUrl: existing.baseUrl || value.baseUrl,\n storageUrl: existing.storageUrl ?? value.storageUrl,\n accountId: existing.accountId || value.accountId,\n webId: webIds[0],\n ...webIdsProperty(webIds),\n nodeId: existing.nodeId ?? value.nodeId,\n edgeNodeId: existing.edgeNodeId ?? value.edgeNodeId,\n });\n }\n return [...byPodId.values()];\n}\n\nfunction parsePayloadRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value) {\n return undefined;\n }\n if (typeof value === 'string') {\n try {\n const parsed = JSON.parse(value) as unknown;\n const unwrapped = unwrapStoredValue(parsed);\n return unwrapped && typeof unwrapped === 'object' ? unwrapped as Record<string, unknown> : undefined;\n } catch {\n return undefined;\n }\n }\n const unwrapped = unwrapStoredValue(value);\n return typeof unwrapped === 'object' ? unwrapped as Record<string, unknown> : undefined;\n}\n\nfunction parseStoredValue(value: unknown): unknown {\n if (typeof value === 'string') {\n try {\n return unwrapStoredValue(JSON.parse(value));\n } catch {\n return undefined;\n }\n }\n return unwrapStoredValue(value);\n}\n\nfunction unwrapStoredValue(value: unknown): unknown {\n if (value && typeof value === 'object' && 'key' in value && 'payload' in value) {\n return (value as Record<string, unknown>).payload;\n }\n return value;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction appendMapValue(map: Map<string, string[]>, key: string, value: string): void {\n const values = map.get(key) ?? [];\n values.push(value);\n map.set(key, values);\n}\n"]}
@@ -11,6 +11,7 @@ export interface ScopedPickWebIdHandlerOptions {
11
11
  }
12
12
  export interface PodWebIdLookupRepository {
13
13
  findByWebId: (webId: string) => Promise<PodLookupResult | undefined>;
14
+ findAllByWebId?: (webId: string) => Promise<PodLookupResult[]>;
14
15
  }
15
16
  /**
16
17
  * CSS-compatible WebID picker scoped to the current storage provider.
@@ -97,8 +97,10 @@ class ScopedPickWebIdHandler extends community_server_1.JsonInteractionHandler {
97
97
  return undefined;
98
98
  }
99
99
  try {
100
- const pod = await this.podLookupRepository.findByWebId(webId);
101
- return pod && matchesTargetStorage(pod, targetStorageUrl) ? pod : undefined;
100
+ const pods = this.podLookupRepository.findAllByWebId
101
+ ? await this.podLookupRepository.findAllByWebId(webId)
102
+ : await this.podLookupRepository.findByWebId(webId).then((pod) => pod ? [pod] : []);
103
+ return pods.find((pod) => matchesTargetStorage(pod, targetStorageUrl));
102
104
  }
103
105
  catch (error) {
104
106
  this.logger.warn(`Pod lookup unavailable for Web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f,CAAC;IAED,KAAK,MAAM,SAAS,IAAI,aAAa,EAAE,CAAC;QACtC,MAAM,aAAa,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,aAAa,IAAI,aAAa,KAAK,UAAU,EAAE,CAAC;YAClD,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,YAAY,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;QACpD,IAAI,YAAY,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;YAC/E,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,oBAAoB,CAAC,eAA+D;IAC3F,MAAM,MAAM,GAAG,eAAe,EAAE,MAA6C,CAAC;IAC9E,MAAM,KAAK,GAAG,MAAM,EAAE,aAAa,CAAC;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AACzF,CAAC","sourcesContent":["import { boolean, object, string } from 'yup';\nimport { getLoggerFor } from 'global-logger-factory';\nimport {\n BadRequestHttpError,\n FoundHttpError,\n JsonInteractionHandler,\n assertAccountId,\n assertOidcInteraction,\n finishInteraction,\n forgetWebId,\n parseSchema,\n validateWithError,\n} from '@solid/community-server';\nimport type {\n Json,\n JsonInteractionHandlerInput,\n JsonRepresentation,\n JsonView,\n ProviderFactory,\n WebIdStore,\n} from '@solid/community-server';\nimport { getIdentityDatabase } from '../drizzle/db';\nimport { PodLookupRepository, type PodLookupResult } from '../drizzle/PodLookupRepository';\nimport { ProvisionCodeCodec } from '../../provision/ProvisionCodeCodec';\n\ntype FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nconst inSchema = object({\n webId: string().trim().required(),\n remember: boolean().default(false),\n});\n\nexport interface ScopedPickWebIdHandlerOptions {\n webIdStore: WebIdStore;\n providerFactory: ProviderFactory;\n identityDbUrl?: string;\n podLookupRepository?: PodWebIdLookupRepository;\n fetch?: FetchLike;\n}\n\nexport interface PodWebIdLookupRepository {\n findByWebId: (webId: string) => Promise<PodLookupResult | undefined>;\n}\n\ninterface WebIdEntry extends Record<string, Json | undefined> {\n webId: string;\n storageUrl?: string;\n storageMode?: 'cloud' | 'local' | 'custom';\n}\n\n/**\n * CSS-compatible WebID picker scoped to the current storage provider.\n *\n * The upstream handler lists every WebID linked to the IdP account. In an\n * IDP/SP split flow that lets a Local SP login pick a Cloud Pod again, so this\n * replacement keeps consent choices constrained by the selected SP's Pod facts.\n */\nexport class ScopedPickWebIdHandler extends JsonInteractionHandler implements JsonView {\n private readonly logger = getLoggerFor(this);\n private readonly webIdStore: WebIdStore;\n private readonly providerFactory: ProviderFactory;\n private readonly podLookupRepository?: PodWebIdLookupRepository;\n private readonly fetch: FetchLike;\n\n public constructor(options: ScopedPickWebIdHandlerOptions) {\n super();\n this.webIdStore = options.webIdStore;\n this.providerFactory = options.providerFactory;\n this.podLookupRepository = options.podLookupRepository ??\n (options.identityDbUrl ? new PodLookupRepository(getIdentityDatabase(options.identityDbUrl)) : undefined);\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getView({ accountId, oidcInteraction }: JsonInteractionHandlerInput): Promise<JsonRepresentation> {\n assertAccountId(accountId);\n const provider = await this.providerFactory.getProvider();\n const description = parseSchema(inSchema);\n const target = await this.resolveTargetStorage(provider, oidcInteraction);\n const entries = await this.resolveScopedEntries(accountId, target);\n\n return {\n json: {\n ...description,\n webIds: entries.map((entry) => entry.webId),\n entries,\n },\n };\n }\n\n public async handle({ oidcInteraction, accountId, json }: JsonInteractionHandlerInput): Promise<never> {\n assertOidcInteraction(oidcInteraction);\n assertAccountId(accountId);\n const { webId, remember } = await validateWithError(inSchema, json);\n const provider = await this.providerFactory.getProvider();\n const target = await this.resolveTargetStorage(provider, oidcInteraction);\n\n if (!await this.webIdStore.isLinked(webId, accountId)) {\n this.logger.warn(`Trying to pick WebID ${webId} which does not belong to account ${accountId}`);\n throw new BadRequestHttpError('WebID does not belong to this account.');\n }\n\n if (!await this.isResolvableByCurrentSp(webId, target)) {\n this.logger.warn(`Trying to pick WebID ${webId} which does not belong to this storage provider`);\n throw new BadRequestHttpError('WebID does not belong to this storage provider.');\n }\n\n await forgetWebId(provider, oidcInteraction);\n const location = await finishInteraction(oidcInteraction, {\n login: {\n accountId: webId,\n remember,\n },\n }, true);\n throw new FoundHttpError(location);\n }\n\n private async resolveScopedEntries(accountId: string, target: TargetStorage): Promise<WebIdEntry[]> {\n const webIds = (await this.webIdStore.findLinks(accountId)).map((link) => link.webId);\n if (target.serviceToken) {\n return this.resolveRemoteSpEntries(webIds, target);\n }\n\n const entries: WebIdEntry[] = [];\n for (const webId of webIds) {\n const pod = await this.findSpPod(webId, target.storageUrl);\n if (!pod) {\n continue;\n }\n const storageUrl = ensureTrailingSlash(pod.storageUrl ?? pod.baseUrl);\n entries.push({\n webId,\n storageUrl,\n storageMode: deriveStorageMode(webId, storageUrl),\n });\n }\n return entries;\n }\n\n private async isResolvableByCurrentSp(webId: string, target: TargetStorage): Promise<boolean> {\n if (target.serviceToken) {\n return (await this.resolveRemoteSpEntries([webId], target)).some((entry) => entry.webId === webId);\n }\n return Boolean(await this.findSpPod(webId, target.storageUrl));\n }\n\n private async findSpPod(webId: string, targetStorageUrl: string): Promise<PodLookupResult | undefined> {\n if (!this.podLookupRepository) {\n this.logger.warn('No PodLookupRepository configured; refusing to expose unscoped WebID choices');\n return undefined;\n }\n\n try {\n const pod = await this.podLookupRepository.findByWebId(webId);\n return pod && matchesTargetStorage(pod, targetStorageUrl) ? pod : undefined;\n } catch (error) {\n this.logger.warn(`Pod lookup unavailable for WebID ${webId}: ${error}`);\n return undefined;\n }\n }\n\n private async resolveTargetStorage(\n provider: { issuer: string },\n oidcInteraction?: JsonInteractionHandlerInput['oidcInteraction'],\n ): Promise<TargetStorage> {\n const provisionCode = extractProvisionCode(oidcInteraction);\n if (!provisionCode) {\n return { storageUrl: ensureTrailingSlash(provider.issuer) };\n }\n\n const payload = new ProvisionCodeCodec(provider.issuer).decode(provisionCode);\n if (!payload) {\n throw new BadRequestHttpError('Invalid or expired provisionCode.');\n }\n\n const targetUrl = payload.spDomain\n ? `https://${payload.spDomain}`\n : payload.spUrl;\n return {\n storageUrl: ensureTrailingSlash(targetUrl),\n lookupUrl: ensureTrailingSlash(payload.spUrl),\n serviceToken: payload.serviceToken,\n };\n }\n\n private async resolveRemoteSpEntries(webIds: string[], target: TargetStorage): Promise<WebIdEntry[]> {\n if (!target.lookupUrl || !target.serviceToken || webIds.length === 0) {\n return [];\n }\n\n const response = await this.fetch(new URL('/provision/webids', target.lookupUrl).toString(), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${target.serviceToken}`,\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n body: JSON.stringify({ webIds }),\n });\n\n if (!response.ok) {\n this.logger.warn(`Remote SP WebID lookup failed: HTTP ${response.status}`);\n return [];\n }\n\n const body = await response.json().catch(() => null) as { entries?: RemoteSpWebIdEntry[] } | null;\n if (!Array.isArray(body?.entries)) {\n return [];\n }\n\n const allowedWebIds = new Set(webIds);\n return body.entries\n .filter((entry) => typeof entry.webId === 'string' && allowedWebIds.has(entry.webId))\n .filter((entry) => typeof entry.storageUrl === 'string' && matchesTargetStorage(\n {\n podId: '',\n accountId: '',\n baseUrl: entry.podUrl ?? entry.storageUrl,\n storageUrl: entry.storageUrl,\n },\n target.storageUrl,\n ))\n .map((entry) => ({\n webId: entry.webId,\n storageUrl: ensureTrailingSlash(entry.storageUrl),\n storageMode: deriveStorageMode(entry.webId, entry.storageUrl),\n }));\n }\n}\n\ninterface TargetStorage {\n storageUrl: string;\n lookupUrl?: string;\n serviceToken?: string;\n}\n\ninterface RemoteSpWebIdEntry {\n webId: string;\n podUrl?: string;\n storageUrl: string;\n}\n\nfunction deriveStorageMode(webId: string, storageUrl: string): 'cloud' | 'local' | 'custom' {\n const webIdRoot = deriveStorageRoot(webId);\n const storageRoot = deriveStorageRoot(storageUrl);\n if (!webIdRoot || !storageRoot) {\n return 'custom';\n }\n return webIdRoot === storageRoot ? 'cloud' : 'local';\n}\n\nfunction deriveStorageRoot(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n const segments = parsed.pathname.split('/').filter(Boolean);\n if (segments.length === 0) {\n return ensureTrailingSlash(parsed.origin);\n }\n\n return ensureTrailingSlash(new URL(`/${segments[0]}/`, parsed.origin).toString());\n } catch {\n return undefined;\n }\n}\n\nfunction ensureTrailingSlash(url: string): string {\n return url.replace(/\\/+$/u, '') + '/';\n}\n\nfunction matchesTargetStorage(pod: PodLookupResult, targetStorageUrl: string): boolean {\n const candidateUrls = [pod.storageUrl, pod.baseUrl].filter((value): value is string => typeof value === 'string' && value.length > 0);\n const targetRoot = deriveStorageRoot(targetStorageUrl);\n if (!targetRoot) {\n return false;\n }\n\n for (const candidate of candidateUrls) {\n const candidateRoot = deriveStorageRoot(candidate);\n if (candidateRoot && candidateRoot === targetRoot) {\n return true;\n }\n\n const candidateUrl = ensureTrailingSlash(candidate);\n if (candidateUrl.startsWith(targetRoot) || targetRoot.startsWith(candidateUrl)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction extractProvisionCode(oidcInteraction: JsonInteractionHandlerInput['oidcInteraction']): string | undefined {\n const params = oidcInteraction?.params as Record<string, unknown> | undefined;\n const value = params?.provisionCode;\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;\n}\n"]}
1
+ {"version":3,"file":"ScopedPickWebIdHandler.js","sourceRoot":"","sources":["../../../src/identity/oidc/ScopedPickWebIdHandler.ts"],"names":[],"mappings":";;;AAAA,6BAA8C;AAC9C,iEAAqD;AACrD,8DAUiC;AASjC,sCAAoD;AACpD,wEAA2F;AAC3F,2EAAwE;AAIx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AO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,MAAM,SAAS,IAAI,aAAa,EAAE,CAAC;QACtC,MAAM,aAAa,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,aAAa,IAAI,aAAa,KAAK,UAAU,EAAE,CAAC;YAClD,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,YAAY,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;QACpD,IAAI,YAAY,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;YAC/E,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,oBAAoB,CAAC,eAA+D;IAC3F,MAAM,MAAM,GAAG,eAAe,EAAE,MAA6C,CAAC;IAC9E,MAAM,KAAK,GAAG,MAAM,EAAE,aAAa,CAAC;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AACzF,CAAC","sourcesContent":["import { boolean, object, string } from 'yup';\nimport { getLoggerFor } from 'global-logger-factory';\nimport {\n BadRequestHttpError,\n FoundHttpError,\n JsonInteractionHandler,\n assertAccountId,\n assertOidcInteraction,\n finishInteraction,\n forgetWebId,\n parseSchema,\n validateWithError,\n} from '@solid/community-server';\nimport type {\n Json,\n JsonInteractionHandlerInput,\n JsonRepresentation,\n JsonView,\n ProviderFactory,\n WebIdStore,\n} from '@solid/community-server';\nimport { getIdentityDatabase } from '../drizzle/db';\nimport { PodLookupRepository, type PodLookupResult } from '../drizzle/PodLookupRepository';\nimport { ProvisionCodeCodec } from '../../provision/ProvisionCodeCodec';\n\ntype FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nconst inSchema = object({\n webId: string().trim().required(),\n remember: boolean().default(false),\n});\n\nexport interface ScopedPickWebIdHandlerOptions {\n webIdStore: WebIdStore;\n providerFactory: ProviderFactory;\n identityDbUrl?: string;\n podLookupRepository?: PodWebIdLookupRepository;\n fetch?: FetchLike;\n}\n\nexport interface PodWebIdLookupRepository {\n findByWebId: (webId: string) => Promise<PodLookupResult | undefined>;\n findAllByWebId?: (webId: string) => Promise<PodLookupResult[]>;\n}\n\ninterface WebIdEntry extends Record<string, Json | undefined> {\n webId: string;\n storageUrl?: string;\n storageMode?: 'cloud' | 'local' | 'custom';\n}\n\n/**\n * CSS-compatible WebID picker scoped to the current storage provider.\n *\n * The upstream handler lists every WebID linked to the IdP account. In an\n * IDP/SP split flow that lets a Local SP login pick a Cloud Pod again, so this\n * replacement keeps consent choices constrained by the selected SP's Pod facts.\n */\nexport class ScopedPickWebIdHandler extends JsonInteractionHandler implements JsonView {\n private readonly logger = getLoggerFor(this);\n private readonly webIdStore: WebIdStore;\n private readonly providerFactory: ProviderFactory;\n private readonly podLookupRepository?: PodWebIdLookupRepository;\n private readonly fetch: FetchLike;\n\n public constructor(options: ScopedPickWebIdHandlerOptions) {\n super();\n this.webIdStore = options.webIdStore;\n this.providerFactory = options.providerFactory;\n this.podLookupRepository = options.podLookupRepository ??\n (options.identityDbUrl ? new PodLookupRepository(getIdentityDatabase(options.identityDbUrl)) : undefined);\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n public async getView({ accountId, oidcInteraction }: JsonInteractionHandlerInput): Promise<JsonRepresentation> {\n assertAccountId(accountId);\n const provider = await this.providerFactory.getProvider();\n const description = parseSchema(inSchema);\n const target = await this.resolveTargetStorage(provider, oidcInteraction);\n const entries = await this.resolveScopedEntries(accountId, target);\n\n return {\n json: {\n ...description,\n webIds: entries.map((entry) => entry.webId),\n entries,\n },\n };\n }\n\n public async handle({ oidcInteraction, accountId, json }: JsonInteractionHandlerInput): Promise<never> {\n assertOidcInteraction(oidcInteraction);\n assertAccountId(accountId);\n const { webId, remember } = await validateWithError(inSchema, json);\n const provider = await this.providerFactory.getProvider();\n const target = await this.resolveTargetStorage(provider, oidcInteraction);\n\n if (!await this.webIdStore.isLinked(webId, accountId)) {\n this.logger.warn(`Trying to pick WebID ${webId} which does not belong to account ${accountId}`);\n throw new BadRequestHttpError('WebID does not belong to this account.');\n }\n\n if (!await this.isResolvableByCurrentSp(webId, target)) {\n this.logger.warn(`Trying to pick WebID ${webId} which does not belong to this storage provider`);\n throw new BadRequestHttpError('WebID does not belong to this storage provider.');\n }\n\n await forgetWebId(provider, oidcInteraction);\n const location = await finishInteraction(oidcInteraction, {\n login: {\n accountId: webId,\n remember,\n },\n }, true);\n throw new FoundHttpError(location);\n }\n\n private async resolveScopedEntries(accountId: string, target: TargetStorage): Promise<WebIdEntry[]> {\n const webIds = (await this.webIdStore.findLinks(accountId)).map((link) => link.webId);\n if (target.serviceToken) {\n return this.resolveRemoteSpEntries(webIds, target);\n }\n\n const entries: WebIdEntry[] = [];\n for (const webId of webIds) {\n const pod = await this.findSpPod(webId, target.storageUrl);\n if (!pod) {\n continue;\n }\n const storageUrl = ensureTrailingSlash(pod.storageUrl ?? pod.baseUrl);\n entries.push({\n webId,\n storageUrl,\n storageMode: deriveStorageMode(webId, storageUrl),\n });\n }\n return entries;\n }\n\n private async isResolvableByCurrentSp(webId: string, target: TargetStorage): Promise<boolean> {\n if (target.serviceToken) {\n return (await this.resolveRemoteSpEntries([webId], target)).some((entry) => entry.webId === webId);\n }\n return Boolean(await this.findSpPod(webId, target.storageUrl));\n }\n\n private async findSpPod(webId: string, targetStorageUrl: string): Promise<PodLookupResult | undefined> {\n if (!this.podLookupRepository) {\n this.logger.warn('No PodLookupRepository configured; refusing to expose unscoped WebID choices');\n return undefined;\n }\n\n try {\n const pods = this.podLookupRepository.findAllByWebId\n ? await this.podLookupRepository.findAllByWebId(webId)\n : await this.podLookupRepository.findByWebId(webId).then((pod) => pod ? [pod] : []);\n return pods.find((pod) => matchesTargetStorage(pod, targetStorageUrl));\n } catch (error) {\n this.logger.warn(`Pod lookup unavailable for WebID ${webId}: ${error}`);\n return undefined;\n }\n }\n\n private async resolveTargetStorage(\n provider: { issuer: string },\n oidcInteraction?: JsonInteractionHandlerInput['oidcInteraction'],\n ): Promise<TargetStorage> {\n const provisionCode = extractProvisionCode(oidcInteraction);\n if (!provisionCode) {\n return { storageUrl: ensureTrailingSlash(provider.issuer) };\n }\n\n const payload = new ProvisionCodeCodec(provider.issuer).decode(provisionCode);\n if (!payload) {\n throw new BadRequestHttpError('Invalid or expired provisionCode.');\n }\n\n const targetUrl = payload.spDomain\n ? `https://${payload.spDomain}`\n : payload.spUrl;\n return {\n storageUrl: ensureTrailingSlash(targetUrl),\n lookupUrl: ensureTrailingSlash(payload.spUrl),\n serviceToken: payload.serviceToken,\n };\n }\n\n private async resolveRemoteSpEntries(webIds: string[], target: TargetStorage): Promise<WebIdEntry[]> {\n if (!target.lookupUrl || !target.serviceToken || webIds.length === 0) {\n return [];\n }\n\n const response = await this.fetch(new URL('/provision/webids', target.lookupUrl).toString(), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${target.serviceToken}`,\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n body: JSON.stringify({ webIds }),\n });\n\n if (!response.ok) {\n this.logger.warn(`Remote SP WebID lookup failed: HTTP ${response.status}`);\n return [];\n }\n\n const body = await response.json().catch(() => null) as { entries?: RemoteSpWebIdEntry[] } | null;\n if (!Array.isArray(body?.entries)) {\n return [];\n }\n\n const allowedWebIds = new Set(webIds);\n return body.entries\n .filter((entry) => typeof entry.webId === 'string' && allowedWebIds.has(entry.webId))\n .filter((entry) => typeof entry.storageUrl === 'string' && matchesTargetStorage(\n {\n podId: '',\n accountId: '',\n baseUrl: entry.podUrl ?? entry.storageUrl,\n storageUrl: entry.storageUrl,\n },\n target.storageUrl,\n ))\n .map((entry) => ({\n webId: entry.webId,\n storageUrl: ensureTrailingSlash(entry.storageUrl),\n storageMode: deriveStorageMode(entry.webId, entry.storageUrl),\n }));\n }\n}\n\ninterface TargetStorage {\n storageUrl: string;\n lookupUrl?: string;\n serviceToken?: string;\n}\n\ninterface RemoteSpWebIdEntry {\n webId: string;\n podUrl?: string;\n storageUrl: string;\n}\n\nfunction deriveStorageMode(webId: string, storageUrl: string): 'cloud' | 'local' | 'custom' {\n const webIdRoot = deriveStorageRoot(webId);\n const storageRoot = deriveStorageRoot(storageUrl);\n if (!webIdRoot || !storageRoot) {\n return 'custom';\n }\n return webIdRoot === storageRoot ? 'cloud' : 'local';\n}\n\nfunction deriveStorageRoot(url: string): string | undefined {\n try {\n const parsed = new URL(url);\n const segments = parsed.pathname.split('/').filter(Boolean);\n if (segments.length === 0) {\n return ensureTrailingSlash(parsed.origin);\n }\n\n return ensureTrailingSlash(new URL(`/${segments[0]}/`, parsed.origin).toString());\n } catch {\n return undefined;\n }\n}\n\nfunction ensureTrailingSlash(url: string): string {\n return url.replace(/\\/+$/u, '') + '/';\n}\n\nfunction matchesTargetStorage(pod: PodLookupResult, targetStorageUrl: string): boolean {\n const candidateUrls = [pod.storageUrl, pod.baseUrl].filter((value): value is string => typeof value === 'string' && value.length > 0);\n const targetRoot = deriveStorageRoot(targetStorageUrl);\n if (!targetRoot) {\n return false;\n }\n\n for (const candidate of candidateUrls) {\n const candidateRoot = deriveStorageRoot(candidate);\n if (candidateRoot && candidateRoot === targetRoot) {\n return true;\n }\n\n const candidateUrl = ensureTrailingSlash(candidate);\n if (candidateUrl.startsWith(targetRoot) || targetRoot.startsWith(candidateUrl)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction extractProvisionCode(oidcInteraction: JsonInteractionHandlerInput['oidcInteraction']): string | undefined {\n const params = oidcInteraction?.params as Record<string, unknown> | undefined;\n const value = params?.provisionCode;\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;\n}\n"]}
@@ -24,5 +24,5 @@ export interface RuntimeBootstrapState {
24
24
  export declare function resolveRuntimeBootstrap(id: string, options: XpodRuntimeOptions, host: RuntimeHost, platform?: RuntimePlatform): Promise<RuntimeBootstrapState>;
25
25
  export declare function buildRuntimeEnv(state: RuntimeBootstrapState, options: XpodRuntimeOptions, envFromFile?: Record<string, string | undefined>): Record<string, string | undefined>;
26
26
  export declare function buildRuntimeShorthand(runtimeEnv: Record<string, string | undefined>, options: XpodRuntimeOptions, state: RuntimeBootstrapState, baseEnv?: Record<string, string | undefined>): Record<string, string | number | boolean>;
27
- export declare function createCssRuntimeConfig(state: RuntimeBootstrapState, open: boolean, platform?: Pick<RuntimePlatform, 'dirname' | 'ensureDir' | 'joinPath' | 'writeTextFile'>): string;
27
+ export declare function createCssRuntimeConfig(state: RuntimeBootstrapState, open: boolean, platform?: Pick<RuntimePlatform, 'dirname' | 'ensureDir' | 'joinPath' | 'readTextFile' | 'writeTextFile'>): string;
28
28
  export declare function initRuntimeLogger(level: string, platform?: Pick<RuntimePlatform, 'cwd' | 'joinPath'>): void;
@@ -215,18 +215,56 @@ function createCssRuntimeConfig(state, open, platform = NodeRuntimePlatform_1.no
215
215
  })()
216
216
  : normalizeWindowsAbsolutePath(platform.joinPath(runtimeRoot, 'css-runtime.config.json'));
217
217
  const openConfigPath = normalizeWindowsAbsolutePath(platform.joinPath(package_root_1.PACKAGE_ROOT, 'config/runtime-open.json'));
218
+ const runtimeConfigDir = platform.dirname(runtimeConfigPath);
219
+ const runtimeConfigImportPath = rewriteConfigForFileUrlImportsIfNeeded(configPath, platform.joinPath(runtimeConfigDir, 'config'), platform);
218
220
  platform.writeTextFile(runtimeConfigPath, JSON.stringify({
219
221
  '@context': [
220
222
  'https://linkedsoftwaredependencies.org/bundles/npm/@solid/community-server/^8.0.0/components/context.jsonld',
221
223
  'https://linkedsoftwaredependencies.org/bundles/npm/asynchronous-handlers/^1.0.0/components/context.jsonld',
222
224
  ],
223
225
  import: [
224
- toConfigImportSpecifier(runtimeConfigPath, configPath),
226
+ toConfigImportSpecifier(runtimeConfigPath, runtimeConfigImportPath),
225
227
  toConfigImportSpecifier(runtimeConfigPath, openConfigPath),
226
228
  ],
227
229
  }, null, 2));
228
230
  return runtimeConfigPath;
229
231
  }
232
+ function rewriteConfigForFileUrlImportsIfNeeded(configPath, outputDir, platform, rewritten = new Map()) {
233
+ const normalizedConfigPath = normalizeWindowsAbsolutePath(configPath);
234
+ if (isWindowsAbsolutePath(normalizedConfigPath) || !pathNeedsEscapedFileUrl(normalizedConfigPath)) {
235
+ return normalizedConfigPath;
236
+ }
237
+ const existing = rewritten.get(normalizedConfigPath);
238
+ if (existing) {
239
+ return existing;
240
+ }
241
+ platform.ensureDir(outputDir);
242
+ const outputPath = normalizeWindowsAbsolutePath(platform.joinPath(outputDir, node_path_1.default.posix.basename(normalizedConfigPath)));
243
+ rewritten.set(normalizedConfigPath, outputPath);
244
+ const parsed = JSON.parse(platform.readTextFile(normalizedConfigPath));
245
+ parsed.import = rewriteConfigImports(normalizedConfigPath, parsed.import, outputDir, platform, rewritten);
246
+ platform.writeTextFile(outputPath, `${JSON.stringify(parsed, null, 2)}\n`);
247
+ return outputPath;
248
+ }
249
+ function rewriteConfigImports(sourceConfigPath, imports, outputDir, platform, rewritten) {
250
+ if (typeof imports === 'string') {
251
+ return rewriteConfigImport(sourceConfigPath, imports, outputDir, platform, rewritten);
252
+ }
253
+ if (Array.isArray(imports)) {
254
+ return imports.map((value) => typeof value === 'string'
255
+ ? rewriteConfigImport(sourceConfigPath, value, outputDir, platform, rewritten)
256
+ : value);
257
+ }
258
+ return imports;
259
+ }
260
+ function rewriteConfigImport(sourceConfigPath, importValue, outputDir, platform, rewritten) {
261
+ if (!importValue.startsWith('./') && !importValue.startsWith('../')) {
262
+ return importValue;
263
+ }
264
+ const targetPath = normalizeWindowsAbsolutePath(node_path_1.default.posix.resolve(platform.dirname(sourceConfigPath), importValue));
265
+ const rewrittenTargetPath = rewriteConfigForFileUrlImportsIfNeeded(targetPath, outputDir, platform, rewritten);
266
+ return (0, node_url_1.pathToFileURL)(rewrittenTargetPath).href;
267
+ }
230
268
  function initRuntimeLogger(level, platform = NodeRuntimePlatform_1.nodeRuntimePlatform) {
231
269
  const loggerFactory = new ConfigurableLoggerFactory_1.ConfigurableLoggerFactory(level, {
232
270
  fileName: platform.joinPath(platform.cwd(), 'logs/xpod-%DATE%.log'),
@@ -1 +1 @@
1
- {"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../src/runtime/bootstrap.ts"],"names":[],"mappings":";;;;;AAgHA,0DAoEC;AAED,0CAgCC;AAED,sDA4CC;AAED,wDAoCC;AAED,8CASC;AArTD,iEAA+D;AAC/D,0DAA6B;AAC7B,uCAAyC;AACzC,oFAAiF;AACjF,iDAA8C;AAE9C,+CAA6E;AAC7E,6EAA0E;AAyB1E,SAAS,mBAAmB,CAAC,GAAW;IACtC,OAAO,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,CAAC;AAC7C,CAAC;AAED,SAAS,4BAA4B,CAAC,QAAgB;IACpD,OAAO,QAAQ,CAAC,OAAO,CAAC,2BAA2B,EAAE,EAAE,CAAC,CAAC;AAC3D,CAAC;AAED,SAAS,qBAAqB,CAAC,QAAgB;IAC7C,OAAO,iBAAiB,CAAC,IAAI,CAAC,4BAA4B,CAAC,QAAQ,CAAC,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,mBAAmB,CAAC,QAAgB;IAC3C,MAAM,cAAc,GAAG,4BAA4B,CAAC,QAAQ,CAAC,CAAC;IAC9D,OAAO,qBAAqB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,mBAAI,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;AACjH,CAAC;AAED,SAAS,gCAAgC,CAAC,SAAiB,EAAE,UAAkB;IAC7E,MAAM,SAAS,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;IAC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UAAU,EAAE;YACV,6GAA6G;YAC7G,2GAA2G;SAC5G;QACD,MAAM,EAAE;YACN,uBAAuB,CAAC,iBAAiB,EAAE,UAAU,CAAC;YACtD,uBAAuB,CAAC,iBAAiB,EAAE,cAAc,CAAC;SAC3D;KACF,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;IAEb,OAAO,iBAAiB,CAAC;AAC3B,CAAC;AAED,SAAgB,iBAAiB,CAC/B,KAAa,EACb,WAAsD,yCAAmB;IAEzE,MAAM,aAAa,GAAG,IAAI,qDAAyB,CAAC,KAAK,EAAE;QACzD,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,sBAAsB,CAAC;QACnE,YAAY,EAAE,IAAI;KACnB,CAAC,CAAC;IACH,IAAA,8CAAsB,EAAC,aAAa,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { setGlobalLoggerFactory } from 'global-logger-factory';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { ConfigurableLoggerFactory } from '../logging/ConfigurableLoggerFactory';\nimport { PACKAGE_ROOT } from './package-root';\nimport type { RuntimeHost } from './host/types';\nimport { oidcTokenEndpoint, resolveExternalOidcIssuer } from './oidc-issuer';\nimport { nodeRuntimePlatform } from './platform/node/NodeRuntimePlatform';\nimport type { RuntimePlatform } from './platform/types';\nimport type { XpodRuntimeOptions, XpodRuntimePorts, XpodRuntimeSockets } from './runtime-types';\n\nexport interface RuntimeBootstrapState {\n id: string;\n host: RuntimeHost;\n mode: 'local' | 'cloud';\n transport: 'socket' | 'port';\n bindHost: string;\n runtimeRoot: string;\n rootFilePath: string;\n sparqlEndpoint: string;\n rdfIndexPath: string;\n identityDbUrl: string;\n usageDbUrl: string;\n cssAuthMode: 'acp' | 'acl' | 'allow-all';\n apiOpen: boolean;\n logLevel: string;\n baseUrl: string;\n envFilePath?: string;\n ports: XpodRuntimePorts;\n sockets: XpodRuntimeSockets;\n}\n\nfunction ensureTrailingSlash(url: string): string {\n return url.endsWith('/') ? url : `${url}/`;\n}\n\nfunction normalizeWindowsAbsolutePath(filePath: string): string {\n return filePath.replace(/^[\\\\/]+(?=[A-Za-z]:[\\\\/])/, '');\n}\n\nfunction isWindowsAbsolutePath(filePath: string): boolean {\n return /^[A-Za-z]:[\\\\/]/.test(normalizeWindowsAbsolutePath(filePath));\n}\n\nfunction getWindowsDriveRoot(filePath: string): string | undefined {\n const normalizedPath = normalizeWindowsAbsolutePath(filePath);\n return isWindowsAbsolutePath(normalizedPath) ? path.win32.parse(normalizedPath).root.toLowerCase() : undefined;\n}\n\nfunction arePathsOnDifferentWindowsDrives(firstPath: string, secondPath: string): boolean {\n const firstRoot = getWindowsDriveRoot(firstPath);\n const secondRoot = getWindowsDriveRoot(secondPath);\n return Boolean(firstRoot && secondRoot && firstRoot !== secondRoot);\n}\n\nfunction toWindowsFileUrl(filePath: string): string {\n const normalizedPath = normalizeWindowsAbsolutePath(filePath).replace(/\\\\/g, '/');\n return new URL(`file:///${normalizedPath}`).href;\n}\n\nfunction toConfigImportSpecifier(fromFilePath: string, toFilePath: string): string {\n const normalizedFromPath = normalizeWindowsAbsolutePath(fromFilePath);\n const normalizedToPath = normalizeWindowsAbsolutePath(toFilePath);\n if (!isWindowsAbsolutePath(normalizedFromPath) && (pathNeedsEscapedFileUrl(normalizedFromPath) || pathNeedsEscapedFileUrl(normalizedToPath))) {\n return pathToFileURL(normalizedToPath).href;\n }\n\n const useWindowsPaths = isWindowsAbsolutePath(normalizedFromPath) || isWindowsAbsolutePath(normalizedToPath);\n const pathApi = useWindowsPaths ? path.win32 : path.posix;\n const fromDirectoryPath = pathApi.dirname(useWindowsPaths ? normalizedFromPath : fromFilePath);\n const targetPath = useWindowsPaths ? normalizedToPath : toFilePath;\n\n if (useWindowsPaths && arePathsOnDifferentWindowsDrives(fromDirectoryPath, targetPath)) {\n return toWindowsFileUrl(targetPath);\n }\n\n const relativePath = pathApi.relative(fromDirectoryPath, targetPath).replace(/\\\\/g, '/');\n if (relativePath.startsWith('./') || relativePath.startsWith('../')) {\n return relativePath;\n }\n return `./${relativePath}`;\n}\n\nfunction pathNeedsEscapedFileUrl(filePath: string): boolean {\n return /\\s/.test(filePath);\n}\n\nfunction withDefinedEntries(entries: Array<[string, string | number | boolean | undefined]>): Record<string, string | number | boolean> {\n const result: Record<string, string | number | boolean> = {};\n for (const [key, value] of entries) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction normalizeDatabaseUrl(\n value: string,\n platform: Pick<RuntimePlatform, 'resolvePath'> = nodeRuntimePlatform,\n): string {\n if (\n value.startsWith('sqlite:') ||\n value.startsWith('postgres://') ||\n value.startsWith('postgresql://') ||\n value.startsWith('mysql://')\n ) {\n return value;\n }\n return `sqlite:${platform.resolvePath(value)}`;\n}\n\nexport async function resolveRuntimeBootstrap(\n id: string,\n options: XpodRuntimeOptions,\n host: RuntimeHost,\n platform: RuntimePlatform = nodeRuntimePlatform,\n): Promise<RuntimeBootstrapState> {\n const mode = options.mode ?? 'local';\n const transport = host.resolveTransport(options.transport);\n const bindHost = options.bindHost ?? '127.0.0.1';\n const runtimeRoot = platform.resolvePath(options.runtimeRoot ?? platform.joinPath(platform.cwd(), '.test-data', 'xpod-runtime', id));\n const rootFilePath = platform.resolvePath(options.rootFilePath ?? platform.joinPath(runtimeRoot, 'data'));\n const sparqlEndpoint = normalizeDatabaseUrl(options.sparqlEndpoint ?? platform.joinPath(runtimeRoot, 'quadstore.sqlite'), platform);\n const rdfIndexPath = platform.resolvePath(options.rdfIndexPath ?? platform.joinPath(runtimeRoot, 'rdf-index.sqlite'));\n const identityDbUrl = normalizeDatabaseUrl(options.identityDbUrl ?? platform.joinPath(runtimeRoot, 'identity.sqlite'), platform);\n const usageDbUrl = normalizeDatabaseUrl(options.usageDbUrl ?? platform.joinPath(runtimeRoot, 'usage.sqlite'), platform);\n const cssAuthMode = options.authMode ?? (options.open ? 'allow-all' : 'acp');\n const apiOpen = options.apiOpen ?? options.open ?? false;\n const logLevel = options.logLevel ?? platform.getEnv('CSS_LOGGING_LEVEL') ?? 'warn';\n\n platform.ensureDir(runtimeRoot);\n platform.ensureDir(rootFilePath);\n\n const socketsRoot = platform.joinPath(runtimeRoot, 'sockets');\n if (transport === 'socket') {\n platform.ensureDir(socketsRoot);\n }\n const ports: XpodRuntimePorts = transport === 'port'\n ? await host.allocatePorts({\n gatewayPort: options.gatewayPort,\n cssPort: options.cssPort,\n apiPort: options.apiPort,\n basePort: 5600,\n })\n : {};\n const sockets: XpodRuntimeSockets = {};\n\n if (transport === 'socket') {\n sockets.gateway = platform.resolvePath(options.gatewaySocketPath ?? platform.joinPath(socketsRoot, 'gateway.sock'));\n sockets.css = platform.resolvePath(options.cssSocketPath ?? platform.joinPath(socketsRoot, 'css.sock'));\n sockets.api = platform.resolvePath(options.apiSocketPath ?? platform.joinPath(socketsRoot, 'api.sock'));\n }\n\n const baseUrl = ensureTrailingSlash(\n options.baseUrl ?? (transport === 'socket'\n ? 'http://localhost'\n : `http://${bindHost}:${ports.gateway}`),\n );\n\n return {\n id,\n host,\n mode,\n transport,\n bindHost,\n runtimeRoot,\n rootFilePath,\n sparqlEndpoint,\n rdfIndexPath,\n identityDbUrl,\n usageDbUrl,\n cssAuthMode,\n apiOpen,\n logLevel,\n baseUrl,\n envFilePath: options.envFile ? platform.resolvePath(options.envFile) : undefined,\n ports,\n sockets,\n };\n}\n\nexport function buildRuntimeEnv(\n state: RuntimeBootstrapState,\n options: XpodRuntimeOptions,\n envFromFile: Record<string, string | undefined> = {},\n): Record<string, string | undefined> {\n const mergedEnv = {\n ...envFromFile,\n ...options.env,\n };\n const externalOidcIssuer = resolveExternalOidcIssuer(mergedEnv);\n\n return {\n ...mergedEnv,\n XPOD_ENV_PATH: state.envFilePath,\n XPOD_EDITION: state.mode,\n CSS_BASE_URL: state.baseUrl,\n CSS_TOKEN_ENDPOINT: externalOidcIssuer\n ? oidcTokenEndpoint(externalOidcIssuer)\n : `${state.baseUrl}.oidc/token`,\n CSS_ROOT_FILE_PATH: state.rootFilePath,\n CSS_SPARQL_ENDPOINT: state.sparqlEndpoint,\n SPARQL_ENDPOINT: state.sparqlEndpoint,\n CSS_IDENTITY_DB_URL: state.identityDbUrl,\n DATABASE_URL: state.identityDbUrl,\n CSS_PORT: state.ports.css !== undefined ? String(state.ports.css) : undefined,\n API_PORT: state.ports.api !== undefined ? String(state.ports.api) : undefined,\n API_HOST: state.bindHost,\n API_SOCKET_PATH: state.sockets.api,\n XPOD_MAIN_PORT: state.ports.gateway !== undefined ? String(state.ports.gateway) : undefined,\n CORS_ORIGINS: new URL(state.baseUrl).origin,\n CSS_LOGGING_LEVEL: state.logLevel,\n };\n}\n\nexport function buildRuntimeShorthand(\n runtimeEnv: Record<string, string | undefined>,\n options: XpodRuntimeOptions,\n state: RuntimeBootstrapState,\n baseEnv: Record<string, string | undefined> = nodeRuntimePlatform.baseEnv,\n): Record<string, string | number | boolean> {\n const envValue = (key: string): string | undefined => runtimeEnv[key] ?? baseEnv[key];\n const externalOidcIssuer = resolveExternalOidcIssuer({\n oidcIssuer: envValue('oidcIssuer'),\n });\n\n return {\n ...withDefinedEntries([\n ['baseStorageDomain', envValue('CSS_BASE_STORAGE_DOMAIN')],\n ['minioAccessKey', envValue('CSS_MINIO_ACCESS_KEY')],\n ['minioSecretKey', envValue('CSS_MINIO_SECRET_KEY')],\n ['minioEndpoint', envValue('CSS_MINIO_ENDPOINT')],\n ['minioBucketName', envValue('CSS_MINIO_BUCKET_NAME')],\n ['redisClient', envValue('CSS_REDIS_CLIENT')],\n ['redisUsername', envValue('CSS_REDIS_USERNAME')],\n ['redisPassword', envValue('CSS_REDIS_PASSWORD')],\n ['emailConfigHost', envValue('CSS_EMAIL_CONFIG_HOST') ?? ''],\n ['emailConfigPort', envValue('CSS_EMAIL_CONFIG_PORT') ?? '587'],\n ['emailConfigAuthUser', envValue('CSS_EMAIL_CONFIG_AUTH_USER') ?? ''],\n ['emailConfigAuthPass', envValue('CSS_EMAIL_CONFIG_AUTH_PASS') ?? ''],\n ['oidcIssuer', externalOidcIssuer],\n ['allowedHosts', envValue('CSS_ALLOWED_HOSTS')],\n ['nodeId', envValue('XPOD_NODE_ID')],\n ['nodeToken', envValue('XPOD_NODE_TOKEN')],\n ['serviceToken', envValue('XPOD_SERVICE_TOKEN')],\n ]),\n baseUrl: state.baseUrl,\n rootFilePath: state.rootFilePath,\n sparqlEndpoint: state.sparqlEndpoint,\n rdfIndexPath: state.rdfIndexPath,\n identityDbUrl: state.identityDbUrl,\n usageDbUrl: state.usageDbUrl,\n logLevel: state.logLevel,\n authMode: state.cssAuthMode,\n edition: state.mode === 'cloud' ? 'server' : 'local',\n edgeNodesEnabled: options.edgeNodesEnabled ?? false,\n centerRegistrationEnabled: options.centerRegistrationEnabled ?? false,\n ...(options.shorthand ?? {}),\n };\n}\n\nexport function createCssRuntimeConfig(\n state: RuntimeBootstrapState,\n open: boolean,\n platform: Pick<RuntimePlatform, 'dirname' | 'ensureDir' | 'joinPath' | 'writeTextFile'> = nodeRuntimePlatform,\n): string {\n const configPath = normalizeWindowsAbsolutePath(platform.joinPath(PACKAGE_ROOT, `config/${state.mode}.json`));\n if (!open) {\n return configPath;\n }\n\n const runtimeRoot = normalizeWindowsAbsolutePath(state.runtimeRoot);\n const runtimeConfigPath = arePathsOnDifferentWindowsDrives(runtimeRoot, configPath)\n ? (() => {\n const runtimeConfigDir = normalizeWindowsAbsolutePath(platform.joinPath(\n platform.dirname(configPath),\n '..',\n '.xpod-runtime',\n state.id,\n ));\n platform.ensureDir(runtimeConfigDir);\n return normalizeWindowsAbsolutePath(platform.joinPath(runtimeConfigDir, 'css-runtime.config.json'));\n })()\n : normalizeWindowsAbsolutePath(platform.joinPath(runtimeRoot, 'css-runtime.config.json'));\n const openConfigPath = normalizeWindowsAbsolutePath(platform.joinPath(PACKAGE_ROOT, 'config/runtime-open.json'));\n platform.writeTextFile(runtimeConfigPath, JSON.stringify({\n '@context': [\n 'https://linkedsoftwaredependencies.org/bundles/npm/@solid/community-server/^8.0.0/components/context.jsonld',\n 'https://linkedsoftwaredependencies.org/bundles/npm/asynchronous-handlers/^1.0.0/components/context.jsonld',\n ],\n import: [\n toConfigImportSpecifier(runtimeConfigPath, configPath),\n toConfigImportSpecifier(runtimeConfigPath, openConfigPath),\n ],\n }, null, 2));\n\n return runtimeConfigPath;\n}\n\nexport function initRuntimeLogger(\n level: string,\n platform: Pick<RuntimePlatform, 'cwd' | 'joinPath'> = nodeRuntimePlatform,\n): void {\n const loggerFactory = new ConfigurableLoggerFactory(level, {\n fileName: platform.joinPath(platform.cwd(), 'logs/xpod-%DATE%.log'),\n showLocation: true,\n });\n setGlobalLoggerFactory(loggerFactory);\n}\n"]}
1
+ {"version":3,"file":"bootstrap.js","sourceRoot":"","sources":["../../src/runtime/bootstrap.ts"],"names":[],"mappings":";;;;;AAgHA,0DAoEC;AAED,0CAgCC;AAED,sDA4CC;AAED,wDA0CC;AAwED,8CASC;AAjYD,iEAA+D;AAC/D,0DAA6B;AAC7B,uCAAyC;AACzC,oFAAiF;AACjF,iDAA8C;AAE9C,+CAA6E;AAC7E,6EAA0E;AAyB1E,SAAS,mBAAmB,CAAC,GAAW;IACtC,OAAO,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,CAAC;AAC7C,CAAC;AAED,SAAS,4BAA4B,CAAC,QAAgB;IACpD,OAAO,QAAQ,CAAC,OAAO,CAAC,2BAA2B,EAAE,EAAE,CAAC,CAAC;AAC3D,CAAC;AAED,SAAS,qBAAqB,CAAC,QAAgB;IAC7C,OAAO,iBAAiB,CAAC,IAAI,CAAC,4BAA4B,CAAC,QAAQ,CAAC,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,mBAAmB,CAAC,QAAgB;IAC3C,MAAM,cAAc,GAAG,4BAA4B,CAAC,QAAQ,CAAC,CAAC;IAC9D,OAAO,q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9B,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACpE,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,UAAU,GAAG,4BAA4B,CAC7C,mBAAI,CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,gBAAgB,CAAC,EAAE,WAAW,CAAC,CACpE,CAAC;IACF,MAAM,mBAAmB,GAAG,sCAAsC,CAAC,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC;IAC/G,OAAO,IAAA,wBAAa,EAAC,mBAAmB,CAAC,CAAC,IAAI,CAAC;AACjD,CAAC;AAED,SAAgB,iBAAiB,CAC/B,KAAa,EACb,WAAsD,yCAAmB;IAEzE,MAAM,aAAa,GAAG,IAAI,qDAAyB,CAAC,KAAK,EAAE;QACzD,QAAQ,EAAE,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,sBAAsB,CAAC;QACnE,YAAY,EAAE,IAAI;KACnB,CAAC,CAAC;IACH,IAAA,8CAAsB,EAAC,aAAa,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { setGlobalLoggerFactory } from 'global-logger-factory';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { ConfigurableLoggerFactory } from '../logging/ConfigurableLoggerFactory';\nimport { PACKAGE_ROOT } from './package-root';\nimport type { RuntimeHost } from './host/types';\nimport { oidcTokenEndpoint, resolveExternalOidcIssuer } from './oidc-issuer';\nimport { nodeRuntimePlatform } from './platform/node/NodeRuntimePlatform';\nimport type { RuntimePlatform } from './platform/types';\nimport type { XpodRuntimeOptions, XpodRuntimePorts, XpodRuntimeSockets } from './runtime-types';\n\nexport interface RuntimeBootstrapState {\n id: string;\n host: RuntimeHost;\n mode: 'local' | 'cloud';\n transport: 'socket' | 'port';\n bindHost: string;\n runtimeRoot: string;\n rootFilePath: string;\n sparqlEndpoint: string;\n rdfIndexPath: string;\n identityDbUrl: string;\n usageDbUrl: string;\n cssAuthMode: 'acp' | 'acl' | 'allow-all';\n apiOpen: boolean;\n logLevel: string;\n baseUrl: string;\n envFilePath?: string;\n ports: XpodRuntimePorts;\n sockets: XpodRuntimeSockets;\n}\n\nfunction ensureTrailingSlash(url: string): string {\n return url.endsWith('/') ? url : `${url}/`;\n}\n\nfunction normalizeWindowsAbsolutePath(filePath: string): string {\n return filePath.replace(/^[\\\\/]+(?=[A-Za-z]:[\\\\/])/, '');\n}\n\nfunction isWindowsAbsolutePath(filePath: string): boolean {\n return /^[A-Za-z]:[\\\\/]/.test(normalizeWindowsAbsolutePath(filePath));\n}\n\nfunction getWindowsDriveRoot(filePath: string): string | undefined {\n const normalizedPath = normalizeWindowsAbsolutePath(filePath);\n return isWindowsAbsolutePath(normalizedPath) ? path.win32.parse(normalizedPath).root.toLowerCase() : undefined;\n}\n\nfunction arePathsOnDifferentWindowsDrives(firstPath: string, secondPath: string): boolean {\n const firstRoot = getWindowsDriveRoot(firstPath);\n const secondRoot = getWindowsDriveRoot(secondPath);\n return Boolean(firstRoot && secondRoot && firstRoot !== secondRoot);\n}\n\nfunction toWindowsFileUrl(filePath: string): string {\n const normalizedPath = normalizeWindowsAbsolutePath(filePath).replace(/\\\\/g, '/');\n return new URL(`file:///${normalizedPath}`).href;\n}\n\nfunction toConfigImportSpecifier(fromFilePath: string, toFilePath: string): string {\n const normalizedFromPath = normalizeWindowsAbsolutePath(fromFilePath);\n const normalizedToPath = normalizeWindowsAbsolutePath(toFilePath);\n if (!isWindowsAbsolutePath(normalizedFromPath) && (pathNeedsEscapedFileUrl(normalizedFromPath) || pathNeedsEscapedFileUrl(normalizedToPath))) {\n return pathToFileURL(normalizedToPath).href;\n }\n\n const useWindowsPaths = isWindowsAbsolutePath(normalizedFromPath) || isWindowsAbsolutePath(normalizedToPath);\n const pathApi = useWindowsPaths ? path.win32 : path.posix;\n const fromDirectoryPath = pathApi.dirname(useWindowsPaths ? normalizedFromPath : fromFilePath);\n const targetPath = useWindowsPaths ? normalizedToPath : toFilePath;\n\n if (useWindowsPaths && arePathsOnDifferentWindowsDrives(fromDirectoryPath, targetPath)) {\n return toWindowsFileUrl(targetPath);\n }\n\n const relativePath = pathApi.relative(fromDirectoryPath, targetPath).replace(/\\\\/g, '/');\n if (relativePath.startsWith('./') || relativePath.startsWith('../')) {\n return relativePath;\n }\n return `./${relativePath}`;\n}\n\nfunction pathNeedsEscapedFileUrl(filePath: string): boolean {\n return /\\s/.test(filePath);\n}\n\nfunction withDefinedEntries(entries: Array<[string, string | number | boolean | undefined]>): Record<string, string | number | boolean> {\n const result: Record<string, string | number | boolean> = {};\n for (const [key, value] of entries) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result;\n}\n\nfunction normalizeDatabaseUrl(\n value: string,\n platform: Pick<RuntimePlatform, 'resolvePath'> = nodeRuntimePlatform,\n): string {\n if (\n value.startsWith('sqlite:') ||\n value.startsWith('postgres://') ||\n value.startsWith('postgresql://') ||\n value.startsWith('mysql://')\n ) {\n return value;\n }\n return `sqlite:${platform.resolvePath(value)}`;\n}\n\nexport async function resolveRuntimeBootstrap(\n id: string,\n options: XpodRuntimeOptions,\n host: RuntimeHost,\n platform: RuntimePlatform = nodeRuntimePlatform,\n): Promise<RuntimeBootstrapState> {\n const mode = options.mode ?? 'local';\n const transport = host.resolveTransport(options.transport);\n const bindHost = options.bindHost ?? '127.0.0.1';\n const runtimeRoot = platform.resolvePath(options.runtimeRoot ?? platform.joinPath(platform.cwd(), '.test-data', 'xpod-runtime', id));\n const rootFilePath = platform.resolvePath(options.rootFilePath ?? platform.joinPath(runtimeRoot, 'data'));\n const sparqlEndpoint = normalizeDatabaseUrl(options.sparqlEndpoint ?? platform.joinPath(runtimeRoot, 'quadstore.sqlite'), platform);\n const rdfIndexPath = platform.resolvePath(options.rdfIndexPath ?? platform.joinPath(runtimeRoot, 'rdf-index.sqlite'));\n const identityDbUrl = normalizeDatabaseUrl(options.identityDbUrl ?? platform.joinPath(runtimeRoot, 'identity.sqlite'), platform);\n const usageDbUrl = normalizeDatabaseUrl(options.usageDbUrl ?? platform.joinPath(runtimeRoot, 'usage.sqlite'), platform);\n const cssAuthMode = options.authMode ?? (options.open ? 'allow-all' : 'acp');\n const apiOpen = options.apiOpen ?? options.open ?? false;\n const logLevel = options.logLevel ?? platform.getEnv('CSS_LOGGING_LEVEL') ?? 'warn';\n\n platform.ensureDir(runtimeRoot);\n platform.ensureDir(rootFilePath);\n\n const socketsRoot = platform.joinPath(runtimeRoot, 'sockets');\n if (transport === 'socket') {\n platform.ensureDir(socketsRoot);\n }\n const ports: XpodRuntimePorts = transport === 'port'\n ? await host.allocatePorts({\n gatewayPort: options.gatewayPort,\n cssPort: options.cssPort,\n apiPort: options.apiPort,\n basePort: 5600,\n })\n : {};\n const sockets: XpodRuntimeSockets = {};\n\n if (transport === 'socket') {\n sockets.gateway = platform.resolvePath(options.gatewaySocketPath ?? platform.joinPath(socketsRoot, 'gateway.sock'));\n sockets.css = platform.resolvePath(options.cssSocketPath ?? platform.joinPath(socketsRoot, 'css.sock'));\n sockets.api = platform.resolvePath(options.apiSocketPath ?? platform.joinPath(socketsRoot, 'api.sock'));\n }\n\n const baseUrl = ensureTrailingSlash(\n options.baseUrl ?? (transport === 'socket'\n ? 'http://localhost'\n : `http://${bindHost}:${ports.gateway}`),\n );\n\n return {\n id,\n host,\n mode,\n transport,\n bindHost,\n runtimeRoot,\n rootFilePath,\n sparqlEndpoint,\n rdfIndexPath,\n identityDbUrl,\n usageDbUrl,\n cssAuthMode,\n apiOpen,\n logLevel,\n baseUrl,\n envFilePath: options.envFile ? platform.resolvePath(options.envFile) : undefined,\n ports,\n sockets,\n };\n}\n\nexport function buildRuntimeEnv(\n state: RuntimeBootstrapState,\n options: XpodRuntimeOptions,\n envFromFile: Record<string, string | undefined> = {},\n): Record<string, string | undefined> {\n const mergedEnv = {\n ...envFromFile,\n ...options.env,\n };\n const externalOidcIssuer = resolveExternalOidcIssuer(mergedEnv);\n\n return {\n ...mergedEnv,\n XPOD_ENV_PATH: state.envFilePath,\n XPOD_EDITION: state.mode,\n CSS_BASE_URL: state.baseUrl,\n CSS_TOKEN_ENDPOINT: externalOidcIssuer\n ? oidcTokenEndpoint(externalOidcIssuer)\n : `${state.baseUrl}.oidc/token`,\n CSS_ROOT_FILE_PATH: state.rootFilePath,\n CSS_SPARQL_ENDPOINT: state.sparqlEndpoint,\n SPARQL_ENDPOINT: state.sparqlEndpoint,\n CSS_IDENTITY_DB_URL: state.identityDbUrl,\n DATABASE_URL: state.identityDbUrl,\n CSS_PORT: state.ports.css !== undefined ? String(state.ports.css) : undefined,\n API_PORT: state.ports.api !== undefined ? String(state.ports.api) : undefined,\n API_HOST: state.bindHost,\n API_SOCKET_PATH: state.sockets.api,\n XPOD_MAIN_PORT: state.ports.gateway !== undefined ? String(state.ports.gateway) : undefined,\n CORS_ORIGINS: new URL(state.baseUrl).origin,\n CSS_LOGGING_LEVEL: state.logLevel,\n };\n}\n\nexport function buildRuntimeShorthand(\n runtimeEnv: Record<string, string | undefined>,\n options: XpodRuntimeOptions,\n state: RuntimeBootstrapState,\n baseEnv: Record<string, string | undefined> = nodeRuntimePlatform.baseEnv,\n): Record<string, string | number | boolean> {\n const envValue = (key: string): string | undefined => runtimeEnv[key] ?? baseEnv[key];\n const externalOidcIssuer = resolveExternalOidcIssuer({\n oidcIssuer: envValue('oidcIssuer'),\n });\n\n return {\n ...withDefinedEntries([\n ['baseStorageDomain', envValue('CSS_BASE_STORAGE_DOMAIN')],\n ['minioAccessKey', envValue('CSS_MINIO_ACCESS_KEY')],\n ['minioSecretKey', envValue('CSS_MINIO_SECRET_KEY')],\n ['minioEndpoint', envValue('CSS_MINIO_ENDPOINT')],\n ['minioBucketName', envValue('CSS_MINIO_BUCKET_NAME')],\n ['redisClient', envValue('CSS_REDIS_CLIENT')],\n ['redisUsername', envValue('CSS_REDIS_USERNAME')],\n ['redisPassword', envValue('CSS_REDIS_PASSWORD')],\n ['emailConfigHost', envValue('CSS_EMAIL_CONFIG_HOST') ?? ''],\n ['emailConfigPort', envValue('CSS_EMAIL_CONFIG_PORT') ?? '587'],\n ['emailConfigAuthUser', envValue('CSS_EMAIL_CONFIG_AUTH_USER') ?? ''],\n ['emailConfigAuthPass', envValue('CSS_EMAIL_CONFIG_AUTH_PASS') ?? ''],\n ['oidcIssuer', externalOidcIssuer],\n ['allowedHosts', envValue('CSS_ALLOWED_HOSTS')],\n ['nodeId', envValue('XPOD_NODE_ID')],\n ['nodeToken', envValue('XPOD_NODE_TOKEN')],\n ['serviceToken', envValue('XPOD_SERVICE_TOKEN')],\n ]),\n baseUrl: state.baseUrl,\n rootFilePath: state.rootFilePath,\n sparqlEndpoint: state.sparqlEndpoint,\n rdfIndexPath: state.rdfIndexPath,\n identityDbUrl: state.identityDbUrl,\n usageDbUrl: state.usageDbUrl,\n logLevel: state.logLevel,\n authMode: state.cssAuthMode,\n edition: state.mode === 'cloud' ? 'server' : 'local',\n edgeNodesEnabled: options.edgeNodesEnabled ?? false,\n centerRegistrationEnabled: options.centerRegistrationEnabled ?? false,\n ...(options.shorthand ?? {}),\n };\n}\n\nexport function createCssRuntimeConfig(\n state: RuntimeBootstrapState,\n open: boolean,\n platform: Pick<RuntimePlatform, 'dirname' | 'ensureDir' | 'joinPath' | 'readTextFile' | 'writeTextFile'> = nodeRuntimePlatform,\n): string {\n const configPath = normalizeWindowsAbsolutePath(platform.joinPath(PACKAGE_ROOT, `config/${state.mode}.json`));\n if (!open) {\n return configPath;\n }\n\n const runtimeRoot = normalizeWindowsAbsolutePath(state.runtimeRoot);\n const runtimeConfigPath = arePathsOnDifferentWindowsDrives(runtimeRoot, configPath)\n ? (() => {\n const runtimeConfigDir = normalizeWindowsAbsolutePath(platform.joinPath(\n platform.dirname(configPath),\n '..',\n '.xpod-runtime',\n state.id,\n ));\n platform.ensureDir(runtimeConfigDir);\n return normalizeWindowsAbsolutePath(platform.joinPath(runtimeConfigDir, 'css-runtime.config.json'));\n })()\n : normalizeWindowsAbsolutePath(platform.joinPath(runtimeRoot, 'css-runtime.config.json'));\n const openConfigPath = normalizeWindowsAbsolutePath(platform.joinPath(PACKAGE_ROOT, 'config/runtime-open.json'));\n const runtimeConfigDir = platform.dirname(runtimeConfigPath);\n const runtimeConfigImportPath = rewriteConfigForFileUrlImportsIfNeeded(\n configPath,\n platform.joinPath(runtimeConfigDir, 'config'),\n platform,\n );\n platform.writeTextFile(runtimeConfigPath, JSON.stringify({\n '@context': [\n 'https://linkedsoftwaredependencies.org/bundles/npm/@solid/community-server/^8.0.0/components/context.jsonld',\n 'https://linkedsoftwaredependencies.org/bundles/npm/asynchronous-handlers/^1.0.0/components/context.jsonld',\n ],\n import: [\n toConfigImportSpecifier(runtimeConfigPath, runtimeConfigImportPath),\n toConfigImportSpecifier(runtimeConfigPath, openConfigPath),\n ],\n }, null, 2));\n\n return runtimeConfigPath;\n}\n\nfunction rewriteConfigForFileUrlImportsIfNeeded(\n configPath: string,\n outputDir: string,\n platform: Pick<RuntimePlatform, 'dirname' | 'ensureDir' | 'joinPath' | 'readTextFile' | 'writeTextFile'>,\n rewritten = new Map<string, string>(),\n): string {\n const normalizedConfigPath = normalizeWindowsAbsolutePath(configPath);\n if (isWindowsAbsolutePath(normalizedConfigPath) || !pathNeedsEscapedFileUrl(normalizedConfigPath)) {\n return normalizedConfigPath;\n }\n\n const existing = rewritten.get(normalizedConfigPath);\n if (existing) {\n return existing;\n }\n\n platform.ensureDir(outputDir);\n const outputPath = normalizeWindowsAbsolutePath(platform.joinPath(outputDir, path.posix.basename(normalizedConfigPath)));\n rewritten.set(normalizedConfigPath, outputPath);\n\n const parsed = JSON.parse(platform.readTextFile(normalizedConfigPath)) as Record<string, unknown>;\n parsed.import = rewriteConfigImports(\n normalizedConfigPath,\n parsed.import,\n outputDir,\n platform,\n rewritten,\n );\n platform.writeTextFile(outputPath, `${JSON.stringify(parsed, null, 2)}\\n`);\n return outputPath;\n}\n\nfunction rewriteConfigImports(\n sourceConfigPath: string,\n imports: unknown,\n outputDir: string,\n platform: Pick<RuntimePlatform, 'dirname' | 'ensureDir' | 'joinPath' | 'readTextFile' | 'writeTextFile'>,\n rewritten: Map<string, string>,\n): unknown {\n if (typeof imports === 'string') {\n return rewriteConfigImport(sourceConfigPath, imports, outputDir, platform, rewritten);\n }\n\n if (Array.isArray(imports)) {\n return imports.map((value) => typeof value === 'string'\n ? rewriteConfigImport(sourceConfigPath, value, outputDir, platform, rewritten)\n : value);\n }\n\n return imports;\n}\n\nfunction rewriteConfigImport(\n sourceConfigPath: string,\n importValue: string,\n outputDir: string,\n platform: Pick<RuntimePlatform, 'dirname' | 'ensureDir' | 'joinPath' | 'readTextFile' | 'writeTextFile'>,\n rewritten: Map<string, string>,\n): string {\n if (!importValue.startsWith('./') && !importValue.startsWith('../')) {\n return importValue;\n }\n\n const targetPath = normalizeWindowsAbsolutePath(\n path.posix.resolve(platform.dirname(sourceConfigPath), importValue),\n );\n const rewrittenTargetPath = rewriteConfigForFileUrlImportsIfNeeded(targetPath, outputDir, platform, rewritten);\n return pathToFileURL(rewrittenTargetPath).href;\n}\n\nexport function initRuntimeLogger(\n level: string,\n platform: Pick<RuntimePlatform, 'cwd' | 'joinPath'> = nodeRuntimePlatform,\n): void {\n const loggerFactory = new ConfigurableLoggerFactory(level, {\n fileName: platform.joinPath(platform.cwd(), 'logs/xpod-%DATE%.log'),\n showLocation: true,\n });\n setGlobalLoggerFactory(loggerFactory);\n}\n"]}