sw 0.4.0
sw: ^0.4.0 copied to clipboard
Generates a service worker and a bootstrap script for a Flutter Web build: per-category caching with integrity checks, a loading screen with real progress, and deploys that land as one coherent build.
0.4.0 — 2026-11-11 #
Added #
- Bootstrap:
data-configtakes astringsobject, so a page can say what the loading screen says — it was English literals with no way to change them, andwindow.updateLoadingProgressonly exists once Dart is running, which is after all of it. Keys:starting,environment,worker,update,engine,app,resources(with{done}and{total}),initializing,running,failed,offline,reload,reset. Audit #30, item 5.1. (packages/sw/src/shared/strings.ts) - Generator:
--log-level(alsolog-level:insw.yamlandSW_LOG_LEVEL) decides how much the generatedsw.jsandbootstrap.jsprint on the browser console:silent,error,warnorinfo(everything, the default and what every earlier release did). The level is baked into both artifacts, and a page can override it per deployment withdata-config='{"logLevel":"warn"}'. Everyconsolecall in both bundles goes through one gate, sosilentreally is silent; nothing else about either artifact changes with the level. Requested in #38. (packages/sw/src/shared/logger.ts,lib/src/config.dart,lib/src/injector.dart,lib/src/generator.dart,README.md,docs/configuration.md,docs/bootstrap-pipeline.md)
Fixed #
-
Service Worker: every deploy downloaded the whole pre-cached set again, including a
main.dart.wasmthat had not changed — a content cache is named after its version, so each new version started from an empty one and the manifest diff always ran against nothing. The manifest cache now records the version its manifest belongs to, and an install copies out of that version's content cache every Core and Required file whose hash and size are unchanged, downloading only the rest. An assets-only deploy costs the assets. Audit #30, item 2.1. (packages/sw/src/sw/cache-manager.ts,packages/sw/src/sw/install-handler.ts) -
Service Worker: an install that failed deleted everything it had downloaded, so the retry on the next page load started the whole pre-cache again — on a flaky connection and a 30 MB
main.dart.wasm, an install that never finishes. The temp cache is kept, and the retry skips an entry that is already there and carrying this entry's hash, which every stored copy records in anx-sw-hashheader (so a build deployed twice under one pinned--version, which shares a temp cache name with the previous one, is re-fetched even where the file's length did not change). The hash is all that is compared: a copy only carries it once it was stored whole, and comparingContent-Lengthtoo rejected every copy from a host that compresses, where that header counts encoded bytes or is absent. Running out of storage is the exception: the temp cache is dropped and the entries not yet downloaded are skipped, instead of a device at its quota re-downloading the whole build on every page load forever. Audit #30, item 1.4. (packages/sw/src/sw/install-handler.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker: the temp → content swap held every pre-cached byte of the app twice for its whole duration, which on Safari's quota is how activate failed with
QuotaExceededErrorfor a wasm app. It now movesSWAP_CONCURRENCY(4) entries at a time and frees each one as soon as it is copied, so at most four exist in both caches at once. A worker that dies mid-swap leaves the moved entries in the content cache and the rest in the temp one;cacheFirstfetches what the content cache is missing on demand. Audit #30, item 1.5. (packages/sw/src/sw/cache-manager.ts,packages/sw/src/shared/constants.ts) -
Service Worker: a swap that ran out of storage then dropped this version's content cache as well, leaving the app loading entirely from the network on every load — on the device with the least room to spare. A
QuotaExceededErrornow keeps what was swapped (whole, size-checked copies) and drops only the temp cache, which holds the duplicates that filled the quota;cacheFirstfetches the rest on demand. Any other failure still starts the version over. Audit #30, item 1.5. (packages/sw/src/sw/activate-handler.ts) -
Service Worker: a navigation waited up to ~33 s (three attempts of a 10 s fetch plus backoff) before the app shell that was already in the cache answered it, with the user watching a blank page. A navigation is now one attempt, and with a cached shell in hand it falls back after
NAVIGATION_TIMEOUT_MS(3 s) — the deadline races the navigation preload as well as the worker's ownfetch, and sinceactivateenables preload, the preload is what it is usually racing; without one it waits as long as the network takes, exactly as a page with no worker would; an answer that arrives after the deadline still refreshes the cached shell in the background, waited for at mostLATE_SHELL_TIMEOUT_MS(30 s): WebKit never settles the preload of a navigation the worker already answered, and an unbounded wait kept the worker busy for good, so a newer build stayedwaitingwith every tab closed until Safari killed the worker and failed a navigation with "Service Worker context closed". It is also no longer passed throughfetchWithRetry, which built a newRequestand so downgraded a navigation's mode fromnavigatetosame-origin— the origin seesSec-Fetch-Mode: navigateagain, and a same-origin 3xx arrives as the opaque redirect the browser must follow. Audit #30, item 1.7. (packages/sw/src/sw/fetch-handler.ts,packages/sw/src/shared/constants.ts) -
Bootstrap: the loading widget showed its "reset cache and reload" overlay 30 s into a perfectly healthy download whenever no worker was serving the page — a first visit whose activation did not land in time, a failed registration, Firefox's private mode, iOS Lockdown Mode. Nothing reports progress to such a page, so the ring sits still for the whole
main.dart.wasmdownload, and on a slow link the reset threw that download away and started it again. The threshold for a load nothing reports on is now 120 s; while this build's worker is installing and reporting, it is 30 s. Audit #30, item 1.8. (packages/sw/src/bootstrap/loading-widget.ts,packages/sw/src/bootstrap/pipeline.ts,packages/sw/src/shared/constants.ts) -
Service Worker: the first load after a deploy ran the previous build's
main.dart.js.index.htmlandbootstrap.jscame from the new build (both network-first, neither ever cached), while the worker still in control answered the entry point from its own cache — the previous build's code inside the new build's page, until the next load handed over to the new worker. A worker whose registration holds an installing or waiting worker now fetches the pre-cached set (Core and Required) from the network instead, asking for the URL the page asked for rather than its own?v={hash}, which on a CDN that keys on the whole URL would return the copy being replaced. Lazily cached files are still served from the cache — a tab open since before the deploy keeps its fonts and images — until the load has taken the new build's code; from then on they come from the network too, since the new code beside the previous build's icon font or translations is missing glyphs and keys. The pre-cached copy still answers when the network cannot (an error, an HTML page from a host that rewrites unknown paths to the shell), with a warning, because old code still boots — and once one code file had to come from it, the rest of the load's code does too. Either way a load runs one build: the new build'smain.dart.mjsbeside the previous build'smain.dart.wasmfails withWebAssembly.instantiate(): Import #N. Reported in #40. (packages/sw/src/sw/fetch-handler.ts,packages/sw/src/sw/registration.ts) -
Service Worker:
Cache write failed for main.dart.js: BodySizeMismatchErroron the first load after a deploy. The same worker was storing the new build's bytes under its own manifest's size for that file, which the body size check refuses — correctly, and then said so on every load. A retired worker no longer writes its version's cache at all, lazily cached files and the app shell included — a changed font or image failed the same check and was reported to the page as a worker failure: the new shell next to the previous build's code is the one pair that cannot boot, and the new worker's install stores the matching one. Reported in #36. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker:
The service worker navigation preload request was cancelled before 'preloadResponse' settledon navigations the worker does not answer — a host-reserved path (__/*, where Firebase Auth lives), orsw.jsandbootstrap.jstyped into the address bar. The browser had already started a preload fetch for them, and a fetch event that ends without consumingpreloadResponsethrows that response away and logs it. Those navigations are now answered with the preload response itself, or with the request on the network — no retries, no cache, no shell fallback, which is what leaving them alone was meant to be. Reported in #37. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: an error from the origin on a navigation was swapped for the cached app shell everywhere. A file the app links to (
/report.pdf) now keeps the origin's own error page, as it already did when the origin was slow; so does a navigation with no shell cached, which got a plain-textOffline503 instead of the page the origin sent. A401or407always reaches the browser: answering it with the shell hid the credentials prompt of a site behind HTTP auth, and the app then failed onbootstrap.jswith no way to log in. (packages/sw/src/sw/fetch-handler.ts) -
Bootstrap: the resource counter stopped at whatever install had reported, and a healthy load warned
No sw-progress from v…; every message came from v…. Thesw-progresslistener was torn down whenflutter.loader.load()resolved, which flutter.js does as soon as the entry point is fetched — it runsonEntrypointLoadedafter that, so every file the engine loads next is reported later still. The listener now stays up until the app's first frame. The warning itself also only fires when the worker still in control is from another build (the shape it was written for: abootstrap.jsserved from the HTTP cache), not when a handover during the load explains the foreign messages. Reported in #39. (packages/sw/src/bootstrap/pipeline.ts,packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap: the loading widget's animated ellipsis turned into a column of dots stacked above the status message. The dots are a
::afterwhose width thesw-dotskeyframes sweep from0to1.5em, and the box inheritsoverflow-wrap: anywherefrom.sw-status— so for the half of every cycle the width stayed under the width of..., the three dots wrapped onto three lines inside it. The box grew three lines tall andvertical-align: bottomhung the extra two above the message. It affected every viewport and every message, which is why it read as a flicker rather than a layout bug. The dots now carrywhite-space: pre. (packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap: the same keyframes shifted the whole splash screen once per cycle. Animating
widthchanges the dots' footprint, so on a line the message nearly filled they moved onto a line of their own and back, taking the percentage below them with them. The animation now clips a fixed-width box withclip-pathinstead; the insets match the widths it used to sweep, so it looks the same and no longer reflows. (packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap: a long status message on a short viewport (a phone held in landscape, roughly 320 px of height) overflowed the centred column in both directions, and the part above the top edge could not be reached.
#sw-loadingnow has a 24/16 px gutter,justify-content: safe centerandoverflow-y: auto, and amax-height: 480pxquery trims the logo, title and spacing so the usual messages fit without scrolling at all. (packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap: a title longer than the viewport ran off both edges —
.sw-titlehad neither a width bound nor a wrapping rule. It now wraps like the status text. (packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap: the progress ring's glow was cut off in a straight line beside and above the ring. The arc carries a
drop-shadow, which reaches past the ring's<svg>, and an outer<svg>clips to its viewport by default. It now hasoverflow: visible. (packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap: the
strings.initializingandstrings.runningoverrides were ignored; the last two stages said their English defaults whatever the page asked for. (packages/sw/src/bootstrap/flutter-loader.ts,packages/sw/src/bootstrap/pipeline.ts) -
Bootstrap: on Safari before 15.4, which has no
Object.hasOwn, the resource counter threw on every message and a page with anystringsoverride did not start at all. (packages/sw/src/shared/strings.ts) -
Bootstrap: a
colorwith an unclosed parenthesis, a quote or a backslash —rgb(37, 211, 102— swallowed the rest of the widget's stylesheet, and the hidden reload button showed as a raw grey button. Such a colour falls back to the default, as one with;or}already did. (packages/sw/src/bootstrap/config.ts) -
Bootstrap: the error screen still looked like a load in progress: the ellipsis kept animating, the stall timer of the last update still fired, and a late progress call still printed progress lines to the console. (
packages/sw/src/bootstrap/loading-widget.ts,packages/sw/src/bootstrap/api.ts) -
Bootstrap: a failure of the app itself — Dart's
mainthrowing before the first frame — never reached the error screen, which sat at "Starting application" until the stall overlay. It is now reported like an engine that fails to start. (packages/sw/src/bootstrap/flutter-loader.ts) -
Bootstrap: the hidden reload button took keyboard focus, with an invisible focus ring, and Enter reloaded the page mid-download; screen readers listed it too. It is
visibility: hiddenuntil shown. (packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap:
data-configthat is valid JSON but not an object (null, a number) stopped the whole bootstrap; it now falls back to the defaults, as invalid JSON did. Abootstrap.jsincluded twice ran two pipelines and two loading screens; the second copy now does nothing. (packages/sw/src/bootstrap/config.ts,packages/sw/src/bootstrap/index.ts) -
Bootstrap:
.sw-statuswas bounded by90vw, which counts the scrollbar on a desktop browser and left the gutter uneven. It is now bounded by the padded root, and by40remso the line length stays readable on a wide screen. (packages/sw/src/bootstrap/loading-widget.ts) -
CI: the E2E job's browser install hit its 5-minute budget and failed the job with nothing wrong in the code — three engines are around 500 MB of download. They are now cached per Playwright version (the revisions are pinned by it), and the step has 15 minutes for a cache miss. (
.github/workflows/checkout.yml) -
CI: the E2E job failed at random, in Firefox and WebKit, waiting 30 s for a service worker that never took control. The specs were served by
python3 -m http.server, which answers one request at a time: a browser that opens a speculative connection without sending a request on it blocks the server until that socket times out, and whatever the worker was fetching stalls with it. The suite now starts a small Node server (packages/sw/e2e/support/serve.mjs) that answers concurrently — which also makes the suite runnable on Windows, wherepython3is not on PATH. (packages/sw/playwright.config.ts,packages/sw/e2e/support/serve.mjs,docs/testing.md) -
Generator:
_flutter.buildConfigwas extracted with a lazy\{[\s\S]*?\}\s*;, which stops at the first}followed by a;. Today's Flutter output happens not to contain one inside the object, but a string value with};in it, or a release that writesObject.freeze({…}), would have made it silently return the wrong text. It is now found by a string-aware brace scan that also sees through a wrapper call. Audit #30, item 3.7. (lib/src/flutter_build.dart) -
Generator: cleanup pruned
canvaskit/webparagraph/, which Flutter 3.47 ships and an app built with the WebParagraph text layout loads. It is kept now, when the build has it, like the other engine variants. Audit #30, item 3.7. (lib/src/generator.dart) -
Generator:
--ignore="*.png"quietly covered only the top level of the build —*does not cross/inpackage:glob, unlike a.gitignoreline. Such a pattern still matches what it always did, and now says so, naming the**/*.pngform. The documentation says it too. Audit #30, item 3.6. (lib/src/config.dart,README.md,docs/configuration.md) -
Bootstrap: a failed load showed the user the engine's own words (
WebAssembly.instantiate(): Import #3 "…"), which tell them nothing, and the only button cleared a cache that was probably fine — throwing away a download they had already paid for. The screen now shows a sentence they can act on, the raw reason goes to the console and toBootstrap.progress.detail, and the button reloads on its first click and clears the caching layer only on the next one. When the browser reports no connection it says that instead, because no reload will help until it is back. Audit #30, item 5.2. (packages/sw/src/bootstrap/loading-widget.ts,packages/sw/src/bootstrap/pipeline.ts,packages/sw/src/bootstrap/api.ts) -
Bootstrap:
subscribeconsumers had no way to learn that loading failed — the phase stayed wherever the pipeline stopped. There is aphase: 'error'now, with the reason indetail, and aBootstrap.onError(handler)beside it. Audit #30, item 5.2. (packages/sw/src/shared/types.ts,packages/sw/src/bootstrap/api.ts) -
Bootstrap: the accent colour was painted as text as given, so the default
#25D366title on the widget's own light background was about 1.9:1 and the error red about 3.3:1, where WCAG asks 4.5:1. Text colours are now darkened or lightened until they pass (3:1 for the reload button's icon), keeping the hue.rgb()and the short hex forms are understood as well as#rrggbb. Audit #30, item 5.1. (packages/sw/src/bootstrap/color.ts,packages/sw/src/bootstrap/loading-widget.ts) -
Service Worker: a failed install, a cache swap that failed or ran out of storage, and a refused cache write were logged inside the worker and nowhere else, so neither the page nor whatever collects its errors could know the caching layer had given up. They now broadcast a structured
sw-lifecyclemessage (phase,status,reason,isQuota), which the bootstrap re-dispatches as asw-lifecycleevent onwindowand hands toBootstrap.onWorkerFailurehandlers. A newgetStatusmessage answers with the app's caches and their sizes,navigator.storage.estimate()and the last failure — for a page that loaded after it and has no broadcast to catch. Audit #30, item 6.1. (packages/sw/src/sw/lifecycle.ts,packages/sw/src/sw/message-handler.ts,packages/sw/src/bootstrap/sw-registration.ts) -
Service Worker: the cache-hit path awaited a
clients.matchAllround trip and a broadcast to every open tab before answering — for every font and image on every load. Progress reports now run beside the response underwaitUntil. Audit #30, item 2.3. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: the loading ring did not move during the download that dominates a cold load:
loadedwas either 0 or the whole file, so a 10 MBmain.dart.wasmmoved it once. Pre-cache now reports the real byte count as it streams, throttled to four messages a second per file, and the bootstrap renders the percentage from bytes while the message still counts whole files. Audit #30, item 2.7. (packages/sw/src/shared/utils.ts,packages/sw/src/sw/cache-manager.ts,packages/sw/src/sw/install-handler.ts,packages/sw/src/bootstrap/pipeline.ts) -
Bootstrap: the CanvasKit CDN probe was two attempts of an 8 s timeout plus backoff — up to ~17 s of "Loading rendering engine" on a network that blocks
gstatic.com, before the local engine every build ships was used. One attempt with a 3 s deadline now; a failure was already remembered for the tab session. Audit #30, item 2.4. (packages/sw/src/bootstrap/canvaskit-loader.ts,packages/sw/src/shared/constants.ts) -
Generator:
--commentswas accepted, documented as reserved and did nothing. It now warns that it has no effect and will be removed;sw.jsandbootstrap.jsare built and minified before the generator sees them, so there is nothing to comment. Audit #30, section 7. (lib/src/config.dart,README.md,docs/configuration.md) -
Tests: three scenarios the audit listed as uncovered now have browser tests: an app deployed under
<base href="/app/">(scope, cache keys, deep routes and the host's reserved namespace), a second tab open across a deploy, and the CanvasKit CDN blocked so the local engine answers.docs/testing.mdlists what the suite covers and what it still does not. Audit #30, item 4.6. (packages/sw/e2e/base-href.spec.ts,packages/sw/e2e/two-tabs.spec.ts,packages/sw/e2e/canvaskit-fallback.spec.ts,packages/sw/e2e/support/host.ts,docs/testing.md) -
Service Worker: the 3 s navigation deadline above never applied in a browser with navigation preload — which
activateenables, so in Chrome and Firefox that is every browser. The preload response was awaited before the race, and it stays pending for exactly as long as the origin takes, so a slow origin held a blank page as it always had while the shell sat in the cache. The preload is now what the deadline races. The fallback also applies only toindex.htmland to paths that look like routes: a path whose last segment looks like a file (/legal/privacy.html) is a document the origin serves itself, and answering it with the app shell because it was slow replaced a page that was coming with the wrong page entirely. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: a retired worker's network request for the pre-cached set could still be answered by the browser's own HTTP cache. That request deliberately carries no
?v={hash}, so on a host that sends noCache-Controlformain.dart.jsthe browser was free to answer it from a heuristically fresh copy — the build being replaced — and the whole bypass quietly served what it exists to avoid, with no log line to show it. It is now sent withcache: 'no-cache', which costs a 304 when the file really is unchanged. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: a retired worker could still serve half of one build and half of another — the one combination that cannot boot, failing inside the engine with
WebAssembly.instantiate(): Import #Nand nothing to retry. Two routes led there: a file the network could not answer fell back to this version's cached copy after other files had come from the network, and a pending worker that wentredundantmid-load (its own install failed on a 404, which is final) flipped the next file back to the cache. A worker that has answered any of those files from the network now keeps doing so and stops falling back to its own copies, failing the request instead (503 plus anerrorprogress event the page can show). A load that never reached the network at all still gets the cached copy, which is where "old code beats no code" was meant to apply. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: a shell that arrived after the navigation deadline was stored even when a newer build had become pending in the meantime — minutes can pass between the two, and the page that booted from the cached shell has had time to register the new worker. That is the new build's shell beside this build's code in one cache, the mix every other path in the file refuses. The late answer is now re-checked before it is stored. (
packages/sw/src/sw/fetch-handler.ts) -
Service Worker: an install that ran out of storage reported an ordinary failure, kept downloading every remaining file it could not store, and left its half-filled temp cache behind — so a device near its quota re-downloaded the whole build on every page load, forever, while the megabytes already in that cache were what the version actually serving the app needed for its own lazy writes. The precache now stops at the first
QuotaExceededError, still failing the install for every Core entry it did not reach, the temp cache is dropped, and the error travels as the aggregate'scauseso the broadcast saysisQuota— which the loading screen reads to say "storage quota" rather than blaming the network. (packages/sw/src/sw/cache-manager.ts,packages/sw/src/sw/install-handler.ts,packages/sw/src/sw/quota.ts,packages/sw/src/sw/lifecycle.ts) -
Service Worker: a cache swap that failed for anything other than the quota dropped the version's caches and said so only in the worker's own console. The app then ran from the network on every load with nothing on the page able to tell, although
SWLifecycleMessagedocuments exactly this. It is now broadcast like the quota case. (packages/sw/src/sw/activate-handler.ts) -
Service Worker: a bounded-concurrency run kept handing out work after one of its tasks had thrown, with nothing left to read the results: a failed swap went on writing into caches its own caller was deleting, and a precache that ran out of storage went on downloading files it could not store. The remaining tasks are now skipped. (
packages/sw/src/shared/utils.ts) -
Service Worker: response bodies nobody was going to read were left to the garbage collector — the network answer that lost the navigation race, the error page a non-ok navigation fell back from, the response a retired worker replaced with a cached copy. Each held its connection open until collection; they are released now. (
packages/sw/src/sw/fetch-handler.ts) -
Bootstrap: the error screen was overwritten by whatever arrived next. The worker reports its install to every client it has, controlled or not, and it keeps going long after a page has given up, so a failed load showed the user a resource counter in error red with no explanation — and
Bootstrap.progress, which an error reporter reads, no longer held the failure it was subscribed for. A failure is now the end of the load: later progress changes neither the screen nor the state. (packages/sw/src/bootstrap/api.ts,packages/sw/src/bootstrap/loading-widget.ts,packages/sw/src/bootstrap/pipeline.ts) -
Bootstrap: the stalled overlay never came back down. One slow stretch on a mobile link left a blurred logo and a pulsing reload button over a download that was going fine for the rest of the load. It is removed as soon as the ring moves again; a label that changes while the ring stands still does not count, since that is the stall being reported. (
packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap:
data-config='{"color": 16711680}'— an integer colour, a common mistake in untyped JSON — threw inside the contrast correction, and a stylesheet that throws leaves the page with no loading screen and no error screen. A value that is not a string now falls back to the default with a warning, and so does a string carrying a;, a}or a comment marker, which would end the declaration it is written into and corrupt every rule after it.rgb(),hsl()andvar()are still passed through. (packages/sw/src/bootstrap/config.ts,packages/sw/src/bootstrap/color.ts) -
Bootstrap: the first status the user reads — before the pipeline's first stage update, and the only one they get from a pipeline that throws before it — was the literal
Initializing, which nostringsoverride could replace. It comes from the string table now, like every other label. (packages/sw/src/bootstrap/loading-widget.ts) -
Bootstrap: a
{placeholder}in an overridden string was filled from anything an object inherits, so{constructor}rendered a function's source onto the loading screen. Only the values actually passed are substituted. (packages/sw/src/shared/strings.ts) -
Generator:
--output=flutter_service_worker.js— the name the browsers already have registered, so a natural choice when migrating — succeeded, printed "Done!" and left nothing behind: cleanup removes Flutter's own loader files after the outputs are written. Those names are now rejected, along withindex.htmlandmain.dart.*, which belong to the build itself. (lib/src/config.dart,docs/configuration.md) -
Generator:
--prefix=(orSW_PREFIX="") was accepted and made the loading screen's "clear the cache and reload" delete every cache on the origin, another app's included, because the prefix is what scopes it. An empty prefix, one with surrounding whitespace and one with a path separator are now rejected. (lib/src/config.dart,docs/configuration.md) -
Generator: a
--configpath that did not exist, was not a mapping or did not parse only warned and then generated with every default — so a typo in--config=sw-prod.yamldeployed the prefix, categories and branding of an app nobody configured, with exit status 0. A file named on the command line is now a requirement (status 64); the defaultsw.yamlstays optional and still only warns. (lib/src/config.dart,docs/configuration.md) -
Build: the script that embeds the compiled bundles into Dart string constants corrupted any JS containing a triple quote — it wrote escaped quotes into a raw string, where the backslashes are literal characters — and emitted something that does not compile at all for JS ending in a quote. Today's bundles contain neither, and both scripts that use the renderer render the same way, so
npm run verifywould have agreed with the corruption. The renderer now splices those sequences in as ordinary quoted pieces, and a round-trip test covers them. (scripts/asset-utils.mjs,packages/sw/src/__tests__/asset-utils.test.ts) -
CI: a tag published after fewer checks than a pull request passes — no lint, no Dart format check, nothing on the oldest supported SDK, and no comparison between the tag and
pubspec.yaml. A hotfix pushed straight to a tag could have shipped a package that does not compile on the Dart 3.8 the pubspec promises, or republished the previous version under a new tag. All four now gate the publish. (.github/workflows/deploy.yml) -
Tests: the mock
Cacheaccepted writes a real one rejects — a 206, aVary: *response, a network error, a non-GET request — so a write the browser would refuse could pass the suite. It now rejects what the Service Worker spec says it must. (packages/sw/src/__tests__/helpers.ts)
Changed #
- Package:
environment.sdkwas>=3.11.0, which kept every Flutter release before 3.41 from installing the package at all, for language features it does not use. The floor is now>=3.8.0, and a CI job runs the analyzer and the unit tests on exactly that SDK, so the claim is tested rather than assumed. Audit #30, item 3.9. (pubspec.yaml,.github/workflows/checkout.yml) - Package:
dart pub global activate swinstalled a binary calledgenerateonPATH. It is nowsw;dart run sw:generateanddart pub global run sw:generateare unchanged. Audit #30, item 3.9. (pubspec.yaml,README.md) - Package:
package:sw/sw.dartexported every internal — the categorizer, the manifest builder, the injector,md5,pathToUrl,cleanup— so any refactor was a breaking change. It now exportsgenerate,GeneratorConfig,ResourceCategory,ResourceEntryandFlutterBuildInfo, and carries a library doc comment. The command-line interface is unaffected. Audit #30, item 3.8. (lib/sw.dart) - Package: the pubspec description said nothing about Flutter or what the tool replaces. Audit #30, item 3.9. (
pubspec.yaml) - CI: every action is pinned to a commit SHA, the reusable publish workflow that receives the OIDC token included, and Dependabot now watches npm, pub and the actions themselves (one grouped pull request a week for the dev toolchain). Audit #30, item 4.3. (
.github/workflows/*.yml,.github/actions/setup/action.yaml,.github/dependabot.yml)
0.3.0 — 2026-10-30 #
Fixed #
-
Docs: an app that does not declare
Robotolost all of its text when started without a network. Flutter's engine fetches that font fromfonts.gstatic.com, which the worker cannot cache, while the layout, buttons and images stay in place. The README now says to declare it, and the example bundles it and pre-caches its fonts. Found on an iPad. (README.md,example/pubspec.yaml,.github/workflows/pages.yml) -
Service Worker: the refill of an evicted Core or Required file did not retry a
5xxor429, although this changelog anddocs/service-worker.mdsaid it did. One503on the hash-busted URL went straight to the plain fallback, and a second one reached the page. It now retries like precache before falling back. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: a lazy cache write refused before reading the body (
Vary: *, say) left its copy of the response buffering the body the page was reading, until the stall timeout cut it. The copy is now released. (packages/sw/src/sw/cache-manager.ts) -
Service Worker: a file fetched on a cache miss was often not stored. The write cloned the response after an
await, by which time the page could already be reading it, so the clone threw and the file stayed uncached until a later request happened to win the race. This hit lazily cached files and the self-healing refill of evicted ones. The clone now happens before the firstawait. -
Bootstrap:
flutter build web --no-web-resources-cdnwas ignored. Flutter records that choice as"useLocalCanvasKit": truein_flutter.buildConfig, but the generator dropped it, and the bootstrap probedgstatic.comon every load and then loaded the engine from the CDN whenever it answered. The probe is acache: "no-store"request, so it cost a network round trip on every load, returning visitors included, before the engine download could start, and up to two 8 s timeouts wheregstatic.comis blocked or slow. The bundledcanvaskit/files the app chose to serve were never used, so the service worker never cached them either. The generator now passesuseLocalCanvasKitthrough to the bootstrap config (only when true), andloadCanvasKitgoes straight to the local directory for such builds; the variant in use is cached lazily on first load like any otherOptionalfile. Builds without the flag behave as before. The generator's summary also reports which source the bootstrap will use. (lib/src/flutter_build.dart,lib/src/injector.dart,lib/src/generator.dart,packages/sw/src/bootstrap/canvaskit-loader.ts,packages/sw/src/bootstrap/pipeline.ts,packages/sw/src/shared/types.ts) -
Generator: cleanup pruned
canvaskit/chromium/canvaskit.jswhile keeping its.wasm.getCanvasKitVariantloads that pair on Chromium-class browsers with thecanvaskitrenderer; the missing half went unnoticed while the engine came from the CDN, but a--no-web-resources-cdnbuild loads it locally, where hosts with an SPA rewrite answer the missing script withindex.htmland the app never starts. The keep-set now lists both files. (lib/src/generator.dart) -
Service Worker: files whose names contain a space or a non-ASCII character were never served from the cache. The manifest is keyed by the name on disk (
assets/my photo.png), but the worker looked requests up by the percent-encoded URL path (assets/my%20photo.png). Core and Required files like that were precached and then fetched from the network anyway; Optional ones were never cached. Keys are now decoded withdecodeURI, which leaves an escaped/escaped. (packages/sw/src/shared/utils.ts) -
Service Worker: an HTML page answering a request for a script, wasm, image or JSON file was cached under that file's name. A host with an SPA rewrite (Firebase, Netlify,
try_files … /index.html) answers a file the deploy lacks with the app shell and status 200, and cache-first then served it as that file until the next deploy. Precache now fails such an entry (for a Core file that fails the install, which is retried on the next load), and the lazy cache skips it. HTML files themselves are unaffected. (packages/sw/src/sw/cache-manager.ts,packages/sw/src/shared/utils.ts) -
Bootstrap: recovering from a foreign service worker (the transition from Flutter's own) awaited
getRegistrations()andunregister()with no deadline, before the pipeline's own budget applies. Those wait on the per-scope job queue that a stuck install wedges, so the page could hang before the loading widget appeared. The cleanup is now bounded byRESET_TIMEOUT_MS(3 s) and the reload is unconditional. (packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap:
Bootstrap.applyUpdate()could hang forever when the waiting worker turned redundant instead of activating, sincecontrollerchangethen never fires. It now resolvesfalseat once when the worker turns redundant, or afterSW_BOOTSTRAP_TIMEOUT_MS(10 s) when nothing lands, and leaves the page as it is. (packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap: the
flutter-first-framelistener that dismisses the loading widget was added only after the app loader resolved, so a first frame dispatched earlier left the widget up until Dart removed it. It is now registered before the app loads. (packages/sw/src/bootstrap/pipeline.ts) -
Generator:
keep-maps,no-cleanupandcommentsinsw.yamlwere ignored, althoughdocs/configuration.mddocuments them: the flags were read from the command line only. They now follow the same CLI > YAML > env precedence as every other option, withSW_KEEP_MAPS,SW_NO_CLEANUPandSW_COMMENTSas the environment variables. An invalid value exits with status 64, like an invalid number. (lib/src/config.dart) -
Generator: cleanup deleted
flutter_bootstrap.jseven whenindex.htmlstill loaded it, which happens when the step that swaps in anindex.htmlloadingbootstrap.jsis skipped, and the deployed page was blank. The file is now kept in that case, with a warning that the page will not usebootstrap.jsor the service worker. (lib/src/cleanup.dart) -
Generator:
bootstrap.jscarriedflutter.js's//# sourceMappingURL=flutter.js.map, which points at a map that is not deployed. The comment is stripped, and a;now separates the loader from the bootstrap IIFE. (lib/src/generator.dart) -
Docs:
docs/configuration.mdreferred to a nonexistent--excludeflag (it is--no-glob) and gave the version default as a timestamp (it is a hash of the manifest). -
Bootstrap: the first load after a deploy ran the previous build's Dart code on the new build's engine. The previous worker still controls that page and serves its cached
main.dart.*, whileindex.htmlandbootstrap.jscome from the new build and the bootstrap loads CanvasKit or skwasm for the new engine revision. On the same engine that mix works, but after a Flutter upgrade it fails in the engine (WebAssembly.instantiate(): Import #N). The worker now reports its build'sengineRevisionin itsgetVersionreply, and the bootstrap asks the controller for it. On the same engine the page boots with it at once, without the 4 s activation wait it used to spend for nothing; the new worker takes over on the next load. On a different engine, or an unknown one (workers from earlier releases don't report it, so the first load after upgrading waits once), the bootstrap waits up toSW_UPDATE_INSTALL_TIMEOUT_MS(60 s) for the new worker to install, hands control to it before any app file is requested, and reloads once if the handover is lost. A failed install leaves the page on its current controller, as before. (packages/sw/src/bootstrap/sw-registration.ts,packages/sw/src/bootstrap/pipeline.ts,packages/sw/src/sw/message-handler.ts,packages/sw/src/sw/index.ts,lib/src/injector.dart,lib/src/generator.dart) -
Service Worker: activating one version deleted the temp cache of a version still installing beside it, which happens when the bootstrap hands control to a waiting worker while a newer deploy installs. That version then activated with an empty content cache. Cleanup now keeps the temp caches of the registration's installing and waiting workers; an abandoned install's leftovers still go. (
packages/sw/src/sw/activate-handler.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker: any failure during activate, including
navigationPreload.enable()after a successful swap, deleted every cache whose name started with the prefix: this version's fresh content cache, a pending install's temp cache, and the caches of another app with a longer prefix. Swap, cleanup and navigation preload are now contained separately; a failed swap drops only this version's content and temp caches and clears the stored manifest, so it starts over from the network. Cleanup claims only this app's caches: prefixapp-cacheno longer claimsapp-cache2-…, norapp-cache-admin-…once that app'sapp-cache-admin-manifestcache exists (see the cache-ownership entry below). Apps sharing an origin still need distinct prefixes; two apps on the same prefix cannot be told apart. (packages/sw/src/sw/activate-handler.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker: under a
<base href>with a space or a non-ASCII character (/my%20app/), no key was re-based onto the scope, because request paths are now decoded and the scope was not. Every manifest lookup missed, the__/pass-through stopped matching (/my%20app/__/auth/handlerreached the app-shell branch), and activate deleted the freshly swapped Core and Required files whose hash changed. The scope path is decoded the same way. (packages/sw/src/shared/utils.ts) -
Bootstrap: the version in
sw.js?v=was not encoded, so a--versionsuch as1.0.0+3read back as1.0.0 3in the worker, and activate deleted the temp cache of that pending version;&or#cut the version short. It is now encoded withencodeURIComponent; the default hash versions are unchanged. (packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap: on an engine change the bootstrap reloaded a page that was already on the new worker, when another tab handed control over meanwhile or the
controllerchangelanded just after the 4 s handover timeout. It now checks the controller before reloading. (packages/sw/src/bootstrap/sw-registration.ts) -
Generator: the
;betweenflutter.jsand the bootstrap landed inside a trailing line comment offlutter.js, should a release end it with one other than the stripped source-map comment; it now goes on a line of its own. (lib/src/generator.dart) -
Generator: cleanup kept
flutter_bootstrap.jsand warned that the page would not use the service worker for a commented-out script tag, adata-srcattribute, or a file merely ending in that name (my_flutter_bootstrap.js,flutter_bootstrap.json). (lib/src/cleanup.dart) -
CI: the check that nothing secret reaches pub.dev ran on the setup action's sparse checkout, which lacks
.pubignore, and before the tests createcoverage/andreports/; the dry run itself failed on the missing LICENSE, and|| truehid it. It now runs last, on the whole tree, and fails when the dry run fails. (.github/workflows/checkout.yml) -
Docs: the
--versiondefault (a hash of the manifest, not a timestamp), CanvasKit listed as Core (it is Optional),index.htmlmissing from Required, the full list of environment variables,engineRevisioninSWConfig, and--comments, which is accepted but has no effect yet. -
Docs: the README promised a "pre-cached shell for offline". The app cannot start offline: the shell loads
bootstrap.js, which is never cached so that shell, bootstrap and worker always come from one deploy. The docs now say so, and say why it stays that way.
Audit findings from #30:
-
Service Worker: a body cut short in transit (a chunked response closed early, a truncating proxy) was cached and then served cache-first until the next deploy, breaking the app for that user only. Pre-cached and lazily cached bodies are now counted against the manifest's
sizewhile they stream into the cache (nothing is buffered), and a mismatch stores nothing; the log names the key and both sizes.index.htmlis exempt. A declaredContent-Lengthnever replaces the manifest's size. Precache fetches a mismatched entry once more and stores the second copy, with a warning, when it has the build's size, or when the host re-encodes the response (Content-Encodingother thanidentity, as a minifier or an injected snippet does) and the length repeats (or both copies are longer); an uncompressed body of the wrong size, an empty body for a non-empty file, a length that changes, or a second copy short of its ownContent-Lengthfails the entry. (packages/sw/src/shared/utils.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker: a
Rangerequest (media seeking) was answered from the cache with the whole file, and a206slice could be cached as the whole file. Range requests now go to the network, and only a plain200is cached lazily. (packages/sw/src/sw/fetch-handler.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker: a transient
503or429for a Core file failed the install. Precache and the refill of a missing Core or Required entry retry5xxand429, honouring a numericRetry-Aftercapped at 5 s; a4xxis final, and navigations are unchanged. The refill now fetches the hash-busted URL withcache: 'reload', so it cannot be answered by a stale HTTP cache entry, and falls back once to the page's own request. (packages/sw/src/shared/utils.ts,packages/sw/src/sw/fetch-handler.ts) -
Service Worker: an abandoned install (tab closed mid-precache, a waiting worker superseded by a newer deploy) left its full temp cache behind until some later activate. Each install now removes temp caches of its prefix that no installing, waiting or active worker of the registration owns, and keeps all of them when the waiting worker's version cannot be read. A
QuotaExceededErroris logged with the storage estimate. (packages/sw/src/sw/install-handler.ts,packages/sw/src/sw/cache-manager.ts,packages/sw/src/sw/quota.ts) -
Bootstrap: an engine loaded from the CDN passed a one-byte probe of its
.js, which says nothing about the.wasm; a proxy that blocks the.wasmleft the app on an error. A failure of the app that involves the CDN engine (see the CDN fallback entry below) now pins the tab session to the local engine and reloads once (only whensessionStoragecan record that, so it cannot loop); a missing_flutter.loader, which no engine fixes, is shown at once. A failed CDN probe is remembered for the session, so later loads skip up to two 8 s timeouts. (packages/sw/src/bootstrap/canvaskit-loader.ts,packages/sw/src/bootstrap/pipeline.ts,packages/sw/src/bootstrap/flutter-loader.ts) -
Bootstrap: a failure in
initializeEngine()never reached the pipeline, because flutter.js does not awaitonEntrypointLoaded, so the splash stayed up with no error; and a loading widget that failed to mount threw out of the pipeline, so the app never started. Both are handled now. (packages/sw/src/bootstrap/flutter-loader.ts,packages/sw/src/bootstrap/pipeline.ts,packages/sw/src/bootstrap/api.ts) -
Bootstrap: the reset button deleted every cache on the origin, including other apps'. It now deletes only this build's caches, by the worker's ownership rule:
{prefix}-…for this build's prefix (passed in the bootstrap config ascachePrefix), minus the caches of an app whose prefix extends it (see the cache-ownership entry below); without a prefix it deletes all, as before. (packages/sw/src/bootstrap/loading-widget.ts,lib/src/injector.dart) -
Bootstrap: loading widget fixes: the icon is built without
innerHTML(Trusted Types), the<style>carries the page's CSP nonce, a bubbling childtransitionendno longer removes the widget early,pointer-eventsis restored to its original value, the progress ring is an ARIAprogressbar, the status is a polite live region (an alert on error) that is not rewritten with the same text, long status lines wrap, and reduced motion turns off every animation. (packages/sw/src/bootstrap/loading-widget.ts,packages/sw/src/bootstrap/config.ts) -
Generator: running it twice over the same output failed with
flutter_bootstrap.js not found; it now says the build was already processed and to re-runflutter build web. Unknown keys insw.yaml(with a suggestion), keys with no value, a missing explicit--config, an unknowntheme, a non-hexcolor, a progress value outside 0..100,min-progressabovemax-progress, an unknown renderer, symlinks in the build, and*.part.jsfiles left in Ignore now print a warning; none of them changes the output. (lib/src/config.dart,lib/src/generator.dart,lib/src/files.dart) -
Generator: ignored files were hashed for nothing, and every hash read the whole file into memory; MD5 is now streamed and computed for manifest entries only. Hashes and the default version are unchanged. Canvaskit pruning no longer follows symlinks. (An output name with a directory,
--output=js/sw.js, is now rejected with status 64; see below.) (lib/src/manifest.dart,lib/src/files.dart,lib/src/generator.dart,lib/src/cleanup.dart) -
Docs: the README advised long-lived caching for files other than
sw.js,bootstrap.jsandindex.html. Flutter's file names carry no hash, somain.dart.jscached for a year outlives a deploy; the examples now sendno-cachefor everything (the worker still serves Core and Required files from its own cache). A section onapplication/wasmand cross-origin isolation was added. -
CI: the publish workflow only checked the embedded assets before publishing; it now also type-checks and tests the TypeScript and analyzes and tests the Dart package, with read-only permissions for that job. (
.github/workflows/deploy.yml) -
Service Worker: a cache-first miss made the page wait for the cache write.
cacheFirstawaitedlazyCacheResponse(acache.putof a clone) before handing the response torespondWith, and the lazy guard had no stall timeout. Refilling an evicted Core or Required file (saymain.dart.wasm) from a body that stalled hung the request for good; on a healthy transfer the page still waited for the whole download plus the store, while the tee buffered every byte it hadn't read yet. The response is now returned as soon as its headers arrive, and the write runs beside it underevent.waitUntil, cut off afterBODY_STALL_TIMEOUT_MS(30 s) of silence. The app-shell refresh on a navigation had the same pattern and is fixed the same way. (packages/sw/src/sw/fetch-handler.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker: the body size check stored the wrong files. An uncompressed response that declared a
Content-Lengthother than the manifest's size was checked against the declared length. So a CDN that ignores the?v=query (CloudFront's default cache key) could serve the previous build's file whole, with that file's length, and it was pinned under the new version until the next deploy. The second precache fetch accepted any length that repeated, so a deterministic truncation (the same short body twice) was stored too, and so were two empty200bodies for a non-empty file. A size other than the manifest's is now accepted only when the host re-encodes the response (Content-Encodingpresent and notidentity) and the length repeats on the second fetch: that is the rewriting host the tolerance was meant for (a minifier, an injected snippet). An uncompressed body of the wrong size, or an empty body for a non-empty file, always fails. A204(ok, no body) on precache now counts as a size mismatch and gets the same second look; before, the guard's error was thrown outside the step that handles a mismatch.index.htmlstays exempt. (packages/sw/src/shared/utils.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker / Bootstrap: cleanup and the reset button still deleted the caches of another app whose prefix extends ours. Matching on
{prefix}-meant prefixapp-cacheclaimed every cache of an app with prefixapp-cache-admin, including the temp cache its install was still writing. Both now use one rule,ownCacheNames: a cache is ours if it starts with{prefix}-and is not shadowed. AnyX-manifestcache whereXstarts with{prefix}-marksXas another app's prefix in use, and every name underX-is left alone. To make that marker reliable, install opens the manifest cache before it creates its temp cache. A failed swap now clears the stored manifest instead of deleting the manifest cache, and a version whose content cache name collides with the manifest cache never deletes it. Caches of earlier workers of the same app (0.2.0 used the same names) are still cleaned. An app on an older release is protected from its first activate on, once its manifest cache exists. The orphaned-temp cleanup also keeps the content cache of a kept version whose name has the temp shape (a version starting withtemp-). (packages/sw/src/shared/cache-ownership.ts,packages/sw/src/sw/cache-manager.ts,packages/sw/src/sw/install-handler.ts,packages/sw/src/sw/activate-handler.ts,packages/sw/src/bootstrap/loading-widget.ts) -
Service Worker: activate deleted the temp cache of a worker still installing. Install keeps every temp cache when the waiting worker's
?v=can't be read, but activate skipped unreadable pending workers and deleted their temp caches in the middle of their install. Activate also read the registration before listing caches, so a worker that started installing in between had its fresh temp cache listed but not kept. Activate now keeps every temp cache when an installing or waiting worker's version can't be read, and reads the registration after the cache listing. (packages/sw/src/sw/activate-handler.ts,packages/sw/src/sw/registration.ts,packages/sw/src/sw/cache-manager.ts) -
Bootstrap: when the engine came from the CDN, any failure of the app reloaded the page onto the local engine, not only one caused by the engine: a
main.dart.js404 in a deploy race, a network blip, or an engine/app mismatch (WebAssembly.instantiate(): Import #N) did too. Offline, that reload landed on a blank page, sincebootstrap.jsis never cached, instead of the error screen and its reset button. The fallback now runs only when the failure involves the CDN engine: the error names a URL under the CDN base, or names no URL and a one-byteno-storeprobe of the CDN engine's.wasmfails. An error naming any other URL (the app'smain.dart.js/.mjs, including flutter.js's script error event) shows the error. It never runs whilenavigator.onLineisfalse, nor when a probe of the local engine shows the origin unreachable as well. (packages/sw/src/bootstrap/canvaskit-loader.ts,packages/sw/src/bootstrap/pipeline.ts) -
Bootstrap: on an engine change, a page whose new worker was activated by another tab while it waited for the install reloaded, although that worker was about to claim it: with nothing left in
waiting, the handover returnedfalseat once. When the pending worker isactivatingoractivated, the bootstrap now waits up toSW_REGISTRATION_TIMEOUT_MS(4 s) for the page's controller to change and boots on it; it reloads once only if the claim never lands. (packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap: the one-shot engine-update reload guard stayed set after a load that found a newer worker on the same engine, so a later engine-changing deploy in the same tab got no reload and booted the previous build's Dart code on the new engine. The guard is now cleared on every path where the page boots on one build: same engine, a handover that lands, and nothing pending. (
packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap: a build config without an
engineRevisionsilently sent every update down the slow unknown-engine path (waiting up to 60 s for the new worker to install). The bootstrap now logs oneconsole.warnper load naming the cause. (packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap: the wait for a new engine's worker to install (up to 60 s, plus the 4 s handover) runs outside the 10 s registration cap, and a large precache on a slow link sends no
sw-progressuntil a resource completes. After 30 s the loading widget declared a stall and showed its reset button, whose reset unregistered the very worker being waited for. The wait is bounded on its own, so it now reports itself to the widget as an "Installing update" step at its start and every 10 s until it ends; stall detection resumes afterwards. (packages/sw/src/bootstrap/sw-registration.ts,packages/sw/src/bootstrap/pipeline.ts) -
Bootstrap:
Bootstrap.applyUpdate()resolvedfalseand did not reload after a hard reload, although the waiting worker activated: such a page has no controller,clients.claim()does not take it, andcontrollerchangenever fires. It now also resolvestrue(and reloads, by default) when the waiting worker reachesactivated, and resolvesfalseat once when it turnsredundantinstead of after the 10 s timeout. (packages/sw/src/bootstrap/sw-registration.ts) -
Bootstrap:
controllerchangeandstatechangelisteners outlived the waits that added them (the bootstrap handover,applyUpdate(), the first-install activation wait), and the handover's 4 s timer kept running after a successful handover. Every such wait now removes its listener and clears its timer whichever way it ends. (packages/sw/src/bootstrap/sw-registration.ts) -
Generator: an output name with a directory part (
--output=js/sw.js, or the same insw.yamlorSW_OUTPUT) created the directory and wrote the worker there. Its default scope is then/js/, so it never controlled the page and nothing reported it.../sw.jsand absolute names wrote outside the build, and the bootstrap still registered them.--outputand--bootstrap-outputnow have to be plain file names: a/,\,.., a drive or absolute path, an empty name, or the same name for both exits with status 64 and says why. The generator no longer creates directories.generate()runs the same checks for configurations built in code. (lib/src/config.dart,lib/src/generator.dart) -
Generator: YAML values went through
toString().glob: ["**.js", "assets/**"]became the single glob[**.js, assets/**], a character class, so the manifest was nearly empty and nothing warned about it.glob,no-glob,core,required,optionalandignorenow accept a YAML list, joined with;like the CLI and environment forms. A mapping, a nested list, an empty item, or a list for a single-value option exits with status 64 and names the key and file. Plain scalars keep the text the user wrote, soversion: 1.10stays1.10instead of becoming1.1, andtitle: 0x1Fstays0x1Finstead of becoming31. Quoted and block scalars are used as written. (lib/src/config.dart) -
Generator:
index.htmlwas stamped with the version before theflutter.jsand "already processed" checks ran and before the outputs were written. If a later step failed, the shell was left stamped. A re-run then hashed the changed shell, derived a different version, and had no placeholder left to stamp. Every check that can fail now runs first. The shell is stamped in memory, its manifest entry is taken from the stamped bytes, and it is written aftersw.jsandbootstrap.js. A failed run leavesindex.htmlbyte-identical and can be repeated as is. (lib/src/generator.dart,lib/src/cleanup.dart) -
Generator: an invalid glob (
--core='[') threw from insidegenerate()and was reported as a crash, with a stack trace and exit status 1. Globs from the CLI, YAML and the environment are now compiled while the configuration is parsed. A bad one exits with status 64 and names the option and the pattern. (lib/src/config.dart) -
Generator: a shell built with
<script>{{flutter_bootstrap_js}}</script>gets Flutter's whole loader pasted in. It boots the app withoutbootstrap.jsor the service worker, and nothing said so: only<script src=…>tags were detected. Cleanup now recognises an inline script that sets_flutter.buildConfigor calls_flutter.loader.load(, and warns the user to replace it inweb/index.htmlwith the bootstrap script tag. The shell is not rewritten. An inline script that injectsflutter_bootstrap.jsitself now keeps that file, like a script tag does. Both warnings name the configured bootstrap file. (lib/src/cleanup.dart,lib/src/generator.dart) -
Generator: the version was written into
index.htmlunescaped, so a supplied--versioncontaining"or<could break out of the attribute or element around{{sw_version}}. It is now HTML-escaped (&,<,>,",'). Generated versions are hex digests and come out unchanged. The newstampIndexHtmlVersion()does the substitution, andapplyIndexHtmlVersion()uses it. (lib/src/cleanup.dart) -
Generator: an invalid integer was always reported as the CLI flag, even when it came from
sw.yamlor the environment. Integer and boolean errors now name their source:--max-progress="lots",SW_MIN_PROGRESS="ten" (environment), ormax-progress="lots" (in sw.yaml). (lib/src/config.dart) -
Generator: some versions collided with the worker's cache names (
{prefix}-{version},{prefix}-temp-{version},{prefix}-manifest):manifestmade the content cache the manifest cache.- A version starting with
temp-looked like the install cache of another version, which can be deleted as one. - A version ending in
-manifestlooked like another app's manifest marker under the new cache-ownership rule, so that content cache would never be cleaned up.
All three now exit with status 64 and an explanation. (
lib/src/config.dart) -
CI: the publish workflow published without the leak check:
dart pub publish --dry-run, which shows what reaches pub.dev, ran only in the checkout workflow.deploy.ymlnow runs it before publishing. The checkout workflow'spathsfilters missed files that change the package or its tests, so edits to them skipped CI; they now cover.pubignore,dart_test.yaml,package-lock.json,packages/sw/package.json,packages/sw/*.ts,packages/sw/tsconfig.json,packages/sw/e2e/**andexample/**. (.github/workflows/deploy.yml,.github/workflows/checkout.yml) -
Docs: the nginx and Apache examples served
.mjswithout a JavaScript MIME type, which the wasm build's module loader rejects (strict MIME check); both now map it totext/javascript. The README's install snippets pin^0.2.0instead of the old0.1.6-dev.
Changed #
- Generator: a command-line usage error (unknown option, missing or disallowed value) exits with status 64 (
EX_USAGE) and printsError:with a--helphint, instead of status 1 with a stack trace. A broken input directory printsError:and exits 1 without a stack trace. - Generator: a Flutter build without
engineRevisionin its buildConfig used to fail with an error. The bootstrap and the worker already handle a missing revision, so the generator now continues with a warning. Every deploy will take the slow update path (the page waits for the new worker to install and take over before the app starts), and CanvasKit loads from the localcanvaskit/directory, never the CDN. The summary printsEngine: (unknown). (lib/src/generator.dart) - Generator: configuration errors are now thrown from
GeneratorConfig.parseasFormatExceptioninstead of callingexit(64). The CLI still exits with status 64, now with the--helphint. The newGeneratorConfig.validate()checks output names and the version for configurations built in code. (lib/src/config.dart) - Generator: corrected the comment on the default Required patterns. Pre-caching
index.htmlputs the shell in the progress-counted set and answers a failed navigation. It does not make the app start offline, becausebootstrap.jsis never cached. (lib/src/categorizer.dart)
Tests #
-
Vitest: keys under a percent-encoded scope; the version round trip through
sw.js?v=; no reload when the page is already on the new worker; activate with a failing cleanup, a waiting worker and an unparsable pending URL; fetch with an unusable CacheStorage; settle with blocked storage, foreign replies, a throwingpostMessageand bounded waits; thewindow.BootstrapAPI,applyUpdate, engine detection, the bootstrap entry point. Line coverage ofpackages/sw/srcis now 99%, exceptsw/index.ts, which only runs once the Dart injector has filled in its config. -
Dart: the CLI in a child process (exit codes 0, 1 and 64, env vs CLI vs YAML), every flag from YAML, script tags that do and do not load
flutter_bootstrap.js, the generator's failure modes, skwasm keep-set, injection round trip of quotes,</script>,$&and U+2028. -
Vitest: activate keeps the temp cache of a worker installing beside it and drops an abandoned one; keeps the swapped content cache when navigation preload fails; on a failed swap drops only its own caches;
cleanupOldCacheskeeps pending versions' temp caches and does not claim a longer prefix. Each fails without the fix. -
Playwright:
engine-update.spec.tsdeploys the example twice over a local host, with a marker inmain.dart.jsand that file's size and MD5 updated in the worker's manifest, since the worker refuses a body the manifest does not describe. When the engine changed, the first load after the second deploy runs the new build's code; it ran the old build's without the fix. On the same engine it boots with the old build at once and reaches the new one on a later load. -
Vitest:
settleUpdateAtBootstrapboots at once on the same engine; waits for the install and hands over on a different engine, on a worker that does not report its engine, and on one that does not answer; stays on the current worker when the install fails or runs out of time; reloads once when the handover is lost and not again; skips a second handover when one already failed.registerServiceWorkerno longer waits for a worker that cannot activate on a controlled page; the pipeline stops when the page reloads;getVersionreports the engine revision. -
Dart:
injectSWConfigcarries the engine revision only when the build has one. -
Vitest:
getResourceKeydecodes percent-escapes, keeps an escaped/and a malformed escape as sent; a file with a space in its name is served from the cache; precache fails a Core entry answered with HTML but still precachesindex.html; the lazy cache skips an HTML fallback; the foreign-controller recovery reloads whenunregister()never settles;activateWaitingSWresolvesfalsewhen the controller never changes; a first frame dispatched while the app loader is still running dismisses the widget. Each fails without its fix. -
Dart: YAML sets
keep-maps,no-cleanupandcomments, and the CLI wins over YAML in both directions; cleanup keepsflutter_bootstrap.jswhileindex.htmlloads it and removes it once it loadsbootstrap.js;bootstrap.jsembedsflutter.jswithout its source-map comment. -
Vitest:
loadCanvasKitreturns the local path without any fetch whenuseLocalCanvasKitis set; the pipeline passesuseLocalCanvasKitto it, andfalsewhen the config omits it. All three fail without the fix. -
Dart:
extractFlutterBuildInforeadsuseLocalCanvasKitand defaults it tofalse;injectBootstrapConfigemits it only when true; the integration build checks thatbootstrap.jscarries whatever the example'sflutter_bootstrap.jsrecorded, so it holds for builds with and without--no-web-resources-cdn. -
Dart:
generate()over a synthetic canvaskit build keeps both files of the standard and Chromium variants and prunes a file no variant uses; it fails without the keep-set fix. -
Playwright: the suite passes against the example built both with and without
--no-web-resources-cdn. With the local build and the keep-set unfixed, "page loads without errors" and the wedged-queue test fail on the missingchromium/canvaskit.js. -
For #30, each fix above has a test that fails without it, among them: a body short of the manifest size or longer; the same wrong length twice, stored only when re-encoded; a second copy short of its own
Content-Length; a mismatch logged whencache.putrejects with a generic error; Range pass-through;5xx/429retry andRetry-After; orphaned temp caches kept for installing, waiting and active workers; the CDN fallback reload, and none for a missing Flutter loader; a reset that keeps another prefix's caches; the CLI exit codes and warnings; streamed MD5 equal to the old digest. -
Vitest: a Core refill and a shell navigation answer before their stalled body is stored, and the background write gives up after the stall timeout;
lazyCacheResponsefails a stalled body. All three fail without the fix (the first two hang). -
Vitest: precache fails a body served whole at another length (a CDN ignoring
?v=), the same short length twice uncompressed, a longer uncompressed body, two empty200s, and a204. It still stores a re-encoded body that repeats a short or longer length, and fails a re-encoded body that changes length or comes back empty. The lazy cache refuses a body whose declared length differs from the manifest and an empty or null body;guardBodychecks against the manifest whateverContent-Lengthsays. Tests that encoded the old "declared length wins" and "same length twice is the host" rules were changed to the new rule. Each fails without the fix. -
Vitest:
ownCacheNamesclaims this prefix's three shapes and older workers' caches but nothing under a longer in-use prefix.cleanupOldCaches,cleanupOrphanedTempCaches, activate and the reset button leaveapp-cache-admin's caches, its in-flight temp cache included, alone. Install opens the manifest cache before its temp cache; a failed swap keeps the emptied manifest cache; a kepttemp-…version keeps its content cache. Each fails without the fix. -
Vitest: activate keeps every temp cache when an installing or waiting worker has no readable version, and keeps the temp cache of a worker that started installing between the registration read and the cache listing. Both fail without the fix.
-
Vitest: the pipeline's CDN fallback through the real classifier: a CDN engine
.wasmthat cannot be fetched reloads once; an error naming a CDN file reloads;main.dart.jsfailing (a script error event),main.dart.mjsfailing, and anImport #Nmismatch on a healthy CDN show the error without a fallback; offline and an unreachable origin do not reload; a local build makes no probe.isCdnEngineFailurereads a wrapped error's cause, probes with ano-storeRange request, and treats a refused connection as unreachable. The no-fallback cases (main.dart.js,main.dart.mjs, mismatch, offline, unreachable origin) and the.wasmprobe check fail without the fix. -
Vitest:
settleUpdateAtBootstrapwaits for the claim of a worker activated by another tab instead of reloading, and reloads once when it never comes; clears the reload guard on the same engine; warns once whenengineRevisionis empty; calls its keep-alive at the start of the wait and at least every 10 s, and stops when the wait ends; the pipeline turns it into an "Installing update" progress beat.applyUpdate()reloads when the waiting worker activates without acontrollerchange, answersfalseat once for a redundant worker, and leaves no listener behind; the bootstrap handover clears its timer on success and removes its listener on timeout; the activation wait removes its listener both ways. All fail without the fix. -
Dart: the output-name, YAML, stamping, glob, inline-loader, escaping, error-source, version and
engineRevisionitems above have tests that fail on the code before the fix. They cover:- Output names with
/,\,..,., absolute and drive paths, empty names and duplicates, from the CLI, YAML, the environment andgenerate(). Nothing is created underjs/, andindex.htmlstays byte-identical. - YAML lists for all six glob options; mappings, nested lists, empty items, and lists for single-value options rejected;
version: 1.10,0x1F,1e3and010.pngkept verbatim; quoted and block scalars. - A run that fails on a missing
flutter.jsleavesindex.htmlbyte-identical, and a repeat derives the same version as a fresh build. - Invalid globs for every glob option, from the CLI, YAML and the environment.
- The inlined-loader warning, a bare
_flutter.loader.load()call, a script that injectsflutter_bootstrap.js, a commented-out loader, and an unrelated inline script. - HTML escaping in text and both attribute quote styles, through both
stampIndexHtmlVersionandgenerate(). The shell's manifest hash still matches the bytes shipped. - Integer and boolean errors naming the environment variable and the YAML key and file.
- Versions
manifest,temp-…and…-manifestrejected;manifest-2,v-temp-1andv1manifestaccepted. - The missing-
engineRevisionwarning, and no warning when the revision is present.
The CLI cases run in a child process and check for exit status 64, no stack trace, and no file written.
- Output names with
-
Dart: the file-system-error CLI test now uses an output name that is taken by a directory. The old
main.dart.js/sw.jsis rejected as a usage error now. -
Playwright: every browser test now runs on Chromium, Firefox and WebKit, in CI too, against a host that records requests, injects faults and really goes down: origin faults, fetch routing and storage purges. Fixed sleeps are gone. Assertions that could not fail were replaced: a failed deploy now waits for the new worker to meet the fault, a Range request is checked with the file already cached, a refill is compared with the whole precache list, and Firefox's refused navigation is pinned by its error instead of a blanket expected failure.
docs/testing.mddescribes the levels and the known engine differences. -
Vitest: the refill retries a
5xxor429by hash, then takes one plain attempt; a lazy write refused before reading releases its copy; a page reading its copy before the write starts still gets the file stored. -
CI:
npm run lintworks (it had no ESLint config) and runs in the TypeScript job, oversrcande2e;npm run checkalso type-checkse2e. -
Totals: Vitest 539, Dart 238 unit and 14 integration, Playwright 35 on each of 3 engines (one skipped on WebKit) against the regenerated example;
tsc, ESLint anddart analyzeare clean.
0.2.0 — 2026-09-16 #
Fixed #
- Bootstrap: the pipeline could wait on
navigator.serviceWorker.register()forever, leaving the app stuck at2% Registering service worker— through reloads, through restarts, with no error and no way out. Service worker jobs are serialised per scope, so an install that never settles blocks every laterregister(),unregister()andgetRegistrations()on the origin until the browser kills the install minutes later. The whole service-worker step is now bounded bySW_BOOTSTRAP_TIMEOUT_MS(10s) and the app boots uncached when it runs out; the abandoned registration is left running, so the worker still installs in the background once the browser frees the queue. The deadline covers the pre-registration cleanup too, which goes through the same queue. (packages/sw/src/bootstrap/sw-registration.ts,packages/sw/src/shared/utils.ts) - Service Worker: a pre-cached response body that stalled mid-stream hung
installindefinitely — the mechanism that wedges the queue above.fetchWithRetrybounds the headers only: its abort timer is cleared as soon as they arrive, after whichcache.putreads a multi-megabyte body (main.dart.jsis routinely ~10 MB) with no deadline at all. Bodies are now wrapped in an idle watchdog (BODY_STALL_TIMEOUT_MS, 30s) that cancels a stream which has stopped producing bytes. Measured against idle time, not total duration, so a slow-but-alive connection still finishes however long it takes; a genuinely dead stream fails one entry, and the install is retried on the next page load instead of blocking the origin. (packages/sw/src/sw/cache-manager.ts,packages/sw/src/shared/utils.ts) - Bootstrap: the loading widget's reset button hung in exactly the situation it exists for. It awaited
unregister()before reloading, andunregister()is one of the calls a wedged job queue never settles — so the button spun forever on the stalled screen the user clicked it to escape. Cleanup is now bounded byRESET_TIMEOUT_MS(3s) and the reload is unconditional. (packages/sw/src/bootstrap/loading-widget.ts)
Changed #
- Bootstrap: the reset button no longer clears
localStorage/sessionStorage. On Flutter webshared_preferencesislocalStorage, so clearing it signs the user out and discards local app state — not something a reload button should do, and unrelated to a stuck cache. It still drops every cache, and it now clears only the one-shot foreign-controller guard key rather than all of session storage. (packages/sw/src/bootstrap/loading-widget.ts) - Bootstrap: the reset button unregisters only the service worker this bootstrap registered, matched on path. Unregistering everything also took out workers at unrelated scopes —
firebase-messaging-sw.jsand its push subscription, for instance — whichreloadIfForeignControllerhas always been careful to spare.LoadingWidgettakes the SW filename for this; constructed without one, it falls back to the previous behaviour. (packages/sw/src/bootstrap/loading-widget.ts,packages/sw/src/bootstrap/pipeline.ts)
Tests #
- Vitest:
registerServiceWorkerreturnsnulland lets the pipeline continue whenregister()never settles, and when the pre-registration cleanup never settles. Both hang without the fix. - Vitest: a
Coreentry whose body stalls fails the install instead of hanging it — asserted through a cache that actually consumes the body, since the shared mock only clones it. - Vitest: the reset action reloads despite an
unregister()that never settles, clears caches, spares unrelated registrations, leaves application storage alone, and re-arms the foreign-controller guard. - Vitest:
withTimeoutresolution, fallback and rejection propagation;guardBodyStallpass-through rules, an intact slow stream, and a stalled one. - Playwright: with the scope's job queue deliberately wedged by a worker whose install never settles, the app still reaches its first frame.
0.1.6-dev — 2026-09-02 #
Fixed #
-
Progress counter: the loading overlay could print a count greater than its own total (
Loaded 5 of 4 resources). The numerator and the denominator were computed from two different sets:resourcesCountcovered the pre-cached set (Core+Required), while the client counted every resource the SW reported — includingOptionalfiles served lazily by the fetch handler, which is unbounded. Progress messages now carrycounted, marking membership of the setresourcesCountdescribes, and the bootstrap only adds counted resources to the numerator. (packages/sw/src/sw/progress.ts,packages/sw/src/bootstrap/pipeline.ts) -
Progress counter: a page can be talked to by two workers at once — an old controller still serving fetches while a new build pre-caches in the background — and their manifests need not agree on a total. Messages now carry
swVersion, and the bootstrap ignores any worker other than the one it was built against, so the denominator cannot change mid-load. (packages/sw/src/sw/progress.ts,packages/sw/src/bootstrap/pipeline.ts) -
App shell:
index.htmlwas categorisedignore, so it never reached the manifest. The fetch handler'smanifest['index.html']lookups were consequently always empty: the shell was neither pre-cached nor reported as progress, and an offline navigation had nothing to fall back to on a cold profile. It is nowrequired— pre-cached on install, counted, and stored under one canonicalindex.htmlcache key that both the precache and the navigation handler use. (lib/src/categorizer.dart,packages/sw/src/sw/fetch-handler.ts) -
App shell: navigations to SPA deep links (
/chat/42) were dropped by the fetch handler. The manifest lookup ran first and returned early for any route without an entry of its own, so therequest.mode === 'navigate'branch below it was unreachable for exactly the routes that need it. The navigation check now runs first. (packages/sw/src/sw/fetch-handler.ts) -
App shell: every same-origin navigation wrote its response into the app-shell cache slot. A page the host serves outside the SPA rewrite — Firebase Hosting's
/__/auth/handlerand/__/auth/iframewhenauthDomainis the app's own domain, a static legal page, a download — replaced the shell with its own HTML, after which any navigation that falls back to cache (offline, origin 5xx, a deep link the origin 404s) served that page instead of the app. Only/and/index.htmlmay refresh the shell now,__/*is passed straight to the network (RESERVED_PATH_PREFIXES),, and a response that followed a redirect is stored only as a rebuilt copy with the flag dropped — browsers refuse to replay a redirected response for a navigation. (packages/sw/src/sw/fetch-handler.ts,packages/sw/src/shared/constants.ts) -
App shell: a failed cache write discarded a good page.
cache.putsat inside the sametryas the fetch, so quota pressure — routine for a wasm-sized app — turned a 200 from the origin into the stale cached copy, or into the literal503 Offlinepage on a profile with nothing cached yet. Cache writes and cache reads are now each contained, and nothing after a successful fetch can reject the response handed torespondWith. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker:
progress.reportis best-effort. Its callers sit on the path that produces arespondWithresponse, so a failure to reach clients could surface as a failed navigation or a failedmain.dart.wasm. (packages/sw/src/sw/progress.ts) -
Generator: making the shell a manifest entry exposed an ordering problem that was harmless while it was
ignore—cleanupsubstitutes{{sw_version}}/{{flutter_service_worker_version}}intoindex.htmlafter the manifest is hashed, so the recorded hash and size would have described a file the origin never serves. The generator now substitutes and re-hashes the entry itself. The version is still derived from the pre-substitution manifest, so it stays deterministic; note that the derived value does change relative to 0.1.5, because the shell is now part of the manifest it is derived from. (lib/src/generator.dart,lib/src/cleanup.dart) -
Bootstrap: a
bootstrap.jsand answ.jsfrom different builds (an HTTP-cached bootstrap withoutCache-Control: no-cache) froze the counter silently, since no message ever passes theswVersioncheck. The mismatch is now reported — once, at teardown, and only when every message was foreign, so an ordinary update load (where the outgoing controller talks alongside the installing worker) stays quiet. (packages/sw/src/bootstrap/pipeline.ts) -
Bootstrap:
reloadIfForeignControllerresolved the SW filename againstlocation.hrefinstead of the document base URL thatnavigator.serviceWorker.registeractually uses. On any deep link it expected/chat/sw.js, judged the perfectly good/sw.jscontroller foreign, unregistered it and reloaded the page — once per tab session, on every deep link. (packages/sw/src/bootstrap/sw-registration.ts) -
Service Worker: resource keys are now relative to the worker's
registration.scope. Keyed by absolute pathname, every manifest lookup missed under a non-root<base href>— and, worse,RESERVED_PATH_PREFIXESstopped matching, so an app served from/app/routed Firebase Auth's/app/__/auth/*navigations through the app-shell branch.swapCachesused the same normalisation and so could evict the shell it had just pre-cached. (packages/sw/src/shared/utils.ts,packages/sw/src/sw/cache-manager.ts) -
Service Worker: a same-origin navigation that the origin redirects is no longer answered with the app shell. A navigation carries redirect mode
manual, so a 3xx arrives as an opaque redirect (status0,okfalse); it is now passed back untouched, which is what lets the browser follow it. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: the install-time pre-cache stores a replayable copy of the shell. It had no redirect guard at all — and on a cold profile it is the only writer of the shell — so a host that redirects
index.html?v=…left a copy the browser refuses to serve for any later navigation. (packages/sw/src/sw/cache-manager.ts) -
Service Worker:
notifyIndex('updated')is sent only when the shell was actually written, instead of announcing a refresh that quota pressure had just discarded. (packages/sw/src/sw/fetch-handler.ts) -
Service Worker: the pre-cache progress callback runs outside the block that attributes failures, so a throwing progress report can no longer be recorded as a failed resource — or, for a
Coreentry, fail the whole install over telemetry. (packages/sw/src/sw/cache-manager.ts) -
Generator:
--no-cleanupleavesindex.htmlalone again, including its version placeholders. Substituting under that flag both broke its contract and made the derived version depend on a file the same run had rewritten, so re-running the documented in-place dev loop shipped a new version for byte-identical content. (lib/src/generator.dart)
Changed #
- Service Worker:
cacheFirstdegrades to a plain network fetch whenCacheStorageis unusable (evicted, blocked by a privacy mode) instead of failing the resource outright. - Protocol:
SWProgressMessagegainsswVersionandcounted.resourcesSizenow describes the counted set rather than every cacheable resource, so it agrees withresourcesCount; consumers reading it as "total bytes on disk" should switch to summing the manifest. See docs/service-worker.md for the two rules a client must follow. - Service Worker: the startup banner reports
counted: N(wasprecache: N) and itssizeis the total cacheable bytes, matchingresources: Nbeside it. - Service Worker: every
sw-progressmessage is emitted through one reporter (createProgressReporter) instead of each handler assembling its own; the pre-cache and the counted set are now driven by the sameCOUNTED_CATEGORIESlist and cannot drift apart.
Tests #
- Playwright: cold, warm and five-consecutive-cold loads assert that the numerator never leaves the counted set, reading the SW messages directly rather than the overlay text (which stops updating when the app takes over). On 0.1.5 the cold load counts 9 resources against a total of 6.
- Playwright: the app shell is pre-cached, answers an offline navigation, and answers a route the origin 404s.
- Playwright: visiting a same-origin page outside the SPA leaves the cached shell intact, and a deep link still gets the app afterwards. Both fail on the first cut of this fix.
- Vitest: host-reserved navigations are passed through; the shell is refreshed only from a request for the shell; a redirected response is not stored; a page the origin served is still returned when the cache write fails; precache and the fetch handler agree on the shell cache key.
- Vitest:
progress.tsset membership and message shape; pipeline counter behaviour for foreign versions, uncounted resources and a fixed denominator. - Vitest: an app served from a subpath keeps host-reserved paths reserved, treats its scope root as the shell request, and serves deep routes from the pre-cached shell.
- Vitest: a redirected shell is stored replayably by both writers; an opaque redirect is passed back rather than answered with the shell.
- Vitest: the counter clamp is reached — two builds reporting under one pinned
--version— and the foreign-version report fires only when every message was foreign. - Dart:
generate()over a synthetic build directory pins the shell entry against the bytes on disk, version stability across in-place re-runs, and that the version still moves for any changed resource including the shell. - Playwright: the counter specs wait for the worker to go quiet instead of sleeping on fixed timers, and the five-load spec installs its recorder once.
0.1.5 — 2026-04-22 #
Changed #
- Example: simplified the platform-specific update-check wiring with a conditional-import entrypoint and clarified the example update API contract for the user-approved refresh flow. (
example/lib/src/update/platform/update_check.dart,example/lib/src/update/platform/update_check_js.dart,example/lib/src/update/platform/update_check_vm.dart,example/lib/src/update/update_check_api.dart)
0.1.4 — 2026-04-22 #
Fixed #
- Bootstrap:
WebAssembly.instantiate(): Import #N "X": module is not an object or functionfailures on first load after a deploy. When an old SW kept controlling the page while a new SW installed in the background, any file missing from the old SW's manifest fell through to the network (fresh) while cached files stayed stale — so Flutter would load a freshmain.dart.mjsagainst a stalemain.dart.wasmand the import schemas would disagree. Bootstrap now force-activates a pre-existing waiting worker at registration time via{type:'skipWaiting'}+controllerchange, so subsequentfetch(main.dart.wasm)/import(main.dart.mjs)go through the new SW with a coherent cache. Bounded bySW_REGISTRATION_TIMEOUT_MS; falls back to the oldwaitForActivationpath on timeout. (packages/sw/src/bootstrap/sw-registration.ts) - Bootstrap: pages controlled by a foreign SW at a different script path (e.g., an old
flutter_service_worker.jsleft from a pre-migration deploy) can serve a similarly incoherent mix of files. Bootstrap now detects this pre-registration and performs a one-shotlocation.reload()after unregistering the offending registration. AsessionStorageguard prevents reload loops if the handoff doesn't take. (packages/sw/src/bootstrap/sw-registration.ts,packages/sw/src/bootstrap/pipeline.ts)
Changed #
- Bootstrap: foreign-controller cleanup is surgical — only the registration whose active worker equals the current
navigator.serviceWorker.controlleris unregistered. Unrelated registrations at other scopes (typicallyfirebase-messaging-sw.jsfor push notifications) are left intact so their subscriptions survive the recovery. (packages/sw/src/bootstrap/sw-registration.ts)
Scope note #
- The pre-existing-waiting auto-activation is intentionally bootstrap-only: once the app is running, updates continue through the existing
sw-update-available→applyUpdateuser-approval flow, so running sessions are never yanked out from under the user.
0.1.3 — 2026-04-20 #
Fixed #
- Bootstrap:
Bootstrap.onUpdateAvailablehandlers were silently dropped onflutter-first-framebecauseBootstrapAPI.dispose()cleared theupdateHandlersSet alongside the (correctly load-phase-scoped) progresssubscribers. Update handlers are now retained for the lifetime of the page, so apps reliably receive the "new SW installed" signal after the loading widget disappears. (packages/sw/src/bootstrap/api.ts) - Bootstrap: the
sw-update-availableDOM bridge listener installed byrunPipelinewas registered with{ once: true }, so a long-lived tab encountering a second deploy never notified handlers. The listener is now permanent for the page lifetime;wireUpdateDetectionalready dispatches at most once per SW install. (packages/sw/src/bootstrap/pipeline.ts)
Changed #
- Bootstrap:
BootstrapAPI.notifyUpdateAvailablenow routes async-handler rejections toconsole.errorinstead of leaving an "Uncaught (in promise)" warning that masks the real error. (packages/sw/src/bootstrap/api.ts)
0.1.2 — 2026-04-20 #
Fixed #
- Bootstrap: production deploys on hosts with SPA rewrites (Firebase Hosting, Netlify with
index.htmlfallback, etc.) crashed at_flutter.loader not available after loading flutter.jsbecause the server returnedindex.htmlfor the bareflutter.jsfetch. The bootstrap now inlines Flutter'sflutter.jsIIFE intobootstrap.jsat generation time, so no runtime fetch offlutter.jsis performed and the loader is available before the pipeline starts.
Changed #
- Cleanup:
version.jsonis no longer deleted — it carries Flutter's app version metadata and may be read by the app or external tooling at runtime. - Cleanup:
flutter.jsis now removed from the deployed output (its loader is inlined intobootstrap.js). - Docs: README "CI step" snippet no longer recommends
rm -f build/web/flutter.jsmanually — the generator handles it.
0.1.1 — 2026-04-20 #
Added #
- Docs: "Local Development" section in README.md covering the monorepo layout, TypeScript ↔ Dart build pipeline, and commands for running the generator against
example/build/web/.
0.1.0 — 2026-04-20 #
Complete rewrite replacing Flutter's default bootstrap with a professional two-artifact system.
Fixed (post-audit hardening) #
- Generator: crash on short or empty
engineRevisionnow surfaces a clear error before artifact generation. - CLI precedence:
--flagwith an ArgParser default no longer shadows YAML / env values (wasParsedgate). Glob options (--core,--required, …) now honourSW_CORE,SW_REQUIRED,SW_OPTIONAL,SW_IGNORE,SW_GLOB,SW_EXCLUDE_GLOBenvironment variables that previously did nothing. - CLI: invalid
--min-progress/--max-progressvalues now fail with exit code 64 instead of silently defaulting to0/90. - Cleanup: canvaskit pruning uses consistent URL-style paths, fixing a Windows case where
\-separated paths never matched the keep-set. - SW
notifyClients: a single dead client no longer aborts iteration — every other client still receives the progress update. - SW
cacheFirst: non-OK responses (4xx/5xx) now emit anerrorprogress event so the bootstrap UI can surface the failure instead of hanging onloading. Fallback 503s carryContent-Type: text/plain. - SW
swapCaches: reordered to copy-then-evict-then-persist-manifest, and eviction now excludes paths that were just re-precached from temp (no more accidental deletion of the fresh bytes). - SW
message-handler: accepts both"skipWaiting"strings and{type: "skipWaiting"|"getVersion", requestId?}objects;getVersionreplies echorequestIdfor correlation. - Loading widget: dispose adds a 600ms safety teardown, so the widget and its stylesheet don't leak when
transitionenddoesn't fire (reduced-motion, background tabs). - CanvasKit loader:
detectWebGLVersionreleases its temporary canvas + GL context viaWEBGL_lose_contextinstead of relying on GC.
Added #
- Deterministic
version: when--version/SW_VERSION/ YAML is absent, the generator derives a stable 12-char sha256 over the manifest contents. Re-running against an unchanged build now yields the same SW version. - Dart UI defaults → bootstrap:
--logo,--title,--theme,--color,--min-progress,--max-progressflags are baked intobootstrap.jsasBuildConfig.uiDefaults.data-configstill overrides at runtime. - Precache concurrency cap (
PRECACHE_CONCURRENCY = 6) so large manifests don't stampede the origin during install. - Manifest size warning: generator emits a stderr warning when
sw.jsexceeds 10 MB. - Update prompt API:
window.Bootstrap.onUpdateAvailable(handler)andwindow.Bootstrap.applyUpdate(reload=true)let apps prompt for and apply a waiting SW upgrade.sw-registration.tsexportsactivateWaitingSW(registration)for lower-level use. - CI: new
e2eGitHub Actions job runsflutter build web+dart run sw:generate+ Playwright on each PR;SW_E2E_BROWSERS=allopts into the Chromium/Firefox/WebKit matrix. - Tests:
test/config_test.dart,test/files_test.dart, and new injector cases coveringuiDefaults. Removed the emptytest/unit_test.dartplaceholder.
Original 0.1.0 feature set #
Breaking Changes #
- CLI arguments updated: new options added, some defaults changed
- Generated output now produces two files (
sw.js+bootstrap.js) instead of one - Requires
<script defer data-sw-bootstrap src="bootstrap.js">inindex.html - Old inline JS/CSS loading UI replaced by the built-in loading widget
Added #
- Bootstrap pipeline — 6-stage initialization replacing
flutter_bootstrap.js- Stages: Init → SW Registration → CanvasKit → Assets → Dart Entry → Dart Init
- Loading widget — Responsive circular progress with SVG ring, stall detection, error display, dark/light/auto theme
- CanvasKit CDN loading — Automatic
engineRevisionextraction, Google CDN with local fallback - Resource categorization — Core, Required, Optional, Ignore with glob-based overrides
- Global API —
window.Bootstrap.dispose(),.progress,.subscribe(cb)for Dart integration - YAML config —
sw.yamlas alternative to CLI args (priority: CLI > YAML > env > defaults) - Exponential backoff — 3 retry attempts with 1s/2s/4s delays and jitter
- Cache busting — Hash-based
?v={hash}query params on all cached resources - Atomic cache updates — Temp cache during install, swapped on activate
- Console logging — Styled version banner with engine revision, SW version, renderer info
- Stall detection — "Reset Cache" button after 30s without progress
- Auto-cleanup — Removes
flutter_bootstrap.js,flutter_service_worker.js,version.json,.js.map,.js.symbols - TypeScript source — SW and Bootstrap written in TypeScript, compiled via Vite to minified IIFE
Changed #
- Monorepo structure:
packages/sw/(TypeScript) + root (Dart CLI) - Service Worker rewritten in TypeScript with modular architecture
- Cache naming:
{prefix}-{version}for content,{prefix}-manifestfor manifest storage bootstrap.js,index.html,sw.jsare never cached by the SW
Removed #
- Inline JS/CSS string templates in Dart (replaced by compiled TypeScript)
downloadOfflinecommand (simplified caching model)- Navigation preload (replaced by simpler network-first for index.html)
- Comment stripping (Vite handles minification)
0.0.7 #
- Simplify service worker by removing retry logic and navigation preload.
- Replace
Promise.racetimeout wrappers with modernAbortController-basedfetchWithTimeout. - Remove unused constants (
MEDIA_EXT,NETWORK_ONLY,RETRY_DELAY). - Remove
INSTALL_TIMEOUT,ACTIVATE_TIMEOUTwrappers from install/activate events. - Streamline activate event handler by removing redundant
Promise.racenesting.
0.0.6 #
- Add timeout protection for install (30s) and activate (30s) events.
- Add fetch timeout (10s) and retry logic (2 retries with 500ms delay).
- Add navigation preload support for online-first strategy.
- Clean up all stale caches with matching prefix on activation.
- Ensure
self.clients.claim()is always called, even on error/timeout. - Emit
sw-version.txtalongsidesw.jsfor CI version injection.
0.0.5 #
- Update index.html example to include more features.
0.0.4 #
- Improved service worker generation.
0.0.3 #
- Service worker generation now based on the flutter's
flutter_service_worker.js.
0.0.2 #
- Proof of concept for service worker generation
0.0.1 #
- Initial release with basic functionality