Treat any value that may be undefined/null (environment globals, optional stream handles, user config fields, optional IDs) as untrusted at the boundary. Use explicit checks/type guards instead of non-null assertions, and either omit invalid fields or return a deterministic safe failure—never let missing data crash module load or runtime.

Apply these patterns:

Example (safe guards):

function getOrigin(): string {
  return typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3737';
}

function safePipeToQueue(stream: NodeJS.ReadableStream | null | undefined) {
  if (!stream) {
    // deterministic safe failure path
    return { ok: false as const, reason: 'missing_stream' };
  }
  // safe to attach listeners
  return { ok: true as const };
}

function parseConfig(raw: Record<string, unknown>) {
  const out: { model?: string } = {};
  if (typeof raw.model === 'string') out.model = raw.model;
  // drop invalid/unknown fields silently
  return out;
}

This prevents null-reference crashes (SSR/tests), avoids fragile ! usage, and keeps the system robust against malformed inputs.