import parse from "json-to-ast";
import { getAstForJsonPointer } from "./pointer-utils.js";
import { validateRicosDocument } from "./validate-ricos-document.js";
function parseFromString(str, options) {
  let obj;
  try {
    obj = JSON.parse(str);
  } catch (e) {
    const error = e;
    const position = getPositionFromJSONError(e);
    return {
      type: "error",
      messages: [
        position !== void 0 ? {
          from: position,
          to: position + 1,
          message: error.message
        } : {
          from: 0,
          to: str.length,
          message: error.message
        }
      ]
    };
  }
  const validationResult = validateRicosDocument(obj, options);
  if (validationResult.type === "ok") {
    return { type: "ok", content: validationResult.content };
  }
  const ast = parse(str);
  return {
    type: "error",
    messages: (validationResult.errors || []).map(convertMessage(ast))
  };
}
function getPositionFromJSONError(e) {
  if (e instanceof SyntaxError) {
    const match = /position (\d+)/.exec(e.message);
    if (match) {
      return parseInt(match[1], 10);
    }
    return void 0;
  }
}
const convertMessage = (ast) => (message) => {
  const astForJsonPointer = getAstForJsonPointer(ast, message.instancePath);
  return {
    message: message.message,
    from: astForJsonPointer.property ? astForJsonPointer.property.loc.start.offset : astForJsonPointer.value.loc.start.offset,
    to: astForJsonPointer.value.loc.end.offset
  };
};
export {
  parseFromString
};
//# sourceMappingURL=parse-from-string.js.map
