Skip to content

Apply Bswup improvements (#12408)#12418

Open
msynk wants to merge 5 commits into
bitfoundation:developfrom
msynk:12408-bswup-improvements
Open

Apply Bswup improvements (#12408)#12418
msynk wants to merge 5 commits into
bitfoundation:developfrom
msynk:12408-bswup-improvements

Conversation

@msynk
Copy link
Copy Markdown
Member

@msynk msynk commented May 31, 2026

closes #12408

Summary by CodeRabbit

  • New Features

    • Error panel added to update UI with detailed failure info and conditional Retry.
    • Optional update polling (interval and visibility-triggered).
    • Broader Blazor entry-script detection and safer single-start behavior.
  • Bug Fixes

    • Hardened service-worker manifest/caching, more robust integrity/error reporting and retrying.
    • Improved multi-tab update sequencing and coordinated reloads.
    • Installer can run in best-effort mode for missing assets, exercising progress/error UI.
  • Documentation

    • Updated setup, options, security notes and JavaScript API examples.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 31, 2026

Review Change Stack

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e74ceb08-4c4c-40be-8bff-030aff1652e6

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

Adds an install-failure UI and retry flow, hardens service-worker manifest loading and caching (validation, normalization, retries/backoff, strict/lax install modes), updates fetch/passive caching and prohibited-URL behavior, adds opt-in update polling and coordinated multi-tab reloads, expands runtime logging/options, and refreshes docs.

Changes

Bit.Bswup Service Worker Error Handling & Update Polling

Layer / File(s) Summary
Error UI & Demo wiring
src/Bswup/Bit.Bswup/BswupProgress.razor, src/Bswup/Bit.Bswup/Styles/bit-bswup.progress.css, src/Bswup/Bit.Bswup/Scripts/bit-bswup.progress.ts, src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.js, src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.published.js
Adds hidden install error panel markup (title, message, details, retry), styles, caches DOM refs in start(), handles BswupMessage.error to show error UI and wire retry (calls provided reload or window.reload), replaces img/onerror bootstrapping with inline script, and documents demo’s intentional missing asset with errorTolerance: 'lax' and published config changes.
Service Worker Manifest Validation & Config
src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
Fail-soft importScripts of assets, normalize/validate self.assetsManifest, add sendError, add cacheVersion support, validate/default self.errorTolerance, and derive VERSION/CACHE_VERSION/CACHE_NAME with cacheVersion preference.
Service Worker Install & Asset Integrity
src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
createAssetsCache reworked: case-insensitive urlEndsWith, old-cache sync hardening, per-asset retry/backoff with Promise.allSettled, integrity tracking, structured error reporting, and strict-mode delete+throw on failures; install awaited in strict mode, fire-and-forget in lax mode.
Service Worker Fetch & Multi-Tab Lifecycle
src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
Prohibited URLs return 403 plain-text; passive caching returns network response immediately while cache.put runs asynchronously with response.clone() and errors logged; SKIP_WAITING/CLAIM_CLIENTS sequencing updated to delete old caches after claim to avoid mid-transition races.
Runtime Registration & Reload Coordination
src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
Global idempotency guard, capture resolved registration and hadActiveWorkerAtStartup, reloadOnce() to ensure a single page reload across signals, new explicit error message emission with reload callback, and adjusted first-install detection.
Update Polling & Blazor Detection
src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
Adds opt-in polling (updateInterval, updateOnVisibility), registration-aware checkForUpdate() that emits updateNotFound/updateCheckFailed, and startBlazor() accepts blazorScript string
Logging, Options & Types
src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
Introduces logLevels and shouldLog(), expands log levels and defaults, broadens BswupOptions and BswupMessage surfaces, and exposes BitBswup.version and idempotency guard.
Docs & Examples
src/Bswup/README.md
Updates examples and docs for handler attributes, polling, error reporting, multi-tab behavior, adds self.cacheVersion sample, expands errorTolerance and cacheVersion semantics, and documents JS API (checkForUpdate, skipWaiting, forceRefresh) and polling guidance.
SW cleanup cast
src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw-cleanup.ts
Adjusts version assignment to use a TypeScript-compatible (self as any) cast; no behavior change.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~65 minutes

Poem

🐰 I tug a thread of worker bits,
Where retries dance and manifest fits,
An error panel winks, "Try once more",
Polling hums and tabs restore,
Logs and docs nibble at the bits.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.19% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Apply Bswup improvements (#12408)' is concise and directly references the linked issue #12408, clearly indicating the PR applies improvements to the Bswup component as enumerated in that issue.
Linked Issues check ✅ Passed The PR addresses most objectives from issue #12408: comprehensive error handling, atomic installs with retry logic, handleInstall/Activate fixes, URL matching improvements, multi-tab lifecycle support, update polling, cacheVersioning, SERVICE WORKER semantics fixes, asset download resiliency, unsafe pattern removal, and missing feature exposure.
Out of Scope Changes check ✅ Passed All changes are within scope of issue #12408: service-worker logic improvements, progress UI updates, error handling, update polling, caching behavior, documentation, and demo configuration directly address enumerated problems.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts`:
- Around line 47-57: The manifest validation detects errors (MANIFEST_ERRORS
from validateAssetsManifest) but the code continues to run and later
dereferences self.assetsManifest.assets, causing a crash; after calling
sendError you should stop further startup: return/throw to prevent asset
enumeration, and guard any access to self.assetsManifest.assets (e.g., use
Array.isArray(self.assetsManifest.assets) before iterating) and ensure VERSION
fallback is computed safely (use (self.assetsManifest && typeof
self.assetsManifest.version === 'string') ? self.assetsManifest.version :
'0.0.0-invalid-manifest') so the service worker does not proceed when the
manifest is invalid; update the block around MANIFEST_ERRORS, sendError,
VERSION, and any asset-enumeration code that uses self.assetsManifest.assets to
enforce this early exit and safe checks.

In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts`:
- Around line 321-324: The catch block in checkForUpdate currently calls
handle(BswupMessage.error, ...) which routes transient registration.update()
failures into the blocking install-error path; change this to emit a
non-blocking message instead (e.g., add a new enum/value like
BswupMessage.updateCheckFailed or use a non-fatal level such as
BswupMessage.warn/info) and call handle(...) with that new message name,
preserving the payload ({ reason: 'update', message: String((err && (err as
any).message) || err), reload }) so callers can still react but the default
progress handler will not hide the app or show the install-failed UI. Ensure to
update any switch/handler that consumes BswupMessage.* to treat the new
updateCheckFailed value as non-blocking.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ae99fd6f-8550-4920-b5b5-7982f9b3572d

📥 Commits

Reviewing files that changed from the base of the PR and between 046d116 and 825d8af.

📒 Files selected for processing (7)
  • src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.js
  • src/Bswup/Bit.Bswup/BswupProgress.razor
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.progress.ts
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
  • src/Bswup/Bit.Bswup/Styles/bit-bswup.progress.css
  • src/Bswup/README.md

Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts Outdated
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts Outdated
@msynk
Copy link
Copy Markdown
Member Author

msynk commented Jun 1, 2026

@coderabbitai re-review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 1, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
echo "=== bit-bswup.sw.ts ==="
fd "bit-bswup.sw.ts" --exec cat {}

echo ""
echo "=== bit-bswup.ts ==="
fd "bit-bswup.ts" -E "*.js" --exec cat {}

echo ""
echo "=== bit-bswup.progress.ts ==="
fd "bit-bswup.progress.ts" --exec cat {}

echo ""
echo "=== BswupProgress.razor ==="
fd "BswupProgress.razor" --exec cat {}

echo ""
echo "=== bit-bswup.progress.css ==="
fd "bit-bswup.progress.css" --exec cat {}

echo ""
echo "=== service-worker.js (demo) ==="
fd "service-worker.js" --search-path "Bit.Bswup.Demo" --exec cat {}

echo ""
echo "=== README.md (Bswup) ==="
cat src/Bswup/README.md

Length of output: 87174



@msynk: Reviewed the PR thoroughly. The improvements are substantial — the structured error reporting, errorTolerance: 'strict' default, retry logic with exponential backoff, update polling, cacheVersion, and multi-tab lifecycle fixes are all well-designed. A few issues worth addressing:


🔴 Critical — Crash when assetsManifest fails to load

In bit-bswup.sw.ts, validateAssetsManifest correctly catches a missing/null manifest and pushes an error — but execution continues and the module-level ALL_ASSETS initialisation immediately dereferences .assets on the potentially-null manifest:

const MANIFEST_ERRORS = validateAssetsManifest(self.assetsManifest);
if (MANIFEST_ERRORS.length) {
    sendError({ reason: 'manifest', message: '...', url: ASSETS_URL });
    // ↑ execution falls through!
}
// ...
const ALL_ASSETS = self.assetsManifest.assets   // TypeError: Cannot read properties of null
    .filter(...);

If the importScripts(ASSETS_URL) call fails (404, network error, syntax error in the generated assets file), self.assetsManifest is undefined and the SW crashes with an unhandled TypeError before any error event can reach the page. Suggest guarding:

if (MANIFEST_ERRORS.length) {
    sendError({ ... });
    // Prevent further initialisation from crashing on a null manifest.
    self.addEventListener('install', (e: any) => e.waitUntil(Promise.reject(new Error('Invalid assetsManifest'))));
    throw new Error('assetsManifest validation failed: ' + MANIFEST_ERRORS.join('; '));
}

🟡 Moderate — checkForUpdate may emit spurious updateNotFound

In bit-bswup.ts, after await registration.update(), the code reads registration.installing immediately:

await registration.update();
if (!registration.installing && !registration.waiting) {
    handle(BswupMessage.updateNotFound);   // ← may fire even when install is in-flight
}

reg.update() resolves when the server responds (the SW byte-comparison is done), but the browser may not have set reg.installing synchronously by the time the next microtask runs. This can produce a false UPDATE_NOT_FOUND that races with the updatefound event. A small setTimeout(0) / requestAnimationFrame or relying solely on the absence of an updatefound event would be more reliable.


🟡 Moderate — Retry button shown for non-retriable errors

In bit-bswup.progress.ts, errorRetryButton is revealed for every BswupMessage.error including manifest validation failures (reason: 'manifest') and SRI integrity failures (reason: 'integrity'). For those cases, reloading won't help without a redeployment. Consider hiding the retry button (or changing its label to "Reload") when data.reason is one of those permanent failure types.


🟡 Moderate — Handler parameter injected unsanitised into JS string

In BswupProgress.razor:

BitBswupProgress.start(..., '@(Handler)');

If Handler contains a single quote or semicolon (e.g. '; alert(1)//), it breaks out of the string literal. Handler is a developer-supplied [Parameter] so the practical risk is low, but HttpUtility.JavaScriptStringEncode or @Json.Serialize(Handler) would make it safe and consistent.


🟢 Minor — verbose() is defined but never called

In bit-bswup.ts, verbose() is defined alongside error/warn/info/debug but is never invoked in the script. If it's intended to be part of the public log-level hierarchy it should be used, otherwise it can be removed to keep the codebase clean.


🟢 Minor — Error panel shown over partial progress bar

When BswupMessage.error fires mid-download in bit-bswup.progress.ts, the error panel appears but the progress bar and percentage elements remain visible showing a partial value. Consider hiding them when revealing the error panel:

case BswupMessage.error:
    // ...
    if (progressEl) progressEl.parentElement!.style.display = 'none';
    if (percentEl) percentEl.style.display = 'none';
    if (errorEl) errorEl.style.display = 'block';

🟢 Minor — README sample handler missing error case

The bitBswupHandler switch in README.md covers updateNotFound (new) but omits BswupMessage.error. Since structured error reporting is a headline feature of this PR, adding a sample case would help developers wire it up:

case BswupMessage.error:
    console.error('Bswup install error:', data.reason, data.message);
    // optionally surface data.url / data.hash for diagnostics
    return;

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves Bit.Bswup’s update experience and robustness by adding user-visible install error reporting (with retry), introducing opt-in update polling (interval and/or tab visibility), improving multi-tab update consistency, and expanding Blazor script auto-detection to cover both Blazor Web App and standalone WebAssembly entry points.

Changes:

  • Add update polling controls (updateInterval, updateOnVisibility) and expose/extend JS API docs (BitBswup.checkForUpdate, skipWaiting, forceRefresh).
  • Improve service worker install reliability (manifest validation, retries/backoff, strict vs lax error tolerance, safer multi-tab activation/claim behavior).
  • Enhance the progress UI with an error panel (message/details + retry) and corresponding styles.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
src/Bswup/README.md Documents new script attributes, error tolerance behavior, multi-tab behavior, security notes, and JS API.
src/Bswup/Bit.Bswup/Styles/bit-bswup.progress.css Adds styling for the new install error panel and retry button behavior.
src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts Adds idempotent initialization, update polling, better controllerchange handling, richer logging levels, and expanded Blazor script detection.
src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts Adds manifest validation + error reporting, retry/backoff for asset fetches, strict/lax install semantics, safer cache update sequencing, and RegExp parsing improvements.
src/Bswup/Bit.Bswup/Scripts/bit-bswup.progress.ts Adds UI handling for install errors (message/details/retry) and keeps assets list visibility in sync with runtime config changes.
src/Bswup/Bit.Bswup/BswupProgress.razor Updates the progress component markup to include an error panel and changes initialization to run via a <script> block.
src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.published.js Removes demo precachedAssetsInclude config line.
src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.js Adjusts demo config to use errorTolerance = 'lax' with explanatory comment.

Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
Comment thread src/Bswup/Bit.Bswup/BswupProgress.razor
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
Comment thread src/Bswup/Bit.Bswup/BswupProgress.razor
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
@msynk msynk requested a review from Copilot June 2, 2026 19:39
@msynk
Copy link
Copy Markdown
Member Author

msynk commented Jun 2, 2026

@coderabbitai re-review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 2, 2026

@msynk: Sure, I'll kick off a fresh review of the PR now.

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Comment thread src/Bswup/Bit.Bswup/BswupProgress.razor
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts (1)

333-362: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use e.waitUntil() for async work in the service worker message handler.

Returning a Promise from the message listener doesn’t reliably keep the worker alive; use ExtendableMessageEvent.waitUntil(...) for skipWaiting(), clients.claim(), cache deletion/filling, and the follow-up postMessage.

Suggested fix
-function handleMessage(e: MessageEvent<string>) {
+function handleMessage(e: any) {
     diag('handleMessage:', e);

     if (e.data === 'SKIP_WAITING') {
-        return self.skipWaiting()
-            .then(() => self.clients.claim())
-            .then(() => deleteOldCaches())
-            .then(() => sendMessage('WAITING_SKIPPED'));
+        e.waitUntil(
+            self.skipWaiting()
+                .then(() => self.clients.claim())
+                .then(() => deleteOldCaches())
+                .then(() => sendMessage('WAITING_SKIPPED'))
+        );
+        return;
     }

     if (e.data === 'CLAIM_CLIENTS') {
-        return self.clients.claim()
-            .then(() => deleteOldCaches())
-            .then(() => e.source?.postMessage('CLIENTS_CLAIMED'));
+        e.waitUntil(
+            self.clients.claim()
+                .then(() => deleteOldCaches())
+                .then(() => e.source?.postMessage('CLIENTS_CLAIMED'))
+        );
+        return;
     }

     if (e.data === 'BLAZOR_STARTED') {
-        createAssetsCache(true);
+        e.waitUntil(createAssetsCache(true));
+        return;
     }

     if (e.data === 'CLEAN_UP') {
-        deleteOldCaches(); // remove the old caches
+        e.waitUntil(deleteOldCaches()); // remove the old caches
     }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts` around lines 333 - 362, The
message handler currently returns Promises but must use e.waitUntil(...) to keep
the service worker alive; wrap each async branch so that SKIP_WAITING uses
e.waitUntil(self.skipWaiting().then(() => self.clients.claim()).then(() =>
deleteOldCaches()).then(() => sendMessage('WAITING_SKIPPED'))), CLAIM_CLIENTS
uses e.waitUntil(self.clients.claim().then(() => deleteOldCaches()).then(() =>
e.source?.postMessage('CLIENTS_CLAIMED'))), BLAZOR_STARTED uses
e.waitUntil(createAssetsCache(true)), and CLEAN_UP uses
e.waitUntil(deleteOldCaches()), ensuring all calls to self.skipWaiting(),
self.clients.claim(), deleteOldCaches(), createAssetsCache(true), sendMessage
and e.source?.postMessage are inside the waitUntil chains.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Bswup/Bit.Bswup/BswupProgress.razor`:
- Around line 37-39: The inline script in BswupProgress.razor calls
BitBswupProgress.start(...) unguarded which throws if bit-bswup.progress.js
hasn't loaded; update the init to check for the global before invoking (e.g.,
use window.BitBswupProgress?.start(...) or an explicit if
(window.BitBswupProgress) call) passing the same parameters (AutoReload,
ShowLogs, ShowAssets, AppContainer, HideApp, AutoHide, Handler), or
alternatively move the startup into the component lifecycle (OnAfterRenderAsync)
and call JS interop to invoke BitBswupProgress.start to guarantee ordering.
- Line 38: The call to BitBswupProgress.start injects AppContainer and Handler
as raw single-quoted JS literals which can be broken by
quotes/backslashes/newlines; change those embeddings to JSON-encoded JS-safe
strings instead (e.g., replace the single-quoted '@(AppContainer)' and
'@(Handler)' with the output of
System.Text.Json.JsonSerializer.Serialize(AppContainer) and
JsonSerializer.Serialize(Handler) so the values are properly escaped and already
quoted), update the BswupProgress.razor to use JsonSerializer.Serialize for both
AppContainer and Handler and add the required using/import for System.Text.Json
if missing.

In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts`:
- Around line 86-94: The cache bucket currently uses only CACHE_VERSION (derived
from self.cacheVersion or VERSION) which allows different manifests to share a
bucket; change the cache naming so the manifest VERSION is always part of the
bucket identity. Keep the existing CACHE_VERSION calculation (using
self.cacheVersion fallback to VERSION) but construct CACHE_NAME to include both
VERSION and CACHE_VERSION (e.g. `${CACHE_NAME_PREFIX} - ${VERSION} -
${CACHE_VERSION}`), so the manifest VERSION remains in the cache bucket while
cacheVersion can still be used to pin/force refresh.
- Around line 516-540: The current logic sets isIntegrity true whenever
hasIntegrity && fetchErr instanceof TypeError, which treats all TypeError fetch
rejections as SRI failures and prevents retries; change the detection in the
addCache flow so a bare TypeError does NOT automatically mark an integrity
failure: remove fetchErr instanceof TypeError from the isIntegrity predicate and
instead only classify as integrity when there is a clear integrity signal (e.g.,
the error message matches the integrity/digest regex) or after explicitly
recomputing and comparing the response bytes to asset.hash; keep transient
TypeError cases as retryable (use lastError/continue while attempt <
MAX_RETRIES), and only increment integrityFailureCount, set sendError.reason to
'integrity', and skip retries when you have a confirmed integrity mismatch (use
the integrity regex or the explicit digest comparison to decide).

In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts`:
- Line 35: Guard runBswup against late script injection by checking
document.readyState before adding the listener: if the document is already
"interactive" or "complete" call runBswup() immediately, otherwise attach
window.addEventListener('DOMContentLoaded', runBswup) (refer to the runBswup
symbol). Also fix BitBswup.forceRefresh where cacheFilter.test(key) is used:
avoid inconsistent results when cacheFilter has the global (g) or sticky (y)
flags by resetting cacheFilter.lastIndex = 0 before each test or by creating a
non-global equivalent RegExp from cacheFilter (use cacheFilter.source with flags
stripped of g/y) and testing against that; reference the BitBswup.forceRefresh
method and the cacheFilter variable so the change is made exactly where repeated
RegExp.test calls occur.
- Around line 497-500: forceRefresh builds the shouldDelete predicate from
cacheFilter but when cacheFilter is a RegExp it calls cacheFilter.test()
repeatedly, which can misbehave for /.../g or /.../y because RegExp.lastIndex is
mutated; fix by updating the RegExp branch in the shouldDelete construction
(used in forceRefresh) to reset cacheFilter.lastIndex = 0 before calling
cacheFilter.test(key) so each key is tested from the start; reference the
shouldDelete variable and cacheFilter RegExp usage in forceRefresh when making
the change.

---

Outside diff comments:
In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts`:
- Around line 333-362: The message handler currently returns Promises but must
use e.waitUntil(...) to keep the service worker alive; wrap each async branch so
that SKIP_WAITING uses e.waitUntil(self.skipWaiting().then(() =>
self.clients.claim()).then(() => deleteOldCaches()).then(() =>
sendMessage('WAITING_SKIPPED'))), CLAIM_CLIENTS uses
e.waitUntil(self.clients.claim().then(() => deleteOldCaches()).then(() =>
e.source?.postMessage('CLIENTS_CLAIMED'))), BLAZOR_STARTED uses
e.waitUntil(createAssetsCache(true)), and CLEAN_UP uses
e.waitUntil(deleteOldCaches()), ensuring all calls to self.skipWaiting(),
self.clients.claim(), deleteOldCaches(), createAssetsCache(true), sendMessage
and e.source?.postMessage are inside the waitUntil chains.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d3c76fdc-5fec-4833-85fc-89e300ee0dd0

📥 Commits

Reviewing files that changed from the base of the PR and between 046d116 and 733a05a.

📒 Files selected for processing (8)
  • src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.js
  • src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.published.js
  • src/Bswup/Bit.Bswup/BswupProgress.razor
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.progress.ts
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
  • src/Bswup/Bit.Bswup/Styles/bit-bswup.progress.css
  • src/Bswup/README.md
💤 Files with no reviewable changes (1)
  • src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.published.js

Comment thread src/Bswup/Bit.Bswup/BswupProgress.razor
Comment thread src/Bswup/Bit.Bswup/BswupProgress.razor Outdated
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts Outdated
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
@msynk msynk requested a review from Copilot June 4, 2026 10:16
@msynk
Copy link
Copy Markdown
Member Author

msynk commented Jun 4, 2026

@coderabbitai re-review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 4, 2026

@msynk: Sure, triggering a fresh review of the PR now.

✅ Action performed

Full review finished.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.

Comment thread src/Bswup/Bit.Bswup/BswupProgress.razor
Comment on lines 383 to 385
const oldRes = await oldCache.match(oldKey.url);
if(!oldRes) continue;
await newCache.put(oldKey.url, oldRes);
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (1)
src/Bswup/README.md (1)

105-110: ⚡ Quick win

Consider showing complete error details in the example.

The comment documents that data.url and data.hash are available "when known", but the example only logs data.reason and data.message. For a more complete reference example, consider showing all available fields.

📝 Suggested enhancement
         case BswupMessage.error:
             // Structured install failure. data.reason is one of 'manifest' | 'integrity' |
             // 'fetch' | 'cache' | 'request' | 'install-incomplete'; data.message is human
             // readable, and data.url / data.hash point at the offending asset when known.
-            console.error('Bswup install error:', data.reason, data.message);
+            console.error('Bswup install error:', data.reason, data.message, data.url, data.hash);
             return;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Bswup/README.md` around lines 105 - 110, The example logging for the
BswupMessage.error case only prints data.reason and data.message; update the
handler for the BswupMessage.error branch (the switch case) to log all available
error details (data.reason, data.message, and when present data.url and
data.hash, plus the whole data object for unknown fields) so consumers see the
complete failure context; use the existing BswupMessage.error case and data
variable to append url and hash if defined and include a fallback of logging the
entire data object.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.progress.ts`:
- Around line 129-149: The retry suppression omitted the 'install-incomplete'
reason so deterministic failures can still show the retry button; update the
nonRetriableReasons used where errorRetryButton is handled (the
nonRetriableReasons array and the isRetriable check in the same block) to
include 'install-incomplete' alongside 'manifest' and 'integrity' so isRetriable
becomes false for that reason, keep the existing behavior for invoking
data.reload() or window.location.reload() unchanged.

In `@src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts`:
- Around line 388-425: The extract() function currently assigns options =
(window[optionsName] || defaultoptions) which replaces defaults when a partial
window[optionsName] exists; change it to merge defaults with any global config
(e.g. create options by combining defaultoptions and window[optionsName] such as
Object.assign({}, defaultoptions, window[optionsName]) or using the spread
operator) so missing keys in window[optionsName] fall back to defaultoptions;
keep the subsequent attribute overrides (log, sw, scope, handlerName,
blazorScript, updateInterval, updateOnVisibility) applied on top of the merged
options.
- Around line 427-438: The current handle function permanently replaces
options.handler with a noop when window[options.handlerName] is missing,
preventing later attachment from being picked up; change it so you do not
overwrite options.handler on missing handler — instead read
window[options.handlerName] into a local variable (e.g., foundHandler) or only
assign to options.handler when a real function is present, call that local/found
handler if available, and leave options.handler untouched (so future
registrations on window[options.handlerName] can be discovered); update the
logic in the handle function that references options.handlerName and
options.handler to reflect this non-destructive check.

In `@src/Bswup/Bit.Bswup/Styles/bit-bswup.progress.css`:
- Around line 74-89: Replace the deprecated word-break: break-word in the
.bit-bswup-error-message and .bit-bswup-error-details selectors by removing
those declarations and adding overflow-wrap: anywhere (leave existing
white-space: pre-wrap intact) so the stylesheet no longer triggers the Stylelint
warning.

In `@src/Bswup/README.md`:
- Line 218: Update the README entry for the `FullOffline` mode to correct the
grammar by changing "from first time the app is loaded" to "from the first time
the app is loaded" so the description reads: "Enables the full offline mode
where all assets are cached and served from the cache from the first time the
app is loaded."
- Around line 228-234: Update the "Polling for updates" paragraph to fix the
numeric inconsistency: change "There are three ways to check more often:" to
"There are two ways to check more often:" (since only the built-in options using
updateInterval/updateOnVisibility and calling BitBswup.checkForUpdate() are
listed), ensuring the section header "Polling for updates" and references to
updateInterval, updateOnVisibility and BitBswup.checkForUpdate() remain
unchanged.
- Line 213: The README wording incorrectly states that per-asset ?v= and SRI
derive from the manifest version; update the text to accurately reflect that
CACHE_VERSION / cacheVersion only affect the cache bucket name (computed into
CACHE_NAME) while per-asset cache-buster and integrity are set inside
createNewAssetRequest() using each asset's asset.hash (with fallback to
self.assetsManifest.version) and requestInit.integrity = asset.hash; replace the
sentence to mention that ?v= primarily comes from asset.hash (fallback to
manifest.version) and SRI uses asset.hash, and remove any implication that those
values reference self.cacheVersion or CACHE_VERSION.

---

Nitpick comments:
In `@src/Bswup/README.md`:
- Around line 105-110: The example logging for the BswupMessage.error case only
prints data.reason and data.message; update the handler for the
BswupMessage.error branch (the switch case) to log all available error details
(data.reason, data.message, and when present data.url and data.hash, plus the
whole data object for unknown fields) so consumers see the complete failure
context; use the existing BswupMessage.error case and data variable to append
url and hash if defined and include a fallback of logging the entire data
object.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 427f1025-c5ef-456e-b74d-6a2168e132d7

📥 Commits

Reviewing files that changed from the base of the PR and between 046d116 and de9c330.

📒 Files selected for processing (9)
  • src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.js
  • src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.published.js
  • src/Bswup/Bit.Bswup/BswupProgress.razor
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.progress.ts
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw-cleanup.ts
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.sw.ts
  • src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
  • src/Bswup/Bit.Bswup/Styles/bit-bswup.progress.css
  • src/Bswup/README.md
💤 Files with no reviewable changes (1)
  • src/Bswup/Bit.Bswup.Demo/wwwroot/service-worker.published.js

Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.progress.ts
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
Comment thread src/Bswup/Bit.Bswup/Scripts/bit-bswup.ts
Comment thread src/Bswup/Bit.Bswup/Styles/bit-bswup.progress.css
Comment thread src/Bswup/README.md Outdated
Comment thread src/Bswup/README.md Outdated
Comment thread src/Bswup/README.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bit Bswup improvements

2 participants