All files jsonld2graphobject.ts

100% Statements 117/117
100% Branches 62/62
100% Functions 21/21
100% Lines 94/94

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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307  1x       1x   1x     591x                                                 186x 103x           186x 142x   186x 186x 76x                       156x 44x           156x 142x                   137x                   156x 69x 87x 85x 599x   85x         8x     79x                                     156x       156x 288x 24x       24x 45x 3x         184x 184x 177x 54x 123x 1x           156x 156x 147x   156x     312x 471x 935x   7x     14x 15x 30x                   471x     624x 52x             52x 537x 35x 35x     76x   88x 64x             64x 12x       12x             76x   35x 76x   251x 58x         156x   156x               1x         25x     25x 25x 50x     25x 147x 147x 156x         25x 25x 1x       48x 144x 144x     154x       134x       144x 140x 140x                         104x     36x 80x         144x 3x         24x    
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[];
    };
    originallyInArray: {
      [predicateId: string]: true;
    };
  };
}
 
/**
 * Helper function to set the proper tripleArcs values
 */
function setTripleArcs(
  tripleArcs: TripleArcs,
  subjectId: string,
  predicateId: string,
  objectId: string,
  isArray: boolean
) {
  if (!tripleArcs[subjectId]) {
    tripleArcs[subjectId] = {
      scopedContexts: [],
      predicates: {},
      originallyInArray: {},
    };
  }
  if (!tripleArcs[subjectId].predicates[predicateId]) {
    tripleArcs[subjectId].predicates[predicateId] = [];
  }
  tripleArcs[subjectId].predicates[predicateId].push(objectId);
  if (isArray) {
    tripleArcs[subjectId].originallyInArray[predicateId] = true;
  }
}
 
/**
 * Helper function to set scopedContext on tripleArcs
 */
function setScopedContext(
  tripleArcs: TripleArcs,
  subjectId: string,
  scopedContext?: IJsonLdContextNormalizedRaw
) {
  if (!tripleArcs[subjectId]) {
    tripleArcs[subjectId] = {
      scopedContexts: [],
      predicates: {},
      originallyInArray: {},
    };
  }
  if (scopedContext) {
    tripleArcs[subjectId].scopedContexts.push(scopedContext);
  }
}
 
/**
 * Combines multiple contexts together
 */
async function combineContexts(
  contexts: IJsonLdContextNormalizedRaw[]
): Promise<IJsonLdContextNormalizedRaw> {
  return (await contextParser.parse(contexts)).getContextRaw();
}
 
/**
 *
 */
function getObjectId(
  object: NodeObject,
  scopedContext?: IJsonLdContextNormalizedRaw
): string {
  if (object["@id"]) {
    return object["@id"];
  } else if (scopedContext) {
    const mappedIdEntry = Object.entries(scopedContext).find(
      ([, value]) => value === "@id"
    );
    if (
      mappedIdEntry &&
      object[mappedIdEntry[0]] &&
      typeof object[mappedIdEntry[0]] === "string"
    ) {
      return object[mappedIdEntry[0]] as string;
    }
  }
  return v4();
}
 
/**
 * 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 = getObjectId(object, scopedContext);
  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, false);
      } else if (Array.isArray(value)) {
        const setTripleArcsParams = (
          await Promise.all<Parameters<typeof setTripleArcs> | undefined>(
            value.map(
              async (
                arrValue
              ): Promise<Parameters<typeof setTripleArcs> | undefined> => {
                if (isObject(arrValue)) {
                  const valueId = await traverseNodesForIdsAndLeafs(
                    arrValue as NodeObject,
                    idMap,
                    tripleArcs,
                    scopedContext,
                    idPredicates
                  );
                  return [tripleArcs, objectId, key, valueId, true];
                } else if (
                  typeof arrValue === "string" &&
                  idPredicates.has(key)
                ) {
                  return [tripleArcs, objectId, key, arrValue as string, true];
                }
              }
            )
          )
        ).filter<Parameters<typeof setTripleArcs>>(
          (value): value is Parameters<typeof setTripleArcs> =>
            value !== undefined
        );
        setTripleArcsParams.forEach((params) => {
          setTripleArcs(...params);
        });
      } else if (typeof value === "string" && idPredicates.has(key)) {
        setTripleArcs(tripleArcs, objectId, key, value, false);
      }
    })
  );
 
  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 jsonld2graphobject<ReturnType extends NodeObject>(
  jsonLd: JsonLdDocument,
  node: string,
  options?: { excludeContext: boolean }
): 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"
              ]
            ) &&
            // Was not originally in an array
            !subjectInfo.originallyInArray[predicate]
          ) {
            subject[predicate] =
              consolodatedIdMap[objectIds[0]] || objectIds[0];
          } else {
            subject[predicate] = objectIds.map(
              (objectId) => consolodatedIdMap[objectId] || objectId
            );
          }
        }
      );
      if (options?.excludeContext) {
        delete subject["@context"];
      }
    })
  );
 
  return nodeToReturn as ReturnType;
}