```ts
/**
 * Parses a semantic version string according to the MAJOR.MINOR.PATCH format,
 * with optional -prerelease and +build metadata.
 * @param version - The semantic version string to parse.
 * @returns An object containing the parsed version components.
 */
export function parseSemver(version: string): { major: number; minor: number; patch: number; prerelease: string | null; build: string | null } {
  const semverRegex = /^(\d+).(\d+).(\d+)(?:-([^+]+))?(?:\+(.+))?$/;
  const match = version.match(semverRegex);

  if (!match) {
    throw new Error(`Invalid semver version: ${version}`);
  }

  const major = parseInt(match[1], 10);
  const minor = parseInt(match[2], 10);
  const patch = parseInt(match[3], 10);

  if (isNaN(major) || isNaN(minor) || isNaN(patch)) {
    throw new Error(`Invalid semver version: ${version}`);
  }

  return {
    major,
    minor,
    patch,
    prerelease: match[4] ?? null,
    build: match[5] ?? null,
  };
}
```