export function truncateStringAtBytesBoundaryWithError()

in glean/src/core/utils.ts [256:275]


export function truncateStringAtBytesBoundaryWithError(metric: MetricType, value: unknown, maxBytes: number): string {
  if (!isString(value)) {
    throw new MetricValidationError(`Expected string, got ${JSON.stringify(value)}`);
  }

  const encoder = new TextEncoder();
  const decoder = new TextDecoder("utf-8");

  const uint8 = encoder.encode(value);
  const section = uint8.slice(0, maxBytes);
  const truncated = decoder.decode(section);
  if (truncated !== value) {
    Context.errorManager.record(
      metric,
      ErrorType.InvalidOverflow,
      `Value length ${new Blob([value]).size} exceeds maximum of ${value.length} bytes.`
    );
  }
  return truncated;
}