/** * @module cosmos-helpers * * Helper functions for CosmosIbGib: genesis, ib parsing/validation, * and member galaxy soft-link management. */ 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 { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.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 { isSpaceQualifiedAddr, getIbGibFromSpace } 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 { COSMOS_ATOM, COSMOS_REL8N_NAME, COSMOS_NAME_REGEXP } from './cosmos-constants.mjs'; import { CosmosIbGib_V1, CosmosData_V1, CosmosIb_V1, CosmosGalaxyEntry, PermissionPolicy } from './cosmos-types.mjs'; import { SpaceQualifiedIbGibAddr } from '../../common/other/ibgib-types.mjs'; import { GalaxyIbGib_V1 } from '../galaxy/galaxy-types.mjs'; const lcFile = `[cosmos-helpers]`; const logalot = GLOBAL_LOG_A_LOT; /** * Validates whether a given string is a valid cosmos name. * Enforces URL-safe naming without whitespace. */ export function validateCosmosName(name: string): boolean { return Boolean(name && COSMOS_NAME_REGEXP.test(name)); } /** * Builds canonical cosmos ib string: `cosmos `. */ export function getCosmosIb({ cosmosName }: { cosmosName: string }): string { if (!validateCosmosName(cosmosName)) { throw new Error(`Invalid cosmos name: "${cosmosName}". Must match ${COSMOS_NAME_REGEXP} (no whitespace). (E: a1b2c3d4e5f67890123456789abcdef0)`); } return `${COSMOS_ATOM} ${cosmosName}`; } /** * Parses a cosmos ib string into its constituent parts. */ export async function parseCosmosIb({ ib }: { ib: string }): Promise { const parts = (ib || '').split(' '); if (parts.length < 2 || parts[0] !== COSMOS_ATOM) { throw new Error(`Invalid cosmos ib: "${ib}". Expected "${COSMOS_ATOM} ". (E: b2c3d4e5f6a17890123456789abcdef1)`); } const cosmosName = parts.slice(1).join(' '); if (!validateCosmosName(cosmosName)) { throw new Error(`Invalid cosmos name inside ib: "${cosmosName}". (E: c3d4e5f6a1b27890123456789abcdef2)`); } return { atom: COSMOS_ATOM, cosmosName, }; } /** * Validates whether an ib string corresponds to a valid cosmos ib. */ export async function validateCosmosIb({ ib }: { ib: string }): Promise { try { await parseCosmosIb({ ib }); return true; } catch { return false; } } /** * Type guard for CosmosIbGib_V1. */ export function isCosmos(ibGib?: IbGib_V1 | null): ibGib is CosmosIbGib_V1 { if (!ibGib?.ib || !ibGib.data) { return false; } const parts = ibGib.ib.split(' '); return parts[0] === COSMOS_ATOM && typeof (ibGib.data as any).cosmosName === 'string'; } export interface CreateCosmosIbGibOpts { cosmosName: string; description?: string; ownerKeystoneTjp?: string; space: IbGibSpaceAny; metaspace?: MetaspaceService; } /** * Creates a new genesis CosmosIbGib in the given space, optionally relating it * to the metaspace special anchor. */ export async function createCosmosIbGib({ cosmosName, description, ownerKeystoneTjp, space, metaspace, }: CreateCosmosIbGibOpts): Promise { const lc = `${lcFile}[${createCosmosIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting for "${cosmosName}"...`); } if (!validateCosmosName(cosmosName)) { throw new Error(`Invalid cosmos name: "${cosmosName}". Must match ${COSMOS_NAME_REGEXP} (no whitespace). (E: d4e5f6a1b2c37890123456789abcdef3)`); } const spaceId = space?.ib ? getSpaceIdFromIb(space.ib) : undefined; const data: CosmosData_V1 = { cosmosName, ...(description ? { description } : {}), uuid: await getUUID(), classname: 'CosmosIbGib_V1', '@galaxy': [], galaxies: {}, layers: [], permissions: [], ...(spaceId ? { mySpaceId: spaceId } : {}), }; const genOpts: any = { parentIbGib: ROOT, ib: getCosmosIb({ cosmosName }), data, tjp: { timestamp: true }, dna: true, nCounter: true, }; if (ownerKeystoneTjp) { genOpts.rel8ns = { owner_keystone: [ownerKeystoneTjp] }; } const res = await Factory_V1.firstGen(genOpts); const cosmosIbGib = res.newIbGib as CosmosIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform: res, space }); await metaspace.registerNewIbGib({ ibGib: cosmosIbGib, space }); // Ensure special anchor exists in space await metaspace.getSpecialIbGib({ type: COSMOS_ATOM, initialize: true, space, }); // Relate cosmos timeline to special ibgib anchor await metaspace.rel8ToSpecialIbGib({ type: COSMOS_ATOM, rel8nName: COSMOS_REL8N_NAME, ibGibsToRel8: [cosmosIbGib], space, linked: true, }); } else { await putInSpace({ ibGib: cosmosIbGib, space }); } if (logalot) { console.log(`${lc} Created CosmosIbGib: ${cosmosIbGib.ib} (addr: ${getIbGibAddr({ ibGib: cosmosIbGib })})`); } return cosmosIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: e5f6a1b2c3d47890123456789abcdef4)`); throw error; } } /** * Returns the soft-linked member galaxy addresses from a CosmosIbGib. */ export function getGalaxyAddrsFromCosmos(cosmosIbGib: CosmosIbGib_V1): SpaceQualifiedIbGibAddr[] { return cosmosIbGib?.data?.['@galaxy'] || []; } export interface AddGalaxyToCosmosOpts { cosmosIbGib: CosmosIbGib_V1; sqGalaxyAddr: SpaceQualifiedIbGibAddr; galaxyEntry?: CosmosGalaxyEntry; galaxyIbGib?: GalaxyIbGib_V1; space: IbGibSpaceAny; metaspace?: MetaspaceService; } /** * Adds a member galaxy to a cosmos timeline, registering both its soft-link address * and its metadata entry in the galaxies dictionary for O(1) manifest retrieval. */ export async function addGalaxyToCosmos({ cosmosIbGib, sqGalaxyAddr, galaxyEntry, galaxyIbGib, space, metaspace, }: AddGalaxyToCosmosOpts): Promise { const lc = `${lcFile}[${addGalaxyToCosmos.name}]`; try { if (!isSpaceQualifiedAddr(sqGalaxyAddr)) { throw new Error(`Invalid space-qualified galaxy address: "${sqGalaxyAddr}". (E: f6a1b2c3d4e57890123456789abcdef5)`); } const currentGalaxies = cosmosIbGib.data['@galaxy'] || []; const currentEntries = cosmosIbGib.data.galaxies || {}; const currentLayers = cosmosIbGib.data.layers || []; let entry: CosmosGalaxyEntry | undefined = galaxyEntry; if (!entry && galaxyIbGib?.data) { entry = { galaxyName: galaxyIbGib.data.galaxyName, discriminator: galaxyIbGib.data.discriminator, policy: galaxyIbGib.data.policy, icon: galaxyIbGib.data.icon, label: galaxyIbGib.data.label, sqGalaxyAddr, galaxyAddr: getIbGibAddr({ ibGib: galaxyIbGib }), }; } const isAddrPresent = currentGalaxies.includes(sqGalaxyAddr); const isEntryPresent = entry ? Boolean(currentEntries[entry.galaxyName]) : true; const isLayerPresent = entry ? currentLayers.includes(entry.galaxyName) : true; if (isAddrPresent && isEntryPresent && isLayerPresent) { return cosmosIbGib; } const updatedGalaxies = isAddrPresent ? currentGalaxies : [...currentGalaxies, sqGalaxyAddr]; const updatedEntries = entry ? { ...currentEntries, [entry.galaxyName]: entry } : currentEntries; let updatedLayers = currentLayers; if (entry && !currentLayers.includes(entry.galaxyName)) { const isSubfolder = Boolean(entry.slice?.rootPath && entry.slice.rootPath !== '.' && entry.slice.rootPath !== './'); if (isSubfolder) { // Insert subfolder layer before the first non-virtual root fallback layer (rootPath === '.' or undefined) const firstRootIndex = currentLayers.findIndex(layerName => { if (layerName.startsWith('virtual:')) { return false; } const existingEntry = currentEntries[layerName]; const existingRoot = existingEntry?.slice?.rootPath; return !existingRoot || existingRoot === '.' || existingRoot === './'; }); if (firstRootIndex >= 0) { updatedLayers = [ ...currentLayers.slice(0, firstRootIndex), entry.galaxyName, ...currentLayers.slice(firstRootIndex), ]; } else { updatedLayers = [...currentLayers, entry.galaxyName]; } } else { updatedLayers = [...currentLayers, entry.galaxyName]; } } const resTransform = await mut8({ src: cosmosIbGib, dataToAddOrPatch: { '@galaxy': updatedGalaxies, galaxies: updatedEntries, layers: updatedLayers, }, dna: true, nCounter: true, }); const updatedCosmos = resTransform.newIbGib as CosmosIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform, space }); await metaspace.registerNewIbGib({ ibGib: updatedCosmos, space }); await metaspace.rel8ToSpecialIbGib({ type: COSMOS_ATOM, rel8nName: COSMOS_REL8N_NAME, ibGibsToRel8: [updatedCosmos], space, linked: true, }); } else { await putInSpace({ ibGib: updatedCosmos, space }); } return updatedCosmos; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 1a2b3c4d5e6f7890123456789abcdef6)`); throw error; } } /** * Retrieves the registered galaxy manifest entry for a galaxy name from CosmosData_V1. */ export function getGalaxyInfoFromCosmos( cosmosIbGib: CosmosIbGib_V1, galaxyName: string ): CosmosGalaxyEntry | undefined { return cosmosIbGib?.data?.galaxies?.[galaxyName]; } /** * Returns all registered member galaxy entries from the Cosmos manifest. */ export function getGalaxiesFromCosmos( cosmosIbGib: CosmosIbGib_V1 ): CosmosGalaxyEntry[] { return Object.values(cosmosIbGib?.data?.galaxies || {}); } /** * Retrieves the owner keystone primary TJP address from a CosmosIbGib, if present. */ export function getOwnerKeystoneTjp(cosmosIbGib: CosmosIbGib_V1): string | undefined { return cosmosIbGib?.rel8ns?.owner_keystone?.[0]; } /** * Retrieves the permission policy governing a specific galaxy or branch in the cosmos. * Looks for exact match on galaxyName and/or branchName, returning undefined if no policy is set. */ export function getPermissionPolicy({ cosmosIbGib, galaxyName, branchName, }: { cosmosIbGib: CosmosIbGib_V1; galaxyName?: string; branchName?: string; }): PermissionPolicy | undefined { const policies = cosmosIbGib?.data?.permissions || []; if (policies.length === 0) { return undefined; } return policies.find(p => { if (galaxyName && p.galaxyName && p.galaxyName === galaxyName) { if (branchName && p.branchName) { return p.branchName === branchName; } return true; } if (branchName && p.branchName && p.branchName === branchName) { return true; } return false; }); } /** * Evaluates whether a candidate keystone is authorized to post or commit to a galaxy/branch. */ export function isAuthorizedToPost({ cosmosIbGib, galaxyName, branchName, candidateKeystoneTjp, }: { cosmosIbGib: CosmosIbGib_V1; galaxyName?: string; branchName?: string; candidateKeystoneTjp?: string; }): { isAuthorized: boolean; reason?: string; requiresModeration?: boolean; } { const ownerTjp = getOwnerKeystoneTjp(cosmosIbGib); const isOwner = Boolean(ownerTjp && candidateKeystoneTjp && ownerTjp === candidateKeystoneTjp); // Owner is always authorized to write to their own cosmos if (isOwner) { return { isAuthorized: true }; } const policy = getPermissionPolicy({ cosmosIbGib, galaxyName, branchName }); // If no policy declared, default access is public-open if (!policy) { return { isAuthorized: true }; } switch (policy.access) { case 'public-open': return { isAuthorized: true }; case 'moderated': return { isAuthorized: false, requiresModeration: true, reason: 'Submission requires maintainer review / moderation.', }; case 'allowlist': if (candidateKeystoneTjp && policy.allowedKeystones?.includes(candidateKeystoneTjp)) { return { isAuthorized: true }; } return { isAuthorized: false, reason: 'Keystone is not on the allowed contributors list.', }; case 'admin-only': return { isAuthorized: false, reason: 'Topic / Galaxy is restricted to the cosmos owner.', }; default: return { isAuthorized: true }; } } /** * Sets or updates a PermissionPolicy in the CosmosIbGib's permissions array. */ export async function setPermissionPolicy({ cosmosIbGib, policy, space, metaspace, }: { cosmosIbGib: CosmosIbGib_V1; policy: PermissionPolicy; space: IbGibSpaceAny; metaspace?: MetaspaceService; }): Promise { const lc = `${lcFile}[${setPermissionPolicy.name}]`; try { const currentPolicies = [...(cosmosIbGib.data.permissions || [])]; const existingIdx = currentPolicies.findIndex(p => (policy.galaxyName && p.galaxyName === policy.galaxyName) || (policy.branchName && p.branchName === policy.branchName) ); if (existingIdx >= 0) { currentPolicies[existingIdx] = policy; } else { currentPolicies.push(policy); } const resTransform = await mut8({ src: cosmosIbGib, dataToAddOrPatch: { permissions: currentPolicies, }, dna: true, nCounter: true, }); const updatedCosmos = resTransform.newIbGib as CosmosIbGib_V1; if (metaspace) { await metaspace.persistTransformResult({ resTransform, space }); await metaspace.registerNewIbGib({ ibGib: updatedCosmos, space }); } else { await putInSpace({ ibGib: updatedCosmos, space }); } return updatedCosmos; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Retrieves all CosmosIbGib instances registered under the special cosmos anchor in space. */ export async function getAllCosmoses({ metaspace, space, }: { metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const specialCosmos = await metaspace.getSpecialIbGib({ type: COSMOS_ATOM, space, initialize: false, }); const cosmosAddrs = specialCosmos?.rel8ns?.[COSMOS_REL8N_NAME] || []; const results: CosmosIbGib_V1[] = []; for (const addr of cosmosAddrs) { const latestAddr = await metaspace.getLatestAddr({ addr, space }) || addr; const cosmos = await getIbGibFromSpace({ addr: latestAddr, space }); if (cosmos?.data && isCosmos(cosmos)) { results.push(cosmos); } } return results; } /** * Retrieves a registered CosmosIbGib by its cosmosName from space. */ export async function getCosmosByName({ metaspace, space, cosmosName, }: { metaspace: MetaspaceService; space: IbGibSpaceAny; cosmosName: string; }): Promise { const all = await getAllCosmoses({ metaspace, space }); return all.find(c => c.data.cosmosName === cosmosName); }