```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 = Infinity): unknown[] {
  if (typeof depth !== 'number' || depth < 0 && depth !== Infinity) {
    throw new Error('Depth must be a non-negative integer or Infinity.');
  }

  const result: unknown[] = [];
  const stack: { items: unknown[]; index: number; currentDepth: number }[] = [{ items, index: 0, currentDepth: 0 }];

  while (stack.length > 0) {
    const { items, index, currentDepth } = stack.pop()!;
    if (index < items.length) {
      if (currentDepth >= depth || typeof items[index] !== 'object' || items[index] === null) {
        result.push(items[index]);
      } else {
        stack.push({ items, index: index + 1, currentDepth });
        stack.push({ items: items[index] as unknown[], index: 0, currentDepth: currentDepth + 1 });
      }
    }
  }

  return result;
}
```