GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / gridatlas / atlas/modules

Teleprint Controls

A JavaScript file in the atlas folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register, using SHA-256 and uses data from the npm repository.

700 lines of JavaScript from gridatlas, in 1 file. Topic: Maps, GIS and field navigation. Section 529 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Teleprint Controls render · gridatlas / atlas/modules/202609051624-teleprint-controls.js lines 1–700

Teleprint Controls

A JavaScript file in the atlas folder of GridAtlas covering the Renewable Energy Planning Database (REPD) register, using SHA-256 and uses data from the npm repository.

Set aside from the main view: A comment at the top of the file says a tool wrote it. (noise-generated, proposed by noise.py). All set-aside files, with reasons. Nothing was deleted.

Evidence
  • line 2 comment: * TELEPRINT CONTROLS -- GENERATED. DO NOT EDIT THIS FILE.

rendergridatlas / atlas/modules/202609051624-teleprint-controls.js · lines 1–700 of 1238 · version 2026-09-05 16:24 · Not reached from any entry point (candidate for review) · pattern showTeleprintPanel (shared by 6 files)

What it does
It draws the REPD register. Defines 27 functions or classes, including stopTracks, pixelsFromSource, fromDisplay, screenFrame, bytes. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'atlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, 400kV.
Inputs & outputs
In: data source: npm data. Out: canvas drawing; SVG drawing. Voltage levels named: 400kV.
What it achieves
It stops tracks (`stopTracks`), reads text (`readText`) and collects source code (`collectSourceCode`). Built by `teleprinter/drivers/gridatlas/build-part.mjs` from the drivers in that directory, which are where any change belongs. Its code works with 400 kV. It responds to click events.
Why it matters
No other file in the estate was found to import it.
Application
gridatlas · atlas/modules · script
Uses
none found
Used by
none found
Produces
stopTracks, pixelsFromSource, fromDisplay, screenFrame, bytes, join, pdfString, deflate, screenPdf, printPdf, textual, readText
Defines here
stopTracks, pixelsFromSource, fromDisplay, screenFrame, bytes, join, pdfString, deflate, screenPdf, printPdf, textual, readText, screenState, discover, add, collectSourceCode
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 atlas/modules/202609051624-teleprint-controls.js:1-700 · blob 29846b46e536d1576dcfd1eff8bf3c8021b3d87b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * TELEPRINT CONTROLS -- GENERATED. DO NOT EDIT THIS FILE.
 *
 * Built by teleprinter/drivers/gridatlas/build-part.mjs from the drivers in
 * that directory, which are where any change belongs. Editing this copy makes
 * the served bytes disagree with the source they claim to come from, and
 * --verify will say so.
 *
 * Two SEPARATE functions, on the architect's instruction:
 *   Print PDF          a picture of the reader's screen, for a person
 *   Print source code  the entire source and its dependencies, for a machine
 *
 * Sources:
 *   screen-frame.js  sha256 18e15c8780df9d6cd16b6bf2841443941ae2ad44222812096aceb6adb237ed8e
 *   print-pdf.js  sha256 c440394609fbd267f3101549d3afccdf275f4089858bb69931d59c692e52b358
 *   print-source-code.js  sha256 8d47ace65048d1874a71e4b8de30f5f5e60a5a58b36e32f289f9063d6a92a34e
 *   gridatlas-wiring.js  sha256 b76b3b8eec0962b0a8f089f5fb53c85fbab5e2f8cc9b92a011b38cdfb82727b5
 */
