/** * @module b2tfs-3way-graft-strategy * * ============================================================================ * ⚠️ CRITICAL GRAFT STRATEGY GUIDANCE WARNING ⚠️ * BEFORE MAKING ANY CHANGES TO THIS FILE, YOU MUST CONSULT AND CAREFULLY READ: * libs/core-gib/src/sync/GRAFT_STRATEGY_GUIDANCE.md * * Graft strategies must strictly fulfill the `GraftTimelinesResult` contract, * ensure timeline `n` monotonicity (using Math.max over base/orphan branch frames), * and include ALL newly referenced ancillary dependency nodes (comments, binary * stones, DNAs) in `ancillaryIbGibsCreated` so that the destination branch * space is completely self-contained. * ============================================================================ * * 3-way text line diff graft strategy for B2tFS file item timelines. * Reconciles diverging file content via 3-way line diff (LCA, Base, Orphan) * and inserts Git conflict markers when line edits collide. * * Non-text binaries and non-file items return early / false in `canGraft` and * fall through to `DefaultDnaReplayGraftStrategy`. * Folder hierarchies are re-synchronized post-merge via `reifyB2tFSHierarchy`. */ import { extractErrorMsg, hash } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { getGib, isDna } from '@ibgib/ts-gib/dist/V1/transforms/transform-helper.mjs'; import { rel8 } from '@ibgib/ts-gib/dist/V1/transforms/rel8.mjs'; import { GraftMergeStrategyBase_V1 } from '../../../sync/graft-info/graft-merge-strategy-base-v1.mjs'; import { GraftContext, GraftStrategy, GraftTimelinesResult } from '../../../sync/graft-info/graft-info-types.mjs'; import { FlatIbGibGraph } from '../../../common/other/graph-types.mjs'; import { getFromSpace, persistTransformResult, registerNewIbGib, putInSpace } from '../../../witness/space/space-helper.mjs'; import { getBinIb, getIbGibsFromCache_fallbackToSpaces, splitPerTjpAndOrDna, getTimelinesGroupedByTjp } from '../../../common/other/ibgib-helper.mjs'; import { getDependencyGraph } from '../../../common/other/graph-helper.mjs'; import { createGraftInfo } from '../../../sync/graft-info/graft-info-helpers.mjs'; import { GRAFT_INFO_REL8N_NAME } from '../../../sync/graft-info/graft-info-constants.mjs'; import { putInSpace_dnasThenNonDnas } from '../../../sync/sync-helpers.mjs'; import { BinIbGib_V1 } from '../../../common/bin/bin-types.mjs'; import { SyncConflictStrategy } from '../../../sync/sync-constants.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { isBinaryBuffer, decodeToLines, computeLineLcsDiff } from '../diff/line-diff-helpers.mjs'; import { B2tFSItemIbGib_V1, BINARY_REL8N_NAME, B2tFSType } from '../item/item-types.mjs'; import { evolveB2tFSItemIbGib, isB2tFSItemIbGib } from '../item/item-helpers.mjs'; import { B2tFS3WayAddlGraftDetails } from './b2tfs-3way-graft-types.mjs'; const lcFile = `[b2tfs-3way-graft-strategy]`; const logalot = GLOBAL_LOG_A_LOT; const mergeDiag = `[MERGE DIAGNOSTIC]`; /** * 3-way text line diff merge result. */ export interface Text3WayMergeResult { mergedText: string; hasConflict: boolean; } /** * Performs 3-way line diff merging across LCA, Base, and Orphan text lines. * Inserts Git conflict markers (`<<<<<<< HEAD`, `=======`, `>>>>>>>`) when overlapping * line changes conflict. */ export function perform3WayTextLineMerge({ textLCA, textBase, textOrphan, }: { textLCA: string; textBase: string; textOrphan: string; }): Text3WayMergeResult { if (textBase === textOrphan) { return { mergedText: textBase, hasConflict: false }; } if (textBase === textLCA) { return { mergedText: textOrphan, hasConflict: false }; } if (textOrphan === textLCA) { return { mergedText: textBase, hasConflict: false }; } const linesLCA = textLCA.split(/\r?\n/); const linesBase = textBase.split(/\r?\n/); const linesOrphan = textOrphan.split(/\r?\n/); const chunksBase = computeLineLcsDiff(linesLCA, linesBase); const chunksOrphan = computeLineLcsDiff(linesLCA, linesOrphan); if (chunksBase.length === 0) { return { mergedText: textOrphan, hasConflict: false }; } if (chunksOrphan.length === 0) { return { mergedText: textBase, hasConflict: false }; } let hasConflict = false; const outputLines: string[] = []; let lcaIdx = 0; let baseChunkIdx = 0; let orphanChunkIdx = 0; while (lcaIdx < linesLCA.length || baseChunkIdx < chunksBase.length || orphanChunkIdx < chunksOrphan.length) { const nextBaseChunk = chunksBase[baseChunkIdx]; const nextOrphanChunk = chunksOrphan[orphanChunkIdx]; const baseAtLca = nextBaseChunk && nextBaseChunk.old_i === lcaIdx; const orphanAtLca = nextOrphanChunk && nextOrphanChunk.old_i === lcaIdx; if (baseAtLca && orphanAtLca) { const bLines = nextBaseChunk.newLines; const oLines = nextOrphanChunk.newLines; const bOldLen = nextBaseChunk.oldLines.length; const oOldLen = nextOrphanChunk.oldLines.length; if (bLines.join('\n') === oLines.join('\n') && bOldLen === oOldLen) { outputLines.push(...bLines); } else { hasConflict = true; outputLines.push('<<<<<<< HEAD'); outputLines.push(...bLines); outputLines.push('======='); outputLines.push(...oLines); outputLines.push('>>>>>>>'); } const consumedLca = Math.max(bOldLen, oOldLen, 1); lcaIdx += consumedLca; baseChunkIdx++; orphanChunkIdx++; } else if (baseAtLca) { outputLines.push(...nextBaseChunk.newLines); const consumedLca = Math.max(nextBaseChunk.oldLines.length, 1); lcaIdx += consumedLca; baseChunkIdx++; } else if (orphanAtLca) { outputLines.push(...nextOrphanChunk.newLines); const consumedLca = Math.max(nextOrphanChunk.oldLines.length, 1); lcaIdx += consumedLca; orphanChunkIdx++; } else { if (lcaIdx < linesLCA.length) { outputLines.push(linesLCA[lcaIdx]); lcaIdx++; } else { if (nextBaseChunk && baseChunkIdx < chunksBase.length) { outputLines.push(...nextBaseChunk.newLines); baseChunkIdx++; } if (nextOrphanChunk && orphanChunkIdx < chunksOrphan.length) { outputLines.push(...nextOrphanChunk.newLines); orphanChunkIdx++; } } } } return { mergedText: outputLines.join('\n'), hasConflict, }; } /** * 3-way text line diff graft strategy for B2tFS file item timelines. * * ⚠️ **IMPORTANT**: Before making ANY changes to this class or its methods, consult: * `libs/core-gib/src/sync/GRAFT_STRATEGY_GUIDANCE.md`. */ export class B2tFS3WayGraftStrategy extends GraftMergeStrategyBase_V1 implements GraftStrategy { readonly strategyId: string = 'B2tFS3WayGraftStrategy'; private lc = '[B2tFS3WayGraftStrategy]'; /** * Returns true only if the graft context has two tips that are text-based file b2tfs item ibgibs. * * @param context info about the divergent timelines {@link GraftContext} * @returns true if it's a text file item ibgib, else false */ async canGraft(context: GraftContext): Promise { const lc = `${this.lc}[${this.canGraft.name}]`; try { const { conflictStrategy, timelineAddrsA, timelineAddrsB, ibGibReadCache, space } = context; const hasRelevantStrategy = conflictStrategy === SyncConflictStrategy.optimisticWithLCS || (conflictStrategy as string) === 'b2tfs3WayMerge'; if (!hasRelevantStrategy) { return false; } const tipAddrA = timelineAddrsA.at(-1); const tipAddrB = timelineAddrsB.at(-1); if (!tipAddrA || !tipAddrB) { if (logalot) { console.log(`${lc} we don't have two tip addrs? (I: b20b6de462c35e0e74360cc8d317f126)`); } return false; } const [tipA, tipB] = await getIbGibsFromCache_fallbackToSpaces({ addrs: [tipAddrA, tipAddrB], readCache_graph: ibGibReadCache, space, }); if (!tipA) { throw new Error(`(UNEXPECTED) tipA falsy? (E: 752101026888140f074614e893531826)`); } if (!tipB) { throw new Error(`(UNEXPECTED) tipB falsy? (E: d4d4a876cad8c7869830d33832bfde26)`); } const bothTipsAreB2tFSNodes = isB2tFSItemIbGib(tipA) && isB2tFSItemIbGib(tipB); if (!bothTipsAreB2tFSNodes) { if (isB2tFSItemIbGib(tipA) || isB2tFSItemIbGib(tipB)) { console.error(`${lc}${mergeDiag} (UNEXPECTED)(NOT THROWN) only tipA or tipB but not both are b2tfs items? (E: cacb38796da881268898e9d1af245826)`); } return false; } if (tipA.data.fsType !== tipB.data.fsType) { throw new Error(`(UNEXPECTED) tipA.data.fsType (${tipA.data.fsType}) !== tipB.data.fsType (${tipB.data.fsType})? (E: c01c1885ac738f679813117852c48426)`); } // only do files. folders and other containers fall back to DefaultDnaReplayGraftStrategy. const isFile = tipA.data.fsType === B2tFSType.file; if (!isFile) { return false; } return true; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 463df8afd9a8c42008856f3737b71826)`); return false; } } /** * Executes 3-way line diff text graft across LCA, Base, and Orphan file items. * * ⚠️ **CRITICAL CONTRACT**: Before modifying this method, review: * `libs/core-gib/src/sync/GRAFT_STRATEGY_GUIDANCE.md` * Ensure: * 1. Monotonic `n` counter (`highestDataN = Math.max(...)`) * 2. Full dependency graph inclusion in `ancillaryIbGibsCreated` (comments, bin stones, DNAs) * 3. Self-contained destination branch space */ async graft(context: GraftContext): Promise { const lc = `${lcFile}[${this.strategyId}][${this.graft.name}]`; try { if (logalot) { console.log(`${lc} starting 3-way B2tFS snapshot graft... (I: 88cf3a0e67b3da14bfea241159296e26)`); } const { conflictStrategy, timelineAddrsA, timelineAddrsB, latestCommonFrameAddr, ibGibReadCache, space, graftPreference, } = context; // 1. Fetch branch slices since LCA (timeline A = Sender, timeline B = Receiver) const indexLCA_A = timelineAddrsA.lastIndexOf(latestCommonFrameAddr); const addrsA_sinceLCA = timelineAddrsA.slice(indexLCA_A + 1); const branchA_sender_sinceLCA = await getIbGibsFromCache_fallbackToSpaces({ readCache_graph: ibGibReadCache, addrs: addrsA_sinceLCA, space, }); const tipA_sender = branchA_sender_sinceLCA.at(-1)!; const indexLCA_B = timelineAddrsB.lastIndexOf(latestCommonFrameAddr); const addrsB_sinceLCA = timelineAddrsB.slice(indexLCA_B + 1); const branchB_receiver_sinceLCA = await getIbGibsFromCache_fallbackToSpaces({ readCache_graph: ibGibReadCache, addrs: addrsB_sinceLCA, space, }); const tipB_receiver = branchB_receiver_sinceLCA.at(-1)!; // 2. Base & Orphan resolution via DRY helper const { baseTip, baseBranch, orphanTip, orphanBranch, } = this.resolveBaseAndOrphan({ graftPreference, tipA_sender, branchA_sender_sinceLCA, tipB_receiver, branchB_receiver_sinceLCA, }); const baseTipAddr = getIbGibAddr({ ibGib: baseTip }); const baseBranchAddrs = baseBranch.map(x => getIbGibAddr({ ibGib: x })); const orphanTipAddr = getIbGibAddr({ ibGib: orphanTip }); const orphanBranchAddrs = orphanBranch.map(x => getIbGibAddr({ ibGib: x })); if (logalot) { console.log(`${lc} baseBranchAddrs:\n${baseBranchAddrs.join('\n')} (I: 2cad420d7bc822f798b8a8785f1f8c26)`); console.log(`${lc} orphanBranchAddrs:\n${orphanBranchAddrs.join('\n')} (I: cc86489d6737e2aced42b585cba13526)`); } // 3. Perform 3-way filesystem tree merge across lcaItem, baseItem, orphanItem const lcaNode = await this.fetchIbGib({ addr: latestCommonFrameAddr, space, readCache_graph: ibGibReadCache }); if (!lcaNode) { throw new Error(`(UNEXPECTED) lcaNode falsy? (E: a8b2d80dc4f8ba1448fa280d89dfb626)`); } const lcaItem = await this.resolveRootItemNode({ nodeOrAddr: lcaNode, space, readCache_graph: ibGibReadCache }); if (!lcaItem) { throw new Error(`(UNEXPECTED) lcaItem falsy? (E: 0944f88dde58cbabf82342b814955826)`); } const baseItem = await this.resolveRootItemNode({ nodeOrAddr: baseTip, space, readCache_graph: ibGibReadCache }); if (!baseItem) { throw new Error(`(UNEXPECTED) baseItem falsy? (E: fac3087884cbebc7083e580514002826)`); } const orphanItem = await this.resolveRootItemNode({ nodeOrAddr: orphanTip, space, readCache_graph: ibGibReadCache }); if (!orphanItem) { throw new Error(`(UNEXPECTED) orphanItem falsy? (E: 8e7e383753a8814f283280ee82156826)`); } if (lcaItem.data.fsType !== baseItem.data.fsType) { throw new Error(`(UNEXPECTED) lcaItem.data.fsType !== baseItem.data.fsType? (E: 794608f3e678a399ed670388629a6826)`); } if (lcaItem.data.fsType !== orphanItem.data.fsType) { throw new Error(`(UNEXPECTED) lcaItem.data.fsType !== orphanItem.data.fsType? (E: 2813981c8c422b41f85a02fd8aa88226)`); } const fsType = lcaItem.data.fsType; if (fsType === B2tFSType.folder) { throw new Error(`(UNEXPECTED) fsType === B2tFSType.folder? Folders fall back to DefaultDnaReplayGraftStrategy and reification. (E: b282b8f77b18575378edb902bd80a826)`); } if (fsType !== B2tFSType.file) { throw new Error(`(UNEXPECTED) fsType (${fsType}) is not a file? (E: 272418fe2067ea3e16dac028e86d1a26)`); } const lcaPayload = await this.getFilePayloadBuffer({ fileItem: lcaItem, space, readCache_graph: ibGibReadCache }); const basePayload = await this.getFilePayloadBuffer({ fileItem: baseItem, space, readCache_graph: ibGibReadCache }); const orphanPayload = await this.getFilePayloadBuffer({ fileItem: orphanItem, space, readCache_graph: ibGibReadCache }); const isBaseBin = basePayload ? isBinaryBuffer(basePayload.buffer) : false; const isOrphanBin = orphanPayload ? isBinaryBuffer(orphanPayload.buffer) : false; const isLcaBin = lcaPayload ? isBinaryBuffer(lcaPayload.buffer) : false; if (isBaseBin || isOrphanBin || isLcaBin) { if (logalot) { console.log(`${lc} Non-text binary file detected (${baseItem.data?.name}). Skipping 3-way line diff and falling through. (I: 8ff3a887d3ea1f162317b77feb7ec326)`); } return undefined; } if (!lcaPayload) { throw new Error(`(UNEXPECTED) lcaPayload falsy? (E: 0b82892204482f5538a430b8915b7826)`); } if (!basePayload) { throw new Error(`(UNEXPECTED) basePayload falsy? (E: af1f68a020280b3a5d6ed4a812acd426)`); } if (!orphanPayload) { throw new Error(`(UNEXPECTED) orphanPayload falsy? (E: 6a521b684763862c3a2e0ca315d62826)`); } const textLCA = decodeToLines(lcaPayload.buffer).join('\n'); const textBase = decodeToLines(basePayload.buffer).join('\n'); const textOrphan = decodeToLines(orphanPayload.buffer).join('\n'); if (logalot) { console.log(`${lc}${mergeDiag} file: ${baseItem.data.name}`); console.log(`${lc}${mergeDiag} textLCA:\n${textLCA}`); console.log(`${lc}${mergeDiag} textBase:\n${textBase}`); console.log(`${lc}${mergeDiag} textOrphan:\n${textOrphan}`); } const { mergedText } = perform3WayTextLineMerge({ textLCA, textBase, textOrphan }); if (logalot) { console.log(`${lc}${mergeDiag} mergedText:\n${mergedText}`); } const dataBuffer = Buffer.from(mergedText, 'utf8'); const fileHash = await hash({ s: mergedText }); if (baseItem.data.fileExt !== orphanItem.data.fileExt) { console.warn(`${lc} baseItem.data.fileExt (${baseItem.data.fileExt}) !== orphanItem.data.fileExt (${orphanItem.data.fileExt})? Using baseItem.data.fileExt for merged fileExt (W: a999b54235bb231fa49224842e212326)`); } const fileExt = baseItem.data.fileExt; const binIb = getBinIb({ binHash: fileHash, binExt: fileExt, binEncoding: 'utf8', }); const binIbGib: BinIbGib_V1 = { ib: binIb, data: dataBuffer, }; binIbGib.gib = await getGib({ ibGib: binIbGib, hasTjp: false }); const binAddr = getIbGibAddr({ ibGib: binIbGib }); if (space) { await putInSpace_dnasThenNonDnas({ ibGibs: [binIbGib], space }); await registerNewIbGib({ ibGib: binIbGib, space }); } const fnGetN = (item: B2tFSItemIbGib_V1): number => { if (item.data.n || item.data.n === 0) { return item.data.n!; } else { throw new Error(`(UNEXPECTED) item.data.n not a number? (E: 896ceae089c83ca67817fff826be5826)`); } }; const baseItemDataN = fnGetN(baseItem); const orphanItemDataN = fnGetN(orphanItem); const highestDataN = Math.max(baseItemDataN, orphanItemDataN); const lcaCommentAddrs = lcaItem.rel8ns?.comment || []; const lcaCommentAddrsSet = new Set(lcaCommentAddrs); const mergedCommentAddrsSinceLCA_base = (baseItem.rel8ns?.comment || []).filter(addr => !lcaCommentAddrsSet.has(addr)); const mergedCommentAddrsSinceLCA_orphan = (orphanItem.rel8ns?.comment || []).filter(addr => !lcaCommentAddrsSet.has(addr)); const newCommentAddrs = Array.from(new Set([...mergedCommentAddrsSinceLCA_base, ...mergedCommentAddrsSinceLCA_orphan])); const allMergedCommentAddrs = Array.from(new Set([...lcaCommentAddrs, ...newCommentAddrs])); const commentDepIbGibs: IbGib_V1[] = []; if (newCommentAddrs.length > 0) { const seenCommentDepAddrs = new Set(); for (const cAddr of newCommentAddrs) { const cIb = await this.fetchIbGib({ addr: cAddr, space, readCache_graph: ibGibReadCache }); if (!cIb) { throw new Error(`(UNEXPECTED) Comment ibgib for address '${cAddr}' not found in cache or space (E: eb6798734f68e8f578fe1da3a2698826)`); } // Ensure cIb and any transitive comment dependencies present in ibGibReadCache are seeded into space const seedQueue = [cIb]; const seedVisited = new Set([getIbGibAddr({ ibGib: cIb })]); const seedNodes: IbGib_V1[] = []; while (seedQueue.length > 0) { const node = seedQueue.shift()!; seedNodes.push(node); if (ibGibReadCache && node.rel8ns) { for (const rel8nAddrs of Object.values(node.rel8ns)) { for (const rAddr of (rel8nAddrs || [])) { if (!seedVisited.has(rAddr) && ibGibReadCache[rAddr]) { seedVisited.add(rAddr); seedQueue.push(ibGibReadCache[rAddr]); } } } } } if (space && seedNodes.length > 0) { await putInSpace_dnasThenNonDnas({ ibGibs: seedNodes, space }); } const resolvedCommentAddr = getIbGibAddr({ ibGib: cIb }); if (!seenCommentDepAddrs.has(resolvedCommentAddr)) { seenCommentDepAddrs.add(resolvedCommentAddr); commentDepIbGibs.push(cIb); } const cDepGraph = await getDependencyGraph({ ibGib: cIb, live: false, space, }); for (const depNode of Object.values(cDepGraph)) { const depAddr = getIbGibAddr({ ibGib: depNode }); if (!seenCommentDepAddrs.has(depAddr)) { seenCommentDepAddrs.add(depAddr); commentDepIbGibs.push(depNode); } } } if (space && commentDepIbGibs.length > 0) { await putInSpace_dnasThenNonDnas({ ibGibs: commentDepIbGibs, space }); } const { mapWithTjp_YesDna } = splitPerTjpAndOrDna({ ibGibs: commentDepIbGibs }); // Register latest tips for timeline frames const timelinesByTjp = getTimelinesGroupedByTjp({ ibGibs: Object.values(mapWithTjp_YesDna) }); for (const tjpAddr of Object.keys(timelinesByTjp)) { const timeline = timelinesByTjp[tjpAddr]; const tip = timeline.at(-1); if (tip && space) { await registerNewIbGib({ ibGib: tip, space }); } } } const evolveRes = await evolveB2tFSItemIbGib({ existingItem: baseItem, dataToUpdate: { fileHash, n: highestDataN + 1, }, rel8nsToUpdate: { [BINARY_REL8N_NAME]: [binAddr], ...(allMergedCommentAddrs.length > 0 ? { comment: allMergedCommentAddrs } : {}), }, }); if (!evolveRes.dnas) { throw new Error(`(UNEXPECTED) evolveRes.dnas falsy? (E: e640e892cc76c77f98f3881301035826)`); } if (!evolveRes.newIbGib) { throw new Error(`(UNEXPECTED) evolveRes.newIbGib falsy? (E: 9e488d07772827b66a2aff4801905426)`); } const newItemWithNewBinPayload = evolveRes.newIbGib as B2tFSItemIbGib_V1; const newItemAddr = getIbGibAddr({ ibGib: newItemWithNewBinPayload }); if (logalot) { console.log(`${lc} newItemAddr: ${newItemAddr} (I: d23eef651b88be1248ee29ca179eff26)`); } const newGraftDnaIbGibs: IbGib_V1[] = []; const newGraftedIntermediateIbGibs_ordered: IbGib_V1[] = []; newGraftDnaIbGibs.push(...evolveRes.dnas); if (evolveRes.intermediateIbGibs) { evolveRes.intermediateIbGibs.forEach(x => newGraftedIntermediateIbGibs_ordered.push(x)); } await persistTransformResult({ resTransform: evolveRes, space }); await registerNewIbGib({ ibGib: evolveRes.newIbGib, space }); const b2tfsAddlGraftDetails: B2tFS3WayAddlGraftDetails = { baseTextB2tFSItemAddr: baseTipAddr, baseTextBinAddr: basePayload.binIbGib ? getIbGibAddr({ ibGib: basePayload.binIbGib }) : undefined, orphanTextB2tFSItemAddr: orphanTipAddr, orphanTextBinAddr: orphanPayload.binIbGib ? getIbGibAddr({ ibGib: orphanPayload.binIbGib }) : undefined, }; // 4. Attach GraftInfo frame const graftInfo = await createGraftInfo({ conflictStrategy, details: `Merged orphan tip text with the baseTip as a starting point.`, addlGraftDetails: [b2tfsAddlGraftDetails], latestCommonFrameAddr, baseAddrsSinceLCA: baseBranchAddrs, orphanAddrsSinceLCA: orphanBranchAddrs, dnaAddrsApplied: [], }); // Seed orphan branch frames for this file from ibGibReadCache into space so graftInfo references resolve if (ibGibReadCache && space && orphanBranchAddrs.length > 0) { const orphanQueue = orphanBranchAddrs.filter(addr => !!ibGibReadCache[addr]).map(addr => ibGibReadCache[addr]); const orphanVisited = new Set(orphanQueue.map(node => getIbGibAddr({ ibGib: node }))); const orphanNodes: IbGib_V1[] = []; while (orphanQueue.length > 0) { const node = orphanQueue.shift()!; orphanNodes.push(node); if (node.rel8ns) { for (const rel8nAddrs of Object.values(node.rel8ns)) { for (const rAddr of (rel8nAddrs || [])) { if (!orphanVisited.has(rAddr) && ibGibReadCache[rAddr]) { orphanVisited.add(rAddr); orphanQueue.push(ibGibReadCache[rAddr]); } } } } } if (orphanNodes.length > 0) { await putInSpace_dnasThenNonDnas({ ibGibs: orphanNodes, space }); } } if (space) { await putInSpace_dnasThenNonDnas({ ibGibs: [graftInfo], space }); await registerNewIbGib({ ibGib: graftInfo, space }); } const graftInfoAddr = getIbGibAddr({ ibGib: graftInfo }); const resRel8GraftInfo = await rel8({ src: newItemWithNewBinPayload, rel8nsToAddByAddr: { [GRAFT_INFO_REL8N_NAME]: [graftInfoAddr], }, dna: true, nCounter: true, }); if (!resRel8GraftInfo.dnas) { throw new Error(`(UNEXPECTED) resRel8GraftInfo.dnas falsy? (E: f3f4a83d3a08bd8de84250c389aed826)`); } const finalGraftTip = resRel8GraftInfo.newIbGib; const finalGraftTipAddr = getIbGibAddr({ ibGib: finalGraftTip }); if (logalot) { console.log(`${lc} finalGraftTipAddr: ${finalGraftTipAddr} (I: 583ac81fb0a84827b85c3076ffeeaf26)`); } newGraftedIntermediateIbGibs_ordered.push(newItemWithNewBinPayload); for (const dna of resRel8GraftInfo.dnas) { newGraftDnaIbGibs.push(dna); } await persistTransformResult({ resTransform: resRel8GraftInfo, space }); await registerNewIbGib({ ibGib: finalGraftTip, space }); return { dnasReplayed: [], dnasCreatedInGraft: newGraftDnaIbGibs, intermediateIbGibsCreatedInGraft: newGraftedIntermediateIbGibs_ordered, ancillaryIbGibsCreated: [binIbGib, ...commentDepIbGibs], newGraftTip: finalGraftTip, graftInfoCreated: graftInfo, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 8acdfd6742487fe88836989dbef30826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: daceba1747880a2d1837eec8129d7726)`); } } } private async fetchIbGib({ addr, space, readCache_graph, }: { addr?: string; space: IbGibSpaceAny; readCache_graph?: FlatIbGibGraph; }): Promise { if (!addr) { return undefined; } if (readCache_graph) { if (readCache_graph[addr]) { return readCache_graph[addr]; } const gib = addr.includes('^') ? addr.substring(addr.lastIndexOf('^') + 1) : addr; const matchingKey = Object.keys(readCache_graph).find(k => k === addr || (gib && k.endsWith('^' + gib))); if (matchingKey) { return readCache_graph[matchingKey]; } } try { const res = await getFromSpace({ space, addrs: [addr] }); if (res) { const found = res.ibGibs?.find((x: any) => !!x) || (res.rawResultIbGib as any)?.ibGibs?.find((x: any) => !!x); if (found) { return found; } } } catch { // Suppress fetch error if address not found } return undefined; } private async resolveRootItemNode({ nodeOrAddr, space, readCache_graph, }: { nodeOrAddr: IbGib_V1 | string | undefined; space: IbGibSpaceAny; readCache_graph?: FlatIbGibGraph; }): Promise { if (!nodeOrAddr) { throw new Error(`(UNEXPECTED) nodeOrAddr falsy? (E: 524108327b9caa00586207ea399f7226)`); } let node: IbGib_V1 | undefined; if (typeof nodeOrAddr === 'string') { node = await this.fetchIbGib({ addr: nodeOrAddr, space, readCache_graph }); } else { node = nodeOrAddr; } if (!node) { throw new Error(`(UNEXPECTED) node falsy? couldn't get node? (E: bd7d1c3b4a3881ff882746281869d826)`); } if (isB2tFSItemIbGib(node)) { return node; } else { throw new Error(`(UNEXPECTED) node is not a B2tFSItemIbGib_V1? (E: ddabb281ccb2fb1a181109a82046b826)`); } } private async getFilePayloadBuffer({ fileItem, space, readCache_graph, }: { fileItem?: B2tFSItemIbGib_V1; space: IbGibSpaceAny; readCache_graph?: FlatIbGibGraph; }): Promise<{ buffer: Uint8Array; binIbGib?: IbGib_V1 } | undefined> { if (!fileItem || !fileItem.rel8ns) { return undefined; } const binAddrs = fileItem.rel8ns[BINARY_REL8N_NAME] || []; const latestBinAddr = binAddrs.at(-1); if (!latestBinAddr) { return undefined; } const binIbGib = await this.fetchIbGib({ addr: latestBinAddr, space, readCache_graph }); if (!binIbGib) { throw new Error(`(UNEXPECTED) couldn't fetch binIbGib? latestBinAddr: ${latestBinAddr}. space.ib: ${space.ib} (E: 3d1238b3a348924038a79f88264d8226)`); } if (binIbGib.data === undefined) { return undefined; } let fileData: Uint8Array; const dataObj = binIbGib.data as any; if (dataObj && typeof dataObj === 'object' && dataObj._dataType === 'Uint8Array_Base64' && typeof dataObj.value === 'string') { fileData = Buffer.from(dataObj.value, 'base64'); } else if (typeof dataObj === 'string') { fileData = Buffer.from(dataObj, 'utf8'); } else if (dataObj instanceof Uint8Array || Buffer.isBuffer(dataObj)) { fileData = dataObj as Uint8Array; } else if (typeof dataObj === 'object' && dataObj !== null) { if (typeof dataObj.text === 'string') { fileData = Buffer.from(dataObj.text, 'utf8'); } else if (typeof dataObj.data === 'string') { fileData = Buffer.from(dataObj.data, 'utf8'); } else { const vals = Object.values(dataObj as object); fileData = new Uint8Array(vals as number[]); } } else { fileData = new Uint8Array(0); } return { buffer: fileData, binIbGib }; } }