All files jsonld2ObjectGraph.ts

100% Statements 99/99
100% Branches 50/50
100% Functions 17/17
100% Lines 78/78

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253  1x       1x   1x     212x                                         51x 35x         51x 42x   51x                     70x 26x         70x 56x                   51x                                     70x       70x 120x 20x       20x 37x 3x         104x 104x 98x 34x 64x 1x           70x 70x 61x   70x     140x 216x 425x   7x     14x 15x 30x                   216x     173x 23x             23x 140x 20x 16x 21x 11x             11x 5x 5x       65x 12x         70x   70x               1x       21x     21x 21x 42x     21x 61x 61x 70x         21x 21x 1x       40x 58x 58x     68x       48x       58x 40x 40x                     29x     11x 20x               20x    
import { JsonLdDocument, NodeObject } from "jsonld";
import {
  ContextParser,
  IJsonLdContextNormalizedRaw,
} from "jsonld-context-parser";
import { v4 } from "uuid";
 
const contextParser = new ContextParser();
 
function isObject(value: unknown): value is NodeObject {
  return typeof value === "object" && !Array.isArray(value) && value !== null;
}
 
interface TripleArcs {
  [subjectId: string]: {
    scopedContexts: IJsonLdContextNormalizedRaw[];
    predicates: {
      [predicateId: string]: string[];
    };
  };
}
 
/**
 * Helper function to set the proper tripleArcs values
 */
function setTripleArcs(
  tripleArcs: TripleArcs,
  subjectId: string,
  predicateId: string,
  objectId: string
) {
  if (!tripleArcs[subjectId]) {
    tripleArcs[subjectId] = {
      scopedContexts: [],
      predicates: {},
    };
  }
  if (!tripleArcs[subjectId].predicates[predicateId]) {
    tripleArcs[subjectId].predicates[predicateId] = [];
  }
  tripleArcs[subjectId].predicates[predicateId].push(objectId);
}
 
/**
 * Helper function to set scopedContext on tripleArcs
 */
function setScopedContext(
  tripleArcs: TripleArcs,
  subjectId: string,
  scopedContext?: IJsonLdContextNormalizedRaw
) {
  if (!tripleArcs[subjectId]) {
    tripleArcs[subjectId] = {
      scopedContexts: [],
      predicates: {},
    };
  }
  if (scopedContext) {
    tripleArcs[subjectId].scopedContexts.push(scopedContext);
  }
}
 
/**
 * Combines multiple contexts together
 */
async function combineContexts(
  contexts: IJsonLdContextNormalizedRaw[]
): Promise<IJsonLdContextNormalizedRaw> {
  return (await contextParser.parse(contexts)).getContextRaw();
}
 
/**
 * Recursively traverses an object to fill out the idMap and tripleArcs
 * @param object The object to traverse
 * @param idMap A map between the object Id and a collection of objects representing it
 * @param tripleArcs A collection of all the arcs between objects
 * @param parentIdPredicates The predicates that are mapped to @ids as defined by the context
 * @return the id of the given Node
 */