(function () {
  'use strict';

  /* ---- screen-frame.js (sha256 18e15c8780df9d6c) ---- */
  /**
   * GET THE FRAME THE READER IS LOOKING AT.
   * ---------------------------------------------------------------------------
   * One job, and one refusal.
   *
   * The job: return the pixels currently on the reader's screen, with their real
   * dimensions and a note saying HOW they were obtained.
   *
   * The refusal: this never reconstructs the page. There is a tempting shortcut
   * -- serialise the DOM into an <svg><foreignObject>, draw that to a canvas, and
   * call the result a screenshot. It is not one. It drops cross-origin images,
   * loses most pseudo-elements, cannot see into shadow roots, and silently
   * substitutes fallback fonts. A reader handed that would be looking at a
   * drawing of their screen while being told it was a record of it, which is the
   * one thing a teleprinter must never do. If no honest frame can be had, this
   * throws and the caller says so.
   *
   * TWO SOURCES, IN ORDER, AND THE RECORD ALWAYS NAMES THE ONE USED
   *
   *   'host'     a capture function supplied by the embedder. This exists so a
   *              test harness can hand in the browser's own screenshot and
   *              exercise every downstream byte without a permission chooser --
   *              and so a future native shell can supply a real device grab.
   *
   *   'display'  navigator.mediaDevices.getDisplayMedia({preferCurrentTab:true}).
   *              The compositor's own output: every layer, WebGL and DOM
   *              together, at the resolution the reader is actually looking at.
   *              Costs one permission click. That click is the price of an
   *              honest record and it is worth paying.
   *
   * WHY NOT canvas.toDataURL ALONE. GridAtlas draws its map into a WebGL canvas
   * created without preserveDrawingBuffer, so the drawing buffer is gone by the
   * time anything outside the frame that drew it goes looking. Reading it gives
   * a fully transparent image that encodes to a perfectly valid, perfectly blank
   * PNG. That is the failure that produced white sheets, and it is why a canvas
   * read is a MAP source, never a SCREEN source.
   */

  /** Milliseconds to wait for the capture track to actually produce a frame. */
  const FRAME_TIMEOUT_MS = 10000;

  /* A display track that never paints must not hang the reader's browser
     forever. Chrome will happily keep an unstarted <video> pending, so the wait
     is bounded and the tracks are stopped whatever happens -- an abandoned
     capture leaves the tab's sharing indicator lit, which reads to the reader as
     "this page is still watching my screen". */
  function stopTracks(stream) {
    if (!stream || typeof stream.getTracks !== 'function') return;
    for (const track of stream.getTracks()) {
      try { track.stop(); } catch (_) { /* already stopped */ }
    }
  }

  function pixelsFromSource(source, width, height) {
    if (!width || !height) throw new Error('The captured frame has no size.');
    /* 40 megapixels is about a 8K screen at dpr 2. Past that the RGBA buffer
       alone is 160 MB and the tab is more likely to die than to print. */
    if (width * height > 40000000) {
      throw new Error('The screen is too large to print in one page.');
    }
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    const context = canvas.getContext('2d', { willReadFrequently: true });
    if (!context) throw new Error('This browser refused a 2D context.');
    context.drawImage(source, 0, 0, width, height);
    return { width, height, rgba: context.getImageData(0, 0, width, height).data };
  }

  async function fromDisplay() {
    const media = navigator.mediaDevices;
    if (!media || typeof media.getDisplayMedia !== 'function') {
      /* This used to say: take a screenshot and use "Print a screenshot"
         instead. THERE IS NO SUCH CONTROL IN THIS LANE. Telling a reader on the
         one platform where this path fails to go and press a button that does
         not exist is worse than telling them nothing, and it went unnoticed
         because no test reads error strings. Say only what is true. */
      throw new Error('This browser will not let a page capture the screen — '
        + 'iOS Safari does not offer it. Print source code still works here, and '
        + 'it records the screen state.');
    }
    /* preferCurrentTab is Chromium-only and is a HINT: it puts this tab at the
       top of the chooser. Elsewhere the reader picks, which is correct -- their
       screen, their choice. */
    /* ASK FOR THE SCREEN'S REAL RESOLUTION.
       ------------------------------------------------------------------------
       getDisplayMedia hands back whatever size the browser feels like unless it
       is asked, and what it feels like is frequently NOT the reader's pixels. On
       a 393x852 phone viewport at devicePixelRatio 3 -- 1179x2556 real pixels --
       an unconstrained capture came back 786x1704: an effective scale of 2.0
       against a dpr of 3, holding 1.34 of the screen's 3.01 megapixels. FORTY-
       FOUR PERCENT of the record, and the receipt said "1:1" because the PDF
       page equalled the captured image, which it did. The page was 1:1 with the
       capture; the capture was not 1:1 with the screen.

       So the real pixel count is asked for explicitly, and whatever arrives is
       MEASURED against it rather than assumed. */
    const wantWidth = Math.round(window.innerWidth * (window.devicePixelRatio || 1));
    const wantHeight = Math.round(window.innerHeight * (window.devicePixelRatio || 1));
    const stream = await media.getDisplayMedia({
      video: {
        frameRate: 1,
        width: { ideal: wantWidth },
        height: { ideal: wantHeight }
      },
      audio: false,
      preferCurrentTab: true,
      selfBrowserSurface: 'include'
    });
    try {
      /* ImageCapture FIRST, because a <video> is the wrong instrument here.
         ---------------------------------------------------------------------
         Piping the track into a detached <video> and reading videoWidth gave
         786x1704 from a track that declares -- and caps at -- 1179x2556. Waiting
         for the resolution to ramp did not fix it: a video element with no
         layout is handed a reduced frame and keeps being handed one.

         ImageCapture.grabFrame() asks the track for a frame directly and returns
         it at the track's own size, with no element and no layout in the path.
         The <video> route is kept only as a fallback for engines that have no
         ImageCapture. */
      const directTrack = stream.getVideoTracks()[0];
      if (typeof ImageCapture === 'function' && directTrack) {
        try {
          /* RETRY WHILE THE TRACK RAMPS.
             WAIT FOR THE FRAME TO STOP CHANGING, NOT FOR A SIZE IT WILL NEVER
             REACH. The first version of this loop waited until the frame matched
             track.getSettings().width, and the comment it carried -- that the
             track "climbs to its own declared size" -- IS CONTRADICTED BY
             MEASUREMENT. On a display track Chrome reports
             `resizeMode: "crop-and-scale", width: 1179, height: 2556`: those are
             the values that were ASKED FOR, echoed back, not the frames being
             produced. It delivered 786x1704 throughout. So the exit condition was
             unsatisfiable, the loop burned its whole timeout on every print, and
             accepted the first frame anyway. There is no ramp on this track.

             Waiting for stability is the honest version: grab until two
             consecutive frames are the same size, which exits immediately when
             the first frame is already final and still catches a source that
             genuinely does climb. It also removes a five-second stall paid on
             every print whose width is odd -- 2326 never reaches 2327. */
          const capture = new ImageCapture(directTrack);
          let grabbed = await capture.grabFrame();
          const rampEnd = Date.now() + 5000;
          let previousWidth = -1;
          let previousHeight = -1;
          while ((grabbed.width !== previousWidth || grabbed.height !== previousHeight)
            && (grabbed.width < wantWidth || grabbed.height < wantHeight)
            && Date.now() < rampEnd) {
            previousWidth = grabbed.width;
            previousHeight = grabbed.height;
            if (typeof grabbed.close === 'function') grabbed.close();
            await new Promise(resolve => setTimeout(resolve, 200));
            grabbed = await capture.grabFrame();
          }
          try {
            const settings = typeof directTrack.getSettings === 'function'
              ? directTrack.getSettings() : {};
            return {
              ...pixelsFromSource(grabbed, grabbed.width, grabbed.height),
              method: 'display',
              screenWidth: wantWidth,
              screenHeight: wantHeight,
              trackWidth: Number(settings.width) || null,
              trackHeight: Number(settings.height) || null,
              /* BOTH AXES. captureScale was width-only, so a frame that was
                 full width and short in height reported as complete. The receipt
                 now carries the exact pixel counts and a flag that is an INTEGER
                 EQUALITY, not a threshold. */
              captureScale: wantWidth ? grabbed.width / wantWidth : null,
              captureScaleHeight: wantHeight ? grabbed.height / wantHeight : null,
              everyScreenPixel: grabbed.width >= wantWidth && grabbed.height >= wantHeight
            };
          } finally {
            if (typeof grabbed.close === 'function') grabbed.close();
          }
        } catch (_) { /* fall through to the video element */ }
      }
      const video = document.createElement('video');
      video.muted = true;
      video.playsInline = true;
      video.srcObject = stream;
      await video.play();
      await new Promise((resolve, reject) => {
        const timer = setTimeout(
          () => reject(new Error('No screen frame arrived within 10 seconds.')),
          FRAME_TIMEOUT_MS
        );
        /* requestVideoFrameCallback fires on a frame that has actually been
           composited. readyState alone can be satisfied by a track that has
           produced metadata and no picture. */
        if (typeof video.requestVideoFrameCallback === 'function') {
          video.requestVideoFrameCallback(() => { clearTimeout(timer); resolve(); });
        } else {
          const poll = setInterval(() => {
            if (video.videoWidth > 0 && video.readyState >= 2) {
              clearInterval(poll);
              clearTimeout(timer);
              resolve();
            }
          }, 60);
        }
      });
      /* WAIT FOR THE CAPTURE TO REACH ITS OWN FULL SIZE.
         ---------------------------------------------------------------------
         This is where the "44% of the screen" defect actually lived, and it was
         not a browser limit. Probed on 2026-09-05 at a 393x852 viewport, dpr 3:
         the TRACK reports width 1179, height 2556, and getCapabilities gives a
         max of exactly 1179x2556 -- the whole screen, available. But the first
         composited frame arrives smaller and Chrome ramps up over the following
         frames, so a capture taken on the first frame yielded 786x1704 and the
         receipt called it the screen.

         (min and exact constraints cannot be used to force it: Chrome rejects
         both outright on getDisplayMedia -- "min constraints are not supported",
         "exact constraints are not supported". Asking politely and then WAITING
         is the whole technique.)

         So the track's own declared size is the target, and this waits for the
         decoded frame to reach it. If it never does, whatever arrived is used
         and the shortfall is reported rather than hidden. */
      const track = stream.getVideoTracks()[0];
      const declared = track && typeof track.getSettings === 'function'
        ? track.getSettings() : {};
      const targetWidth = Math.max(Number(declared.width) || 0, 0) || wantWidth;
      const targetHeight = Math.max(Number(declared.height) || 0, 0) || wantHeight;
      const rampDeadline = Date.now() + 4000;
      while (video.videoWidth < targetWidth && Date.now() < rampDeadline) {
        await new Promise(resolve => {
          if (typeof video.requestVideoFrameCallback === 'function') {
            video.requestVideoFrameCallback(() => resolve());
            setTimeout(resolve, 200);
          } else {
            setTimeout(resolve, 100);
          }
        });
      }

      const frame = pixelsFromSource(video, video.videoWidth, video.videoHeight);
      video.pause();
      video.srcObject = null;
      return {
        ...frame,
        method: 'display',
        screenWidth: wantWidth,
        screenHeight: wantHeight,
        trackWidth: targetWidth,
        trackHeight: targetHeight,
        /* 1 means the file holds every pixel that was on the screen. Anything
           less is a reduction and must be printed on the receipt as one. */
        captureScale: wantWidth ? frame.width / wantWidth : null,
        captureScaleHeight: wantHeight ? frame.height / wantHeight : null,
        everyScreenPixel: frame.width >= wantWidth && frame.height >= wantHeight
      };
    } finally {
      stopTracks(stream);
    }
  }

  /**
   * @param {object} [options]
   * @param {function} [options.capture] host-supplied capture returning a Blob,
   *        an ImageBitmap, or {width,height,rgba}. Used by the proof harness.
   * @returns {Promise<{width:number,height:number,rgba:Uint8ClampedArray,method:string}>}
   */
  async function screenFrame({ capture } = {}) {
    if (typeof capture === 'function') {
      const supplied = await capture();
      if (supplied && supplied.rgba && supplied.width && supplied.height) {
        return { ...supplied, method: supplied.method || 'host' };
      }
      if (supplied && typeof createImageBitmap === 'function') {
        /* colorSpaceConversion:'none' matters: the browser's image decoder will
           otherwise shift sample values by a level or two on a tagged image, and
           a print engine that claims to preserve pixels must not quietly alter
           them. Codex measured exactly this in WebKit on 2026-09-05. */
        const bitmap = await createImageBitmap(supplied, {
          colorSpaceConversion: 'none',
          premultiplyAlpha: 'none'
        });
        try {
          return { ...pixelsFromSource(bitmap, bitmap.width, bitmap.height), method: 'host' };
        } finally {
          bitmap.close();
        }
      }
      throw new Error('The supplied capture produced nothing usable.');
    }
    return fromDisplay();
  }


  /* ---- print-pdf.js (sha256 c440394609fbd267) ---- */
  /**
   * PRINT PDF -- one PDF unit per captured pixel, and a strip that says where it
   * came from.
   * ---------------------------------------------------------------------------
   * This is the FIRST of the two Teleprinter functions and it is entirely
   * separate from the second. It answers "give me what is on my screen as a
   * file". It knows nothing about source code.
   *
   * NO PAPER. The page box is exactly the captured raster's width, and its
   * height is the raster plus one provenance strip. Not A4, not A3, not "the
   * long edge scaled to 1190pt" -- that last one was real, it shipped, and on a
   * 1390x518 desktop capture it emitted a 1190x443 page: a 14% REDUCTION of the
   * record presented as the record. "THE PRINT MUST BE HIGH RES OF WHAT THE USER
   * SEES NOT A REDUCED CRAP VERSION". "WE ARE NOT USING PAPER".
   *
   * WHY FLATE AND RAW RGB RATHER THAN JPEG. JPEG is lossy, and a lossy record is
   * an edited one: text in the layer panel and the thin 400 kV lines are exactly
   * the content its ringing artefacts damage most. /FlateDecode over raw RGB
   * samples is bit-exact, so the bytes in the file ARE the bytes that were on
   * the screen, and a reviewer can say so rather than hope so.
   *
   * WHY THE STRIP IS OUTSIDE THE IMAGE. The furniture used to be painted over
   * the map. It covered the menu bar at the top and the legend at the bottom,
   * and on a real sheet it truncated the generation stamp to "generation
   * 202609051211 - 2026-09-". The record must not be written on. So the page is
   * made taller than the capture and the strip lives in the space that adds:
   * every pixel of the reader's screen survives untouched, and the provenance is
   * still on the sheet. "I like the headers and footers thats nice ... KEEP
   * THAT".
   */

  const encoder = new TextEncoder();
  const bytes = (text) => encoder.encode(text);

  function join(parts) {
    let length = 0;
    for (const part of parts) length += part.length;
    const out = new Uint8Array(length);
    let at = 0;
    for (const part of parts) { out.set(part, at); at += part.length; }
    return out;
  }

  /* PDF strings are parenthesised, so a literal parenthesis or backslash in a
     project name would end the string early and corrupt every object offset
     after it. Non-ASCII is dropped rather than guessed at: WinAnsi is not UTF-8
     and a mojibake stamp is worse than a plain one. */
  function pdfString(text) {
    return String(text == null ? '' : text)
      .replace(/[\\()]/g, '\\$&')
      .replace(/[^\x20-\x7e]/g, '');
  }

  async function deflate(data) {
    if (typeof CompressionStream !== 'function') {
      throw new Error('This browser cannot compress the page.');
    }
    const stream = new Blob([data]).stream().pipeThrough(new CompressionStream('deflate'));
    return new Uint8Array(await new Response(stream).arrayBuffer());
  }

  /**
   * Build a one-page PDF whose page is the capture plus a provenance strip.
   *
   * @param {{width:number,height:number,rgba:Uint8ClampedArray}} frame
   * @param {{brand?:string,title?:string,url?:string,stamp?:string,credit?:string,method?:string}} [note]
   */
  async function screenPdf(frame, note = {}) {
    const { width, height, rgba } = frame || {};
    if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height)
        || width < 1 || height < 1) {
      throw new Error('The captured frame has invalid dimensions.');
    }
    if (!rgba || rgba.length !== width * height * 4) {
      throw new Error('The captured frame has the wrong number of samples.');
    }

    /* The strip scales with the record, not with an assumed sheet: a 2514px-tall
       phone capture and a 518px-tall desktop one both need a legible credit, and
       a fixed 9pt is illegible on one and enormous on the other. */
    const unit = Math.max(1, Math.min(width, height) / 900);
    const headSize = Math.max(9, Math.round(13 * unit));
    const footSize = Math.max(7, Math.round(9 * unit));
    const pad = Math.max(10, Math.round(14 * unit));
    const strip = headSize + footSize + pad * 2 + Math.round(pad * 0.6);
    const pageH = height + strip;

    const rgb = new Uint8Array(width * height * 3);
    for (let i = 0, o = 0; i < rgba.length; i += 4, o += 3) {
      rgb[o] = rgba[i]; rgb[o + 1] = rgba[i + 1]; rgb[o + 2] = rgba[i + 2];
    }
    const image = await deflate(rgb);

    const heading = pdfString(note.title || 'GlobalGrid2050 · Grid Atlas');
    const brand = pdfString(note.brand || 'VENTUS · GLOBALGRID2050 · GRID ATLAS');
    const left = pdfString(note.credit || '');
    const right = pdfString([note.stamp, note.method && ('capture: ' + note.method)]
      .filter(Boolean).join('  ·  '));
    const link = pdfString(note.url || '');

    /* The image is placed at y=strip so the strip occupies the BOTTOM of the
       page, below the record, in PDF's origin-at-bottom-left space. */
    const content = [
      'q', `${width} 0 0 ${height} 0 ${strip} cm`, '/Screen Do', 'Q',
      'q', '0.016 0.039 0.047 rg', `0 0 ${width} ${strip} re f`, 'Q',
      `BT /F1 ${headSize} Tf 1 1 1 rg ${pad} ${strip - pad - headSize + Math.round(headSize * 0.25)} Td (${brand}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.86 0.93 0.94 rg ${pad} ${Math.round(pad * 0.9) + footSize} Td (${heading}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.66 0.78 0.80 rg ${pad} ${Math.round(pad * 0.55)} Td (${link}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.66 0.78 0.80 rg ${pad} ${Math.round(pad * 0.55) + footSize + 2} Td (${left}) Tj ET`,
      `BT /F1 ${footSize} Tf 0.86 0.93 0.94 rg ${Math.max(pad, width - pad - right.length * footSize * 0.52)} ${Math.round(pad * 0.9) + footSize} Td (${right}) Tj ET`
    ].join('\n');
    const contentBytes = await deflate(bytes(content));

    const objects = [
      bytes('<< /Type /Catalog /Pages 2 0 R >>'),
      bytes('<< /Type /Pages /Kids [3 0 R] /Count 1 >>'),
      bytes(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${width} ${pageH}] `
        + '/Resources << /XObject << /Screen 5 0 R >> /Font << /F1 6 0 R >> >> '
        + '/Contents 4 0 R >>'),
      join([bytes(`<< /Length ${contentBytes.length} /Filter /FlateDecode >>\nstream\n`),
        contentBytes, bytes('\nendstream')]),
      join([bytes('<< /Type /XObject /Subtype /Image '
        + `/Width ${width} /Height ${height} /ColorSpace /DeviceRGB `
        + '/BitsPerComponent 8 /Interpolate false /Filter /FlateDecode '
        + `/Length ${image.length} >>\nstream\n`), image, bytes('\nendstream')]),
      bytes('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>')
    ];

    const chunks = [bytes('%PDF-1.4\n')];
    const offsets = [];
    let at = chunks[0].length;
    objects.forEach((body, index) => {
      offsets.push(at);
      const piece = join([bytes(`${index + 1} 0 obj\n`), body, bytes('\nendobj\n')]);
      chunks.push(piece);
      at += piece.length;
    });
    let xref = `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;
    for (const offset of offsets) xref += String(offset).padStart(10, '0') + ' 00000 n \n';
    chunks.push(bytes(xref + `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\n`
      + `startxref\n${at}\n%%EOF\n`));

    return { bytes: join(chunks), pageWidth: width, pageHeight: pageH, strip };
  }

  /**
   * Capture the screen and put a PDF of it on the reader's disk.
   *
   * Separate from printSourceCode() on purpose: one produces a picture of the
   * screen, the other produces text for a machine to read, and conflating them
   * gives a reader a file that is bad at both.
   */
  async function printPdf({ capture, note = {}, filename } = {}) {
    const frame = await screenFrame({ capture });
    const built = await screenPdf(frame, { ...note, method: frame.method });
    const blob = new Blob([built.bytes], { type: 'application/pdf' });
    const name = filename
      || `gridatlas-screen-${new Date().toISOString().replace(/[:.]/g, '-')}.pdf`;
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = name;
    link.rel = 'noopener';
    document.body.appendChild(link);
    link.click();
    /* Revoking immediately races the browser's own fetch of the blob on some
       builds; 30 s is long enough for any of them and short enough that a reader
       printing repeatedly does not accumulate them. */
    setTimeout(() => {
      URL.revokeObjectURL(url);
      if (link.parentNode) link.parentNode.removeChild(link);
    }, 30000);
    return {
      method: frame.method,
      width: frame.width,
      height: frame.height,
      /* Carried out so the caller can tell the reader the truth about what the
         file holds rather than repeating a "1:1" that describes only the
         relationship between the page and the image inside it. */
      screenWidth: frame.screenWidth || null,
      screenHeight: frame.screenHeight || null,
      captureScale: typeof frame.captureScale === 'number' ? frame.captureScale : null,
      captureScaleHeight: typeof frame.captureScaleHeight === 'number' ? frame.captureScaleHeight : null,
      everyScreenPixel: frame.everyScreenPixel === true,
      pageWidth: built.pageWidth,
      pageHeight: built.pageHeight,
      bytes: built.bytes.length,
      filename: name
    };
  }


  /* ---- print-source-code.js (sha256 8d47ace65048d187) ---- */
  /**
   * PRINT SOURCE CODE -- the entire source and its dependencies, as the browser
   * actually has them, in one plain text file an AI can read.
   * ---------------------------------------------------------------------------
   * This is the SECOND Teleprinter function and it shares nothing with the
   * first. Print PDF makes a picture of the screen for a person. This makes text
   * for a machine: "the ENTIRE SOURCE CODE AND DEPENDENCIES IN THE BROWSER FOR
   * AI REVIEW", so a reader on a phone can attach one file in ChatGPT and get a
   * real answer about the thing they are looking at.
   *
   * The reader is not assumed to know what GitHub is, what a commit is, or where
   * any of these files live. They press one button and get one .txt.
   *
   * WHY .txt AND NOT .zip OR .pdf. A .zip does not open on an iPhone and cannot
   * be attached to a chat as readable text. A PDF of code is worse to read than
   * code -- it reflows, it loses indentation, and line numbers stop meaning
   * anything. Plain UTF-8 text attaches and pastes everywhere.
   *
   * HOW DEPENDENCIES ARE FOUND, AND WHY THIS WAY. The spine is
   * performance.getEntriesByType('resource') -- what the browser ACTUALLY
   * fetched to build this page -- rather than a scan of the source for things
   * that look like imports. The two disagree in both directions and the
   * disagreement matters:
   *
   *   - a literal scan finds files that were never loaded (a dead import behind
   *     a feature flag, a string that happens to end in .js), and printing them
   *     tells a reviewer the page runs code that it does not;
   *   - the browser's list finds files a scan cannot see: anything assembled at
   *     runtime, a worker started from a blob, a cartridge whose URL is built by
   *     concatenation -- which is exactly how GridAtlas loads its cartridges.
   *
   * The Codex driver in ../codex takes the literal-scan approach deliberately.
   * Where the two disagree, that disagreement is the finding, not a bug.
   *
   * WHAT IT CANNOT DO, STATED IN THE FILE ITSELF. A cross-origin response
   * without CORS is opaque: the browser has the bytes and will not let the page
   * read them. Basemap tiles, some CDN fonts and any third-party script are in
   * that category. Those are LISTED WITH THEIR URL AND THE REASON, never
   * silently dropped and never replaced with a guess -- a reviewer who cannot
   * see a gap will reason as though it is not there.
   */

  /* Written this way on purpose: a newline literal typed into this file has
     twice been turned into a REAL line break by the tooling that edits it,
     producing a single-quoted string spanning two lines -- valid-looking here
     and a syntax error once flattened into a cartridge. A named constant
     cannot be corrupted the same way. */
  const NL = String.fromCharCode(10);

  const MAX_RESOURCES = 400;
  const MAX_TOTAL_BYTES = 48 * 1024 * 1024;
  const FETCH_TIMEOUT_MS = 20000;

  /* CODE IN FULL, DATA IN SUMMARY -- and the difference stated in the file.
     ------------------------------------------------------------------------
     The first working version of this printed everything it could read and
     produced a 13,237,685-byte file: 33 resources, of which one was the 10 MB
     decoded REPD dataset. That file is useless for the job it exists to do. The
     architect's purpose is "so we can debug in chatgpt chat on mobile", and no
     phone is attaching 13 MB of mostly numbers to a chat.

     The distinction that fixes it is not "big vs small", it is CODE vs DATA. An
     AI reviewing why a screen is wrong needs every line of the code that drew
     it. It does not need all 7,680 REPD rows to answer that; it needs to know
     the dataset is there, how large it is, and what its first rows look like.

     So code is never truncated -- truncating code is how a reviewer is led to a
     wrong conclusion about a branch they cannot see -- and data is headed,
     measured and marked TRUNCATED in the file itself. */
  const CODE = /\.(m?js|cjs|css|html?|svg)(\?|#|$)/i;
  const DATA_HEAD_CHARS = 4000;

  const TEXTUAL = /\.(m?js|cjs|css|json|html?|txt|svg|map|geojson|csv)(\?|#|$)/i;

  function textual(url, type) {
    if (TEXTUAL.test(url)) return true;
    return type === 'script' || type === 'link' || type === 'css' || type === 'fetch'
      || type === 'xmlhttprequest';
  }

  async function readText(url) {
    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
    try {
      /* force-cache so printing does not re-download a 10 MB dataset the page
         already has, and so the text printed is the text the page is RUNNING
         rather than whatever the server would serve now. */
      const response = await fetch(url, { cache: 'force-cache', signal: controller.signal });
      if (!response.ok) {
        return { ok: false, reason: `HTTP ${response.status}` };
      }
      if (response.type === 'opaque') {
        return { ok: false, reason: 'opaque cross-origin response; the browser will not let this page read it' };
      }
      return { ok: true, text: await response.text() };
    } catch (error) {
      return { ok: false, reason: String((error && error.message) || error) };
    } finally {
      clearTimeout(timer);
    }
  }

  /* What is on the screen right now, in words a reviewer can act on. Without
     this the source is a pile of files with no indication of which branch the
     reader was standing in when it went wrong. */
  function screenState() {
    const layers = Array.from(document.querySelectorAll('input[type=checkbox]'))
      .filter(node => {
        const rect = node.getBoundingClientRect();
        return rect.width > 0 && rect.height > 0;
      })
      .map(node => {
        const label = node.closest('label') || node.parentElement;
        const text = ((label && label.textContent) || node.name || node.id || '').trim();
        return { control: text.replace(/\s+/g, ' ').slice(0, 80), checked: !!node.checked };
      });
    const selected = document.querySelector('.project-popup .name, .gm-panel .project-name');
    return {
      url: location.href,
      title: document.title,
      generation: (document.documentElement.dataset || {}).gridatlasGeneration || null,
      viewport: {
        width: window.innerWidth,
        height: window.innerHeight,
        devicePixelRatio: window.devicePixelRatio,
        orientation: window.innerWidth >= window.innerHeight ? 'landscape' : 'portrait'
      },
      userAgent: navigator.userAgent,
      capturedAt: new Date().toISOString(),
      selectedProject: selected ? selected.textContent.trim().slice(0, 160) : null,
      layersOn: layers.filter(l => l.checked).map(l => l.control),
      layersOff: layers.filter(l => !l.checked).map(l => l.control),
      attribution: Array.from(document.querySelectorAll('.maplibregl-ctrl-attrib-inner'))
        .map(n => n.textContent.trim()).filter(Boolean).join(' | ')
    };
  }

  function discover() {
    const seen = new Map();
    const add = (url, how) => {
      if (!url) return;
      let absolute;
      /* NEVER INVENT A SAME-ORIGIN URL.
         jsDelivr's `+esm` bundles begin with imports that are ROOT-RELATIVE to
         the CDN. Resolved against location.href they became
         https://ventusltd.github.io/npm/... , which 404s -- so the teleprint
         reported three missing dependencies that do not exist, while the
         architect's own iPhone print carried all three from the CDN correctly.
         A printer that invents a defect is worse than one that misses it.
         A root-relative name is therefore dropped rather than guessed at;
         everything performance.getEntriesByType reports is already absolute. */
      if (String(url).startsWith('/') && !String(url).startsWith('//')) return;
      try { absolute = new URL(url, location.href).href; } catch (_) { return; }
      if (absolute.startsWith('blob:') || absolute.startsWith('data:')) return;
      if (seen.has(absolute)) { seen.get(absolute).how.add(how); return; }
      seen.set(absolute, { url: absolute, how: new Set([how]) });
    };

    add(location.href, 'the page itself');
    for (const node of document.querySelectorAll('script[src]')) add(node.src, '<script src>');
    for (const node of document.querySelectorAll('link[rel~="stylesheet"][href]')) {
      add(node.href, '<link stylesheet>');
    }
    if (typeof performance !== 'undefined' && performance.getEntriesByType) {
      for (const entry of performance.getEntriesByType('resource')) {
        if (textual(entry.name, entry.initiatorType)) {
          add(entry.name, `loaded by the browser (${entry.initiatorType})`);
        }
      }
    }
    /* A CAP THAT SAYS SO, OR IT IS A LIE.
       This was `.slice(0, MAX_RESOURCES)`. Resource 401 onwards simply vanished
       -- no entry in `missing`, no line in the file -- while the same teleprint
       printed "EVERY file is here in full. Nothing is truncated". A reader
       cannot see a gap that is not declared, so they reason as though it is not
       there, which is the one failure this whole format exists to prevent.
       The cap remains, because an unbounded fetch on a phone is its own
       failure; what changes is that anything beyond it is NAMED. */
    const all = Array.from(seen.values());
    const kept = all.slice(0, MAX_RESOURCES);
    kept.overflow = all.slice(MAX_RESOURCES);
    return kept;
  }

  /**
   * Collect everything and render one text file.
   * @returns {Promise<{text:string,filename:string,included:number,missing:Array}>}
   */
  async function collectSourceCode({ appName = 'GridAtlas', inlineDom = true } = {}) {
    const state = screenState();
    const targets = discover();
    const included = [];