{
  "version": 3,
  "sources": ["offline_audit.js"],
  "sourcesContent": ["/*\n * static/js/offline_audit.js \u2014 read what this device actually holds, and\n * paint the offline-content report (SNOW-907).\n *\n * The collector and the DOM half. ``offline_audit_core.js`` turns the\n * readings into the report; everything that touches Cache Storage,\n * IndexedDB, the service worker or the page is here.\n *\n * ## Two hosts, one module\n *\n * This runs on ``/offline/`` (SNOW-930 moved it off ``/account/settings/``)\n * and on ``static/offline.html`` (the branded fallback page). The second\n * is the point: ``/offline/`` is a normal Django page, and a device that\n * cannot reach the network cannot be relied on to have it cached \u2014 the\n * moment a user most needs to know what is stored is the moment the only\n * page they can open is the one telling them nothing is. So this file and\n * its core are warmed into the shell cache on install (``AUDIT_SCRIPTS``,\n * static/js/sw.js), and the offline page loads them by their unhashed\n * ``/static/`` path.\n *\n * Both hosts provide the same markup contract and style it themselves \u2014\n * this module writes classless semantic HTML carrying\n * ``data-audit-status`` and nothing else. A Tailwind class string would\n * be inert on the offline page, whose stylesheet is inline and whose\n * whole design rule is \"no external assets\".\n *\n * ## The log is one line per check\n *\n * Strictly one, and nothing under it. A row is label and answer, and\n * everything a failing row would want to explain is composed into the\n * summary instead (``composeSummary``). The rule is not stylistic:\n * per-row helper text made this panel three times taller, turned\n * scanning into reading, and repeated one remedy across three rows\n * rather than saying it once. The renderer enforces it by having nowhere\n * to put a second line, and ``tests/js/test_offline_audit.js`` asserts a\n * row never grows one.\n *\n * ## The build is an animation, and says nothing about timing\n *\n * Every reading is taken before a single answer is painted. The rows then\n * fill in on a fixed ``ROW_INTERVAL_MS`` cadence \u2014 a reveal, not a\n * measurement, and deliberately carrying no numbers that could be read as\n * one. An earlier cut printed each row's real elapsed time; on any\n * ordinary device that was fifteen rows of ``0.00s``, which looked like\n * precision and conveyed nothing.\n *\n * What the build IS for: the list of questions is on screen in full,\n * unanswered, from the first frame, and the reader watches each one get\n * answered. That is the whole confidence argument \u2014 thirteen separate\n * things were asked, and here is each of them being settled \u2014 and it is\n * why the skeleton is painted before the answers rather than the rows\n * appearing one at a time out of nothing.\n *\n * ``prefers-reduced-motion`` skips the cadence and paints the answered\n * report in one go. Nothing is lost: the reveal is decoration over a\n * report that is complete before it starts.\n *\n * ## It reads storage, it does not ask another module\n *\n * `pwaBasemapAreas`, `pwaBasemapDownloadCore` and `pwaDb` all expose\n * readers for most of this, and none of them is used here. A report whose\n * job is to catch storage and the app disagreeing must not take the app's\n * word for what storage holds \u2014 SNOW-843 was three separate surfaces\n * agreeing an area was downloaded while the map drew nothing. Reading the\n * buckets and the object stores directly is the only way the report can\n * contradict them.\n *\n * It also has to run where those modules are absent. The offline page\n * loads two files; `basemap_download_core.js` alone is 116 KB of tile\n * arithmetic this has no use for.\n *\n * SNOW-1138 is the one place it asks another module anything, and it\n * asks for arithmetic, not for what is stored: which terrain-class tiles\n * an opted-in area's ground implies (`expectedTerrainTiles`), from the\n * same pure function the Manage downloads sheet uses. Optional \u2014 where\n * those cores are absent the report makes no claim about class tiles.\n * The same ticket made the report list the pinned buckets no record\n * accounts for (`unrecordedBuckets`), as the sheet does, so the two\n * surfaces no longer disagree about what is downloaded.\n *\n * ## Never writes\n *\n * Every read is opened read-only and the one action \u2014 warming the map\n * page into the shell cache \u2014 goes through the worker's existing\n * ``warm-cache`` message rather than writing a cache entry from here.\n * A diagnostic that changes what it is diagnosing is worse than none.\n *\n * SNOW-912: that message now warms the page's own same-origin scripts and\n * stylesheets alongside its HTML, because a page whose JavaScript is\n * missing does not open \u2014 so saving the HTML alone would have moved this\n * report's own \"The app opens\" row to Yes while leaving the user with\n * exactly the failure the row exists to catch.\n */\n\n(function () {\n  'use strict';\n\n  var ROOT_SELECTOR = '[data-offline-audit]';\n  var SHELL_CACHE_PREFIX = 'snowdesk-shell-';\n  var PINNED_CACHE_PREFIX = 'snowdesk-basemap-pinned-';\n  // SNOW-1058: the PASSIVE browsing cache \u2014 `sw.js`'s `BASEMAP_CACHE`,\n  // which `_basemapStaleWhileRevalidate` fills as the user looks at the\n  // map and SNOW-1060 trims by tile count. Named here rather than read\n  // from the worker for the reason every other name in this block is:\n  // this file reads storage directly, and must run without the worker.\n  var PASSIVE_BASEMAP_CACHE = 'snowdesk-basemap-v1';\n  var DB_NAME = 'snowdesk-pwa-v1';\n\n  // The stores whose depth the report states. Not every store in db.js:\n  // `queue:events` is the telemetry buffer and `log:*` are diagnostics,\n  // neither of which is content the user would miss offline.\n  var DATA_STORES = [\n    'data:favourites',\n    'data:map_overlays',\n    'data:panel_rows',\n  ];\n\n  // How long to wait for the worker to name its own cache version before\n  // falling back to reading every shell cache present. Short because the\n  // reply is a postMessage round trip to a worker that is, by definition,\n  // already running \u2014 and because the fallback is correct, just less\n  // precise.\n  var VERSION_PROBE_MS = 1500;\n\n  // SNOW-925 review: the bound on the two manifest fetches the per-row\n  // sync control derives its plan from. `pwaWarmCache` settles on the\n  // worker's own budget; these do not go through it, and without a bound\n  // a connection that stalls without rejecting leaves the operation\n  // pending \u2014 the button disabled, the status line mid-sentence, and the\n  // verification re-run never reached. Generous next to the read budgets\n  // below because this is a deliberate press over a real network rather\n  // than a storage probe, and it is a ceiling on a hang, not a target.\n  var MANIFEST_FETCH_BUDGET_MS = 15000;\n\n  // How long between one row's answer and the next. Thirteen rows plus\n  // however many downloads, at 70ms, is about a second \u2014 long enough to\n  // read as deliberate, short enough that nobody waits for it. It is an\n  // animation over an already-finished report; see the header.\n  var ROW_INTERVAL_MS = 70;\n\n  // Every reading this module takes is time-bounded, for the reason\n  // docs/decisions/bounded-offline-read-paths.md gives for bounding every\n  // read path in sw.js: storage in trouble HANGS, it does not reject. An\n  // IndexedDB request whose event never fires and a `caches.match` that\n  // never settles have no catch branch \u2014 the `await` simply never returns\n  // \u2014 so every `try`/`catch` below is written against a failure mode the\n  // broken device does not have.\n  //\n  // That is not hypothetical. This panel was reported reading \"Checking\u2026\"\n  // for ever on an iPad whose owner had just had to reset local data\n  // after an update left the app frozen and insisting it was offline \u2014\n  // and in the same screenshot the reset panel beside it, which reads the\n  // same two stores through entirely different code, was stuck on\n  // \"Loading\u2026\". Two surfaces, one unbounded await each, both silent.\n  //\n  // A diagnostic that hangs on exactly the devices it exists for is worse\n  // than no diagnostic. So this file may take longer than it likes, but\n  // it always finishes, and it always says which readings it could not\n  // take.\n  var READ_BUDGET_MS = 4000;\n\n  // The whole collection. A healthy device with four hundred cache\n  // entries finishes well inside a second; this is the point past which\n  // the answer is \"this device's storage is not answering\", which is\n  // itself a finding and has to be painted rather than waited out.\n  var COLLECT_BUDGET_MS = 20000;\n\n  // Consecutive overruns after which the run stops asking, exactly as\n  // sw.js's OFFLINE_LATCH_THRESHOLD stops it asking the network. Without\n  // it a device with a wedged IndexedDB and twelve downloads pays\n  // READ_BUDGET_MS per read and takes the full COLLECT_BUDGET_MS to say\n  // so. Any reading that lands resets the count, so one slow read never\n  // latches a run on its own.\n  var READ_LATCH_THRESHOLD = 3;\n\n  /**\n   * One run's read budget: its deadline, the readings that overran it,\n   * and the latch.\n   *\n   * @returns {{deadline: number, timedOut: string[], consecutive: number,\n   *   latched: boolean}}\n   */\n  function createBudget() {\n    return {\n      deadline: Date.now() + COLLECT_BUDGET_MS,\n      timedOut: [],\n      consecutive: 0,\n      latched: false,\n    };\n  }\n\n  /**\n   * Record one overrun, and latch the run after enough of them.\n   *\n   * @param {Object} budget\n   * @param {string} label Which reading \u2014 it reaches the reader, in the\n   *   copied report, as the list of what could not be checked.\n   * @returns {void}\n   */\n  function recordOverrun(budget, label) {\n    if (budget.timedOut.indexOf(label) < 0) budget.timedOut.push(label);\n    budget.consecutive += 1;\n    if (budget.consecutive >= READ_LATCH_THRESHOLD) budget.latched = true;\n  }\n\n  /**\n   * Take one reading under the budget.\n   *\n   * Resolves with ``fallback`` rather than rejecting, on three paths: the\n   * work threw, the work rejected, or the work never settled. Only the\n   * third counts towards the latch \u2014 a device that answers \"no\" is\n   * answering, and latching on a rejection would stop a run that is\n   * working perfectly well.\n   *\n   * The fallback must mean \"could not read\", never \"read, and there is\n   * nothing there\". The report's oldest rule is that an unknown is not a\n   * No (see the module header of offline_audit_core.js), and a bound that\n   * fell back to an absence would print \"The app will not open\" over an\n   * app that opens perfectly.\n   *\n   * @param {Object} budget\n   * @param {string} label\n   * @param {function(): *} work\n   * @param {*} fallback\n   * @returns {Promise<*>}\n   */\n  function bounded(budget, label, work, fallback) {\n    if (budget.latched || Date.now() >= budget.deadline) {\n      recordOverrun(budget, label);\n      return Promise.resolve(fallback);\n    }\n    var promise;\n    try {\n      promise = work();\n    } catch (_err) {\n      budget.consecutive = 0;\n      return Promise.resolve(fallback);\n    }\n    if (!promise || typeof promise.then !== 'function') {\n      budget.consecutive = 0;\n      return Promise.resolve(promise === undefined ? fallback : promise);\n    }\n    var remaining = Math.max(\n      0,\n      Math.min(READ_BUDGET_MS, budget.deadline - Date.now()),\n    );\n    return new Promise(function (resolve) {\n      var settled = false;\n      var timer = setTimeout(function () {\n        if (settled) return;\n        settled = true;\n        recordOverrun(budget, label);\n        resolve(fallback);\n      }, remaining);\n      var finish = function (value) {\n        if (settled) return;\n        settled = true;\n        clearTimeout(timer);\n        budget.consecutive = 0;\n        resolve(value);\n      };\n      promise.then(finish, function (_err) {\n        finish(fallback);\n      });\n    });\n  }\n\n  // SNOW-620: server-translated copy where a template provides it, the\n  // English literal everywhere else. `pwaStrings` is not loaded on the\n  // offline page, so the fallbacks are not a safety net there \u2014 they are\n  // the copy, exactly as every other string on that page is.\n  //\n  // Four families:\n  //   section-* / label-*   the log's section rules and its left column\n  //   the answers           what a row's right column says\n  //   note-*                one standalone clause for the summary\n  //   group-* / effect-*    the parts the summary composes into a single\n  //                         sentence when several Nos share one remedy\n  var FALLBACKS = {\n    'section-access': 'Getting in',\n    'section-map': 'The map',\n    'section-content': 'Your content',\n\n    'row-offline-support': 'Offline support is installed',\n    'row-network-use': 'The app may use the network',\n    'row-app-opens': 'The app opens',\n    'row-app-looks-right': 'The app looks right',\n    'row-danger-ratings': 'Danger ratings',\n    'row-region-shapes': 'Region outlines',\n    'row-basemap': '%(name)s',\n    'row-basemap-current': '%(name)s (on screen)',\n    'row-bulletins': 'Bulletins you have opened',\n    'row-region-sheets': 'Region details for downloaded days',\n    'row-saved-places': 'Your saved places',\n    'row-routes': 'Your routes',\n    'row-reports': 'Community observations',\n    'row-weather': 'Weather',\n\n    'basemap-openfreemap_liberty': 'OpenFreeMap',\n    'basemap-swisstopo_winter': 'Winter map',\n    'basemap-swisstopo_light': 'Swisstopo light (CH)',\n    'basemap-ign_plan': 'IGN (FR)',\n    'basemap-basemap_at': 'basemap.at (AT)',\n\n    'answer-yes': 'Yes',\n    'answer-no': 'No',\n    'answer-unknown': '\u2014',\n    'answer-pending': '\u2026',\n    // SNOW-1483: the network row's `info` answers, one per state.\n    'answer-info-forced': 'Offline mode on',\n    'answer-info-latched': 'No signal',\n\n    'note-sw-unsupported': 'this browser has no offline mode at all',\n    'note-sw-starting': 'offline mode is starting up and will be ready on the next load',\n    'note-sw-absent': 'offline mode has not been set up on this device',\n    // SNOW-922: the user's own switch, and the worker's own latch. Two\n    // different Nos with two different remedies \u2014 one is a control to\n    // press, the other lifts itself \u2014 so they never share a clause.\n    'note-network-forced':\n      'Offline mode is switched on, so the app will not call the server even with a signal',\n    'note-network-latched':\n      'the app stopped calling the server after it went unanswered, and will try again on its own',\n    'note-other-account': 'the saved copy belongs to %(stamped)s',\n    'note-basemap-unstyled':\n      'the %(name)s map style is not saved, so nothing drawn on it will appear',\n    // SNOW-1058: the passive cache is trimmed by Snowdesk's own count cap\n    // as the user browses (SNOW-1060), not by the device running short of\n    // room \u2014 so none of these three says \"when the device needs the space\".\n    'note-basemap-downloads-only':\n      'outside your downloads the %(name)s map is only what you have browsed, and older areas drop out as you look at new ones',\n    'note-basemap-browsed-only':\n      'the %(name)s map is only what you have browsed \u2014 it is not saved, and older areas drop out as you look at new ones',\n    'note-basemap-style-only':\n      'only the %(name)s map style is saved, not the map itself \u2014 download the map to see it offline',\n    'note-no-bulletins': 'no bulletin has been opened on this device yet',\n    'note-no-region-sheets': 'no downloaded area has saved its region details yet',\n    'note-empty-region-sheets': 'no area is downloaded, so there are no region details to save',\n    'note-no-favourites': 'none of your saved places has been loaded here yet',\n    'note-no-routes': 'none of your routes has been loaded on this device',\n    'note-no-reports': 'community observations have not been loaded on this device',\n    'note-no-weather': 'the weather overlay has not been opened on this device',\n    // SNOW-914: the row is readable and there is simply nothing in it \u2014\n    // neither a capability nor a fault, so neither Yes nor No.\n    'note-empty-favourites': 'you have not saved any places yet',\n    'note-empty-routes': 'you have not uploaded any routes yet',\n    'note-empty-reports': 'there are no community observations in what has been loaded here',\n    'note-empty-weather': 'the weather that was loaded here holds nothing to draw',\n\n    'effect-styles': 'will look plain',\n    'effect-ratings': 'will show no danger ratings',\n    'effect-shapes': 'will draw no region outlines',\n    'group-open-map-lead': 'Without a signal the app %(effects)s.',\n    'group-open-map-remedy': 'Opening the map once while connected fixes %(count)s.',\n    // SNOW-1308: the area notes and the content-age group sentences\n    // (SNOW-926/1138) moved with the download rows to the `/offline/`\n    // panels, which say the same per area (offline_journey.js).\n\n    'principal-anonymous': 'a signed-out visitor',\n    'principal-account': 'account %(id)s\u2026',\n    'principal-unknown': 'an unknown account',\n\n    'verdict-ok': 'Everything you need is on this device.',\n    'verdict-partial': 'The app will open, but not everything will be there.',\n    'verdict-unchecked':\n      'The app will open, but some things could not be checked on this device.',\n    'verdict-no-worker': 'This device is not set up for offline use yet.',\n    'verdict-forced-lockout':\n      'Offline mode is on and the app is not saved here, so it will not open. ' +\n      'Switch Offline mode off to reconnect.',\n    'verdict-no-page':\n      'The app will not open without a signal. Open the map once while connected.',\n    'verdict-other-account':\n      'The saved app belongs to another account. Open the map once while connected.',\n    'verdict-no-map': 'The app opens, but there is no map to show in it.',\n    'verdict-browsed-only':\n      'The map shows what you have looked at, but nothing is downloaded. ' +\n      \"Download the map to ensure it isn't overwritten or deleted.\",\n    'verdict-downloads-broken': 'The app opens, but none of your downloads will draw.',\n    'verdict-failed': 'This check could not run on this device.',\n\n    'note-storage-slow':\n      'this device\u2019s storage stopped answering part way through, so the rows marked \u2014 were not checked',\n\n    'notes-sentence': 'Also worth knowing: %(notes)s.',\n    'list-pair': '%(first)s and %(last)s',\n    'list-join': '%(first)s, %(rest)s',\n    'count-one': 'it',\n    'count-two': 'both',\n    'count-many': 'all of them',\n\n    'counts-line': '%(yes)s of %(total)s available offline',\n    'counts-line-blocked': '%(yes)s of %(total)s saved, none of it reachable yet',\n\n    running: 'Checking\u2026',\n    copied: 'copied',\n    'copy-failed': 'copy failed',\n    saving: 'Saving the app\u2026',\n    saved: 'Saved. Re-checking\u2026',\n    'save-failed': 'That could not be saved. Try again while connected.',\n    'check-failed': 'The check could not run. Copy the report and send it in.',\n    // SNOW-925: Sync now's status line. The control itself is on the\n    // `/offline/` panels since SNOW-1308, and carries its own label there.\n    completing: 'Saving this area\u2019s bulletins and weather\u2026',\n    completed: 'Saved. Re-checking\u2026',\n    'complete-failed':\n      'Not everything could be saved. Re-checking what landed.',\n    // SNOW-1141: `?sync=all`, the network menu's \"Get ready for offline\"\n    // handed to this page. The same sentences as the menu's own (the same\n    // msgids, rendered in this page's template), worded by\n    // `offline_ready_core.js`'s `describe` / `progressText`.\n    'ready-running': 'Getting ready\u2026',\n    'ready-progress': 'Getting ready\u2026 (%(n)s of %(total)s)',\n    'ready-all': 'Ready \u2014 %(total)s areas up to date',\n    'ready-all-one': 'Ready \u2014 1 area up to date',\n    'ready-some': '%(ready)s of %(total)s ready',\n    'queue-waiting': '%(n)s changes still waiting to send',\n    'queue-waiting-one': '1 change still waiting to send',\n    // SNOW-1415: what one area's sync is fetching now (`progressText`).\n    'sync-stage-bulletins': 'Saving bulletins\u2026 (%(n)s of %(total)s)',\n    'sync-stage-weather': 'Saving weather\u2026 (%(n)s of %(total)s)',\n    'sync-stage-things': 'Saving your trips and pins\u2026 (%(n)s of %(total)s)',\n  };\n\n  /**\n   * The translated copy for this surface, or the English fallbacks.\n   *\n   * @returns {Record<string, string>}\n   */\n  function strings() {\n    if (self.pwaStrings && typeof self.pwaStrings.read === 'function') {\n      return self.pwaStrings.read('offline-audit-strings-template', FALLBACKS);\n    }\n    return FALLBACKS;\n  }\n\n  /**\n   * Every Cache Storage bucket name.\n   *\n   * ``null`` \u2014 not ``[]`` \u2014 where the API is absent or the listing fails,\n   * because the two are different findings and the report says so. A\n   * device whose Cache Storage cannot be listed has not been checked; one\n   * that lists no buckets has been checked and holds nothing. Returning\n   * ``[]`` for both is how \"we could not look\" becomes \"the app will not\n   * open\".\n   *\n   * @returns {Promise<string[]|null>}\n   */\n  async function cacheNames() {\n    try {\n      if (!self.caches || typeof self.caches.keys !== 'function') return null;\n      return await self.caches.keys();\n    } catch (_err) {\n      return null;\n    }\n  }\n\n  /**\n   * Ask the controlling worker which shell cache it is using.\n   *\n   * ``sw.js`` answers the bare ``'version'`` message with its\n   * ``CACHE_VERSION``, which IS the cache name. Worth the round trip\n   * because ``activate`` deletes stale shell caches but a worker that has\n   * installed and not yet activated leaves two on disk \u2014 and reading the\n   * wrong one would report a page as saved that the live worker will\n   * never serve.\n   *\n   * @returns {Promise<string|null>} Null on timeout, no controller, or no\n   *   service-worker support at all.\n   */\n  function liveShellCacheName() {\n    return new Promise(function (resolve) {\n      var controller =\n        'serviceWorker' in navigator ? navigator.serviceWorker.controller : null;\n      if (!controller) {\n        resolve(null);\n        return;\n      }\n      var settled = false;\n      var finish = function (value) {\n        if (settled) return;\n        settled = true;\n        navigator.serviceWorker.removeEventListener('message', onMessage);\n        resolve(value);\n      };\n      var onMessage = function (event) {\n        if (event.data && event.data.type === 'version') {\n          finish(event.data.version || null);\n        }\n      };\n      navigator.serviceWorker.addEventListener('message', onMessage);\n      setTimeout(function () {\n        finish(null);\n      }, VERSION_PROBE_MS);\n      try {\n        controller.postMessage('version');\n      } catch (_err) {\n        finish(null);\n      }\n    });\n  }\n\n  /**\n   * Whether a cached URL is a page rather than a file, by path shape.\n   *\n   * The cheap half of the classification: anything the core calls a\n   * ``page`` is worth opening to read its principal stamp, and nothing\n   * else is. On a device holding hundreds of hashed asset entries, that\n   * is the difference between a handful of ``cache.match`` calls and one\n   * per entry.\n   *\n   * @param {string} url\n   * @returns {boolean}\n   */\n  function looksLikePage(url) {\n    var core = self.pwaOfflineAuditCore;\n    return !!core && core.classifyEntry(url) === 'page';\n  }\n\n  // SNOW-913: where map_state.js keeps the visitor's basemap choice. Named\n  // here rather than imported because this module runs on static/offline.html\n  // too, where map_state.js is not loaded \u2014 the same reason every other\n  // reading in this file is taken from storage directly.\n  var BASEMAP_STORAGE_KEY = 'snowdesk.map.basemap';\n\n  /**\n   * The basemap the reader is looking at (SNOW-913).\n   *\n   * The stored choice, or the deployed default the host page was rendered\n   * with when nobody has chosen. ``localStorage`` is written only when\n   * someone opens the picker and picks, so an untouched device has no key\n   * and is looking at ``settings.BASEMAP``.\n   *\n   * Null on ``offline.html``, which is a static file with no server to ask\n   * for that default: the report then names no current basemap rather than\n   * guessing at one, which is the same rule every other reading here\n   * follows.\n   *\n   * @param {HTMLElement|null} root The panel element, which carries the\n   *   deployed default as ``data-default-basemap-key`` where a server\n   *   rendered it.\n   * @param {{keys: string[], fallback: string|null}|null} catalogue The\n   *   basemaps the CACHED map page offers, read out of its own markup \u2014 the\n   *   set the map's own resolution will run against.\n   * @returns {string|null}\n   */\n  function selectedBasemap(root, catalogue) {\n    var stored = null;\n    try {\n      stored = self.localStorage ? self.localStorage.getItem(BASEMAP_STORAGE_KEY) : null;\n    } catch (_err) {\n      // A private window, or site data blocked outright. Falls through to\n      // the default, which is still true for a device that cannot remember\n      // a choice.\n      stored = null;\n    }\n    var core = self.pwaOfflineAuditCore;\n    var serverDefault = root ? root.getAttribute('data-default-basemap-key') : null;\n    if (!core) return stored || serverDefault || null;\n    // Resolved the way the map resolves it: a stored key the cached page's\n    // picker no longer offers is not what the map will show \u2014 it falls back\n    // to the deployed default and leaves the preference behind.\n    return core.resolveBasemap(catalogue, stored, serverDefault);\n  }\n\n  /**\n   * Whether a cached URL is the map page, by pathname.\n   *\n   * Query dropped, for the reason the core's ``pages()`` drops it: the map\n   * writes ``?d=YYYY-MM-DD`` with ``history.replaceState`` while the user\n   * scrubs, and those URLs are never fetched and never cached.\n   *\n   * @param {string} url\n   * @param {string} mapPath\n   * @returns {boolean}\n   */\n  function isMapPage(url, mapPath) {\n    try {\n      return new URL(url, self.location.origin).pathname === mapPath;\n    } catch (_err) {\n      return false;\n    }\n  }\n\n  /**\n   * Every entry in the shell cache, with a principal stamp on the pages,\n   * and a handle on every copy of the map page (SNOW-912).\n   *\n   * The map page's body is read because \"The app opens\" has to be an\n   * answer about THAT page. A device holding the HTML and none of its\n   * JavaScript opens to a blank frame, and the row read Yes on a count of\n   * any cached script at all \u2014 a count two precached audit modules make\n   * true on every device.\n   *\n   * The body is NOT read here. Several entries can share the map's path \u2014\n   * ``/map/`` and any ``/map/?\u2026`` link that was navigated to \u2014 and which\n   * one the app would open depends on the account, which is read later.\n   * Reading the first in cache order read the OLDEST copy: on 30 Nov 2026\n   * a ``/map/?\u2026`` page saved before 5 Nov, carried across every update\n   * since, made the row say No over five scripts that no longer exist,\n   * while the ``/map/`` the app opens had every script it needs.\n   * ``readMapPage`` reads the copy the core judges instead.\n   *\n   * @param {string[]} names Which shell caches to read. More than one\n   *   means the worker did not answer and every candidate is being read,\n   *   which overstates rather than understates.\n   * @param {string} mapPath\n   * @returns {Promise<{entries: Array<{url: string, isPage: boolean,\n   *   principal: string|null}>, mapCopies: Array<{entry: Object,\n   *   cache: Cache, request: Request}>, complete: boolean,\n   *   pagesComplete: boolean}>}\n   */\n  async function readShellEntries(names, mapPath, budget) {\n    var entries = [];\n    var mapCopies = [];\n    // Two different kinds of incompleteness, because they cost different\n    // rows and conflating them would send five rows to unknown over one\n    // unread page body.\n    //\n    // `complete` is the LISTING: the buckets opened and their keys read.\n    // A partial listing cannot answer anything at all \u2014 the entry that\n    // would have answered it may be in the part that never arrived.\n    var complete = true;\n    // `pagesComplete` is the per-page reads inside an intact listing: a\n    // `match` or a body that did not come back. The entry list is still\n    // good, so the rows read off URLs alone are still answerable; what is\n    // not is anything needing a page's stamp or its contents.\n    var pagesComplete = true;\n    for (var i = 0; i < names.length; i += 1) {\n      var cache = await bounded(\n        budget,\n        'caches.open',\n        (function (name) {\n          return function () {\n            return self.caches.open(name);\n          };\n        })(names[i]),\n        null,\n      );\n      if (!cache) {\n        complete = false;\n        continue;\n      }\n      var requests = await bounded(\n        budget,\n        'shell.keys',\n        (function (target) {\n          return function () {\n            return target.keys();\n          };\n        })(cache),\n        null,\n      );\n      if (!requests) {\n        complete = false;\n        continue;\n      }\n      for (var j = 0; j < requests.length; j += 1) {\n        var url = requests[j].url;\n        var isPage = looksLikePage(url);\n        var principal = null;\n        // SNOW-1308: a trip's route.geojson and a pin's place sheet are\n        // served offline only under the stamp of the account they were\n        // cached for, as a page is \u2014 so the area panels need their stamp\n        // too. Read in the same pass: one walk, one bounded `match` each.\n        var scopedCore = self.pwaOfflineAuditCore;\n        var scoped =\n          isPage ||\n          !!(scopedCore && typeof scopedCore.isPrincipalScoped === 'function' &&\n            scopedCore.isPrincipalScoped(url));\n        var stampUnread = false;\n        if (scoped) {\n          // One bounded `match` per page. This is the loop that made the\n          // panel unusable on the reported device: a shell cache holds\n          // every page the user has visited, and an unbounded `match`\n          // anywhere in it stops the whole report for ever rather than\n          // costing one row its answer.\n          var response = await bounded(\n            budget,\n            'shell.match',\n            (function (target, request) {\n              return function () {\n                return target.match(request);\n              };\n            })(cache, requests[j]),\n            null,\n          );\n          // `null` is the bound's fallback and `undefined` is a genuine\n          // miss, and the difference matters more here than anywhere: an\n          // entry with no stamp is one the worker REFUSES to serve, so a\n          // timed-out `match` read as an unstamped page would tell the\n          // user \"the saved copy belongs to another account\" about a page\n          // stamped for them all along.\n          if (response === null) {\n            stampUnread = true;\n            // Only a PAGE's unread stamp costs the report's page rows; a\n            // route's or a sheet's costs that one item its answer.\n            if (isPage) pagesComplete = false;\n          }\n          // The same header ``sw.js``'s ``_principalMatches`` reads.\n          try {\n            principal = response ? response.headers.get('X-SW-Principal') : null;\n          } catch (_err) {\n            principal = null;\n          }\n        }\n        entries.push(\n          scoped && !isPage\n            ? { url: url, isPage: false, principal: principal, scoped: true, stampUnread: stampUnread }\n            : isPage\n              ? { url: url, isPage: true, principal: principal, stampUnread: stampUnread }\n              : { url: url, isPage: false, principal: principal },\n        );\n        if (isPage && isMapPage(url, mapPath)) {\n          mapCopies.push({ entry: entries[entries.length - 1], cache: cache, request: requests[j] });\n        }\n        // The latch, checked inside the hot loop rather than only between\n        // caches: a shell cache can hold hundreds of pages, and a device\n        // whose Cache Storage has stopped answering must not pay\n        // READ_BUDGET_MS for each of them.\n        if (budget.latched) {\n          complete = false;\n          break;\n        }\n      }\n      if (budget.latched) {\n        complete = false;\n        break;\n      }\n    }\n    return {\n      entries: entries,\n      mapCopies: mapCopies,\n      complete: complete,\n      pagesComplete: pagesComplete,\n    };\n  }\n\n  /**\n   * What the copy of the map page the app would open asks for: its\n   * scripts and stylesheets, the day it opens on and its basemap picker\n   * (SNOW-912, SNOW-913, SNOW-914).\n   *\n   * The copy is the one the core's ``mapPageEntry`` judges \u2014 the first the\n   * worker would serve this account, else the searchless page, else the\n   * first \u2014 so the dependencies are read off the same page the row's\n   * verdict names. See ``readShellEntries`` for what reading the first\n   * copy in cache order got wrong.\n   *\n   * The body is fetched with a fresh bounded ``match`` rather than kept\n   * from the listing pass: a ``Response`` body can be read once, and\n   * holding every copy's response open to read one of them is a cost paid\n   * for nothing.\n   *\n   * @param {Array<{entry: Object, cache: Cache, request: Request}>} copies\n   * @param {Array<Object>} entries\n   * @param {string} mapPath\n   * @param {string|null} currentPrincipal\n   * @param {Object} budget\n   * @returns {Promise<{mapDependencies: string[]|null, mapDay: string|null,\n   *   mapBasemaps: Object|null, bodyUnread: boolean}>}\n   *   ``mapDependencies`` is null when there is no map page to read, or\n   *   when its body could not be read \u2014 which the core answers No to\n   *   rather than guessing.\n   */\n  async function readMapPage(copies, entries, mapPath, currentPrincipal, budget) {\n    var none = { mapDependencies: null, mapDay: null, mapBasemaps: null, bodyUnread: false };\n    var core = self.pwaOfflineAuditCore;\n    if (!core || !copies.length) return none;\n    var chosen = core.mapPageEntry(entries, mapPath, currentPrincipal);\n    var copy = null;\n    for (var i = 0; i < copies.length; i += 1) {\n      if (copies[i].entry === chosen) copy = copies[i];\n    }\n    if (!copy) return none;\n    var response = await bounded(\n      budget,\n      'shell.match',\n      function () {\n        return copy.cache.match(copy.request);\n      },\n      null,\n    );\n    if (!response) return Object.assign({}, none, { bodyUnread: response === null });\n    // `.text()` on the response itself, NOT on a `clone()`: `clone()` tees\n    // the stream, which is one of the few constructs in this file that can\n    // leave a body pending indefinitely rather than failing.\n    var html = await bounded(\n      budget,\n      'shell.body',\n      function () {\n        return response.text();\n      },\n      null,\n    );\n    // `text()` always resolves a string, so a null is the bound and nothing\n    // else. Without this the core reads `mapDependencies: null` as \"body\n    // unreadable\", which is a No \u2014 and warming, the remedy it then offers,\n    // fixes nothing about a read that simply did not come back.\n    if (typeof html !== 'string') return Object.assign({}, none, { bodyUnread: true });\n    try {\n      return {\n        mapDependencies: core.pageDependencies(html, self.location.origin),\n        // SNOW-914: and the day that page will open on, which is the day\n        // whose ratings it will ask the cache for.\n        mapDay: core.pageDay(html),\n        // SNOW-913: and the basemaps its picker offers, which is the\n        // catalogue the map's own choice-resolution runs against.\n        mapBasemaps: core.pageBasemaps(html),\n        bodyUnread: false,\n      };\n    } catch (_err) {\n      return none;\n    }\n  }\n\n  /**\n   * Open the app database read-only, without ever creating or upgrading\n   * it.\n   *\n   * Opening with no version means the request never triggers an upgrade,\n   * so this cannot race ``db.js``'s own migrations or leave a\n   * half-created schema behind. Where ``indexedDB.databases()`` exists the\n   * open is skipped entirely for a device that has no database yet \u2014\n   * otherwise a bare open would CREATE an empty one, which is a write, and\n   * this file does not write.\n   *\n   * @returns {Promise<IDBDatabase|null>}\n   */\n  async function openDb(budget) {\n    if (!self.indexedDB) return null;\n    // `databases()` is a read like any other, and on WebKit it is one of\n    // the calls that hangs rather than rejecting when the store is\n    // wedged. Bounded, and a bound that expires falls through to the open\n    // \u2014 which is exactly what happens everywhere the method was never\n    // implemented, so the degraded path is the pre-existing one.\n    var present = await bounded(\n      budget,\n      'indexeddb.databases',\n      function () {\n        if (typeof self.indexedDB.databases !== 'function') return null;\n        return self.indexedDB.databases();\n      },\n      null,\n    );\n    if (Array.isArray(present)) {\n      var found = present.some(function (entry) {\n        return entry && entry.name === DB_NAME;\n      });\n      if (!found) return null;\n    }\n    return await bounded(\n      budget,\n      'indexeddb.open',\n      function () {\n        return new Promise(function (resolve) {\n          var request;\n          try {\n            request = self.indexedDB.open(DB_NAME);\n          } catch (_err) {\n            resolve(null);\n            return;\n          }\n          request.onsuccess = function () {\n            var db = request.result;\n            // A versionless open joins the connection queue, so this\n            // connection is now something another context's upgrade can\n            // block on \u2014 db.js's own migration after an app update, or\n            // the worker's. Holding it while a report animates would\n            // wedge the very upgrade the user needs; letting go is free,\n            // because every read here has already been taken by then.\n            if (db) {\n              db.onversionchange = function () {\n                try {\n                  db.close();\n                } catch (_err2) {\n                  // Non-fatal.\n                }\n              };\n            }\n            resolve(db);\n          };\n          request.onerror = function () {\n            resolve(null);\n          };\n          // Fires only for an upgrade this open is holding up, which a\n          // versionless open never is. Kept because the reverse \u2014 an open\n          // queued BEHIND someone else's upgrade \u2014 fires nothing at all,\n          // and is the case the bound above is really for.\n          request.onblocked = function () {\n            resolve(null);\n          };\n        });\n      },\n      null,\n    );\n  }\n\n  /**\n   * One record from ``meta:app``, by key.\n   *\n   * @param {IDBDatabase} db\n   * @param {string} key\n   * @returns {Promise<*>} The row's ``value``, or null for a missing row,\n   *   a missing store, or any failure.\n   */\n  function readMeta(db, key) {\n    return new Promise(function (resolve) {\n      try {\n        if (!db.objectStoreNames.contains('meta:app')) {\n          resolve(null);\n          return;\n        }\n        var request = db\n          .transaction('meta:app', 'readonly')\n          .objectStore('meta:app')\n          .get(key);\n        request.onsuccess = function () {\n          resolve(request.result ? request.result.value : null);\n        };\n        request.onerror = function () {\n          resolve(null);\n        };\n      } catch (_err) {\n        resolve(null);\n      }\n    });\n  }\n\n  /**\n   * How many rows a store holds.\n   *\n   * @param {IDBDatabase} db\n   * @param {string} name\n   * @returns {Promise<number|null>} Null where the store does not exist or\n   *   cannot be read \u2014 which the report prints as unknown, never as zero.\n   */\n  function countStore(db, name) {\n    return new Promise(function (resolve) {\n      try {\n        if (!db.objectStoreNames.contains(name)) {\n          resolve(null);\n          return;\n        }\n        var request = db.transaction(name, 'readonly').objectStore(name).count();\n        request.onsuccess = function () {\n          resolve(Number(request.result));\n        };\n        request.onerror = function () {\n          resolve(null);\n        };\n      } catch (_err) {\n        resolve(null);\n      }\n    });\n  }\n\n  /**\n   * ``countStore``, under the budget.\n   *\n   * Its own helper only because the count is taken for four stores and\n   * the closure-per-store is the part that is easy to get wrong in a\n   * loop.\n   *\n   * @param {Object} budget\n   * @param {IDBDatabase} db\n   * @param {string} name\n   * @returns {Promise<number|null>} Null for a store that does not exist,\n   *   cannot be read, or did not answer \u2014 all three of which the report\n   *   prints as unknown rather than as zero.\n   */\n  function boundedStore(budget, db, name) {\n    return bounded(\n      budget,\n      'store:' + name,\n      function () {\n        return countStore(db, name);\n      },\n      null,\n    );\n  }\n\n  /**\n   * What each ``data:map_overlays`` row actually holds (SNOW-914/915).\n   *\n   * The key alone used to be the answer \u2014 'weather' being present made\n   * \"will the weather show\" a Yes. It does not: ``getOverlay`` in\n   * map_overlay_offline_cache.js returns null for a row whose\n   * ``principal`` does not match the account signed in now (favourites and\n   * routes are account-scoped), and a row holding an empty\n   * FeatureCollection draws nothing at all. Both read as Yes and showed\n   * the user nothing.\n   *\n   * @param {IDBDatabase} db\n   * @param {string} name\n   * @returns {Promise<Record<string, {features: number|null,\n   *   principal: string|null}>>} Empty where the store cannot be read.\n   *   ``features`` is null when the row holds no readable\n   *   FeatureCollection, which answers unknown rather than either way.\n   */\n  function readOverlayRows(db, name) {\n    return new Promise(function (resolve) {\n      try {\n        if (!db.objectStoreNames.contains(name)) {\n          resolve({});\n          return;\n        }\n        var request = db.transaction(name, 'readonly').objectStore(name).getAll();\n        request.onsuccess = function () {\n          var rows = {};\n          (request.result || []).forEach(function (row) {\n            if (!row || !row.key) return;\n            var features =\n              row.geojson && Array.isArray(row.geojson.features)\n                ? row.geojson.features.length\n                : null;\n            rows[String(row.key)] = {\n              features: features,\n              // Undefined on a public resource, which never carries one;\n              // null on an account row written before SNOW-493. The core\n              // tells the two apart \u2014 an absent stamp on an account-scoped\n              // resource is one `getOverlay` refuses.\n              principal: row.principal === undefined ? undefined : row.principal,\n            };\n          });\n          resolve(rows);\n        };\n        request.onerror = function () {\n          resolve({});\n        };\n      } catch (_err) {\n        resolve({});\n      }\n    });\n  }\n\n  /**\n   * What each ``data:panel_rows`` row holds, by panel (SNOW-950).\n   *\n   * The store holds one row per PANEL \u2014 'observations', 'routes' \u2014 so the\n   * key is a third of the answer: a row count would say two and mean\n   * nothing. The second third is the principal, for the reason\n   * ``readOverlayRows`` above reads one. Each panel's own module refuses a\n   * row stamped for another account (``observations_offline.js`` /\n   * ``routes_offline.js`` compare the stored value untouched), so a row\n   * from another session is on the device and unreadable \u2014 and the key\n   * alone would have called it a Yes.\n   *\n   * The last third is what the body HOLDS. The idle warm persists a\n   * successful list response whether or not the user has anything to\n   * list, so a user with no routes still carries a row \u2014 one whose body is\n   * the panel's empty clause and nothing else. That row is the\n   * ``features: 0`` of the overlays: readable, and not content. Every\n   * panel row is a ``<li>`` (includes/_ugc_panel_row.html, the one shape\n   * all four panels render), so the body is parsed and its ``<li>``\n   * elements counted; the empty clause is a ``<p>`` and counts nothing.\n   *\n   * @param {IDBDatabase} db\n   * @param {string} name\n   * @returns {Promise<Record<string, {principal: string|null,\n   *   rows: number|null}>>} ``{}`` where the store does not exist or\n   *   cannot be read. ``principal`` is undefined on a row written before\n   *   SNOW-661 stamped one \u2014 the same convention ``readOverlayRows`` uses,\n   *   and the core reads an absent stamp the way the panels do. ``rows``\n   *   is null when the body is not a string, which the core reads as\n   *   unreadable rather than as empty.\n   */\n  /**\n   * How many rows a panel's stored body renders.\n   *\n   * @param {unknown} body The row's ``body`` \u2014 the list response, verbatim.\n   * @returns {number|null} The count of ``<li>`` elements, or null when\n   *   the body is not a string or cannot be parsed.\n   */\n  function countPanelRows(body) {\n    if (typeof body !== 'string') return null;\n    try {\n      var parsed = new DOMParser().parseFromString(body, 'text/html');\n      return parsed.querySelectorAll('li').length;\n    } catch (_err) {\n      return null;\n    }\n  }\n\n  // SNOW-1582: how long a running download's heartbeat may be quiet before\n  // it reads as stopped \u2014 download_run_log_core.js's `STALE_AFTER_MS`, for\n  // the page that does not load the core.\n  var RUN_STALE_AFTER_MS = 120000;\n\n  /**\n   * SNOW-1582: every entry of ``log:download_runs`` \u2014 each download's own\n   * log \u2014 read straight from the store, as every other reading here is. A\n   * run still `running` whose heartbeat has been quiet for two minutes\n   * reads as `stopped` (download_run_log_core.js's `readEntry`, where it is\n   * loaded; the same rule inline on a page without it). One another tab is\n   * still writing reads as running.\n   *\n   * @param {IDBDatabase} db\n   * @returns {Promise<Array<Object>|null>} Null where the store is missing\n   *   or cannot be read.\n   */\n  function readDownloadRuns(db) {\n    var name = 'log:download_runs';\n    var runCore = self.pwaDownloadRunLogCore;\n    var nowIso = new Date().toISOString();\n    var nowMs = Date.parse(nowIso);\n    return new Promise(function (resolve) {\n      try {\n        if (!db.objectStoreNames.contains(name)) {\n          resolve(null);\n          return;\n        }\n        var request = db.transaction(name, 'readonly').objectStore(name).getAll();\n        request.onsuccess = function () {\n          resolve(\n            (request.result || []).map(function (entry) {\n              if (runCore) return runCore.readEntry(entry, nowIso);\n              // The core's rule, inline for static/offline.html, which does\n              // not load it: running, and its heartbeat quiet for two\n              // minutes (`STALE_AFTER_MS`).\n              var beat = entry ? Date.parse(String(entry.updatedAt || entry.startedAt || '')) : NaN;\n              return entry && entry.outcome === 'running' && nowMs - beat > RUN_STALE_AFTER_MS\n                ? Object.assign({}, entry, { outcome: 'stopped' })\n                : entry;\n            }),\n          );\n        };\n        request.onerror = function () {\n          resolve(null);\n        };\n      } catch (_err) {\n        resolve(null);\n      }\n    });\n  }\n\n  function readPanelRows(db, name) {\n    return new Promise(function (resolve) {\n      try {\n        if (!db.objectStoreNames.contains(name)) {\n          resolve({});\n          return;\n        }\n        var request = db.transaction(name, 'readonly').objectStore(name).getAll();\n        request.onsuccess = function () {\n          var rows = {};\n          (request.result || []).forEach(function (row) {\n            if (!row || !row.key) return;\n            rows[String(row.key)] = {\n              principal: row.principal === undefined ? undefined : row.principal,\n              rows: countPanelRows(row.body),\n            };\n          });\n          resolve(rows);\n        };\n        request.onerror = function () {\n          resolve({});\n        };\n      } catch (_err) {\n        resolve({});\n      }\n    });\n  }\n\n  /**\n   * Every URL in one pinned bucket, and whether the bucket exists at all.\n   *\n   * ``caches.has`` first, deliberately: ``caches.open`` CREATES a bucket\n   * that was not there, so probing with it would silently manufacture the\n   * very thing being checked for and turn \"this area is gone\" into \"this\n   * area is empty\" for every subsequent run.\n   *\n   * @param {string} areaId\n   * @returns {Promise<{present: boolean, entries: string[]}>}\n   */\n  async function readBucket(areaId, budget) {\n    var name = PINNED_CACHE_PREFIX + areaId;\n    // `readable: false` is the important third state. \"This area's tiles\n    // are gone, download it again\" is a serious thing to tell someone\n    // about a 200 MB download they made on purpose, and a read that never\n    // came back is not evidence for it.\n    var unreadable = { present: false, entries: [], readable: false };\n    var has = await bounded(\n      budget,\n      'bucket.has',\n      function () {\n        return self.caches.has(name);\n      },\n      null,\n    );\n    if (has === null) return unreadable;\n    if (!has) return { present: false, entries: [], readable: true };\n    var cache = await bounded(\n      budget,\n      'bucket.open',\n      function () {\n        return self.caches.open(name);\n      },\n      null,\n    );\n    if (!cache) return unreadable;\n    var requests = await bounded(\n      budget,\n      'bucket.keys',\n      function () {\n        return cache.keys();\n      },\n      null,\n    );\n    if (!requests) return unreadable;\n    return {\n      present: true,\n      readable: true,\n      entries: requests.map(function (request) {\n        return request.url;\n      }),\n    };\n  }\n\n  /**\n   * What the passive browsing cache holds for each basemap asked about\n   * (SNOW-1058).\n   *\n   * The report looked only in the download buckets, so a device with\n   * nothing downloaded was told \"there is no map to show\" over a map that\n   * was drawing from `snowdesk-basemap-v1` at that moment. This is the\n   * missing half: per basemap, is its style here, and is at least one of\n   * its tiles \u2014 the core's ``browsedState`` decides, from what is read\n   * here.\n   *\n   * The same discipline as ``readBucket``: ``caches.has`` before\n   * ``caches.open``, because ``open`` CREATES the cache it is asked for\n   * and a diagnostic must not write. The listing is taken ONCE and shared\n   * by every basemap; after it, one bounded ``match`` for each style and\n   * one for each TileJSON its sources name. Every read is under the\n   * budget, and every read that does not come back makes that basemap\n   * ``null`` \u2014 unknown \u2014 never ``'none'``: \"nothing browsed\" is a claim,\n   * and a timeout is not evidence for it.\n   *\n   * @param {string[]} keys The basemaps to answer for.\n   * @param {Record<string, string>} styleUrls Each key's style URL, off\n   *   the cached map page's picker. A key with no URL is skipped and\n   *   absent from the result: there is nowhere to look it up.\n   * @param {Object} budget\n   * @returns {Promise<Record<string, 'tiles'|'style-only'|'none'|null>>}\n   */\n  async function readBrowsed(keys, styleUrls, budget) {\n    var core = self.pwaOfflineAuditCore;\n    var result = /** @type {Record<string, *>} */ ({});\n    var asked = keys.filter(function (key, index) {\n      return keys.indexOf(key) === index && styleUrls && styleUrls[key];\n    });\n    if (!asked.length || !core) return result;\n    var all = function (value) {\n      asked.forEach(function (key) {\n        result[key] = value;\n      });\n      return result;\n    };\n    if (!self.caches || typeof self.caches.has !== 'function') return all(null);\n    var has = await bounded(\n      budget,\n      'passive.has',\n      function () {\n        return self.caches.has(PASSIVE_BASEMAP_CACHE);\n      },\n      null,\n    );\n    if (has === null) return all(null);\n    // Never browsed at all, and read as such \u2014 without opening it.\n    if (!has) return all('none');\n    var cache = await bounded(\n      budget,\n      'passive.open',\n      function () {\n        return self.caches.open(PASSIVE_BASEMAP_CACHE);\n      },\n      null,\n    );\n    if (!cache) return all(null);\n    var requests = await bounded(\n      budget,\n      'passive.keys',\n      function () {\n        return cache.keys();\n      },\n      null,\n    );\n    if (!requests) return all(null);\n    var passiveUrls = requests.map(function (request) {\n      return request.url;\n    });\n\n    // `null` is the bound's fallback and `undefined` a genuine miss, the\n    // distinction `readShellEntries` draws for the same reason: only the\n    // second is evidence of absence. The match is EXACT, query included,\n    // because that is how sw.js's `_basemapStaleWhileRevalidate` serves it\n    // offline (`cache.match(request)`): an older style cached under a\n    // different query is not one the worker would hand MapLibre, and\n    // reading it would put a Yes over a style that does not load.\n    //\n    // `unparsedIsMiss` is for the TileJSON reads. A source `url` that is\n    // not a TileJSON at all (basemap.at's ESRI service root) can still match\n    // a cached response, and its body failing to parse is not a read that\n    // did not come back: it is the absence of a TileJSON, which sends the\n    // core to its site fallback instead of turning the whole row unknown.\n    var readJson = function (url, unparsedIsMiss) {\n      return bounded(\n        budget,\n        'passive.match',\n        function () {\n          return cache.match(url).then(function (response) {\n            if (!response) return undefined;\n            return unparsedIsMiss\n              ? response.json().catch(function () {\n                  return undefined;\n                })\n              : response.json();\n          });\n        },\n        null,\n      );\n    };\n\n    for (var i = 0; i < asked.length; i += 1) {\n      var key = asked[i];\n      var styleUrl = styleUrls[key];\n      var style = await readJson(styleUrl);\n      if (style === null) {\n        result[key] = null;\n        continue;\n      }\n      if (!style || typeof style !== 'object') {\n        result[key] = 'none';\n        continue;\n      }\n      var tileJsons = {};\n      var unread = false;\n      var sources = style.sources && typeof style.sources === 'object' ? style.sources : {};\n      var ids = Object.keys(sources);\n      for (var j = 0; j < ids.length; j += 1) {\n        var source = sources[ids[j]];\n        if (!source || typeof source.url !== 'string' || Array.isArray(source.tiles)) continue;\n        var absolute = null;\n        try {\n          absolute = new URL(source.url, styleUrl).toString();\n        } catch (_err) {\n          absolute = null;\n        }\n        if (!absolute) continue;\n        var tileJson = await readJson(absolute, true);\n        if (tileJson === null) {\n          unread = true;\n          break;\n        }\n        // A miss is left out, and the core falls back to the source's\n        // site \u2014 see `tileTemplatesForStyle`.\n        if (tileJson) tileJsons[source.url] = tileJson;\n      }\n      result[key] = unread ? null : core.browsedState(style, tileJsons, passiveUrls, styleUrl);\n      if (budget.latched) {\n        // Whatever is left is unread, not absent.\n        for (var k = i + 1; k < asked.length; k += 1) result[asked[k]] = null;\n        break;\n      }\n    }\n    return result;\n  }\n\n  /**\n   * The downloaded areas this device has records for, normalised.\n   *\n   * Three record shapes become one: a region (keyed by ``region_id``, its\n   * bucket named ``region-<id>``), a custom area (its own ``id``) and a\n   * shared base layer (``base-<basemapKey>``, the zoomed-out tiles every\n   * area reads). The base layers are included because they are stored,\n   * they take space, and they are invisible everywhere else \u2014 a user\n   * comparing this report against the Manage downloads sheet should not\n   * find tiles the sheet never mentions and conclude the report is wrong.\n   *\n   * @param {IDBDatabase|null} db\n   * @returns {Promise<Array<Object>>}\n   */\n  async function readAreaRecords(db, budget) {\n    if (!db) return [];\n    var areas = [];\n    var meta = function (key) {\n      return bounded(\n        budget,\n        'meta:' + key,\n        function () {\n          return readMeta(db, key);\n        },\n        null,\n      );\n    };\n    var regions = (await meta('basemap.regions')) || [];\n    if (Array.isArray(regions)) {\n      regions.forEach(function (record) {\n        if (!record || !record.region_id) return;\n        areas.push({\n          id: 'region-' + record.region_id,\n          kind: 'region',\n          name: record.name || record.region_id,\n          basemapKey: record.basemapKey || null,\n          bytes: record.bytes,\n          savedAt: record.savedAt,\n          deps: Array.isArray(record.deps) ? record.deps : [],\n          // SNOW-926: when the bulletins and weather inside this area's\n          // boundary were last fetched in full (SNOW-924 records it).\n          // Separate from `savedAt` because the two halves age\n          // differently: the tiles are a fixed grid over fixed ground and\n          // never go stale, the bulletins are new every day. Absent means\n          // never, which is every area downloaded before that ticket.\n          contentAt: record.contentAt || null,\n          // SNOW-1138: the terrain opt-in and the ground it is derived\n          // from \u2014 the run's own `z` row spans \u2014 so the report can judge\n          // the class tiles this area should hold (`terrainTiles`).\n          terrain: !!record.terrain,\n          z: record.z || null,\n          // SNOW-1308: the tile template the run fetched under, so the\n          // `/offline/` panels can check every basemap tile the ground\n          // implies is in the bucket (`blobFullyCached`); the reader's\n          // own things the last sync expected (`stampContentRecord`); and\n          // the account the area was stamped for (SNOW-1142), so those\n          // things are never named to another account.\n          template: record.template || null,\n          // SNOW-1478: every map the area holds, when its download saved\n          // more than one or a sync added Swisstopo; null before that.\n          basemaps: Array.isArray(record.basemaps) ? record.basemaps : null,\n          items: record.items || null,\n          principal: typeof record.principal === 'string' ? record.principal : null,\n          // SNOW-1487: what the last sync learned, its unfinished steps\n          // among it, for the copied report.\n          verified: record.verified && typeof record.verified === 'object' ? record.verified : null,\n        });\n      });\n    }\n    var custom = (await meta('basemap.customAreas')) || [];\n    if (Array.isArray(custom)) {\n      custom.forEach(function (record) {\n        if (!record || !record.id) return;\n        areas.push({\n          id: record.id,\n          kind: 'custom',\n          // SNOW-XXX: a drop zone is its own kind, not a custom area with\n          // a particular name \u2014 `basemap_manage_core.js` reads the same\n          // field for the same reason, and the report groups by it.\n          type: record.type === 'dropzone' ? 'dropzone' : 'custom',\n          // SNOW-1133: the stored name only. An unrenamed area's\n          // \"Custom area N\" is built from `ordinal` where the report\n          // speaks of it (offline_audit_core.js's `areaName`), as the\n          // sheet does, rather than falling back to the raw id here.\n          name: record.name || '',\n          ordinal: Number.isFinite(record.ordinal) ? record.ordinal : undefined,\n          basemapKey: record.basemapKey || null,\n          bytes: record.bytes,\n          savedAt: record.savedAt,\n          deps: Array.isArray(record.deps) ? record.deps : [],\n          // SNOW-926: see the region branch above.\n          contentAt: record.contentAt || null,\n          // SNOW-1138: see the region branch above. A custom area has no\n          // `z`; its ground is `bbox` + `band`, rebuilt into a blob.\n          terrain: !!record.terrain,\n          bbox: Array.isArray(record.bbox) ? record.bbox : null,\n          band: Array.isArray(record.band) ? record.band : null,\n          // SNOW-1308: see the region branch above.\n          template: record.template || null,\n          // SNOW-1478: every map the area holds, when its download saved\n          // more than one or a sync added Swisstopo; null before that.\n          basemaps: Array.isArray(record.basemaps) ? record.basemaps : null,\n          items: record.items || null,\n          principal: typeof record.principal === 'string' ? record.principal : null,\n          // SNOW-1487: what the last sync learned, its unfinished steps\n          // among it, for the copied report.\n          verified: record.verified && typeof record.verified === 'object' ? record.verified : null,\n        });\n      });\n    }\n    var baseLayers = (await meta('basemap.baseLayers')) || [];\n    if (Array.isArray(baseLayers)) {\n      baseLayers.forEach(function (record) {\n        if (!record || !record.basemapKey) return;\n        areas.push({\n          id: 'base-' + record.basemapKey,\n          kind: 'base',\n          name: record.name || record.basemapKey,\n          basemapKey: record.basemapKey,\n          bytes: record.bytes,\n          savedAt: record.savedAt,\n          // SNOW-929: a base layer carries the documents that draw it \u2014\n          // its style, each source's TileJSON, the sprite pair and the\n          // glyph ranges, pinned into its own bucket beside the band. So\n          // it is verified by what it renders, exactly like a region or a\n          // custom area.\n          //\n          // This read `deps: []` under a comment saying \"a base layer is\n          // tiles only ... the area downloads that share it carry those\",\n          // which was false in the way that mattered: the sharing ran the\n          // other way, a user with no downloaded area had no documents at\n          // all, and the report called that bucket ready.\n          //\n          // An empty list now means a record written before SNOW-929 \u2014\n          // `areaState` still reads that as ready rather than\n          // unverifiable, deliberately; see its own comment.\n          deps: Array.isArray(record.deps) ? record.deps : [],\n        });\n      });\n    }\n    return areas;\n  }\n\n  /**\n   * The pinned buckets no record accounts for, as area readings\n   * (SNOW-1138).\n   *\n   * The shared reader the Manage downloads sheet lists from\n   * (`basemap_downloaded_areas.js`) treats two kinds of unrecorded bucket\n   * differently, and so does this:\n   *\n   *   - a `base-<basemapKey>` bucket is a shared base layer whose record\n   *     never landed (SNOW-863) \u2014 the bucket names its own basemap, so it\n   *     is a base layer, not an orphan, with an empty dependency list\n   *     read as `areaState`'s pre-SNOW-929 case;\n   *   - anything else is an ORPHAN: a download that never finished, which\n   *     the sheet lists as \"Incomplete\" with Remove as its only action.\n   *     It used to be computed here and never shown, so a device holding\n   *     one read clean on this report and not on the sheet.\n   *\n   * @param {string[]} names Every Cache Storage name.\n   * @param {Array<Object>} records The recorded areas.\n   * @returns {Array<Object>}\n   */\n  function unrecordedBuckets(names, records) {\n    var recorded = new Set(\n      records.map(function (area) {\n        return area.id;\n      }),\n    );\n    var out = [];\n    names.forEach(function (name) {\n      if (name.indexOf(PINNED_CACHE_PREFIX) !== 0) return;\n      var id = name.slice(PINNED_CACHE_PREFIX.length);\n      if (!id || recorded.has(id)) return;\n      recorded.add(id);\n      if (id.indexOf('base-') === 0) {\n        out.push({\n          id: id,\n          kind: 'base',\n          name: id.slice('base-'.length),\n          basemapKey: id.slice('base-'.length),\n          deps: [],\n        });\n        return;\n      }\n      out.push({\n        id: id,\n        // Still a region or a custom area \u2014 `orphaned` says the record is\n        // missing, not that it is a third kind of thing (the same reading\n        // `basemap_manage_core.js`'s `manageRows` makes).\n        kind: id.indexOf('region-') === 0 ? 'region' : 'custom',\n        type: 'custom',\n        orphaned: true,\n        // No record means no name, no basemap and no dependency list. The\n        // id is the label, as it is on the sheet.\n        name: '',\n        basemapKey: null,\n        deps: [],\n      });\n    });\n    return out;\n  }\n\n  /**\n   * The terrain-class tiles one recorded area should hold (SNOW-1138), or\n   * null when this page cannot say.\n   *\n   * The same rule the Manage downloads sheet's `markIncompleteRows` and\n   * the region roundel apply, through the same pure function\n   * (`pwaBasemapDownloadCore.areaTerrainClassTileURLs`), fed the same\n   * three inputs: the tile template (here off the panel, there off\n   * `#map`) and the tileset's rectangle and zoom band from\n   * `pwaTerrainFilterCore`. This asks those modules for ARITHMETIC \u2014 which\n   * URLs an area's ground implies \u2014 and never for what storage holds, so\n   * the header's rule stands.\n   *\n   * Null, not `[]`, wherever any input is absent: static/offline.html\n   * loads neither core, and a deployment without the terrain filter has\n   * no template. Null makes no claim, which is also what the sheet does\n   * with no template.\n   *\n   * @param {Object} record\n   * @param {HTMLElement|null} panel\n   * @returns {string[]|null}\n   */\n  function expectedTerrainTiles(record, panel) {\n    if (!record || !record.terrain || record.kind === 'base') return null;\n    var core = self.pwaBasemapDownloadCore;\n    var terrain = self.pwaTerrainFilterCore;\n    var template = (panel && panel.getAttribute('data-terrain-class-tile-url')) || '';\n    if (!template || !terrain || !core || typeof core.areaTerrainClassTileURLs !== 'function') {\n      return null;\n    }\n    try {\n      return core.areaTerrainClassTileURLs(\n        record,\n        template,\n        terrain.COVERAGE_BOUNDS,\n        terrain.MIN_ZOOM,\n        terrain.MAX_ZOOM,\n        terrain.tileInCoverage,\n      );\n    } catch (_err) {\n      return null;\n    }\n  }\n\n  /**\n   * The elevation tiles one recorded area should hold (SNOW-1453), or null\n   * when this page cannot say \u2014 `expectedTerrainTiles`' twin, through the\n   * core's `areaElevationTileURLs`, with the template off the panel's\n   * `data-dem-tile-url`. The view renders it only for a reader the map\n   * shows the 3D view to, as the map pins elevation only where its 3D\n   * toggle is, so the two surfaces judge the same areas.\n   *\n   * @param {Object} record\n   * @param {HTMLElement|null} panel\n   * @returns {string[]|null}\n   */\n  function expectedElevationTiles(record, panel) {\n    if (!record || !record.terrain || record.kind === 'base') return null;\n    var core = self.pwaBasemapDownloadCore;\n    var terrain = self.pwaTerrainFilterCore;\n    var template = (panel && panel.getAttribute('data-dem-tile-url')) || '';\n    if (!template || !terrain || !core || typeof core.areaElevationTileURLs !== 'function') {\n      return null;\n    }\n    try {\n      // swissALTI3D's box: SNOW-1459 widened the class tiles, not 3D.\n      return core.areaElevationTileURLs(record, template, terrain.SWISS_BOUNDS);\n    } catch (_err) {\n      return null;\n    }\n  }\n\n  /**\n   * Take every reading the report is built from, marking the clock as\n   * each one lands.\n   *\n   * @param {HTMLElement|null} [root] The panel being painted, which carries\n   *   the deployed default basemap where a server rendered it (SNOW-913).\n   *   Defaults to the first panel on the page, so a bare ``collect()`` \u2014\n   *   the console, a test \u2014 still reads the same thing the panel does.\n   * @returns {Promise<Object>} The readings object ``buildReport``\n   *   documents.\n   */\n  /**\n   * Fetch one area's shared feeds and boundary content into the cache\n   * (SNOW-925).\n   *\n   * The payload behind the per-row \"Sync now\" control. Everything goes\n   * through ``self.pwaWarmCache`` \u2014 the worker's own warm path \u2014 rather\n   * than a ``fetch`` from here, for the reason the Save control already\n   * documents: the worker stamps a same-origin HTML response with the\n   * principal its body declares (SNOW-624), and that stamp is the whole\n   * reason the entry will be servable offline. A ``cache.put`` from this\n   * page writes an entry the worker refuses for ever.\n   *\n   * SNOW-953: the plan comes from ``/api/area-content/`` \u2014 one bbox-keyed\n   * request answering which regions and which weather locations the\n   * boundary contains. The four country region feeds are still WARMED,\n   * because the map needs those outlines offline, but nothing here parses\n   * them any more: a plan derived from four feeds is short of a country\n   * whenever one of them fails, which is the under-fetch\n   * ``inside-the-boundary-is-complete.md`` promises not to produce, and a\n   * feed that fails to warm is already counted by ``warm``'s own tally.\n   * An endpoint that cannot be read leaves the plan short, and the run\n   * reports failure rather than stamping a completion over it.\n   *\n   * @param {HTMLElement} root The panel, carrying the endpoints.\n   * @param {string} areaId\n   * @param {Object|null} report The report the press was made against \u2014\n   *   its ``app-opens`` row is what decides whether the shell is warmed.\n   * @returns {Promise<boolean>} Whether everything asked for landed.\n   */\n  /**\n   * Ask the server what one rectangle contains (SNOW-953).\n   *\n   * Through ``fetchJson``, so it inherits that reader's bound: a\n   * connection that stalls without rejecting reads as an endpoint that did\n   * not answer, which makes the plan short and the run report failure \u2014\n   * rather than leaving the control disabled for the browser's full\n   * network timeout (SNOW-918).\n   *\n   * @param {string|undefined} endpoint The panel's ``data-area-content-url``.\n   * @param {number[]} bbox ``[west, south, east, north]``.\n   * @param {string} [areaId] SNOW-1582: the area whose sync's log hears a\n   *   failure.\n   * @returns {Promise<{regions: Array<Object>, weather: Array<Object>,\n   *   resorts: Array<Object>}|null>}\n   *   ``null`` for a missing endpoint, a failed request, or an answer that\n   *   is not the documented shape \u2014 all three are \"cannot say\". SNOW-1318:\n   *   the shape includes ``resorts``, so an answer from before the field\n   *   is a short plan rather than one without resort sheets.\n   */\n  async function fetchAreaContentPlan(endpoint, bbox, areaId) {\n    if (!endpoint) return null;\n    // SNOW-1582: a failure is logged on the sync's run, under content-plan.\n    var url = endpoint + '?bbox=' + encodeURIComponent(bbox.join(','));\n    var meta = { logStage: 'content-plan', areaId: areaId };\n    var data = await fetchJson(url, meta);\n    if (!data) return null;\n    if (!Array.isArray(data.regions) || !Array.isArray(data.weather) || !Array.isArray(data.resorts)) {\n      runFetchFailed(meta, url, { status: meta.status, detail: 'shape' });\n      return null;\n    }\n    return data;\n  }\n\n  /**\n   * Ask the server for the reader's own things in one rectangle (SNOW-965).\n   *\n   * Through ``fetchJson`` and its bound, as ``fetchAreaContentPlan`` is.\n   *\n   * @param {string|undefined} endpoint The panel's ``data-area-items-url``.\n   * @param {number[]} bbox ``[west, south, east, north]``.\n   * @param {string} [areaId] SNOW-1582: as ``fetchAreaContentPlan``.\n   * @returns {Promise<{trips: Array<Object>, pins: Array<Object>}|null>}\n   *   ``null`` for a failed request or an answer that is not the\n   *   documented shape \u2014 \"cannot say\".\n   */\n  async function fetchAreaItems(endpoint, bbox, areaId) {\n    // SNOW-1308: `meta` collects the answer's `X-Snowdesk-Principal` \u2014\n    // whose things these are, as the server answered \u2014 for the stamp.\n    // SNOW-1582: and names the sync's run, for a failure's log line.\n    var url = endpoint + '?bbox=' + encodeURIComponent(bbox.join(','));\n    var meta = { logStage: 'content-plan', areaId: areaId };\n    var data = await fetchJson(url, meta);\n    if (!data) return null;\n    if (!Array.isArray(data.trips) || !Array.isArray(data.pins)) {\n      runFetchFailed(meta, url, { status: meta.status, detail: 'shape' });\n      return null;\n    }\n    return Object.assign({}, data, { attestedPrincipal: meta.principal || '' });\n  }\n\n  /**\n   * The days an area's content is taken for: today and forward only\n   * (SNOW-1312).\n   *\n   * The map's own window, from the same two pieces: the last day the\n   * season ratings carry (`pwaCalendarCore.latestKnownDate`, SNOW-927 \u2014\n   * calendar_core.js is loaded on `/offline/` for this) and the shared\n   * `pwaBasemapDownloadCore.forwardContentDays`. So an area updated from\n   * here holds the same days as one downloaded from the map: today's\n   * bulletin, tomorrow's once issued, and nothing from before today. The\n   * season feed is read through ``fetchJson``'s bound, and an answer that\n   * does not come back is \"today alone\" \u2014 the window the map falls back\n   * to as well.\n   *\n   * The ceiling is the latest day ANY content country has published \u2014\n   * the map merges every country into the season payload it reads\n   * (`loadCountryRatings`), so a forward day France has issued and\n   * Switzerland has not is still in its window, and must be here too.\n   *\n   * @param {Object} core ``pwaBasemapDownloadCore``.\n   * @param {string} today An ISO date key.\n   * @param {string} ratingsUrl The panel's ``data-ratings-url``.\n   * @param {string[]} countries The panel's content countries.\n   * @returns {Promise<string[]>} Date keys, oldest first.\n   */\n  async function contentDays(core, today, ratingsUrl, countries) {\n    var ceiling = today;\n    var calendar = self.pwaCalendarCore;\n    if (ratingsUrl && calendar && typeof calendar.latestKnownDate === 'function') {\n      var codes = countries && countries.length > 0 ? countries : ['ch'];\n      var seasons = await Promise.all(\n        codes.map(function (code) {\n          return fetchJson(ratingsUrl + '?country=' + encodeURIComponent(code));\n        }),\n      );\n      seasons.forEach(function (season) {\n        var latest = calendar.latestKnownDate(season, today) || today;\n        if (latest > ceiling) ceiling = latest;\n      });\n    }\n    var days =\n      typeof core.forwardContentDays === 'function'\n        ? core.forwardContentDays(today, ceiling, null)\n        : [];\n    return days.length > 0 ? days : [today];\n  }\n\n  // SNOW-1141 review: `shell` is optional run-wide state, `{ok?: boolean}`.\n  // `?sync=all` passes one object to every area so the map shell is warmed\n  // at most ONCE per run: the report it holds was taken before the run and\n  // keeps saying the app cannot open even after the first area warms it,\n  // so without this every later area refetched `/map/` over the very\n  // connection the reader is about to lose. The first attempt's outcome is\n  // reused, failed or not.\n  async function fetchAreaContent(root, areaId, report, shell, onStage) {\n    // SNOW-1582: a Sync from this page keeps its own log, as one from the\n    // map does \u2014 one entry, kind `sync`, with its content-plan and warm\n    // stages and every failed request. An id nothing on this device\n    // records was never downloaded, and is answered without a log.\n    var log = self.pwaDownloadRunLog || null;\n    var runLog = log && (await readAreaRecordById(areaId)) ? log : null;\n    var owns = !!runLog && runLog.begin(areaId, 'sync');\n    var complete = false;\n    try {\n      complete = await syncAreaContent(root, areaId, report, shell, onStage, runLog);\n      return complete;\n    } finally {\n      if (runLog && owns) {\n        try {\n          await runLog.end(areaId, complete ? 'ok' : 'failed');\n        } catch (_err) {\n          // Diagnostic only: the log never fails a sync.\n        }\n      } else if (runLog) {\n        runLog.leave(areaId);\n      }\n    }\n  }\n\n  /**\n   * The body of `fetchAreaContent`: fetch the plan, warm it, stamp the\n   * record. `runLog` is the run log when this sync keeps one, else null.\n   *\n   * @param {HTMLElement} root\n   * @param {string} areaId\n   * @param {Object|null} report\n   * @param {{ok?: boolean}|undefined} shell\n   * @param {Function|undefined} onStage\n   * @param {Object|null} runLog\n   * @returns {Promise<boolean>}\n   */\n  async function syncAreaContent(root, areaId, report, shell, onStage, runLog) {\n    var tell = typeof onStage === 'function' ? onStage : function () {};\n    // SNOW-1582: what the warm stage logs \u2014 every list this sync warms.\n    var warmed = { planned: 0, ok: 0, failed: 0, failures: [] };\n    function tally(urls, answer) {\n      warmed.planned += urls.length;\n      warmed.ok += (answer && answer.ok) || 0;\n      warmed.failed += answer ? answer.failed || 0 : urls.length;\n      if (answer && Array.isArray(answer.failures)) {\n        warmed.failures = warmed.failures.concat(answer.failures);\n      }\n    }\n    var core = self.pwaBasemapDownloadCore;\n    var warm = self.pwaWarmCache;\n    var data = (root && root.dataset) || {};\n    if (!core || typeof core.areaContentURLs !== 'function') return false;\n    if (typeof warm !== 'function' || !data.regionsUrl) return false;\n\n    var record = await readAreaRecordById(areaId);\n    var bbox = record ? core.areaBBox(record) : null;\n    if (!bbox) return false;\n\n    // The bulletin day, from the CLIENT's own clock. The rendered\n    // `data-today` is the server's date at render time and is the\n    // fallback for a clock that will not answer; where the two agree \u2014\n    // which is the ordinary case \u2014 nothing changes.\n    var day = localDay() || data.today || '';\n    if (!day) return false;\n    // SNOW-965: a weather sheet is dated with the SERVER's day instead \u2014\n    // the map's sheet asks with its rendered `data-today`, and the worker\n    // answers a sheet offline on an exact url only. Dated by this device's\n    // clock, a reader in another timezone or near midnight would warm\n    // sheets under a date the map never asks for.\n    var weatherDay = data.today || day;\n\n    // Step 1: the map shell, when the report just said it is not saved.\n    // Not per-area and not this control's subject, but an area's content\n    // is no use inside an app that will not open, and the reader pressing\n    // this is asking for the area to work.\n    var shellOk = true;\n    if (!appOpens(report)) {\n      if (shell && typeof shell.ok === 'boolean') {\n        shellOk = shell.ok;\n      } else {\n        var shellAnswer = await warm(['/map/']);\n        tally(['/map/'], shellAnswer);\n        shellOk = !!(shellAnswer && shellAnswer.ok > 0 && shellAnswer.failed === 0);\n        if (shell) shell.ok = shellOk;\n      }\n    }\n\n    // Step 2: the four overlay feeds, whole and unfiltered \u2014 the boundary\n    // decides what must VERIFY present, not what gets stored, and each is\n    // one small request. A feed with no URL is one this reader is not\n    // eligible for (favourites and routes need an account), which is not\n    // a failure.\n    var feedUrls = [\n      data.weatherUrl,\n      data.favouritesUrl,\n      data.routesUrl,\n      data.communityReportsUrl,\n    ].filter(Boolean);\n\n    // Step 3: the plan, from the one endpoint that answers for it.\n    // The country region feeds below are warmed, not read: the map needs\n    // those outlines offline, and a feed that fails to warm is already\n    // counted by `warm`'s own tally.\n    var countries = String(data.contentCountries || '')\n      .split(/\\s+/)\n      .filter(Boolean);\n    var regionUrls = countries.map(function (code) {\n      return data.regionsUrl + '?country=' + encodeURIComponent(code);\n    });\n    // SNOW-1312: and each country's season ratings, which the scrubber\n    // paints every day from \u2014 the map's download warms them with its\n    // feeds (`assembleBasemapDownloadFeedURLs`), so an Update from here\n    // warms them too. The dated per-day feeds come with the plan below.\n    var seasonRatingsUrls = data.ratingsUrl\n      ? countries.map(function (code) {\n          return data.ratingsUrl + '?country=' + encodeURIComponent(code);\n        })\n      : [];\n    // SNOW-1529: and each country's sub-levels, as the map's download warms\n    // them beside the ratings.\n    if (data.ratingSubdivisionsUrl) {\n      seasonRatingsUrls = seasonRatingsUrls.concat(\n        countries.map(function (code) {\n          return data.ratingSubdivisionsUrl + '?country=' + encodeURIComponent(code);\n        }),\n      );\n    }\n    // SNOW-965: the reader's own trips and pins, asked alongside. Signed\n    // out, the page renders no endpoint \u2014 nothing to ask, not a shortfall.\n    var itemsUrl = data.areaItemsUrl || '';\n    if (runLog) runLog.open(areaId, 'content-plan');\n    var answers = await Promise.all([\n      fetchAreaContentPlan(data.areaContentUrl, bbox, areaId),\n      itemsUrl ? fetchAreaItems(itemsUrl, bbox, areaId) : Promise.resolve(null),\n    ]);\n    var content = answers[0];\n    var items = answers[1];\n    // An endpoint that cannot be read is a short plan, never a\n    // confidently empty one: every url the warm does fetch can still\n    // land, so no tally over the list could tell that the area's\n    // bulletins \u2014 or the reader's trips \u2014 were never named.\n    var short = !content || (!!itemsUrl && !items);\n    if (runLog) {\n      await runLog.stage(areaId, 'content-plan', {\n        planned: itemsUrl ? 2 : 1,\n        ok: (content ? 1 : 0) + (itemsUrl && items ? 1 : 0),\n        reason: short ? 'short' : null,\n      });\n    }\n\n    var plan = core.areaContentURLs({\n      regions: (content && content.regions) || [],\n      weather: (content && content.weather) || [],\n      // SNOW-1318: each resort's place sheet per day, as the map's download.\n      resorts: (content && content.resorts) || [],\n      // SNOW-1312: today to the last published day, never before today\n      // \u2014 the map's own window (`contentDays`).\n      //\n      // Today itself is resolved at PRESS time, not read off the rendered\n      // attribute. `data-today` is the date the HTML was rendered on, and\n      // this page is warmed into the shell and reopened from cache \u2014 so\n      // on a tab left open across midnight, or a cached copy reconnecting\n      // the next morning, it names yesterday. The first cut warmed\n      // yesterday's bulletins and then stamped a completion with the\n      // current timestamp, after which the report called the area fresh\n      // with today's bulletins never saved.\n      days: await contentDays(core, day, data.ratingsUrl || '', countries),\n      weatherDetailTemplate: data.weatherDetailUrl || '',\n      // SNOW-965: dated, the url the map's sheet asks for today and the\n      // only one the worker answers offline \u2014 see `weatherDay` above.\n      weatherDay: weatherDay,\n      // SNOW-1312: the map's region sheet per region and day, and the\n      // dated ratings feed per day \u2014 composed by the same core the map's\n      // download uses, so the urls are the map's.\n      regionSheetTemplate: data.regionSheetUrl || '',\n      resortSheetTemplate: data.resortSheetUrl || '',\n      ratingsUrl: data.ratingsUrl || '',\n      // SNOW-1529: the dated sub-level feed per day, as the map's download.\n      subdivisionsUrl: data.ratingSubdivisionsUrl || '',\n      // SNOW-1379: the problem-terrain feed per day, for an area the map\n      // downloaded with terrain tiles \u2014 the record's own opt-in.\n      terrain: !!record.terrain,\n    });\n    var planned = plan.bulletinUrls\n      .concat(plan.regionSheetUrls || [])\n      .concat(plan.resortSheetUrls || [])\n      .concat(plan.ratingsUrls || [])\n      .concat(plan.subdivisionsUrls || [])\n      .concat(plan.problemTerrainUrls || [])\n      .concat(plan.weatherDetailUrls);\n    // SNOW-965: each trip's page and route, and the sheet each pin\n    // borrows \u2014 composed by the same core the map's download uses.\n    var itemTemplates = {\n      tripPage: data.tripPageUrlTemplate || '',\n      tripRoute: data.tripRouteUrlTemplate || '',\n      weatherDetail: data.weatherDetailUrl || '',\n      weatherDay: weatherDay,\n      // SNOW-1313: each pin's own place sheet, dated with the server's day\n      // as the weather sheet is \u2014 the day the map's place sheet asks with\n      // on boot.\n      favouriteSheet: data.favouriteSheetUrl || '',\n    };\n    var itemUrls =\n      items && typeof core.areaItemURLs === 'function'\n        ? core.areaItemURLs(items, itemTemplates, planned)\n        : [];\n    // SNOW-1308: the same things by name, for the stamp \u2014 the composition\n    // the map's own syncs stamp, so a panel names them whichever surface\n    // synced the area.\n    // SNOW-1308 review: stamped with the account the SERVER answered for\n    // (`X-Snowdesk-Principal`), and only where that is the account this\n    // page was rendered for \u2014 so another account's names are never shown\n    // back as this one's (`attestedExpectation`, `thingsStage`).\n    var expectation =\n      items &&\n      typeof core.areaItemExpectation === 'function' &&\n      typeof core.attestedExpectation === 'function'\n        ? core.attestedExpectation(\n            core.areaItemExpectation(items, itemTemplates),\n            items.attestedPrincipal,\n            sessionPrincipal(),\n          )\n        : null;\n    // SNOW-1379: and the problem-terrain days, every reader's, so the\n    // panel's Conditions stage can count them after a signed-out sync too.\n    if (typeof core.withProblemTerrain === 'function') {\n      expectation = core.withProblemTerrain(expectation, plan.problemTerrainUrls);\n    }\n\n    // SNOW-1415: warmed one stage at a time \u2014 bulletins and the sheets\n    // beside them, then the weather sheets, then the reader's own things \u2014\n    // so the connection panel can say which it is on. The three lists\n    // together are exactly the one list this used to warm in a single call.\n    var weatherUrls = plan.weatherDetailUrls || [];\n    var batches = [\n      {\n        stage: 'bulletins',\n        urls: regionUrls\n          .concat(seasonRatingsUrls)\n          .concat(feedUrls)\n          .concat(planned.slice(0, planned.length - weatherUrls.length)),\n      },\n      { stage: 'weather', urls: weatherUrls },\n      { stage: 'things', urls: itemUrls },\n    ].filter(function (batch) {\n      return batch.urls.length > 0;\n    });\n    if (batches.length === 0) return false;\n\n    var ok = 0;\n    var failed = 0;\n    if (runLog) runLog.open(areaId, 'warm');\n    for (var b = 0; b < batches.length; b += 1) {\n      tell(batches[b].stage);\n      var answer = await warm(batches[b].urls);\n      tally(batches[b].urls, answer);\n      ok += (answer && answer.ok) || 0;\n      failed += answer ? answer.failed || 0 : batches[b].urls.length;\n    }\n    if (runLog) await runLog.stage(areaId, 'warm', warmed);\n    var landed = ok > 0 && failed === 0;\n    var complete = shellOk && landed && !short;\n    await stampAreaContent(areaId, complete, expectation);\n    return complete;\n  }\n\n  /**\n   * The account this page was rendered for \u2014 base.html's `pwa-user-id`,\n   * the value `db.js` and the area records stamp with. `''` signed out.\n   *\n   * @returns {string}\n   */\n  function sessionPrincipal() {\n    try {\n      var meta = document.querySelector('meta[name=\"pwa-user-id\"]');\n      return (meta && meta.getAttribute('content')) || '';\n    } catch (_err) {\n      return '';\n    }\n  }\n\n  /**\n   * Whether the report says the app opens without a signal.\n   *\n   * @param {Object|null} report\n   * @returns {boolean}\n   */\n  function appOpens(report) {\n    if (!report || !Array.isArray(report.sections)) return false;\n    var found = false;\n    report.sections.forEach(function (section) {\n      section.checks.forEach(function (check) {\n        if (check.id === 'app-opens' && check.status === 'yes') found = true;\n      });\n    });\n    return found;\n  }\n\n  /**\n   * Read one area's stored record by its bucket id.\n   *\n   * Through ``window.pwaDb``, NOT this module's own IndexedDB reader. That\n   * reader is deliberately bounded, read-only and independent \u2014 a report\n   * whose job is to catch storage and the app disagreeing must not take\n   * the app's word for what storage holds. This is not a report read: it\n   * is the operation behind a control, and an operation that writes back\n   * has to read and write through the same surface the rest of the app\n   * does or the two will drift.\n   *\n   * @param {string} areaId\n   * @returns {Promise<Object|null>}\n   */\n  async function readAreaRecordById(areaId) {\n    try {\n      var db = self.pwaDb;\n      if (!db) return null;\n      var customRow = await db.get('meta:app', 'basemap.customAreas');\n      var custom = (customRow && customRow.value) || [];\n      if (Array.isArray(custom)) {\n        for (var i = 0; i < custom.length; i += 1) {\n          if (custom[i] && custom[i].id === areaId) return custom[i];\n        }\n      }\n      var regionRow = await db.get('meta:app', 'basemap.regions');\n      var regions = (regionRow && regionRow.value) || [];\n      if (Array.isArray(regions)) {\n        for (var j = 0; j < regions.length; j += 1) {\n          var entry = regions[j];\n          if (entry && 'region-' + entry.region_id === areaId) return entry;\n        }\n      }\n      return null;\n    } catch (_err) {\n      return null;\n    }\n  }\n\n  /**\n   * Move one area's content stamp, in whichever store holds it.\n   *\n   * The same field SNOW-924 writes from the map and SNOW-926 reads back \u2014\n   * one meaning, written by both entry points, so a refresh from here and\n   * a refresh from the map's roundel cannot leave the record saying\n   * different things. ``contentIncomplete`` is the durable half of that\n   * (SNOW-932), deleted on a completion rather than set false.\n   *\n   * @param {string} areaId\n   * @param {boolean} complete\n   * @param {Object|null} [expectation] SNOW-1308: the reader's own things\n   *   the sync expected (`areaItemExpectation`), stamped on success.\n   * @returns {Promise<void>} Best-effort: a failed stamp costs a stale\n   *   verdict on one panel, never the fetch that just landed.\n   */\n  async function stampAreaContent(areaId, complete, expectation) {\n    // SNOW-1308: the one stamping rule, shared with the map's region\n    // roundel and Manage downloads sheet \u2014 `contentAt` /\n    // `contentIncomplete`, and the reader's own things this sync expected.\n    var downloadCore = self.pwaBasemapDownloadCore;\n    await rewriteAreaRecord(areaId, function (entry) {\n      return downloadCore.stampContentRecord(entry, complete, expectation || null);\n    });\n  }\n\n  /**\n   * SNOW-1415: write what this page's panels read about one area onto its\n   * record (`verified`), so the connection panel on every other page can\n   * answer for it. The shape and merge rule are `offline_journey_core.js`'s.\n   *\n   * @param {string} areaId\n   * @param {Object|null} verified From `verifiedFromStages`.\n   * @returns {Promise<void>}\n   */\n  async function stampAreaVerified(areaId, verified) {\n    var journey = self.pwaOfflineJourneyCore;\n    if (!verified || !journey || typeof journey.stampVerifiedRecord !== 'function') return;\n    await rewriteAreaRecord(areaId, function (entry) {\n      return journey.stampVerifiedRecord(entry, verified);\n    });\n  }\n\n  /**\n   * Rewrite one area's record in its array, on one transaction.\n   *\n   * @param {string} areaId The bucket id.\n   * @param {function(Object): Object} apply Synchronous: it runs inside a\n   *   `readModifyWrite` mutator.\n   * @returns {Promise<void>} Best-effort.\n   */\n  async function rewriteAreaRecord(areaId, apply) {\n    try {\n      var db = self.pwaDb;\n      if (!db) return;\n      // SNOW-959: read and write on ONE transaction each. This page became\n      // the SECOND writer of these two rows in SNOW-950/953 \u2014 the map page\n      // was the first \u2014 and `/offline/` and the map are both SHELL_PAGES,\n      // so a user can hold them open in separate tabs. Each row is a whole\n      // ARRAY rewritten to change one entry, so a `get` followed later by a\n      // `put` meant the tab that wrote second silently discarded the\n      // other's stamp. IndexedDB serialises overlapping `readwrite`\n      // transactions across every connection, tabs included, so doing both\n      // halves on one transaction is the whole fix. `readModifyWrite`'s\n      // docstring has the mechanism; its one constraint is that `apply`\n      // and the mutators below stay synchronous.\n      //\n      // `undefined` from a mutator commits nothing, which is what each of\n      // the old early returns did.\n      var wroteCustom = false;\n      await db.readModifyWrite('meta:app', 'basemap.customAreas', function (row) {\n        var custom = (row && row.value) || [];\n        if (!Array.isArray(custom)) return undefined;\n        if (\n          !custom.some(function (area) {\n            return area && area.id === areaId;\n          })\n        ) {\n          return undefined;\n        }\n        wroteCustom = true;\n        return {\n          key: 'basemap.customAreas',\n          value: custom.map(function (area) {\n            return area && area.id === areaId ? apply(area) : area;\n          }),\n        };\n      });\n      if (wroteCustom) return;\n      await db.readModifyWrite('meta:app', 'basemap.regions', function (row) {\n        var regions = (row && row.value) || [];\n        if (!Array.isArray(regions)) return undefined;\n        var touched = false;\n        var next = regions.map(function (entry) {\n          if (!entry || 'region-' + entry.region_id !== areaId) return entry;\n          touched = true;\n          return apply(entry);\n        });\n        if (!touched) return undefined;\n        return { key: 'basemap.regions', value: next };\n      });\n    } catch (_err) {\n      // Best-effort, per the docstring.\n    }\n  }\n\n  /**\n   * Today, as this device reckons it \u2014 ``YYYY-MM-DD`` in local time.\n   *\n   * SNOW-925 review: the bulletin day cannot be read off the rendered\n   * ``data-today``. That is the date the HTML was rendered on, and this\n   * page is warmed into the shell and reopened from cache \u2014 so on a tab\n   * left open across midnight, or a cached copy reconnecting the next\n   * morning, the attribute names yesterday. Warming yesterday's bulletins\n   * and stamping a completion for it is the false green the whole report\n   * exists to prevent, one layer down.\n   *\n   * Local rather than UTC, because a bulletin belongs to a calendar day in\n   * the reader's own zone \u2014 the same rule ``areaContentState`` applies\n   * when it decides whether that content is stale.\n   *\n   * @returns {string} ``''`` when the clock will not answer, which leaves\n   *   the caller falling back to the rendered date.\n   */\n  function localDay() {\n    try {\n      var now = new Date();\n      if (Number.isNaN(now.getTime())) return '';\n      var month = String(now.getMonth() + 1).padStart(2, '0');\n      var date = String(now.getDate()).padStart(2, '0');\n      return now.getFullYear() + '-' + month + '-' + date;\n    } catch (_err) {\n      return '';\n    }\n  }\n\n  /**\n   * Fetch and parse one JSON document, or null.\n   *\n   * BOUNDED, and that is not decoration. Unlike `pwaWarmCache` \u2014 which the\n   * worker settles on its own budget \u2014 these preliminary requests had no\n   * timeout at all, so on a connection that stalls without rejecting (a\n   * captive portal, a lift) any one of them could stay pending for the\n   * browser's full network timeout. `completeArea` holds `running` true\n   * and the button disabled for the whole of it, and never reaches its\n   * failure message or the verification re-run: the panel simply sits\n   * there. A bound that expires reads as a feed that did not answer, which\n   * makes the plan short and the run report failure \u2014 the honest outcome,\n   * and the one every other read on this page already degrades to\n   * (SNOW-918).\n   *\n   * @param {string} url\n   * @param {{principal?: string}} [meta] SNOW-1308: filled with the\n   *   answer's `X-Snowdesk-Principal`, where the caller asks.\n   * @returns {Promise<Object|null>}\n   */\n  async function fetchJson(url, meta) {\n    var controller =\n      typeof AbortController === 'function' ? new AbortController() : null;\n    var timer = null;\n    try {\n      if (controller) {\n        timer = setTimeout(function () {\n          controller.abort();\n        }, MANIFEST_FETCH_BUDGET_MS);\n      }\n      var response = await fetch(url, controller ? { signal: controller.signal } : {});\n      if (meta) meta.status = response ? response.status : null;\n      if (!response || !response.ok) {\n        // SNOW-1582: a sync's plan requests name the run they belong to.\n        if (meta && meta.logStage) {\n          runFetchFailed(meta, url, { status: response ? response.status : null, detail: 'status' });\n        }\n        return null;\n      }\n      if (meta) {\n        // SNOW-1308: the viewer a private answer names (`attest_principal`).\n        try {\n          meta.principal =\n            (response.headers && response.headers.get('X-Snowdesk-Principal')) || '';\n        } catch (_err) {\n          meta.principal = '';\n        }\n      }\n      return await response.json();\n    } catch (err) {\n      if (meta && meta.logStage) {\n        var status = typeof meta.status === 'number' ? meta.status : null;\n        runFetchFailed(\n          meta,\n          url,\n          status === null ? { error: err } : { status: status, why: 'parse', detail: 'json' },\n        );\n      }\n      return null;\n    } finally {\n      if (timer !== null) clearTimeout(timer);\n    }\n  }\n\n  /**\n   * SNOW-1582: report one failed request to the download run log, for the\n   * run `meta.areaId` names. Diagnostic only: a page without the log\n   * (`static/offline.html`) or a log that throws changes nothing.\n   *\n   * @param {{logStage?: string, areaId?: string}} meta\n   * @param {string} url\n   * @param {Object} info `{status, why, detail, error}`.\n   * @returns {void}\n   */\n  function runFetchFailed(meta, url, info) {\n    try {\n      var log = self.pwaDownloadRunLog;\n      if (log) log.fetchFailed(meta.logStage, url, info, meta.areaId);\n    } catch (_err) {\n      // Diagnostic only.\n    }\n  }\n\n  async function collect(root) {\n    var budget = createBudget();\n    var panel = root || document.querySelector(ROOT_SELECTOR);\n    var swSupported = 'serviceWorker' in navigator;\n    var registration = null;\n    if (swSupported) {\n      registration = await bounded(\n        budget,\n        'serviceworker.registration',\n        function () {\n          return navigator.serviceWorker.getRegistration();\n        },\n        null,\n      );\n    }\n\n    var live = await liveShellCacheName();\n    var names = await bounded(budget, 'caches.keys', cacheNames, null);\n    // Null is \"could not be listed\", which is not the same finding as an\n    // empty Cache Storage and must not be reported as one \u2014 see\n    // `cacheNames`. Everything downstream reads the flag, not the array.\n    var cachesReadable = names !== null;\n    names = names || [];\n    var shellNames = live\n      ? [live]\n      : names.filter(function (name) {\n          return name.indexOf(SHELL_CACHE_PREFIX) === 0;\n        });\n    // The map is /map/ (the site root is the marketing homepage). Hard-coded\n    // rather than derived from the current location, because this panel is\n    // reached from two pages and neither of them is the one being asked about.\n    var mapPath = '/map/';\n    var shell = shellNames.length\n      ? await readShellEntries(shellNames, mapPath, budget)\n      : {\n          entries: [],\n          mapCopies: [],\n          complete: true,\n          pagesComplete: true,\n        };\n    if (!shell.complete) cachesReadable = false;\n    var shellEntries = shell.entries;\n\n    var db = await openDb(budget);\n    var currentPrincipal = db\n      ? await bounded(\n          budget,\n          'meta:mutations.principal',\n          function () {\n            return readMeta(db, 'mutations.principal');\n          },\n          null,\n        )\n      : null;\n    // The copy of the map page the app would open, chosen with the account\n    // just read \u2014 see `readMapPage`.\n    var mapPage = await readMapPage(\n      shell.mapCopies,\n      shellEntries,\n      mapPath,\n      typeof currentPrincipal === 'string' ? currentPrincipal : null,\n      budget,\n    );\n    if (mapPage.bodyUnread) shell.pagesComplete = false;\n    var areaRecords = await readAreaRecords(db, budget);\n    // SNOW-1138: and every pinned bucket no record accounts for, as the\n    // shared reader (`basemap_downloaded_areas.js`) lists them for the\n    // Manage downloads sheet. Read straight off the bucket names, not\n    // through that reader, for the reason the header gives.\n    areaRecords = areaRecords.concat(unrecordedBuckets(names, areaRecords));\n    var areas = [];\n    for (var i = 0; i < areaRecords.length; i += 1) {\n      var bucket = await readBucket(areaRecords[i].id, budget);\n      areas.push(\n        Object.assign({}, areaRecords[i], {\n          bucketPresent: bucket.present,\n          bucketReadable: bucket.readable,\n          entries: bucket.entries,\n          terrainTiles: expectedTerrainTiles(areaRecords[i], panel),\n          elevationTiles: expectedElevationTiles(areaRecords[i], panel),\n        }),\n      );\n    }\n\n    // SNOW-913: the style on screen, resolved before the browsing-cache\n    // read below needs it.\n    var current = selectedBasemap(panel, mapPage.mapBasemaps);\n    // SNOW-1058: and what the passive browsing cache holds for it, and for\n    // every basemap a download names \u2014 the same set the core makes rows\n    // for. The style URLs come off the cached map page's own picker.\n    var browsedKeys = (current ? [current] : []).concat(\n      areas\n        .map(function (area) {\n          return area.basemapKey;\n        })\n        .filter(Boolean),\n    );\n    var browsed = await readBrowsed(\n      browsedKeys,\n      mapPage.mapBasemaps && mapPage.mapBasemaps.urls ? mapPage.mapBasemaps.urls : {},\n      budget,\n    );\n\n    // The orphans by id, for the copied report's context. They are rows in\n    // `areas` too since SNOW-1138; this was computed and never shown.\n    var orphanBuckets = areas\n      .filter(function (area) {\n        return area.orphaned;\n      })\n      .map(function (area) {\n        return area.id;\n      });\n\n    var stores = {};\n    if (db) {\n      for (var j = 0; j < DATA_STORES.length; j += 1) {\n        stores[DATA_STORES[j]] = await boundedStore(budget, db, DATA_STORES[j]);\n      }\n    }\n    // SNOW-914/915: the ROWS, not their keys. \"Is there a weather row\" and\n    // \"will the weather show\" turned out to be different questions \u2014 a row\n    // stamped for another account is refused by the reader, and a row\n    // holding an empty FeatureCollection draws nothing.\n    var overlays = db\n      ? await bounded(\n          budget,\n          'store:data:map_overlays',\n          function () {\n            return readOverlayRows(db, 'data:map_overlays');\n          },\n          {},\n        )\n      : {};\n    var panelRows = db\n      ? await bounded(\n          budget,\n          'store:data:panel_rows',\n          function () {\n            return readPanelRows(db, 'data:panel_rows');\n          },\n          {},\n        )\n      : {};\n    var mutations = db ? await boundedStore(budget, db, 'queue:mutations') : null;\n    // SNOW-1582: each download's own log, for the panels' Last download\n    // and the copied report's downloads section.\n    var downloadRuns = db\n      ? await bounded(\n          budget,\n          'store:log:download_runs',\n          function () {\n            return readDownloadRuns(db);\n          },\n          null,\n        )\n      : null;\n    var networkMode = db\n      ? await bounded(\n          budget,\n          'meta:network.mode',\n          function () {\n            return readMeta(db, 'network.mode');\n          },\n          null,\n        )\n      : null;\n    if (db) {\n      try {\n        db.close();\n      } catch (_err) {\n        // Non-fatal.\n      }\n    }\n\n    // `storage.estimate()` walks every origin-scoped store to add up the\n    // bytes, so on a device holding 200 MB of tiles it is the single\n    // slowest reading here \u2014 and it answers no row, only the copied\n    // report's context. Bounded like the rest, and the last thing read,\n    // so an overrun costs nothing anyone is looking at.\n    var storage = await bounded(\n      budget,\n      'storage.estimate',\n      async function () {\n        if (!navigator.storage || typeof navigator.storage.estimate !== 'function') {\n          return null;\n        }\n        var estimate = await navigator.storage.estimate();\n        if (typeof navigator.storage.persisted !== 'function') return estimate;\n        return Object.assign({}, estimate, {\n          persisted: await navigator.storage.persisted(),\n        });\n      },\n      null,\n    );\n\n    return {\n      now: new Date().toISOString(),\n      online: navigator.onLine !== false,\n      networkMode: typeof networkMode === 'string' ? networkMode : null,\n      serviceWorker: {\n        supported: swSupported,\n        registered: !!registration,\n        controlled: swSupported && !!navigator.serviceWorker.controller,\n        waiting: !!(registration && registration.waiting),\n      },\n      storage: storage,\n      shellCacheNames: shellNames,\n      shellEntries: shellEntries,\n      // SNOW-912: what the cached map page itself boots from, or null when\n      // there is no page to read. The core verifies \"The app opens\"\n      // against this rather than against a count of cached scripts.\n      mapDependencies: mapPage.mapDependencies,\n      // SNOW-914: the day the cached page will boot on \u2014 its own\n      // ``data-today``, not this device's clock. The ratings it asks the\n      // cache for are that day's.\n      mapDay: mapPage.mapDay,\n      // SNOW-913: the style on screen. The basemap rows are otherwise a\n      // roll-up of what the device has STORED, which is a different\n      // question from the one the reader is asking.\n      selectedBasemap: current,\n      currentPrincipal: typeof currentPrincipal === 'string' ? currentPrincipal : null,\n      mapPath: mapPath,\n      areas: areas,\n      // SNOW-1058: what the map can draw from the passive browsing cache,\n      // per basemap. `null` is a read that did not come back.\n      browsed: browsed,\n      // Whether Cache Storage answered at all. The rows about the saved\n      // page, the bulletins and the boot feeds are all read out of it, and\n      // a device that could not be asked has not been checked \u2014 see\n      // `cacheNames`.\n      cachesReadable: cachesReadable,\n      // The narrower of the two: the listing is good, but a page's stamp\n      // or its body did not come back. Costs the rows that need a page\n      // opened, and leaves the ones answered from URLs alone.\n      shellPartial: !shell.pagesComplete,\n      orphanBuckets: orphanBuckets,\n      stores: stores,\n      // SNOW-914/915: the rows, not their keys \u2014 whether each overlay is\n      // readable by this account and whether it has anything in it.\n      overlays: overlays,\n      panelRows: panelRows,\n      mutations: { count: mutations },\n      // SNOW-1582: every download's log, newest entries included.\n      downloadRuns: downloadRuns,\n      dbAvailable: !!db,\n      // What could not be read, and whether the run gave up part way. The\n      // report states this rather than quietly reporting a half-read\n      // device as a whole one, and `reportText` carries the list off the\n      // phone \u2014 which on a device with no devtools is the only place this\n      // information will ever exist.\n      degraded: budget.timedOut.length\n        ? { timedOut: budget.timedOut.slice(), latched: budget.latched }\n        : null,\n    };\n  }\n\n  /**\n   * Can the map page be opened offline, right now, by whoever is signed\n   * in on this device?\n   *\n   * The narrow version of the report's ``app-opens`` row, for a caller\n   * that needs one boolean and cannot afford a whole report.\n   * ``static/offline.html`` is that caller: it is a dead end that tells\n   * its reader \"the interactive map is the one part of Snowdesk built to\n   * work offline\" and then offers no way to reach it. Someone whose map\n   * IS saved \u2014 the exact person the sentence is addressed to \u2014 was being\n   * shown a wall with a Retry button that cannot work without a signal.\n   *\n   * A handful of bounded reads rather than ``collect``'s twenty-odd: the\n   * shell caches, the map entry in one of them, its principal stamp, and\n   * the account signed in now. Same rule as everything else here \u2014 a\n   * reading that does not come back means false, because offering a link\n   * that lands the reader back on this page is worse than not offering\n   * one.\n   *\n   * It deliberately does NOT check the page's scripts the way the report\n   * does. This gates a LINK, not a claim: a page that half-loads is still\n   * a better answer than a dead end, and the report is one press away for\n   * anyone who wants the full picture.\n   *\n   * @returns {Promise<boolean>}\n   */\n  async function canOpenMap() {\n    var core = self.pwaOfflineAuditCore;\n    if (!core || !self.caches || typeof self.caches.open !== 'function') return false;\n    var budget = createBudget();\n    var live = await liveShellCacheName();\n    var names = await bounded(budget, 'caches.keys', cacheNames, null);\n    var shellNames = live\n      ? [live]\n      : (names || []).filter(function (name) {\n          return name.indexOf(SHELL_CACHE_PREFIX) === 0;\n        });\n    if (!shellNames.length) return false;\n\n    var db = await openDb(budget);\n    var stored = db\n      ? await bounded(\n          budget,\n          'meta:mutations.principal',\n          function () {\n            return readMeta(db, 'mutations.principal');\n          },\n          null,\n        )\n      : null;\n    if (db) {\n      try {\n        db.close();\n      } catch (_err) {\n        // Non-fatal.\n      }\n    }\n    var currentPrincipal = typeof stored === 'string' ? stored : null;\n\n    var mapUrl = self.location.origin + '/map/';\n    for (var i = 0; i < shellNames.length; i += 1) {\n      var cache = await bounded(\n        budget,\n        'caches.open',\n        (function (name) {\n          return function () {\n            return self.caches.open(name);\n          };\n        })(shellNames[i]),\n        null,\n      );\n      if (!cache) continue;\n      var response = await bounded(\n        budget,\n        'shell.match',\n        (function (target) {\n          return function () {\n            return target.match(mapUrl);\n          };\n        })(cache),\n        null,\n      );\n      if (!response) continue;\n      var principal = null;\n      try {\n        principal = response.headers.get('X-SW-Principal');\n      } catch (_err) {\n        principal = null;\n      }\n      // The worker's own rule, borrowed rather than restated: an entry\n      // stamped for another account is one `_networkFirstFallback`\n      // refuses, so a link to it would land right back here.\n      if (core.principalMatches(principal, currentPrincipal)) return true;\n    }\n    return false;\n  }\n\n  /**\n   * One log row: label, answer. Never more.\n   *\n   * Two cells and no third, which is what stops per-row explanation\n   * growing back. ``data-audit-row`` is the handle the reveal uses to\n   * find this row again once its answer is known.\n   *\n   * SNOW-1308: the third cell SNOW-925 added \u2014 the per-area Sync now \u2014\n   * went with the download rows to the `/offline/` panels.\n   *\n   * @param {Object} check\n   * @param {Document} doc\n   * @returns {HTMLElement}\n   */\n  function renderRow(check, doc) {\n    var row = doc.createElement('li');\n    row.setAttribute('data-audit-check', '');\n    row.setAttribute('data-audit-row', check.id);\n    row.setAttribute('data-audit-status', check.status);\n\n    var label = doc.createElement('span');\n    label.setAttribute('data-audit-label', '');\n    label.textContent = check.label;\n    // The label is the one field with no length bound, and the row must\n    // stay one line \u2014 so CSS truncates and the full text goes in the title.\n    label.title = check.label;\n\n    var value = doc.createElement('span');\n    value.setAttribute('data-audit-value', '');\n    value.textContent = check.value;\n\n    row.appendChild(label);\n    row.appendChild(value);\n    return row;\n  }\n\n  /**\n   * Paint the log \u2014 every section, every row \u2014 with whatever answers the\n   * report carries.\n   *\n   * Called once with the answers blanked and once, implicitly, as each\n   * one arrives: the DOM built here is what ``revealRow`` updates in\n   * place, so the row list never changes shape mid-build.\n   *\n   * @param {HTMLElement} target\n   * @param {Object} report\n   */\n  function renderLog(target, report) {\n    var doc = target.ownerDocument;\n    target.textContent = '';\n    var log = doc.createElement('div');\n    log.setAttribute('data-audit-log', '');\n    report.sections.forEach(function (section) {\n      if (section.checks.length === 0) return;\n      var el = doc.createElement('section');\n      el.setAttribute('data-audit-section', '');\n      var heading = doc.createElement('h3');\n      heading.textContent = section.title;\n      el.appendChild(heading);\n      var list = doc.createElement('ol');\n      section.checks.forEach(function (check) {\n        list.appendChild(renderRow(check, doc));\n      });\n      el.appendChild(list);\n      log.appendChild(el);\n    });\n    target.appendChild(log);\n  }\n\n  /**\n   * Fill one row's answer into the row already on screen.\n   *\n   * @param {HTMLElement} target\n   * @param {Object} check\n   */\n  function revealRow(target, check) {\n    var row = target.querySelector('[data-audit-row=\"' + cssEscape(check.id) + '\"]');\n    if (!row) return;\n    row.setAttribute('data-audit-status', check.status);\n    var value = row.querySelector('[data-audit-value]');\n    if (value) value.textContent = check.value;\n  }\n\n  /**\n   * Whether this panel's host can fetch anything at all (SNOW-925).\n   *\n   * The endpoints Sync now needs are rendered onto the panel root by a\n   * Django view. ``static/offline.html`` has no server to render\n   * them \u2014 and no connection either, which is the whole reason that page\n   * exists \u2014 so a control there would offer a fetch that cannot arrive.\n   * One endpoint stands for all of them: they are written together or not\n   * at all.\n   *\n   * @param {HTMLElement} target The panel root, or anything inside it.\n   * @returns {boolean}\n   */\n  function hostCanFetch(target) {\n    var host = target && target.closest ? target.closest('[data-offline-audit]') : null;\n    return !!(host && host.dataset && host.dataset.regionsUrl);\n  }\n\n  /**\n   * Quote a row id for use inside an attribute selector.\n   *\n   * Area rows are keyed ``area:region-CH-4115``, and a colon in a\n   * selector is a pseudo-class. ``CSS.escape`` where the browser has it,\n   * a backslash before every non-word character otherwise \u2014 this runs on\n   * the offline page, which is the one surface with no polyfills at all.\n   *\n   * @param {string} value\n   * @returns {string}\n   */\n  function cssEscape(value) {\n    if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {\n      return CSS.escape(value);\n    }\n    return String(value).replace(/[^\\w-]/g, '\\\\$&');\n  }\n\n  /**\n   * The summary and the count, appended under the finished log.\n   *\n   * @param {HTMLElement} target\n   * @param {Object} report\n   * @param {Record<string, string>} t\n   */\n  function renderSummary(target, report, t) {\n    var doc = target.ownerDocument;\n    var summary = doc.createElement('div');\n    summary.setAttribute('data-audit-summary', '');\n    summary.setAttribute('data-audit-status', report.verdict.status);\n    var verdict = doc.createElement('p');\n    verdict.setAttribute('data-audit-verdict', '');\n    verdict.textContent = report.verdict.text;\n    summary.appendChild(verdict);\n    if (report.summary) {\n      var detail = doc.createElement('p');\n      detail.setAttribute('data-audit-detail', '');\n      detail.textContent = report.summary;\n      summary.appendChild(detail);\n    }\n    target.appendChild(summary);\n\n    var counts = doc.createElement('p');\n    counts.setAttribute('data-audit-counts', '');\n    // \"11 of 12 available offline\" under \"this device is not set up for\n    // offline use\" is the tally contradicting the verdict directly above\n    // it. Every one of those eleven is CONDITIONAL on the thing that just\n    // failed \u2014 the data is there and none of it is reachable \u2014 so a\n    // blocked device gets a line that says exactly that instead.\n    var key = report.verdict.status === 'fail' ? 'counts-line-blocked' : 'counts-line';\n    counts.textContent = String(t[key] || FALLBACKS[key])\n      .replace('%(yes)s', String(report.counts.yes))\n      .replace('%(total)s', String(report.counts.total));\n    target.appendChild(counts);\n  }\n\n  /**\n   * Paint a finished report in one go, no build.\n   *\n   * The reduced-motion path, and the one the tests drive: the reveal is\n   * decoration over a report that is complete before it starts, so\n   * skipping it loses nothing.\n   *\n   * @param {HTMLElement} target\n   * @param {Object} report\n   * @param {Record<string, string>} t\n   */\n  function render(target, report, t) {\n    renderLog(target, report);\n    if (!report.pending) renderSummary(target, report, t);\n  }\n\n  /**\n   * Whether this device has asked for less animation.\n   *\n   * @returns {boolean}\n   */\n  function prefersReducedMotion() {\n    try {\n      return !!(\n        self.matchMedia && self.matchMedia('(prefers-reduced-motion: reduce)').matches\n      );\n    } catch (_err) {\n      return false;\n    }\n  }\n\n  /**\n   * Wait, as a promise.\n   *\n   * @param {number} ms\n   * @returns {Promise<void>}\n   */\n  function wait(ms) {\n    return new Promise(function (resolve) {\n      setTimeout(resolve, ms);\n    });\n  }\n\n  /**\n   * Paint the log unanswered, then fill each answer in on a fixed\n   * cadence, then the summary.\n   *\n   * The order matters: the whole list of questions is on screen before\n   * the first answer lands, so the reader sees what is being asked rather\n   * than watching rows appear out of nothing. Every reading was taken\n   * before this was called.\n   *\n   * @param {HTMLElement} target\n   * @param {Object} report\n   * @param {Record<string, string>} t\n   * @returns {Promise<void>}\n   */\n  async function build(target, report, t) {\n    if (prefersReducedMotion()) {\n      render(target, report, t);\n      return;\n    }\n    var blanked = {\n      sections: report.sections.map(function (section) {\n        return {\n          id: section.id,\n          title: section.title,\n          checks: section.checks.map(function (check) {\n            return {\n              id: check.id,\n              label: check.label,\n              value: t['answer-pending'] || FALLBACKS['answer-pending'],\n              status: 'pending',\n            };\n          }),\n        };\n      }),\n    };\n    renderLog(target, blanked);\n    for (var i = 0; i < report.sections.length; i += 1) {\n      var checks = report.sections[i].checks;\n      for (var j = 0; j < checks.length; j += 1) {\n        await wait(ROW_INTERVAL_MS);\n        revealRow(target, checks[j]);\n      }\n    }\n    renderSummary(target, report, t);\n  }\n\n  /**\n   * SNOW-951: the area the URL asks this page to bring up to date, taken\n   * once and removed from the address bar in the same breath.\n   *\n   * The network menu's \"Get ready for offline\" (SNOW-1141; per-area until\n   * then) runs in place on the map page, where\n   * `pwaBasemapDownloads.syncArea` exists, and NAVIGATES here with\n   * `?sync=all` everywhere else \u2014 `basemap_download_core.js` is 140KB of map-and-this-\n   * page-only code, there is no lazy-script precedent in the tree, and the\n   * two content-fetch implementations genuinely differ (day range, which\n   * feeds), so a third copy of the stamp rule is exactly what this avoids.\n   * The param is the whole handover.\n   *\n   * The removal is `replaceState` rather than a flag, which buys two\n   * things from one call: a reload does not re-run a fetch the user asked\n   * for once, and a second bound host on the same page finds nothing left\n   * to take.\n   *\n   * @returns {string} The requested id, `'all'`, or `''`. An id is either\n   *   an area id as minted (`region-CH-4115`, `custom-a1`) or a bare region id \u2014 see\n   *   `syncRequestedArea` for why both are accepted and why resolving\n   *   between them happens here rather than in the menu.\n   */\n  function takeRequestedSyncArea() {\n    var search = self.location ? self.location.search : '';\n    if (!search) return '';\n    var requested = '';\n    try {\n      requested = new URLSearchParams(search).get('sync') || '';\n    } catch (_err) {\n      // A URL this runtime will not parse is not an instruction.\n      return '';\n    }\n    if (!requested) return '';\n    try {\n      var url = new URL(self.location.href);\n      url.searchParams.delete('sync');\n      self.history.replaceState(null, '', url.pathname + url.search + url.hash);\n    } catch (_err) {\n      // Best-effort: a browser that refuses the rewrite costs a repeated\n      // fetch on reload, which is wasteful rather than wrong.\n    }\n    return requested;\n  }\n\n  /**\n   * Bind one host's markup.\n   *\n   * Every control is optional. The offline page carries no Save button\n   * (there is nothing to save without a connection) and a host that omits\n   * Copy simply has no Copy.\n   *\n   * @param {HTMLElement} root\n   */\n  function bind(root) {\n    var t = strings();\n    var output = root.querySelector('[data-offline-audit-output]');\n    var runButton = root.querySelector('[data-offline-audit-run]');\n    var copyButton = root.querySelector('[data-offline-audit-copy]');\n    var saveButton = root.querySelector('[data-offline-audit-save]');\n    var statusEl = root.querySelector('[data-offline-audit-status]');\n    if (!output) return;\n\n    var lastReport = null;\n    // SNOW-1308: the readings the last run or read collected, shared with\n    // the `/offline/` panels (`offline_journey.js`) \u2014 one storage walk\n    // answers both the report and the panels.\n    var lastReadings = null;\n    // SNOW-1308: whether this page was opened with `?sync=all`, so a\n    // panel's \"tap to fix\" runs the whole \"Get ready for offline\" rather\n    // than one area.\n    var syncAllRequested = false;\n    // One run at a time. Two interleaved collections paint the same\n    // output element, and the loser's reveal finishes last \u2014 so a second\n    // press part way through the first run could leave rows answered from\n    // a report the summary underneath them did not come from.\n    var running = false;\n\n    var say = function (message) {\n      if (statusEl) statusEl.textContent = message || '';\n    };\n\n    /**\n     * SNOW-1308: hand the readings to whoever paints from them \u2014 the\n     * panels \u2014 with what they need to offer controls. An event rather than\n     * a call, because the panels are a separate module that may not be on\n     * the page at all.\n     */\n    var publish = function () {\n      var detail = latest();\n      try {\n        root.ownerDocument.dispatchEvent(\n          new CustomEvent('snowdesk:offline-readings', { detail: detail }),\n        );\n      } catch (_err) {\n        // A host with no CustomEvent has no panels to tell.\n      }\n    };\n\n    var latest = function () {\n      return {\n        root: root,\n        readings: lastReadings,\n        report: lastReport,\n        canFetch: hostCanFetch(root),\n        syncAllRequested: syncAllRequested,\n        running: running,\n      };\n    };\n\n    var collectSafely = async function () {\n      try {\n        return await collect(root);\n      } catch (err) {\n        // A report that cannot be taken is itself a finding, and it gets\n        // painted like any other.\n        return { now: new Date().toISOString(), failure: describeError(err) };\n      }\n    };\n\n    // SNOW-1308: the read `refresh` is taking, if one is. A press on Run\n    // the check during it waits for it rather than being dropped.\n    var reading = null;\n\n    var run = async function () {\n      if (reading) await reading;\n      if (running) return;\n      running = true;\n      try {\n        await runOnce();\n      } finally {\n        running = false;\n      }\n      publish();\n      drainQueued();\n    };\n\n    // SNOW-1308 review: a refresh asked for while something else holds\n    // `running` (a run, a Sync now, a read) is QUEUED, not dropped \u2014 a\n    // Remove pressed mid-run must still end in a repaint from storage. At\n    // most one is held; every caller asking meanwhile shares it.\n    var queued = null;\n    var resolveQueued = null;\n    var drainQueued = function () {\n      if (!queued || running) return;\n      var resolve = resolveQueued;\n      queued = null;\n      resolveQueued = null;\n      refreshNow().then(resolve, resolve);\n    };\n\n    /**\n     * SNOW-1308: take the readings and hand them to the panels without\n     * painting the report \u2014 what the page does on load, so every area's\n     * panel is answered before anyone presses Run the check. A report\n     * already on screen is re-run instead, so it never sits answering from\n     * readings older than the panels above it.\n     */\n    var refresh = function () {\n      if (running) {\n        if (!queued) {\n          queued = new Promise(function (resolve) {\n            resolveQueued = resolve;\n          });\n        }\n        return queued;\n      }\n      return refreshNow();\n    };\n\n    var refreshNow = async function () {\n      if (!output.hidden) {\n        await run();\n        return;\n      }\n      running = true;\n      reading = (async function () {\n        try {\n          lastReadings = await collectSafely();\n        } finally {\n          running = false;\n          reading = null;\n        }\n      })();\n      await reading;\n      publish();\n      drainQueued();\n    };\n\n    var runOnce = async function () {\n      var core = self.pwaOfflineAuditCore;\n      if (!core) {\n        // The core is precached separately from this file (AUDIT_SCRIPTS,\n        // sw.js) and either can be the one a device is missing. Say so\n        // rather than throwing on the first property read and leaving the\n        // button looking broken.\n        say(t['check-failed'] || FALLBACKS['check-failed']);\n        return;\n      }\n      say(t.running || FALLBACKS.running);\n      // The fixed questions, unanswered, before anything is read.\n      output.hidden = false;\n      renderLog(output, core.pendingReport(t));\n\n      // Nothing below this point may leave the status line reading\n      // \"Checking\u2026\". Every reading is already bounded, so a hang cannot\n      // get here \u2014 but a THROW could, and did nothing visible when it\n      // did: `run()` is called unawaited from a click handler, so a\n      // rejection became an unhandled promise nobody on a phone can see,\n      // and the panel sat on its skeleton for ever.\n      var readings = await collectSafely();\n      lastReadings = readings;\n\n      try {\n        lastReport = core.buildReport(readings, t);\n        try {\n          logReport(lastReport);\n        } catch (_logErr) {\n          // The trace must never cost the report.\n        }\n        output.hidden = false;\n        await build(output, lastReport, t);\n      } catch (err) {\n        // The collector came back and the renderer did not. Fall back to\n        // the report with no reveal \u2014 `render` is the same paint without\n        // the animation \u2014 and if even that fails there is nothing left to\n        // try but the status line.\n        try {\n          lastReport = core.buildReport(\n            { now: new Date().toISOString(), failure: describeError(err) },\n            t,\n          );\n          render(output, lastReport, t);\n        } catch (_err2) {\n          lastReport = null;\n        }\n      }\n\n      // The status line carries only what the report itself cannot: that\n      // it is a report about a failure.\n      say(readings.failure ? t['check-failed'] || FALLBACKS['check-failed'] : '');\n\n      // Copy is offered for any report at all, including a failed one.\n      // That is the whole escape route from a phone with no devtools: the\n      // run that went wrong is exactly the one worth sending in.\n      if (copyButton) copyButton.hidden = !lastReport;\n      if (saveButton) {\n        // Offered only when it could actually work, and only when it is\n        // the thing that would help: a controlled page, a connection, and\n        // a map page that is not already saved for this account.\n        //\n        // The id and the status are the core's, not this module's\n        // vocabulary. Both were once invented here \u2014 a row called\n        // `map-page` and a status of `ok`, neither of which the core has\n        // ever produced \u2014 so the lookup found nothing and the control was\n        // hidden on every device. The real names are `app-opens` and the\n        // AuditStatus union, whose pass value is `yes`.\n        //\n        // Every failing state, with no exceptions \u2014 SNOW-912 made the warm\n        // repair every one of them.\n        var pageCheck = null;\n        if (lastReport) {\n          lastReport.sections.forEach(function (section) {\n            section.checks.forEach(function (check) {\n              if (check.id === 'app-opens') pageCheck = check;\n            });\n          });\n        }\n        saveButton.hidden = !(\n          readings.online &&\n          readings.serviceWorker &&\n          readings.serviceWorker.controlled &&\n          pageCheck &&\n          pageCheck.status !== 'yes'\n        );\n      }\n    };\n\n    if (runButton) {\n      runButton.addEventListener('click', function () {\n        run();\n      });\n    }\n\n    if (copyButton) {\n      copyButton.addEventListener('click', async function () {\n        if (!lastReport) return;\n        var text = reportTextFor(lastReport);\n        try {\n          await navigator.clipboard.writeText(text);\n          say(t.copied || FALLBACKS.copied);\n        } catch (_err) {\n          say(t['copy-failed'] || FALLBACKS['copy-failed']);\n        }\n      });\n    }\n\n    /**\n     * Whether this host can run Sync now for one area, by the readings it\n     * last took (SNOW-925's gate, read here since SNOW-1308 moved the\n     * control onto the panels).\n     *\n     * @param {string} areaId\n     * @returns {boolean}\n     */\n    var syncable = function (areaId) {\n      var core = self.pwaOfflineAuditCore;\n      if (!core || !lastReadings || !hostCanFetch(root)) return false;\n      return core.chosenAreas(lastReadings).some(function (area) {\n        return area.id === areaId && core.completableArea(area, lastReadings.now);\n      });\n    };\n\n    /**\n     * Fetch everything this page can fetch for one area, then re-check it.\n     *\n     * The payload behind each panel's Sync now (SNOW-925; on the panels\n     * since SNOW-1308). The order is cheapest first, and the last step is\n     * the point: storage is re-read and the panels repainted from what is\n     * there. Nothing else on the site claims a download succeeded without\n     * verifying it, and this is not going to be the first thing that does.\n     *\n     *   1. the map shell, if the report just said it is not saved;\n     *   2. the four overlay feeds, whole and unfiltered;\n     *   3. the bulletins and weather sheets inside THIS area's boundary,\n     *      and the reader's own things in it.\n     *\n     * What it deliberately does NOT do is fetch tiles. The tile half needs\n     * the loaded basemap style, which exists only on the map \u2014 so an area\n     * whose tiles do not verify is not offered this at all\n     * (`completableArea`), and its panel names the map instead.\n     *\n     * @param {string} areaId\n     * @returns {Promise<boolean>} Whether it ran and everything landed.\n     */\n    async function completeArea(areaId) {\n      if (running || !syncable(areaId)) return false;\n      running = true;\n      publish();\n      say(t.completing || FALLBACKS.completing);\n      var ok = false;\n      try {\n        ok = await fetchAreaContent(root, areaId, lastReport || reportFor(lastReadings));\n      } catch (_err) {\n        ok = false;\n      }\n      say(\n        ok\n          ? t['completed'] || FALLBACKS['completed']\n          : t['complete-failed'] || FALLBACKS['complete-failed'],\n      );\n      running = false;\n      // Always, success or not: a run that half landed has still changed\n      // what is on disk, and the panels must say what is true now rather\n      // than what they said before the press.\n      await refresh();\n      return ok;\n    }\n\n    /**\n     * The report for a set of readings, built without painting \u2014 what\n     * `fetchAreaContent` reads its `app-opens` row from when Sync now is\n     * pressed before anyone ran the check.\n     *\n     * @param {Object|null} readings\n     * @returns {Object|null}\n     */\n    function reportFor(readings) {\n      var core = self.pwaOfflineAuditCore;\n      if (!core || !readings) return null;\n      try {\n        return core.buildReport(readings, t);\n      } catch (_err) {\n        return null;\n      }\n    }\n\n    /**\n     * SNOW-951: run the report, then update the area the URL named.\n     *\n     * The report FIRST: it is what the page answers with either way. If\n     * the area can be updated, Sync now runs and the panels re-read\n     * storage; if it cannot \u2014 its tiles do not verify \u2014 its panel names\n     * the remedy instead of a press that silently did nothing.\n     *\n     * Both id forms resolve HERE: the bucket id as minted, or a bare region\n     * id through `pwaBasemapDownloadCore.areaIdForRegion`, which owns the\n     * bucket-id format. The value is a URL parameter, so it is compared,\n     * never interpolated into a selector.\n     *\n     * @param {string} requested The `?sync=` value.\n     * @returns {Promise<void>}\n     */\n    async function syncRequestedArea(requested) {\n      if (requested === 'all') {\n        await syncAllAreas();\n        return;\n      }\n      await run();\n      var core = self.pwaBasemapDownloadCore;\n      var candidates = [requested];\n      if (core && typeof core.areaIdForRegion === 'function') {\n        candidates.push(core.areaIdForRegion(requested));\n      }\n      for (var i = 0; i < candidates.length; i += 1) {\n        if (syncable(candidates[i])) {\n          await completeArea(candidates[i]);\n          return;\n        }\n      }\n    }\n\n    /**\n     * SNOW-1141: `?sync=all` \u2014 the network menu's \"Get ready for offline\",\n     * run here because this page is not the map.\n     *\n     * The SAME runner as the menu's (`offline_ready_core.js`): the queue\n     * drains first, then every downloaded area in turn. What differs is\n     * only what \"one area\" means on this page \u2014 its own content fetch\n     * (`fetchAreaContent`, as Sync now uses), and nothing at all for an\n     * area whose tiles do not verify: this page cannot mend tiles, so such\n     * an area counts as not ready.\n     *\n     * The report runs FIRST, to learn which areas there are, and the\n     * readings are taken AGAIN LAST, which is the proof. The outcome line\n     * goes in the status line after that.\n     *\n     * @returns {Promise<void>}\n     */\n    async function syncAllAreas() {\n      syncAllRequested = true;\n      await run();\n      var ready = self.pwaOfflineReadyCore;\n      var core = self.pwaOfflineAuditCore;\n      if (!ready || !core || !lastReadings || running) return;\n      var areas = core.chosenAreas(lastReadings).map(function (area) {\n        return area.id;\n      });\n      var fetchable = {};\n      areas.forEach(function (id) {\n        if (syncable(id)) fetchable[id] = true;\n      });\n      var report = lastReport || reportFor(lastReadings);\n      var shell = {};\n      running = true;\n      publish();\n      var result;\n      try {\n        result = await ready.run({\n          drain: function () {\n            var queue = self.pwaMutationQueue;\n            return queue && typeof queue.drain === 'function' ? queue.drain() : undefined;\n          },\n          waiting: async function () {\n            var db = self.pwaDb;\n            if (!db || typeof db.getAll !== 'function') return 0;\n            return ready.waitingCount(await db.getAll('queue:mutations'));\n          },\n          areas: areas,\n          syncOne: async function (areaId, onStage) {\n            if (!Object.prototype.hasOwnProperty.call(fetchable, areaId)) return 'partial';\n            return (await fetchAreaContent(root, areaId, report, shell, onStage))\n              ? 'ready'\n              : 'partial';\n          },\n          onStep: function (step) {\n            say(ready.progressText(step, t));\n          },\n        });\n      } finally {\n        running = false;\n      }\n      await refresh();\n      var described = ready.describe(result, t);\n      say([described.summary, described.queue].filter(Boolean).join(' \u00B7 '));\n    }\n\n    if (saveButton) {\n      saveButton.addEventListener('click', async function () {\n        say(t.saving || FALLBACKS.saving);\n        saveButton.disabled = true;\n        try {\n          // The worker's own warm path, not a `fetch` from here. SNOW-624\n          // made it stamp a same-origin HTML response with the principal\n          // its body declares \u2014 which is the whole reason the entry will\n          // be servable offline.\n          var result =\n            typeof self.pwaWarmCache === 'function'\n              ? await self.pwaWarmCache(['/map/'])\n              : null;\n          if (result && result.ok > 0 && result.failed === 0) {\n            say(t.saved || FALLBACKS.saved);\n            await run();\n          } else {\n            say(t['save-failed'] || FALLBACKS['save-failed']);\n          }\n        } catch (_err) {\n          say(t['save-failed'] || FALLBACKS['save-failed']);\n        } finally {\n          saveButton.disabled = false;\n        }\n      });\n    }\n\n    controllers.push({\n      root: root,\n      latest: latest,\n      refresh: refresh,\n      syncArea: completeArea,\n      syncAll: syncAllAreas,\n    });\n\n    // SNOW-951/1141: the handover from the network menu on a page that is\n    // not the map \u2014 one area by id, or `all` for \"Get ready for offline\".\n    // Last in `bind`, because it runs the report and everything above it\n    // has to be listening by then.\n    var requestedSync = takeRequestedSyncArea();\n    if (requestedSync === 'all') syncAllRequested = true;\n    if (requestedSync) syncRequestedArea(requestedSync);\n  }\n\n  // SNOW-1308: one controller per bound host, for the panels to ask.\n  var controllers = [];\n\n  /**\n   * The controller for one host, or the first on the page.\n   *\n   * @param {HTMLElement} [root]\n   * @returns {Object|null}\n   */\n  function controllerFor(root) {\n    // The most recent binding first, and only one still in the document:\n    // a host that was replaced (a re-render, a test) must not answer for\n    // the one on the page now.\n    for (var i = controllers.length - 1; i >= 0; i -= 1) {\n      var c = controllers[i];\n      if (root ? c.root === root : c.root.isConnected !== false) return c;\n    }\n    return null;\n  }\n\n\n  /**\n   * The account this page was rendered for, from its ``pwa-user-id`` meta.\n   *\n   * @returns {string} The uuid, or ``''`` when signed out or absent.\n   */\n  function pageUser() {\n    var meta = document.querySelector('meta[name=\"pwa-user-id\"]');\n    return (meta && meta.getAttribute('content')) || '';\n  }\n\n  /**\n   * Write each row that is not Yes to the debug log, with its reason.\n   *\n   * The check used to leave no trace there, so a recorded session showed\n   * the page loading and nothing about why \"The app opens\" said No. One\n   * line per such row, and only while recording is on.\n   *\n   * @param {*} report\n   * @returns {void}\n   */\n  function logReport(report) {\n    var log = window.pwaDebugLog;\n    var core = self.pwaOfflineAuditCore;\n    if (!log || !log.on || !core || !report || !Array.isArray(report.sections)) return;\n    report.sections.forEach(function (/** @type {*} */ section) {\n      (section.checks || []).forEach(function (/** @type {*} */ check) {\n        if (check.status === 'yes') return;\n        log.record('cache', 'audit.row', {\n          id: check.id,\n          status: check.status,\n          reason: check.reason || null,\n          missing: core.missingLine(check.missing) || null,\n          stamped: check.stamped || null,\n          current: check.current || null,\n          // What this page was rendered for, beside what the device has\n          // recorded: a gap between them is a stale record, not a stale page.\n          page: check.stamped ? core.shortPrincipal(pageUser() || 'anonymous') : null,\n        });\n      });\n    });\n  }\n\n  /**\n   * One line naming what went wrong, for the failure report.\n   *\n   * It reaches the reader only through Copy, so it is for whoever is sent\n   * the report rather than for the person holding the phone \u2014 which is\n   * why it is the raw message and not a translated sentence.\n   *\n   * @param {*} err\n   * @returns {string}\n   */\n  function describeError(err) {\n    if (!err) return 'unknown error';\n    if (err.name && err.message) return err.name + ': ' + err.message;\n    return String(err.message || err);\n  }\n\n  /**\n   * The deployed app version, for a copied report.\n   *\n   * @returns {string} Empty where the meta tag is absent \u2014 the offline\n   *   page carries none.\n   */\n  function appVersion() {\n    var meta = document.querySelector('meta[name=\"pwa-app-version\"]');\n    return (meta && meta.getAttribute('content')) || '';\n  }\n\n  /**\n   * The text a copied report carries: the report, and the page, browser and\n   * build it was taken on. One helper for /offline/'s Copy button and for\n   * `copyReport`, so the two copies cannot drift (SNOW-1488).\n   *\n   * @param {Object} report `pwaOfflineAuditCore.buildReport`'s answer.\n   * @returns {string}\n   */\n  function reportTextFor(report) {\n    return self.pwaOfflineAuditCore.reportText(report, {\n      url: self.location ? self.location.href : '',\n      userAgent: navigator.userAgent,\n      appVersion: appVersion(),\n    });\n  }\n\n  /**\n   * SNOW-1488: take the report and put it on the clipboard, from a page\n   * with no audit panel \u2014 the map's Downloads sheet, whose \"\u2026\" menu is how\n   * a reader of the installed app (no address bar) reaches the report.\n   *\n   * Collected against `host`, which carries the same inputs `/offline/`'s\n   * `[data-offline-audit]` does (includes/_offline_audit_host_attrs.html),\n   * so the copy holds the same checks. A collection that throws is copied\n   * as the failure report /offline/ paints for it, since a report that\n   * could not be taken is itself the finding.\n   *\n   * Its words come from `strings()`: the map renders no audit strings\n   * template, so they are the English fallbacks there, and the copy is a\n   * diagnostic for whoever it is sent to rather than a surface.\n   *\n   * The clipboard is asked before the report is taken. Collecting crosses\n   * the service worker, Cache Storage and IndexedDB, and WebKit drops the\n   * tap's user activation across those, refusing a write made afterwards\n   * (https://bugs.webkit.org/show_bug.cgi?id=222262). So where\n   * `ClipboardItem` exists, `clipboard.write` is called within the tap with\n   * an item whose text is a promise the collection resolves. Elsewhere the\n   * text is written once taken, as /offline/'s button does.\n   *\n   * Call it from the click handler, before any `await`.\n   *\n   * @param {HTMLElement|null} host\n   * @returns {Promise<boolean>} Whether the clipboard took it.\n   */\n  function copyReport(host) {\n    var core = self.pwaOfflineAuditCore;\n    if (!core) return Promise.resolve(false);\n    var text = collect(host)\n      .catch(function (err) {\n        return { now: new Date().toISOString(), failure: describeError(err) };\n      })\n      .then(function (readings) {\n        return reportTextFor(core.buildReport(readings, strings()));\n      });\n    var clipboard = navigator.clipboard;\n    var written;\n    try {\n      if (typeof ClipboardItem === 'function' && clipboard && typeof clipboard.write === 'function') {\n        var item = new ClipboardItem({\n          'text/plain': text.then(function (value) {\n            return new Blob([value], { type: 'text/plain' });\n          }),\n        });\n        written = clipboard.write([item]);\n      } else {\n        written = text.then(function (value) {\n          return clipboard.writeText(value);\n        });\n      }\n    } catch (_err) {\n      return Promise.resolve(false);\n    }\n    return Promise.resolve(written).then(\n      function () {\n        return true;\n      },\n      function () {\n        return false;\n      },\n    );\n  }\n\n  /**\n   * Bind every host present on this page.\n   *\n   * @returns {void}\n   */\n  function init() {\n    var roots = document.querySelectorAll(ROOT_SELECTOR);\n    for (var i = 0; i < roots.length; i += 1) {\n      bind(/** @type {HTMLElement} */ (roots[i]));\n    }\n  }\n\n  self.pwaOfflineAudit = Object.freeze({\n    canOpenMap: canOpenMap,\n    collect: collect,\n    render: render,\n    build: build,\n    init: init,\n    // SNOW-1308: the `/offline/` panels read the same collection the\n    // report does, and act through the same Sync now and re-read. Each\n    // takes an optional host root and defaults to the first on the page.\n    // `latest` answers `{root, readings, report, canFetch,\n    // syncAllRequested, running}` (readings null until the first read);\n    // every change is also announced as `snowdesk:offline-readings` on the\n    // document, carrying the same object.\n    // SNOW-1415: the panels stamp what they read on each record, so the\n    // connection panel can answer on pages that cannot read tiles.\n    stampVerified: stampAreaVerified,\n    // SNOW-1488: the Downloads sheet's Copy report; see `copyReport`.\n    copyReport: copyReport,\n    latest: function (root) {\n      var c = controllerFor(root);\n      return c ? c.latest() : null;\n    },\n    refresh: function (root) {\n      var c = controllerFor(root);\n      return c ? c.refresh() : Promise.resolve();\n    },\n    syncArea: function (areaId, root) {\n      var c = controllerFor(root);\n      return c ? c.syncArea(areaId) : Promise.resolve(false);\n    },\n    syncAll: function (root) {\n      var c = controllerFor(root);\n      return c ? c.syncAll() : Promise.resolve();\n    },\n  });\n\n  if (document.readyState === 'loading') {\n    document.addEventListener('DOMContentLoaded', init);\n  } else {\n    init();\n  }\n})();\n"],
  "mappings": "CA8FC,UAAY,CACX,aAEA,IAAIA,GAAgB,uBAChBC,GAAqB,kBACrBC,EAAsB,2BAMtBC,GAAwB,sBACxBC,GAAU,kBAKVC,EAAc,CAChB,kBACA,oBACA,iBACF,EAOIC,GAAmB,KAUnBC,GAA2B,KAM3BC,GAAkB,GAqBlBC,GAAiB,IAMjBC,GAAoB,IAQpBC,GAAuB,EAS3B,SAASC,IAAe,CACtB,MAAO,CACL,SAAU,KAAK,IAAI,EAAIF,GACvB,SAAU,CAAC,EACX,YAAa,EACb,QAAS,EACX,CACF,CAUA,SAASG,GAAcC,EAAQC,EAAO,CAChCD,EAAO,SAAS,QAAQC,CAAK,EAAI,GAAGD,EAAO,SAAS,KAAKC,CAAK,EAClED,EAAO,aAAe,EAClBA,EAAO,aAAeH,KAAsBG,EAAO,QAAU,GACnE,CAuBA,SAASE,EAAQF,EAAQC,EAAOE,EAAMC,EAAU,CAC9C,GAAIJ,EAAO,SAAW,KAAK,IAAI,GAAKA,EAAO,SACzC,OAAAD,GAAcC,EAAQC,CAAK,EACpB,QAAQ,QAAQG,CAAQ,EAEjC,IAAIC,EACJ,GAAI,CACFA,EAAUF,EAAK,CACjB,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IX", "PINNED_CACHE_PREFIX", "PASSIVE_BASEMAP_CACHE", "DB_NAME", "DATA_STORES", "VERSION_PROBE_MS", "MANIFEST_FETCH_BUDGET_MS", "ROW_INTERVAL_MS", "READ_BUDGET_MS", "COLLECT_BUDGET_MS", "READ_LATCH_THRESHOLD", "createBudget", "recordOverrun", "budget", "label", "bounded", "work", "fallback", "promise", "remaining", "resolve", "settled", "timer", "finish", "value", "_err", "FALLBACKS", "strings", "cacheNames", "liveShellCacheName", "controller", "onMessage", "event", "looksLikePage", "url", "core", "BASEMAP_STORAGE_KEY", "selectedBasemap", "root", "catalogue", "stored", "serverDefault", "isMapPage", "mapPath", "readShellEntries", "names", "entries", "mapCopies", "complete", "pagesComplete", "i", "cache", "name", "requests", "target", "j", "isPage", "principal", "scopedCore", "scoped", "stampUnread", "response", "request", "readMapPage", "copies", "currentPrincipal", "none", "chosen", "copy", "html", "openDb", "present", "found", "entry", "db", "readMeta", "key", "countStore", "boundedStore", "readOverlayRows", "rows", "row", "features", "countPanelRows", "body", "parsed", "RUN_STALE_AFTER_MS", "readDownloadRuns", "runCore", "nowIso", "nowMs", "beat", "readPanelRows", "readBucket", "areaId", "unreadable", "has", "readBrowsed", "keys", "styleUrls", "result", "asked", "index", "all", "passiveUrls", "readJson", "unparsedIsMiss", "styleUrl", "style", "tileJsons", "unread", "sources", "ids", "source", "absolute", "tileJson", "readAreaRecords", "areas", "meta", "regions", "record", "custom", "baseLayers", "unrecordedBuckets", "records", "recorded", "area", "out", "id", "expectedTerrainTiles", "panel", "terrain", "template", "expectedElevationTiles", "fetchAreaContentPlan", "endpoint", "bbox", "data", "fetchJson", "runFetchFailed", "fetchAreaItems", "contentDays", "today", "ratingsUrl", "countries", "ceiling", "calendar", "codes", "seasons", "code", "season", "latest", "days", "fetchAreaContent", "report", "shell", "onStage", "log", "runLog", "readAreaRecordById", "owns", "syncAreaContent", "tell", "warmed", "tally", "urls", "answer", "warm", "day", "localDay", "weatherDay", "shellOk", "appOpens", "shellAnswer", "feedUrls", "regionUrls", "seasonRatingsUrls", "itemsUrl", "answers", "content", "items", "short", "plan", "planned", "itemTemplates", "itemUrls", "expectation", "sessionPrincipal", "weatherUrls", "batches", "batch", "ok", "failed", "b", "landed", "stampAreaContent", "section", "check", "customRow", "regionRow", "downloadCore", "rewriteAreaRecord", "stampAreaVerified", "verified", "journey", "apply", "wroteCustom", "touched", "next", "now", "month", "date", "err", "status", "info", "collect", "swSupported", "registration", "live", "cachesReadable", "shellNames", "shellEntries", "mapPage", "areaRecords", "bucket", "current", "browsedKeys", "browsed", "orphanBuckets", "stores", "overlays", "panelRows", "mutations", "downloadRuns", "networkMode", "storage", "estimate", "canOpenMap", "mapUrl", "renderRow", "doc", "renderLog", "el", "heading", "list", "revealRow", "cssEscape", "hostCanFetch", "host", "renderSummary", "t", "summary", "verdict", "detail", "counts", "render", "prefersReducedMotion", "wait", "ms", "build", "blanked", "checks", "takeRequestedSyncArea", "search", "requested", "bind", "output", "runButton", "copyButton", "saveButton", "statusEl", "lastReport", "lastReadings", "syncAllRequested", "running", "say", "message", "publish", "collectSafely", "describeError", "reading", "run", "runOnce", "drainQueued", "queued", "resolveQueued", "refreshNow", "refresh", "readings", "logReport", "pageCheck", "text", "reportTextFor", "syncable", "completeArea", "reportFor", "syncRequestedArea", "syncAllAreas", "candidates", "ready", "fetchable", "queue", "step", "described", "controllers", "requestedSync", "controllerFor", "c", "pageUser", "appVersion", "copyReport", "clipboard", "written", "item", "init", "roots"]
}
