/** * @module galaxy-helpers * * Helper functions for Universal GalaxyIbGib: genesis, ib parsing/validation, * policy resolution, and archetype helpers. */ import { getUUID, extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs'; import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs'; import { getIbGibFromSpace, getTjpAddr, resolveLatestIbGibInSpace, } from '../../common/other/ibgib-helper.mjs'; import { MetaspaceService } from '../../witness/space/metaspace/metaspace-types.mjs'; import { IbGibSpaceAny } from '../../witness/space/space-base-v1.mjs'; import { putInSpace } from '../../witness/space/space-helper.mjs'; import { getSpaceIdFromIb } from '../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace-helper.mjs'; import { GALAXY_ATOM, GALAXY_REL8N_NAME, GALAXY_NAME_REGEXP, } from './galaxy-constants.mjs'; import { GalaxyIbGib_V1, GalaxyData_V1, GalaxyRel8ns_V1, GalaxyIb_V1, GalaxyPolicy, GalaxyTopology, GalaxyStorageMode, } from './galaxy-types.mjs'; import { getGalaxyPresetConfig } from './galaxy-configs.mjs'; const lcFile = `[galaxy-helpers]`; const logalot = GLOBAL_LOG_A_LOT; /** * Validates whether a given string is a valid galaxy name. * Enforces URL-path friendly naming without whitespace or tildes (~). */ export function validateGalaxyName(name: string): boolean { return Boolean(name && GALAXY_NAME_REGEXP.test(name)); } /** * Builds canonical galaxy ib string: `galaxy `. */ export function getGalaxyIb({ galaxyName, topology = 'branching', storageMode = 'text', concreteClassname = 'GalaxyIbGib_V1', }: { galaxyName: string; topology?: GalaxyTopology; storageMode?: GalaxyStorageMode; concreteClassname?: string; }): string { if (!validateGalaxyName(galaxyName)) { throw new Error(`Invalid galaxy name: "${galaxyName}". Must match ${GALAXY_NAME_REGEXP} (no whitespace or tildes). (E: 7a8b9c0d1e2f34567890123456789abc)`); } return `${GALAXY_ATOM} ${topology} ${storageMode} ${concreteClassname} ${galaxyName}`; } /** * Parses a galaxy ib string into its constituent parts. */ export async function parseGalaxyIb({ ib }: { ib: string }): Promise { const parts = (ib || '').split(' '); if (parts.length < 5 || parts[0] !== GALAXY_ATOM) { throw new Error(`Invalid galaxy ib: "${ib}". Expected "${GALAXY_ATOM} ". (E: 8b9c0d1e2f3a4567890123456789abcd)`); } const [atom, topology, storageMode, concreteClassname, ...rest] = parts; const galaxyName = rest.join(' '); if (!validateGalaxyName(galaxyName)) { throw new Error(`Invalid galaxy name inside ib: "${galaxyName}". (E: 9c0d1e2f3a4b567890123456789abcde)`); } return { atom: GALAXY_ATOM, topology: topology as GalaxyTopology, storageMode: storageMode as GalaxyStorageMode, concreteClassname, galaxyName, }; } /** * Validates whether an ib string corresponds to a valid galaxy ib. */ export async function validateGalaxyIb({ ib }: { ib: string }): Promise { try { await parseGalaxyIb({ ib }); return true; } catch { return false; } } /** * Type guard for Universal GalaxyIbGib_V1. */ export function isGalaxy(ibGib?: IbGib_V1 | null): ibGib is GalaxyIbGib_V1 { if (!ibGib?.ib || !ibGib.data) { return false; } const parts = ibGib.ib.split(' '); return parts[0] === GALAXY_ATOM && typeof (ibGib.data as any).galaxyName === 'string' && typeof (ibGib.data as any).discriminator === 'string' && Boolean((ibGib.data as any).policy); } /** * Returns true if the galaxy has a branching topology (multiple branch spaces / worktrees). */ export function isBranchingGalaxy(galaxy: GalaxyIbGib_V1): boolean { return galaxy?.data?.policy?.topology === 'branching'; } /** * Returns true if the galaxy has a linear topology (single CAS space / append-only). */ export function isLinearGalaxy(galaxy: GalaxyIbGib_V1): boolean { return galaxy?.data?.policy?.topology === 'linear'; } export interface CreateGalaxyIbGibOpts { /** * Unique name for this galaxy within its containing cosmos (e.g. 'code-1', 'notes-1'). */ galaxyName: string; /** * Archetype discriminator (standard preset like 'code', 'notes', or downstream custom string). */ discriminator: string; /** * Explicit policy override. If omitted, resolved from preset config or fallback defaults. */ policy?: GalaxyPolicy; description?: string; icon?: string; label?: string; space: IbGibSpaceAny; metaspace?: MetaspaceService; customData?: Record; } /** * Creates a new genesis Universal GalaxyIbGib in the given space, optionally relating it * to the metaspace special anchor. */ export async function createGalaxyIbGib({ galaxyName, discriminator, policy: explicitPolicy, description: explicitDescription, icon: explicitIcon, label: explicitLabel, space, metaspace, customData, }: CreateGalaxyIbGibOpts): Promise { const lc = `${lcFile}[${createGalaxyIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting for "${galaxyName}" (discriminator: ${discriminator})...`); } if (!validateGalaxyName(galaxyName)) { throw new Error(`Invalid galaxy name: "${galaxyName}". Must match ${GALAXY_NAME_REGEXP}. (E: 0d1e2f3a4b5c67890123456789abcdef)`); } const presetConfig = getGalaxyPresetConfig(discriminator); // Resolve policy: explicit -> preset -> default linear/extrinsic const policy: GalaxyPolicy = explicitPolicy ?? presetConfig?.policy ?? { topology: 'linear', role: 'extrinsic', storageMode: 'text', }; const icon = explicitIcon ?? presetConfig?.icon; const label = explicitLabel ?? presetConfig?.label ?? galaxyName; const description = explicitDescription ?? presetConfig?.description; const spaceId = space?.ib ? getSpaceIdFromIb(space.ib) : undefined; const data: GalaxyData_V1 = { galaxyName, discriminator, policy, uuid: await getUUID(), classname: 'GalaxyIbGib_V1', ...(description ? { description } : {}), ...(icon ? { icon } : {}), ...(label ? { label } : {}), ...(spaceId ? { mySpaceId: spaceId } : {}), ...(policy.topology === 'branching' ? { '$@branch': [] } : { '$@topic': [] }), ...(customData ?? {}), }; const res = await Factory_V1.firstGen({ parentIbGib: ROOT, ib: getGalaxyIb({ galaxyName, topology: policy.topology, storageMode: policy.storageMode ?? 'text', concreteClassname: 'GalaxyIbGib_V1', }), data, tjp: { timestamp: true }, dna: true, nCounter: true, }); const galaxyIbGib = res.newIbGib as GalaxyIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform: res, space }); await metaspace.registerNewIbGib({ ibGib: galaxyIbGib, space }); // Ensure special anchor exists in space await metaspace.getSpecialIbGib({ type: GALAXY_ATOM, initialize: true, space, }); // Relate galaxy timeline to special ibgib anchor await metaspace.rel8ToSpecialIbGib({ type: GALAXY_ATOM, rel8nName: GALAXY_REL8N_NAME, ibGibsToRel8: [galaxyIbGib], space, linked: true, }); } else { await putInSpace({ ibGib: galaxyIbGib, space }); } if (logalot) { console.log(`${lc} Created GalaxyIbGib: ${galaxyIbGib.ib} (addr: ${getIbGibAddr({ ibGib: galaxyIbGib })})`); } return galaxyIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 1e2f3a4b5c6d7890123456789abcdef0)`); throw error; } } /** * Retrieves authoritative GalaxyIbGib_V1 from space by address or via * special ibgib anchor, and resolves its latest frame in space. */ export async function getGalaxyIbGib< TData extends GalaxyData_V1 = GalaxyData_V1, TRel8ns extends GalaxyRel8ns_V1 = GalaxyRel8ns_V1 >({ space, metaspace, galaxyAddr, }: { /** * space for galaxy. */ space: IbGibSpaceAny; /** * ref to metaspace for driving getting at the galaxy via the "special" ibgib anchor. * * @throws if both this and {@link galaxyAddr} are falsy * * @see {@link MetaspaceService.getSpecialRel8dIbGibs} */ metaspace?: MetaspaceService; /** * if provided, this will drive getting the galaxy. if not, will get the * "special" anchor ibgib via {@link metaspace} * * @throws if both this and {@link metaspace} are falsy */ galaxyAddr?: string; }): Promise | undefined> { const lc = `${lcFile}[${getGalaxyIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } let baseGalaxyIbGib: GalaxyIbGib_V1 | undefined; if (galaxyAddr) { baseGalaxyIbGib = await getIbGibFromSpace>({ addr: galaxyAddr, space, }); } else if (metaspace) { const specialIbGibs = await metaspace.getSpecialRel8dIbGibs>({ type: GALAXY_ATOM, rel8nName: GALAXY_REL8N_NAME, space, }); baseGalaxyIbGib = specialIbGibs?.at(0); } else { throw new Error(`(UNEXPECTED) both galaxyAddr and metaspace falsy? one of these is required. (E: 2c7b508f635442beae6c83ef87349b1a)`); } if (!baseGalaxyIbGib) { if (galaxyAddr) { if (logalot) { console.log(`${lc} Could not get galaxyAddr (${galaxyAddr}) from space (${space.ib}). Not initialized?`); } } else { if (logalot) { console.log(`${lc} Could not get galaxyIbGib via metaspace special anchor type ${GALAXY_ATOM} and rel8nName ${GALAXY_REL8N_NAME}. Not initialized?`); } } return undefined; /* <<<< returns early */ } const baseGalaxyAddr = getIbGibAddr({ ibGib: baseGalaxyIbGib }); const galaxyTjpAddr = getTjpAddr({ ibGib: baseGalaxyIbGib }); if (logalot) { console.log(`${lc} baseGalaxyAddr: ${baseGalaxyAddr}, tjpAddr: ${galaxyTjpAddr}`); } // Resolve latest tip of the galaxy timeline in space using pure helper const latestGalaxyIbGib = await resolveLatestIbGibInSpace>({ ibGib: baseGalaxyIbGib, space, }); if (!latestGalaxyIbGib) { throw new Error(`(UNEXPECTED) baseGalaxyIbGib (${baseGalaxyAddr}) exists but we couldn't get the latest galaxy ibGib? (E: a1b2c3d4e5f647890123456789abcdef)`); } if (logalot) { console.log(`${lc} foundLatest addr: ${getIbGibAddr({ ibGib: latestGalaxyIbGib })}, n: ${latestGalaxyIbGib.data?.n}`); } return latestGalaxyIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }