```ts
export function flatten(items: readonly unknown[], depth?: number): unknown[] {
    if (depth === undefined) depth = Infinity;
    if (typeof depth !== 'number' || depth < 0) throw new Error('Depth must be a non-negative integer or Infinity');

    const result: unknown[] = [];

    function* iterate(item: unknown, currentDepth: number): Generator<unknown> {
        if (Array.isArray(item)) {
            for (const subItem of item) yield* iterate(subItem, currentDepth + 1);
        } else if (typeof item === 'object' && item !== null && !(item instanceof Set || item instanceof Map)) {
            for (const key in item) {
                if (item.hasOwnProperty(key)) {
                    yield* iterate(item[key], currentDepth + 1);
                }
            }
        } else {
            yield item;
        }
    }

    for (const item of items) yield* iterate(item, 0);

    return result;
}
```