```ts
/**
 * Flattens a nested array up to a specified depth.
 * @param items - The array to flatten.
 * @param depth - The maximum depth to flatten. Defaults to Infinity.
 * @returns A new flattened array.
 */
export function flatten(items: readonly unknown[], depth?: number): unknown[] {
  if (depth === undefined) depth = Infinity;
  if (!Number.isInteger(depth) || depth < 0) throw new Error('Depth must be a non-negative integer or Infinity');

  const result: unknown[] = [];
  const stack: { items: unknown[]; depth: number }[] = [{ items, depth }];

  while (stack.length > 0) {
    const { items, depth } = stack.pop()!;
    for (const item of items) {
      if (Array.isArray(item) && depth > 0) {
        stack.push({ items: item, depth: depth - 1 });
      } else {
        result.push(item);
      }
    }
  }

  return result;
}
```