feat: implement service worker caching and update build configuration - #303
feat: implement service worker caching and update build configuration#303amitsinghsutara wants to merge 2 commits into
Conversation
📝 WalkthroughWalkthroughThe PR bundles the application and service worker separately, replaces direct Workbox registration with confirmation-mode update registration, delegates update notification to Workbox, and updates GDL asset caching with progress reporting and guaranteed lock cleanup. ChangesService worker update and caching flow
Estimated code review effort: 4 (Complex) | ~45 minutes Possibly related PRs
Suggested reviewers: Sequence Diagram(s)sequenceDiagram
participant App
participant registerServiceWorkerUpdates
participant ServiceWorker
participant cacheUrlsWithProgress
participant BroadcastChannel
App->>registerServiceWorkerUpdates: register /sw.js in confirm mode
registerServiceWorkerUpdates->>ServiceWorker: connect to bundled worker
App->>ServiceWorker: request GDL asset caching
ServiceWorker->>cacheUrlsWithProgress: cache asset URLs
cacheUrlsWithProgress->>BroadcastChannel: send CachingProgress
BroadcastChannel->>App: forward caching progress
🚥 Pre-merge checks | ✅ 4 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 `@sw-src.js`:
- Around line 300-315: Update the caching flow around cacheUrlsWithProgress and
its onItemError callback to track failed URLs, and prevent CachingProgress from
reporting successful 100% completion when any asset failed. Send the established
failure or partial-cache status consumed by App.ts/GdlBookRuntime.ts so later
launches retry incomplete caches.
- Around line 4-7: Remove the unsupported exclude option from the
precacheAndRoute call in sw-src.js, and configure manifest generation in
workbox-config.js to omit lang/**/* via globIgnores or an equivalent manifest
transform.
In `@webpack.config.js`:
- Around line 27-31: Update the HtmlWebpackPlugin configuration to include only
the app entry in index.html, using chunks: ['app'] or excluding the sw chunk.
Ensure the emitted document no longer contains a script reference to sw.js while
preserving the existing app output.
🪄 Autofix
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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: 75d88aec-e37d-43ce-808a-6c1c0fa224a9
⛔ Files ignored due to path filters (23)
dist/app.jsis excluded by!**/dist/**,!dist/**dist/index.htmlis excluded by!**/dist/**,!dist/**dist/src/Models/AudioElement.jsis excluded by!**/dist/**,!dist/**dist/src/Models/AudioElement.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/Models/AudioTimestamps.jsis excluded by!**/dist/**,!dist/**dist/src/Models/AudioTimestamps.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/Models/Book.jsis excluded by!**/dist/**,!dist/**dist/src/Models/Book.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/Models/ImageElement.jsis excluded by!**/dist/**,!dist/**dist/src/Models/ImageElement.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/Models/Models.jsis excluded by!**/dist/**,!dist/**dist/src/Models/Models.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/Models/Page.jsis excluded by!**/dist/**,!dist/**dist/src/Models/Page.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/Models/TextElement.jsis excluded by!**/dist/**,!dist/**dist/src/Models/TextElement.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/Models/WordTimestampElement.jsis excluded by!**/dist/**,!dist/**dist/src/Models/WordTimestampElement.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/src/PlayBackEngine/PlayBackEngine.jsis excluded by!**/dist/**,!dist/**dist/src/PlayBackEngine/PlayBackEngine.js.mapis excluded by!**/dist/**,!**/*.map,!dist/**dist/sw.jsis excluded by!**/dist/**,!dist/**package-lock.jsonis excluded by!**/package-lock.json,!**/*.json,!package-lock.jsonpackage.jsonis excluded by!**/*.json
📒 Files selected for processing (6)
App.tssrc/Books/GdlBookRuntime.tssw-src.jssw.jswebpack.config.jsworkbox-config.js
| precacheAndRoute(self.__WB_MANIFEST, { | ||
| ignoreURLParametersMatching: [/^book/, /^cr_user_id/], | ||
| exclude: [/^lang\//], | ||
| }); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
(
cd "$tmp_dir"
npm pack workbox-precaching@7.4.1 --silent >/dev/null
tar -xzf ./*.tgz
rg -n -C 3 'PrecacheRouteOptions|ignoreURLParametersMatching|exclude' package
)
rg -n -C 3 'globPatterns|globIgnores|lang/' workbox-config.jsRepository: curiouslearning/CRWebPlayer
Length of output: 50384
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|package\.json$'
echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
sed -n '1,20p;280,330p' sw-src.js | cat -n
fi
echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
sed -n '1,220p' workbox-config.js | cat -n
fi
echo
echo "package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
if [ -f "$f" ]; then
echo "--- $f ---"
rg -n '"workbox-(inject-manifest|-cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80
fi
done
echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' .Repository: curiouslearning/CRWebPlayer
Length of output: 50384
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|package\.json$'
echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
sed -n '1,20p;280,330p' sw-src.js | cat -n
fi
echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
sed -n '1,220p' workbox-config.js | cat -n
fi
echo
echo "package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
if [ -f "$f" ]; then
echo "--- $f ---"
rg -n '"workbox-(inject-manifest|cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80
fi
done
echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' .Repository: curiouslearning/CRWebPlayer
Length of output: 50384
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|(^|/)package\.json$'
echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
sed -n '1,20p;280,330p' sw-src.js | cat -n
fi
echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
sed -n '1,220p' workbox-config.js | cat -n
fi
echo
echo "Package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
if [ -f "$f" ]; then
echo "--- $f ---"
rg -n '"workbox-(inject-manifest|cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80
fi
done
echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' .Repository: curiouslearning/CRWebPlayer
Length of output: 50384
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Repository files of interest:"
git ls-files | rg '(^|/)sw-src\.js$|(^|/)workbox-config\.js$|(^|/)package\.json$' || true
echo
echo "sw-src.js lines 1-20 and 280-330:"
if [ -f sw-src.js ]; then
sed -n '1,20p;280,330p' sw-src.js | cat -n
fi
echo
echo "workbox-config.js:"
if [ -f workbox-config.js ]; then
sed -n '1,220p' workbox-config.js | cat -n
fi
echo
echo "Package manager lock/workbox versions:"
for f in package-lock.json npm-shrinkwrap.json pnpm-lock.yaml yarn.lock; do
if [ -f "$f" ]; then
echo "--- $f ---"
rg -n '"workbox-(inject-manifest|cli|precaching)/?:"|workbox-(inject-manifest|cli|precaching)' "$f" | head -80 || true
fi
done
echo
echo "Search for lang exclusion configuration:"
rg -n -C 3 'globIgnores|globPatterns|exclude:|lang/\*|lang/' . || true
echo
echo "Type/interface check for PrecacheRouteOptions excluding exclude:"
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
(
cd "$tmp_dir"
npm pack workbox-precaching@7.4.1 --silent >/dev/null
tar -xzf ./*.tgz
rg -n 'interface PrecacheRouteOptions|function generateURLVariations|urlManipulation|exclude' package/_types.d.ts package/utils/generateURLVariations.js package/build/workbox-precaching.dev.js package/build/workbox-precaching.prod.js || true
)Repository: curiouslearning/CRWebPlayer
Length of output: 50384
Move the lang/ exclusion to manifest generation.
exclude is not a precacheAndRoute option; it does not remove lang/ files from self.__WB_MANIFEST. Remove it from this call. Add "lang/**/*" to workbox-config.js globIgnores, or use a manifest transform to filter those entries.
🤖 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 `@sw-src.js` around lines 4 - 7, Remove the unsupported exclude option from the
precacheAndRoute call in sw-src.js, and configure manifest generation in
workbox-config.js to omit lang/**/* via globIgnores or an equivalent manifest
transform.
| await cacheUrlsWithProgress(cache, bookAudioAndImageFiles, { | ||
| batchSize: 5, | ||
| delayBetweenBatchesMs: 100, | ||
| onProgress: async (progress) => { | ||
| const clients = await self.clients.matchAll(); | ||
| if (clients.length > 0) { | ||
| await channel.postMessage({ | ||
| command: "CachingProgress", | ||
| data: { progress: Math.round(progress), bookName: bookData.bookName }, | ||
| }); | ||
| } | ||
| }, | ||
| onItemError: (url, error) => { | ||
| // Optional: log at a low level for debugging, but don't treat as a hard error. | ||
| console.log("Skipping missing or unreachable asset:", url); | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 8 'cacheUrlsWithProgress|onProgress|onItemError|CachingProgress' sw-src.js
rg -n -C 8 'CachingProgress|progressValue >= 100|localStorage\.setItem' App.ts src/Books/GdlBookRuntime.ts
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
(
cd "$tmp_dir"
npm pack `@curiouslearning/sw`@1.0.0 --silent >/dev/null
tar -xzf ./*.tgz
rg -n -C 8 'cacheUrlsWithProgress|onProgress|onItemError' package
)Repository: curiouslearning/CRWebPlayer
Length of output: 41373
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect the cached-book loading/skipping paths and all `localStorage.setItem(event.data.data.bookName, "true")` sites.
rg -n -C 9 'localStorage\.getItem|setItem\(event\.data\.data\.bookName|bookName|download_completed|readLanguageDataFromCacheAndNotifyAndroidApp|gdl|load.*book|loadBooks|Book' App.ts src src/Books src/Books/GdlBookRuntime.ts src/Books/*.ts 2>/dev/null || true
# Search for any other persistent markers or download-completed behavior near `localStorage.setItem(event.data.data.bookName, "true")`.
rg -n -C 7 'download_completed|CachingProgress|localStorage\.setItem\(event\.data\.data\.bookName|cached|loadBook|GdlBookRuntime' app src || trueRepository: curiouslearning/CRWebPlayer
Length of output: 50383
Do not mark incomplete caches as complete.
cacheUrlsWithProgress treats per-item failures as progress. If onItemError only logs, CachingProgress can still reach 100, then App.ts/GdlBookRuntime.ts skip the cache request on later launches. Track failed URLs and send a failure or partial-cache status instead of reporting 100% completion.
🤖 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 `@sw-src.js` around lines 300 - 315, Update the caching flow around
cacheUrlsWithProgress and its onItemError callback to track failed URLs, and
prevent CachingProgress from reporting successful 100% completion when any asset
failed. Send the established failure or partial-cache status consumed by
App.ts/GdlBookRuntime.ts so later launches retry incomplete caches.
| new HtmlWebpackPlugin({ | ||
| title: 'Curious Reader', | ||
| template: 'index.html', | ||
| filename: 'index.html', | ||
|
|
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
if [[ -f dist/index.html ]]; then
rg -n 'src="[^"]*(app|sw)\.js"' dist/index.html
else
echo "Build output is absent. Run the normal build locally, then verify that dist/index.html includes app.js but not sw.js."
fiRepository: curiouslearning/CRWebPlayer
Length of output: 700
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf 'Files matching config templates:\n'
git ls-files | rg '(^|/)(webpack\.config\.js|workbox-config\.js|index\.html)$' || true
printf '\nwebpack.config.js:\n'
if [[ -f webpack.config.js ]]; then
cat -n webpack.config.js
fi
printf '\nworkbox-config.js:\n'
if [[ -f workbox-config.js ]]; then
cat -n workbox-config.js
fi
printf '\nindex.html head/body context:\n'
if [[ -f index.html ]]; then
cat -n index.html
fi
printf '\nPackage versions:\n'
if [[ -f package.json ]]; then
node - <<'JS'
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json','utf8'));
console.log(JSON.stringify({
deps: pkg.dependencies,
devDeps: pkg.devDependencies
}, null, 2));
JS
fiRepository: curiouslearning/CRWebPlayer
Length of output: 4864
Exclude the service-worker entry from the emitted index.html.
webpack.config.js defines app and sw entries, and HtmlWebpackPlugin emits both as document scripts. Build output currently includes src="sw.js", which runs the pre-injection source worker in the page context while Workbox generates the registration worker at the root path /sw.js. Set chunks: ['app'] or excludeChunks: ['sw'] on HtmlWebpackPlugin to prevent executing service-worker code in the document.
Proposed fix
new HtmlWebpackPlugin({
title: 'Curious Reader',
template: 'index.html',
filename: 'index.html',
+ chunks: ['app'],
}),📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| new HtmlWebpackPlugin({ | |
| title: 'Curious Reader', | |
| template: 'index.html', | |
| filename: 'index.html', | |
| new HtmlWebpackPlugin({ | |
| title: 'Curious Reader', | |
| template: 'index.html', | |
| filename: 'index.html', | |
| chunks: ['app'], | |
| }), |
🤖 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 `@webpack.config.js` around lines 27 - 31, Update the HtmlWebpackPlugin
configuration to include only the app entry in index.html, using chunks: ['app']
or excluding the sw chunk. Ensure the emitted document no longer contains a
script reference to sw.js while preserving the existing app output.
|
Also, the tests to ensure functionality:
|
There was a problem hiding this comment.
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 `@sw-src.ts`:
- Around line 312-334: Update cacheBookAssets so its catch block posts a
terminal CachingError message through channel, including the book identity and
error details alongside the existing logging. In the consumers that currently
process CachingProgress, including App.ts handling and GdlBookRuntime, handle
CachingError by hiding the loading screen and exposing the established retry
path, while preserving normal progress behavior.
- Around line 9-12: Move the lang/ exclusion from the precacheAndRoute options
into Workbox manifest generation by adding the appropriate lang/**/* pattern to
globIgnores or an equivalent manifest transform. Remove the unsupported exclude
option and the as any cast from the precacheAndRoute call, preserving the
existing URL-parameter matching.
🪄 Autofix
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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: c0984462-bcea-483d-b836-e764332ccc84
⛔ Files ignored due to path filters (2)
dist/app.jsis excluded by!**/dist/**,!dist/**dist/sw.jsis excluded by!**/dist/**,!dist/**
📒 Files selected for processing (6)
App.tssrc/Books/GdlBookRuntime.tssw-src.tssw.jswebpack.config.jsworkbox-config.js
🚧 Files skipped from review as they are similar to previous changes (4)
- workbox-config.js
- App.ts
- src/Books/GdlBookRuntime.ts
- webpack.config.js
| precacheAndRoute(self.__WB_MANIFEST, { | ||
| ignoreURLParametersMatching: [/^book/, /^cr_user_id/], | ||
| exclude: [/^lang\//], | ||
| }); | ||
| } as any); |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Inspect where the precache manifest excludes language assets.
rg -n -C 4 'globIgnores|manifestTransforms|exclude|lang/' \
sw-src.ts workbox-config.js webpack.config.js 2>/dev/null || trueRepository: curiouslearning/CRWebPlayer
Length of output: 1334
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- workbox-config.js ---'
cat -n workbox-config.js
printf '%s\n' '--- sw-src.ts ---'
cat -n sw-src.ts
printf '%s\n' '--- Workbox dependencies and precache API usage ---'
rg -n -C 3 '"workbox|workbox-webpack-plugin|precacheAndRoute|__WB_MANIFEST|globIgnores|manifestTransforms|lang/' \
package.json package-lock.json yarn.lock pnpm-lock.yaml sw-src.ts webpack.config.js .github 2>/dev/null || true
printf '%s\n' '--- language asset paths ---'
rg -n -C 2 '(^|[/_ -])lang(/|[/_ -])|lang/' \
--glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' . 2>/dev/null | head -200 || trueRepository: curiouslearning/CRWebPlayer
Length of output: 38344
🌐 Web query:
Workbox 7.4.1 precacheAndRoute PrecacheRouteOptions exclude ignoreURLParametersMatching source
💡 Result:
In Workbox, including version 7.4.1, the precacheAndRoute method is a convenience function that registers a route to serve precached assets [1][2]. It accepts an optional second argument of type PrecacheRouteOptions, which allows you to customize how incoming requests are matched against your precache manifest [1][3]. The ignoreURLParametersMatching option is a property within PrecacheRouteOptions that accepts an array of Regular Expressions (RegExp[]) [1][3]. This configuration determines which search parameters should be ignored when matching a request URL against the entries in your precache [1][4]. By default, Workbox ignores parameters that match /^utm_/ (e.g., utm_source, utm_campaign), meaning requests with these parameters will be treated as matching the underlying precached asset without those parameters [4]. If you wish to customize or override this behavior, you can provide your own array of regex patterns [1][3]. For example, to ignore all URL parameters, you would configure it as follows [1][3]: import {precacheAndRoute} from 'workbox-precaching'; precacheAndRoute( [ {url: '/index.html', revision: '383676'}, //... other entries ], { // Ignore all URL parameters. ignoreURLParametersMatching: [/.*/], }); Other available options within PrecacheRouteOptions include: - cleanURLs (boolean): Whether to automatically check the cache for a URL with a.html extension if the original request does not match [3][4]. - directoryIndex (string): The filename to append when a request ends in a slash (default is index.html) [3][4]. - urlManipulation (function): A callback to perform custom URL transformations for matching [3][4].
Citations:
- 1: https://developer.chrome.com/docs/workbox/modules/workbox-precaching
- 2: https://github.com/GoogleChrome/workbox/blob/bd5f4114a90178476e60be549f72ddce779e3344/packages/workbox-precaching/precacheAndRoute.mjs
- 3: https://developer.chrome.com/docs/workbox/modules/workbox-precaching.md.txt
- 4: https://github.com/GoogleChrome/workbox/blob/390f16c/packages/workbox-precaching/addRoute.mjs
🏁 Script executed:
#!/bin/bash
set -euo pipefail
python3 - <<'PY'
import json
from pathlib import Path
cfg = json.loads(Path("package.json").read_text())
print("workbox-precaching:", cfg.get("dependencies", {}).get("workbox-precaching"))
print("workbox-cli:", cfg.get("dependencies", {}).get("workbox-cli"))
print("globIgnores:", json.loads(Path("workbox-config.js").read_text().split("globIgnores:", 1)[1].split("]", 1)[0] + "]") if False else "inspect source above")
PY
printf '%s\n' '--- all config keys ---'
rg -n '^[[:space:]]*[A-Za-z][A-Za-z0-9]*[[:space:]]*:' workbox-config.js
printf '%s\n' '--- candidate language directories/files ---'
find . -path './node_modules' -prune -o -path './.git' -prune -o \( -type d -name 'lang' -o -type f -path '*/lang/*' \) -printRepository: curiouslearning/CRWebPlayer
Length of output: 490
🌐 Web query:
site:github.com/GoogleChrome/workbox v7.4.1 addRoute.mjs PrecacheRouteOptions cleanURLs directoryIndex urlManipulation ignoreURLParametersMatching
💡 Result:
In Workbox v7.4.1 (and other versions), the PrecacheRouteOptions interface defines the configuration for how precached assets are matched against fetch requests [1][2]. These options are utilized by the addRoute.mjs module (and by extension, precacheAndRoute.mjs) to determine which URL variations to check in the precache when a fetch event occurs [3][4]. The configuration properties within PrecacheRouteOptions are: 1. cleanURLs (boolean, default: true): When enabled, if a request does not match directly, Workbox will attempt to find a match by appending.html to the end of the pathname [3][2]. 2. directoryIndex (string, default: index.html): If a request ends with a trailing slash (/), Workbox will attempt to find a match by appending the specified directoryIndex value to the pathname [3][2]. 3. ignoreURLParametersMatching (Array, default: [/^utm_/, /^fbclid$/]): This array contains regular expressions used to identify and remove search parameters from the request URL before attempting to match it against precached entries [3][2]. This ensures that common tracking parameters do not prevent a match [3]. 4. urlManipulation (function): This optional function allows developers to provide custom logic to generate alternative URLs [3][5]. It takes the request URL as input and should return an array of alternative URLs that Workbox will then attempt to match in the cache [6][2]. These options are processed by the internal generateURLVariations utility, which yields these potential variations for cache matching one at a time [6][2].
Citations:
- 1: https://github.com/GoogleChrome/workbox/blob/v7/packages/workbox-precaching/src/_types.ts
- 2: https://github.com/GoogleChrome/workbox/blob/ae29e1748bb976351db8e0c64a9ea9fc8ba2583f/packages/workbox-precaching/src/utils/generateURLVariations.ts
- 3: https://github.com/GoogleChrome/workbox/blob/bd5f4114a90178476e60be549f72ddce779e3344/packages/workbox-precaching/addRoute.mjs
- 4: https://github.com/GoogleChrome/workbox/blob/bd5f4114a90178476e60be549f72ddce779e3344/packages/workbox-precaching/precacheAndRoute.mjs
- 5: https://github.com/GoogleChrome/workbox/releases/tag/v3.0.0
- 6: https://github.com/GoogleChrome/workbox/blob/f1164254b8abdd12c5c601ee7e7fc7d73fffd979/packages/workbox-precaching/utils/generateURLVariations.mjs
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- package.json dependency section ---'
cat -n package.json | sed -n '1,45p'
printf '%s\n' '--- workbox config syntax and exclusions ---'
cat -n workbox-config.js
rg -n -C 3 'workbox|globDirectory|globPatterns|globIgnores|lang/' \
package.json package-lock.json workbox-config.js webpack.config.js README.md .github 2>/dev/null || true
printf '%s\n' '--- tracked files that match the manifest patterns under lang ---'
git ls-files | awk '
/^lang\// || /\/lang\// {
if ($0 ~ /\.(wav|mp3|WAV|gif|png|webp|otf|jpg|js|json|css|html)$/) print
}
'Repository: curiouslearning/CRWebPlayer
Length of output: 37048
Move the lang/ exclusion to manifest generation.
exclude is not a valid PrecacheRouteOptions member in Workbox 7.4.1. The as any cast hides this mismatch. Add lang/**/* to globIgnores or use a manifest transform, then remove the unsupported route option.
🤖 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 `@sw-src.ts` around lines 9 - 12, Move the lang/ exclusion from the
precacheAndRoute options into Workbox manifest generation by adding the
appropriate lang/**/* pattern to globIgnores or an equivalent manifest
transform. Remove the unsupported exclude option and the as any cast from the
precacheAndRoute call, preserving the existing URL-parameter matching.
| async function cacheBookAssets(bookData: any, bookAudioAndImageFiles: any) { | ||
| try { | ||
| const cache = await caches.open(bookData.bookName); | ||
| await cacheUrlsWithProgress(cache, bookAudioAndImageFiles, { | ||
| batchSize: 5, | ||
| delayBetweenBatchesMs: 100, | ||
| onProgress: async (progress) => { | ||
| const clients = await self.clients.matchAll(); | ||
| if (clients.length > 0) { | ||
| channel.postMessage({ | ||
| command: "CachingProgress", | ||
| data: { progress: Math.round(progress), bookName: bookData.bookName }, | ||
| }); | ||
| } | ||
| }, | ||
| onItemError: (url, error) => { | ||
| // Optional: log at a low level for debugging, but don't treat as a hard error. | ||
| console.log("Skipping missing or unreachable asset:", url, error); | ||
| } | ||
| } | ||
|
|
||
| // Whether or not all files in the batch were cached successfully, count the batch as processed | ||
| // so that progress can eventually reach 100% even if some assets are missing. | ||
| cachingProgress += batch.length; | ||
|
|
||
| // Send progress update after each batch | ||
| const progress = Math.round((cachingProgress / bookAudioAndImageFiles.length) * 100); | ||
| const clients = await self.clients.matchAll(); | ||
| if (clients.length > 0) { | ||
| await channel.postMessage({ | ||
| command: "CachingProgress", | ||
| data: { progress, bookName: bookData.bookName }, | ||
| }); | ||
| } | ||
|
|
||
| // Introduce a small delay between batches | ||
| await new Promise((resolve) => setTimeout(resolve, 100)); | ||
| }); | ||
| } catch (error) { | ||
| console.error("Unhandled error in cacheBookAssets:", error); | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Send a terminal failure message when caching fails.
If caches.open() or cacheUrlsWithProgress() fails, this catch only logs the error and resolves the cache request. App.ts:93-125 and src/Books/GdlBookRuntime.ts:12-54 set the loading screen visible before caching and process only CachingProgress. They cannot clear the loading screen or offer retry after this failure.
Post a terminal CachingError message from this catch. Update both consumers to hide the loading screen and show a retry path when they receive it.
🤖 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 `@sw-src.ts` around lines 312 - 334, Update cacheBookAssets so its catch block
posts a terminal CachingError message through channel, including the book
identity and error details alongside the existing logging. In the consumers that
currently process CachingProgress, including App.ts handling and GdlBookRuntime,
handle CachingError by hiding the loading screen and exposing the established
retry path, while preserving normal progress behavior.
Changes
Ref: AJ-742
Summary by CodeRabbit
New Features
Bug Fixes