async function traverseNodesForIdsAndLeafs(
  object: NodeObject,
  idMap: Record<string, NodeObject[]>,
  tripleArcs: TripleArcs,
  parentScopedContext?: IJsonLdContextNormalizedRaw,
  // All predicates that are made of Ids
  parentIdPredicates?: Set<string>
): Promise<string> {
  let scopedContext: IJsonLdContextNormalizedRaw | undefined =
    parentScopedContext;
  // Get the current idPredicates. If this object does
  // have a context, then recalculate them.
  const idPredicates: Set<string> = parentIdPredicates || new Set<string>();
  if (object["@context"]) {
    scopedContext =
      // The typings for these two libraries disagree, but they are correct
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      (await contextParser.parse(object["@context"])).getContextRaw();
    if (parentScopedContext) {
      scopedContext = await combineContexts([
        parentScopedContext,
        scopedContext,
      ]);
    }
    Object.entries(scopedContext).forEach(([key, value]) => {
      if (key.charAt(0) === "@") return;
      if (isObject(value) && value["@type"] && value["@type"] === "@id") {
        idPredicates.add(key);
      } else if (idPredicates.has(key)) {
        idPredicates.delete(key);
      }
    });
  }
 
  // Record this node's Id
  const objectId = object["@id"] || v4();
  if (!idMap[objectId]) {
    idMap[objectId] = [];
  }
  idMap[objectId].push(object);
 
  // Traverse the keys of this Object
  await Promise.all(
    Object.entries(object).map(async ([key, value]) => {
      if (key === "@graph") {
        // TODO: handle the case the a graph is a string
        const graph: NodeObject[] = (
          Array.isArray(value) ? value : [value]
        ) as NodeObject[];
        await Promise.all(
          graph.map(async (graphValue: NodeObject) => {
            await traverseNodesForIdsAndLeafs(
              graphValue,
              idMap,
              tripleArcs,
              scopedContext,
              idPredicates
            );
          })
        );
      }
      if (key.charAt(0) === "@") return;
 
      // Save object keys to triplearc
      if (isObject(value)) {
        const valueId = await traverseNodesForIdsAndLeafs(
          value,
          idMap,
          tripleArcs,
          scopedContext,
          idPredicates
        );
        setTripleArcs(tripleArcs, objectId, key, valueId);
      } else if (Array.isArray(value)) {
        await Promise.all(
          value.map(async (arrValue) => {
            if (isObject(arrValue)) {
              const valueId = await traverseNodesForIdsAndLeafs(
                arrValue as NodeObject,
                idMap,
                tripleArcs,
                scopedContext,
                idPredicates
              );
              setTripleArcs(tripleArcs, objectId, key, valueId);
            } else if (typeof arrValue === "string" && idPredicates.has(key)) {
              setTripleArcs(tripleArcs, objectId, key, arrValue as string);
            }
          })
        );
      } else if (typeof value === "string" && idPredicates.has(key)) {
        setTripleArcs(tripleArcs, objectId, key, value);
      }
    })
  );
 
  setScopedContext(tripleArcs, objectId, scopedContext);
 
  return objectId;
}
 
/**
 * Converts any JSON-LD object into object literals linked in a graph
 * @param jsonLd The JSON-LD document
 * @param node The id of the node that should be returned as the root value
 */
export async function json2ObjectGraph<ReturnType extends NodeObject>(
  jsonLd: JsonLdDocument,
  node: string
): Promise<ReturnType> {
  const jsonLdClone = JSON.parse(JSON.stringify(jsonLd));
 
  // Traverse the document, getting the leafs and the ids
  const idMap: Record<string, NodeObject[]> = {};
  const tripleArcs: TripleArcs = {};
  await traverseNodesForIdsAndLeafs(jsonLdClone, idMap, tripleArcs);
 
  // Consolodate all the objects in IdMap into one object
  const consolodatedIdMap: Record<string, NodeObject> = {};
  Object.entries(idMap).forEach(([key, value]) => {
    consolodatedIdMap[key] = value.reduce((agg, newNode) => {
      return { ...agg, ...newNode };
    }, {});
  });
 
  // Get the node to return
  const nodeToReturn = consolodatedIdMap[node];
  if (!nodeToReturn) {
    throw new Error(`Node "${node}" is not in the graph.`);
  }
 
  // Link the triple arcs
  await Promise.all(
    Object.entries(tripleArcs).map(async ([subjectId, subjectInfo]) => {
      const subject = consolodatedIdMap[subjectId];
 
      // Construct to @context for this subject
      if (subjectInfo.scopedContexts.length > 0) {
        // Again, these two library types do not work together, but it's actual fine.
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        subject["@context"] = await combineContexts(subjectInfo.scopedContexts);
      }
 
      // Build the object links
      Object.entries(subjectInfo.predicates).forEach(
        ([predicate, objectIds]) => {
          if (
            objectIds.length === 1 &&
            // Is not a container predicate
            !(
              subject["@context"] &&
              (subject["@context"] as IJsonLdContextNormalizedRaw)[predicate] &&
              (subject["@context"] as IJsonLdContextNormalizedRaw)[predicate][
                "@container"
              ]
            )
          ) {
            subject[predicate] =
              consolodatedIdMap[objectIds[0]] || objectIds[0];
          } else {
            subject[predicate] = objectIds.map(
              (objectId) => consolodatedIdMap[objectId] || objectId
            );
          }
        }
      );
    })
  );
 
  return nodeToReturn as ReturnType;
}