/**
 * SET 42d — /assets/* must never SPA-fallback to HTML.
 *
 * During deploy windows (and on Pages soft-404s), a missing hashed asset can
 * be answered with index.html at 200 + cacheable headers. Browsers then cache
 * text/html under the .js URL permanently → "Failed to load module script …
 * MIME type text/html". Real assets pass through; HTML-shaped answers become
 * a non-cacheable 404.
 */
type PagesContext = {
  request: Request;
  next: (input?: Request | string) => Promise<Response>;
};

const NOT_FOUND = () =>
  new Response('Not Found', {
    status: 404,
    headers: {
      'content-type': 'text/plain; charset=utf-8',
      'cache-control': 'no-store',
    },
  });

export const onRequest = async (context: PagesContext): Promise<Response> => {
  const res = await context.next();
  const ct = res.headers.get('content-type') || '';
  if (res.ok && /text\/html/i.test(ct)) return NOT_FOUND();
  if (res.status === 404) return NOT_FOUND();
  return res;
};
