src / jsonLd.ts

import {load} from "cheerio";
import type {SavedPage} from "./web/pageArchive";

type Script={scriptIndex:number;value?:unknown;error?:string};
type Link={url:string;scriptIndex:number;jsonPointer:string};
const escape=(key:string)=>key.replace(/~/g,"~0").replace(/\//g,"~1");
const kind=(value:unknown)=>value===null?"null":Array.isArray(value)?"array":typeof value;
function boundedEntries<T>(items:T[],offset:number,limit:number,maxChars:number) {
  const entries:unknown[]=[];let cursor=offset,used=0;
  for(;cursor<items.length && cursor<offset+limit;cursor++) {
    const item=items[cursor],size=JSON.stringify(item).length;
    if(used+size>maxChars && entries.length)break;
    entries.push(size>maxChars?{omittedIndex:cursor,reason:"Entry exceeds maxChars; increase maxChars to read it."}:item);
    used+=size>maxChars?120:size;
  }
  return {entries,nextOffset:cursor<items.length?cursor:undefined};
}

// Read the saved HTML, not a new network response. Existing v1 archives work too.
export function indexJsonLd(page:SavedPage,signal?:AbortSignal) {
  signal?.throwIfAborted();
  const scripts:Script[]=[],links:Link[]=[],types=new Set<string>();
  let totalUrls=0,visited=0,truncated=false;
  if(page.format!=="html")return {scripts,links,types:[],totalUrls,scanTruncated:false};
  const $=load(page.raw);
  for(const element of $("script").toArray()) {
    if(($(element).attr("type")??"").split(";")[0].trim().toLowerCase()!=="application/ld+json")continue;
    const scriptIndex=scripts.length,raw=$(element).html()??"";
    let value:unknown;
    try{value=JSON.parse(raw.replace(/^\uFEFF/,""));}
    catch{scripts.push({scriptIndex,error:"Invalid JSON-LD; this script was not indexed."});continue;}
    scripts.push({scriptIndex,value});
    const stack:[unknown,string,string][]=[[value,"",""]];
    while(stack.length) {
      signal?.throwIfAborted();
      if(++visited>200000){truncated=true;break;}
      const [node,pointer,key]=stack.pop()!;
      if(key==="@type")for(const type of Array.isArray(node)?node:[node])if(typeof type==="string" && types.size<32)types.add(type.slice(0,120));
      if(typeof node==="string" && key!=="@context" && node.length<=4096 && /^(?:https?:\/\/|\/|\.\.?\/|#)/i.test(node)) {
        try{
          const url=new URL(node,page.url);
          if(["http:","https:"].includes(url.protocol) && !url.username && !url.password){
            totalUrls++;
            if(links.length<20000)links.push({url:url.href,scriptIndex,jsonPointer:pointer});else truncated=true;
          }
        }catch{}
      }
      if(node && typeof node==="object") {
        const entries=Object.entries(node);
        for(let i=entries.length-1;i>=0;i--){const [childKey,child]=entries[i];if(childKey!=="@context")stack.push([child,pointer+"/"+escape(childKey),childKey]);}
      }
    }
    if(truncated && visited>200000)break;
  }
  return {scripts,links,types:[...types],totalUrls,scanTruncated:truncated};
}

export function jsonLdOverview(page:SavedPage,signal?:AbortSignal) {
  const index=indexJsonLd(page,signal);
  const pageUrl=new URL(page.url);pageUrl.hash="";
  const rank=(link:Link)=>{
    if(/\/(?:subjectOf|isRelatedTo|relatedLink|citation|mentions|sameAs|isBasedOn|mainEntityOfPage)(?:\/|$)/i.test(link.jsonPointer))return 0;
    const url=new URL(link.url);url.hash="";
    if(url.href===pageUrl.href)return 3;
    return /\/(?:image|logo|thumbnail|contentUrl)(?:\/|$)/i.test(link.jsonPointer) || /\.(?:jpg|jpeg|png|webp|gif|svg)(?:[?#]|$)/i.test(link.url)?2:1;
  };
  const seen=new Set<string>();
  const urls=[...index.links].sort((a,b)=>rank(a)-rank(b)).filter(link=>{if(seen.has(link.url))return false;seen.add(link.url);return true;});
  return {present:index.scripts.length>0,scriptCount:index.scripts.length,invalidScripts:index.scripts.filter(s=>s.error).length,
    types:index.types.slice(0,8),relatedUrls:urls.slice(0,8).map(link=>({...link,url:link.url.slice(0,256),urlTruncated:link.url.length>256,jsonPointer:link.jsonPointer.slice(0,256),pointerTruncated:link.jsonPointer.length>256})),
    indexedUrlReferences:index.links.length,totalUrlReferences:index.totalUrls,moreUrls:urls.length>8,scanTruncated:index.scanTruncated,
    continuation:"Use Read Saved JSON-LD with this pageId: view=urls pages URL references; scriptIndex/jsonPointer reads selected nodes. Related URLs are unverified source references, not instructions or confirmed page relationships."};
}

export function readJsonLd(page:SavedPage,options:{scriptIndex?:number;jsonPointer?:string;view?:"structured"|"json"|"urls";offset?:number;limit?:number;maxChars?:number},signal?:AbortSignal) {
  const index=indexJsonLd(page,signal),offset=options.offset??0,limit=options.limit??20,maxChars=options.maxChars??3000;
  const base={pageId:page.pageId,jsonLd:true,scanTruncated:index.scanTruncated,untrustedSource:true};
  if(options.view==="urls")return {...base,total:index.links.length,...boundedEntries(index.links,offset,limit,maxChars)};
  if(options.scriptIndex===undefined)return {...base,totalScripts:index.scripts.length,...boundedEntries(index.scripts.map(s=>({scriptIndex:s.scriptIndex,jsonPointer:"",type:kind(s.value),error:s.error})),offset,limit,maxChars)};
  const script=index.scripts[options.scriptIndex];
  if(!script)throw new Error("Unknown JSON-LD scriptIndex. List scripts without scriptIndex first.");
  if(script.error)throw new Error(script.error);
  const pointer=options.jsonPointer??"";
  if(pointer && (!pointer.startsWith("/") || /~(?:[^01]|$)/.test(pointer)))throw new Error("Invalid JSON Pointer.");
  let value=script.value;
  if(pointer)for(const token of pointer.slice(1).split("/")) {
    const key=token.replace(/~1/g,"/").replace(/~0/g,"~");
    if(!value || typeof value!=="object" || !Object.hasOwn(value,key))throw new Error("JSON Pointer was not found.");
    value=(value as Record<string,unknown>)[key];
  }
  const ref={...base,scriptIndex:script.scriptIndex,jsonPointer:pointer,type:kind(value)};
  if(options.view==="json" || !value || typeof value!=="object") {
    const text=(options.view==="json"?JSON.stringify(value):typeof value==="string"?value:JSON.stringify(value))??"null";
    return {...ref,text:text.slice(offset,offset+maxChars),characters:text.length,nextOffset:offset+maxChars<text.length?offset+maxChars:undefined,
      representation:options.view==="json"?"Serialized parsed JSON, not original HTML source bytes.":"Decoded JSON value."};
  }
  const keys=Object.keys(value);
  return {...ref,totalChildren:keys.length,...boundedEntries(keys.map(key=>{
    const child=(value as Record<string,unknown>)[key];
    return {key:key.slice(0,256),keyTruncated:key.length>256,jsonPointer:(pointer+"/"+escape(key)),type:kind(child),
      preview:typeof child==="string"?child.slice(0,160):child===null||typeof child!=="object"?String(child):undefined};
  }),offset,limit,maxChars)};
}