Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

1.9 KB
Raw Blame
import { contentEngineLimits } from "./limits";
import {
  ByteLimitExceededError,
  decodeUtf8,
  getUtf8ByteLength,
  readBoundedBytes,
  stripUtf8ByteOrderMark,
  type ByteSource,
} from "./byte-stream";
import { MarkdownMetadataError } from "./markdown-errors";
import { findMarkdownFrontmatter } from "./markdown-scanner";

export type MarkdownBody = {
  body: string;
  bodyBytes: number;
  sourceBytes: number;
};

/** Reads and decodes one complete bounded Markdown file, excluding frontmatter. */
export const extractMarkdownBody = async (
  source: ByteSource,
  maximumBytes = contentEngineLimits.hydratedFileBytes
): Promise<MarkdownBody> => {
  if (
    Number.isInteger(maximumBytes) === false ||
    maximumBytes <= 0 ||
    maximumBytes > contentEngineLimits.hydratedFileBytes
  ) {
    throw new MarkdownMetadataError(
      "MARKDOWN_BODY_BYTES_EXCEEDED",
      "Markdown body byte limit is outside the supported range"
    );
  }
  let bytes: Uint8Array;
  try {
    bytes = await readBoundedBytes(source, maximumBytes);
  } catch (error) {
    if (error instanceof ByteLimitExceededError) {
      throw new MarkdownMetadataError(
        "MARKDOWN_BODY_BYTES_EXCEEDED",
        "Markdown content exceeds the byte limit"
      );
    }
    throw error;
  }
  let sourceText: string;
  try {
    sourceText = decodeUtf8(bytes);
  } catch {
    throw new MarkdownMetadataError(
      "MARKDOWN_BODY_DECODING_FAILED",
      "Markdown content is not valid UTF-8"
    );
  }

  const located = findMarkdownFrontmatter(bytes, true);
  const bodyStart = located?.blockEnd ?? 0;
  let body: string;
  try {
    body =
      bodyStart === 0
        ? stripUtf8ByteOrderMark(sourceText)
        : decodeUtf8(bytes.subarray(bodyStart));
  } catch {
    throw new MarkdownMetadataError(
      "MARKDOWN_BODY_DECODING_FAILED",
      "Markdown content is not valid UTF-8"
    );
  }
  return {
    body,
    bodyBytes: getUtf8ByteLength(body),
    sourceBytes: bytes.byteLength,
  };
};