diff --git a/adev-es/src/app/routing/sub-navigation-data.ts b/adev-es/src/app/routing/sub-navigation-data.ts
index d8090d2..ad15821 100644
--- a/adev-es/src/app/routing/sub-navigation-data.ts
+++ b/adev-es/src/app/routing/sub-navigation-data.ts
@@ -915,7 +915,7 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
],
},
{
- label: 'Extended Ecosystem',
+ label: 'Ecosistema extendido',
children: [
{
label: 'NgModules',
@@ -976,42 +976,42 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
label: 'Service Workers & PWAs',
children: [
{
- label: 'Overview',
+ label: 'Visión general',
path: 'ecosystem/service-workers',
contentPath: 'ecosystem/service-workers/overview',
},
{
- label: 'Getting started',
+ label: 'Empezando',
path: 'ecosystem/service-workers/getting-started',
contentPath: 'ecosystem/service-workers/getting-started',
},
{
- label: 'Custom service worker scripts',
+ label: 'Scripts de service worker personalizados',
path: 'ecosystem/service-workers/custom-service-worker-scripts',
contentPath: 'ecosystem/service-workers/custom-service-worker-scripts',
},
{
- label: 'Configuration file',
+ label: 'Archivo de configuración',
path: 'ecosystem/service-workers/config',
contentPath: 'ecosystem/service-workers/config',
},
{
- label: 'Communicating with the service worker',
+ label: 'Comunicación con el service worker',
path: 'ecosystem/service-workers/communications',
contentPath: 'ecosystem/service-workers/communications',
},
{
- label: 'Push notifications',
+ label: 'Notificaciones push',
path: 'ecosystem/service-workers/push-notifications',
contentPath: 'ecosystem/service-workers/push-notifications',
},
{
- label: 'Service worker devops',
+ label: 'Devops del service worker',
path: 'ecosystem/service-workers/devops',
contentPath: 'ecosystem/service-workers/devops',
},
{
- label: 'App shell pattern',
+ label: 'Patrón App shell',
path: 'ecosystem/service-workers/app-shell',
contentPath: 'ecosystem/service-workers/app-shell',
},
diff --git a/adev-es/src/content/ecosystem/service-workers/app-shell.en.md b/adev-es/src/content/ecosystem/service-workers/app-shell.en.md
new file mode 100644
index 0000000..e4fdf2f
--- /dev/null
+++ b/adev-es/src/content/ecosystem/service-workers/app-shell.en.md
@@ -0,0 +1,64 @@
+# App shell pattern
+
+The [App shell pattern](https://developer.chrome.com/blog/app-shell) is a way to render a portion of your application using a route at build time.
+It can improve the user experience by quickly launching a static rendered page (a skeleton common to all pages) while the browser downloads the full client version and switches to it automatically after the code loads.
+
+This gives users a meaningful first paint of your application that appears quickly because the browser can render the HTML and CSS without the need to initialize any JavaScript.
+
+
+
+Do this with the following Angular CLI command:
+
+
+
+ng new my-app
+
+
+
+For an existing application, you have to manually add the `Router` and defining a `` within your application.
+
+
+Use the Angular CLI to automatically create the application shell.
+
+
+
+ng generate app-shell
+
+
+
+For more information about this command, see [App shell command](cli/generate/app-shell).
+
+The command updates the application code and adds extra files to the project structure.
+
+
+src
+├── app
+│ ├── app.config.server.ts # server application configuration
+│ └── app-shell # app-shell component
+│ ├── app-shell.component.html
+│ ├── app-shell.component.scss
+│ ├── app-shell.component.spec.ts
+│ └── app-shell.component.ts
+└── main.server.ts # main server application bootstrapping
+
+
+
+
+
+
+ng build --configuration=development
+
+
+
+Or to use the production configuration.
+
+
+
+ng build
+
+
+
+To verify the build output, open dist/my-app/browser/index.html.
+Look for default text `app-shell works!` to show that the application shell route was rendered as part of the output.
+
+
diff --git a/adev-es/src/content/ecosystem/service-workers/app-shell.md b/adev-es/src/content/ecosystem/service-workers/app-shell.md
index e4fdf2f..ce1b0de 100644
--- a/adev-es/src/content/ecosystem/service-workers/app-shell.md
+++ b/adev-es/src/content/ecosystem/service-workers/app-shell.md
@@ -1,13 +1,13 @@
-# App shell pattern
+# Patrón App shell
-The [App shell pattern](https://developer.chrome.com/blog/app-shell) is a way to render a portion of your application using a route at build time.
-It can improve the user experience by quickly launching a static rendered page (a skeleton common to all pages) while the browser downloads the full client version and switches to it automatically after the code loads.
+El [patrón App shell](https://developer.chrome.com/blog/app-shell) es una forma de renderizar una parte de tu aplicación usando una ruta en tiempo de compilación.
+Puede mejorar la experiencia de usuario al lanzar rápidamente una página estática renderizada (un esqueleto común a todas las páginas) mientras el navegador descarga la versión completa del cliente y cambia a ella automáticamente cuando el código termina de cargar.
-This gives users a meaningful first paint of your application that appears quickly because the browser can render the HTML and CSS without the need to initialize any JavaScript.
+Esto brinda a las personas usuarias un primer render significativo de tu aplicación que aparece rápidamente porque el navegador puede mostrar el HTML y el CSS sin necesidad de inicializar JavaScript.
-
-Do this with the following Angular CLI command:
+
+Hazlo con el siguiente comando de Angular CLI:
@@ -15,10 +15,10 @@ ng new my-app
-For an existing application, you have to manually add the `Router` and defining a `` within your application.
+Para una aplicación existente, debes agregar manualmente el `Router` y definir un `` dentro de tu aplicación.
-
-Use the Angular CLI to automatically create the application shell.
+
+Usa Angular CLI para crear automáticamente el shell de la aplicación.
@@ -26,23 +26,23 @@ ng generate app-shell
-For more information about this command, see [App shell command](cli/generate/app-shell).
+Para obtener más información sobre este comando, consulta [App shell command](cli/generate/app-shell).
-The command updates the application code and adds extra files to the project structure.
+El comando actualiza el código de la aplicación y agrega archivos adicionales a la estructura del proyecto.
src
├── app
-│ ├── app.config.server.ts # server application configuration
-│ └── app-shell # app-shell component
+│ ├── app.config.server.ts # configuración de la aplicación del servidor
+│ └── app-shell # componente app-shell
│ ├── app-shell.component.html
│ ├── app-shell.component.scss
│ ├── app-shell.component.spec.ts
│ └── app-shell.component.ts
-└── main.server.ts # main server application bootstrapping
+└── main.server.ts # arranque principal de la aplicación del servidor
-
+
@@ -50,7 +50,7 @@ ng build --configuration=development
-Or to use the production configuration.
+O usa la configuración de producción.
@@ -58,7 +58,7 @@ ng build
-To verify the build output, open dist/my-app/browser/index.html.
-Look for default text `app-shell works!` to show that the application shell route was rendered as part of the output.
+Para verificar el resultado de la compilación, abre dist/my-app/browser/index.html.
+Busca el texto predeterminado `app-shell works!` para confirmar que la ruta del shell de la aplicación se renderizó como parte de la salida.
diff --git a/adev-es/src/content/ecosystem/service-workers/communications.en.md b/adev-es/src/content/ecosystem/service-workers/communications.en.md
new file mode 100644
index 0000000..59ab2db
--- /dev/null
+++ b/adev-es/src/content/ecosystem/service-workers/communications.en.md
@@ -0,0 +1,108 @@
+# Communicating with the Service Worker
+
+Enabling service worker support does more than just register the service worker; it also provides services you can use to interact with the service worker and control the caching of your application.
+
+## `SwUpdate` service
+
+The `SwUpdate` service gives you access to events that indicate when the service worker discovers and installs an available update for your application.
+
+The `SwUpdate` service supports three separate operations:
+
+* Receiving notifications when an updated version is *detected* on the server, *installed and ready* to be used locally or when an *installation fails*.
+* Asking the service worker to check the server for new updates.
+* Asking the service worker to activate the latest version of the application for the current tab.
+
+### Version updates
+
+The `versionUpdates` is an `Observable` property of `SwUpdate` and emits five event types:
+
+| Event types | Details |
+|:--- |:--- |
+| `VersionDetectedEvent` | Emitted when the service worker has detected a new version of the app on the server and is about to start downloading it. |
+| `NoNewVersionDetectedEvent` | Emitted when the service worker has checked the version of the app on the server and did not find a new version. |
+| `VersionReadyEvent` | Emitted when a new version of the app is available to be activated by clients. It may be used to notify the user of an available update or prompt them to refresh the page. |
+| `VersionInstallationFailedEvent` | Emitted when the installation of a new version failed. It may be used for logging/monitoring purposes. |
+| `VersionFailedEvent` | Emitted when a version encounters a critical failure (such as broken hash errors) that affects all clients using that version. Provides error details for debugging and transparency. |
+
+
+
+### Checking for updates
+
+It's possible to ask the service worker to check if any updates have been deployed to the server.
+The service worker checks for updates during initialization and on each navigation request —that is, when the user navigates from a different address to your application.
+However, you might choose to manually check for updates if you have a site that changes frequently or want updates to happen on a schedule.
+
+Do this with the `checkForUpdate()` method:
+
+
+
+This method returns a `Promise` which indicates if an update is available for activation.
+The check might fail, which will cause a rejection of the `Promise`.
+
+
+In order to avoid negatively affecting the initial rendering of the page, by default the Angular service worker service waits for up to 30 seconds for the application to stabilize before registering the ServiceWorker script.
+
+Constantly polling for updates, for example, with [setInterval()](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or RxJS' [interval()](https://rxjs.dev/api/index/function/interval), prevents the application from stabilizing and the ServiceWorker script is not registered with the browser until the 30 seconds upper limit is reached.
+
+This is true for any kind of polling done by your application.
+Check the [isStable](api/core/ApplicationRef#isStable) documentation for more information.
+
+Avoid that delay by waiting for the application to stabilize first, before starting to poll for updates, as shown in the preceding example.
+Alternatively, you might want to define a different [registration strategy](api/service-worker/SwRegistrationOptions#registrationStrategy) for the ServiceWorker.
+
+
+### Updating to the latest version
+
+You can update an existing tab to the latest version by reloading the page as soon as a new version is ready.
+To avoid disrupting the user's progress, it is generally a good idea to prompt the user and let them confirm that it is OK to reload the page and update to the latest version:
+
+
+
+
+Calling `activateUpdate()` updates a tab to the latest version without reloading the page, but this could break the application.
+
+Updating without reloading can create a version mismatch between the application shell and other page resources, such as lazy-loaded chunks, whose filenames may change between versions.
+
+You should only use `activateUpdate()`, if you are certain it is safe for your specific use case.
+
+
+### Handling an unrecoverable state
+
+In some cases, the version of the application used by the service worker to serve a client might be in a broken state that cannot be recovered from without a full page reload.
+
+For example, imagine the following scenario:
+
+1. A user opens the application for the first time and the service worker caches the latest version of the application.
+ Assume the application's cached assets include `index.html`, `main..js` and `lazy-chunk..js`.
+
+1. The user closes the application and does not open it for a while.
+1. After some time, a new version of the application is deployed to the server.
+ This newer version includes the files `index.html`, `main..js` and `lazy-chunk..js`.
+
+IMPORTANT: The hashes are different now, because the content of the files changed. The old version is no longer available on the server.
+
+1. In the meantime, the user's browser decides to evict `lazy-chunk..js` from its cache.
+ Browsers might decide to evict specific (or all) resources from a cache in order to reclaim disk space.
+
+1. The user opens the application again.
+ The service worker serves the latest version known to it at this point, namely the old version (`index.html` and `main..js`).
+
+1. At some later point, the application requests the lazy bundle, `lazy-chunk..js`.
+1. The service worker is unable to find the asset in the cache (remember that the browser evicted it).
+ Nor is it able to retrieve it from the server (because the server now only has `lazy-chunk..js` from the newer version).
+
+In the preceding scenario, the service worker is not able to serve an asset that would normally be cached.
+That particular application version is broken and there is no way to fix the state of the client without reloading the page.
+In such cases, the service worker notifies the client by sending an `UnrecoverableStateEvent` event.
+Subscribe to `SwUpdate#unrecoverable` to be notified and handle these errors.
+
+
+
+## More on Angular service workers
+
+You might also be interested in the following:
+
+
+
+
+
diff --git a/adev-es/src/content/ecosystem/service-workers/communications.md b/adev-es/src/content/ecosystem/service-workers/communications.md
index 59ab2db..c3867b5 100644
--- a/adev-es/src/content/ecosystem/service-workers/communications.md
+++ b/adev-es/src/content/ecosystem/service-workers/communications.md
@@ -1,108 +1,103 @@
-# Communicating with the Service Worker
+# Comunícate con el Service Worker
-Enabling service worker support does more than just register the service worker; it also provides services you can use to interact with the service worker and control the caching of your application.
+Habilitar el soporte de service worker implica algo más que registrarlo; también proporciona servicios que puedes usar para interactuar con el service worker y controlar la caché de tu aplicación.
-## `SwUpdate` service
+## Servicio `SwUpdate`
-The `SwUpdate` service gives you access to events that indicate when the service worker discovers and installs an available update for your application.
+El servicio `SwUpdate` te da acceso a eventos que indican cuándo el service worker descubre e instala una actualización disponible para tu aplicación.
-The `SwUpdate` service supports three separate operations:
+El servicio `SwUpdate` admite tres operaciones diferentes:
-* Receiving notifications when an updated version is *detected* on the server, *installed and ready* to be used locally or when an *installation fails*.
-* Asking the service worker to check the server for new updates.
-* Asking the service worker to activate the latest version of the application for the current tab.
+* Recibir notificaciones cuando se *detecta* una versión actualizada en el servidor, cuando se *instala y está lista* para usarse localmente o cuando una *instalación falla*.
+* Pedirle al service worker que verifique en el servidor si hay nuevas actualizaciones.
+* Pedirle al service worker que active la versión más reciente de la aplicación para la pestaña actual.
-### Version updates
+### Actualizaciones de versión
-The `versionUpdates` is an `Observable` property of `SwUpdate` and emits five event types:
+`versionUpdates` es una propiedad `Observable` de `SwUpdate` y emite cinco tipos de eventos:
-| Event types | Details |
+| Tipos de eventos | Detalles |
|:--- |:--- |
-| `VersionDetectedEvent` | Emitted when the service worker has detected a new version of the app on the server and is about to start downloading it. |
-| `NoNewVersionDetectedEvent` | Emitted when the service worker has checked the version of the app on the server and did not find a new version. |
-| `VersionReadyEvent` | Emitted when a new version of the app is available to be activated by clients. It may be used to notify the user of an available update or prompt them to refresh the page. |
-| `VersionInstallationFailedEvent` | Emitted when the installation of a new version failed. It may be used for logging/monitoring purposes. |
-| `VersionFailedEvent` | Emitted when a version encounters a critical failure (such as broken hash errors) that affects all clients using that version. Provides error details for debugging and transparency. |
+| `VersionDetectedEvent` | Se emite cuando el service worker detecta una nueva versión de la aplicación en el servidor y está a punto de comenzar a descargarla. |
+| `NoNewVersionDetectedEvent` | Se emite cuando el service worker verifica la versión de la aplicación en el servidor y no encuentra una versión nueva. |
+| `VersionReadyEvent` | Se emite cuando hay una nueva versión disponible para que los clientes la activen. Puede usarse para notificar a la persona usuaria que hay una actualización disponible o para pedirle que actualice la página. |
+| `VersionInstallationFailedEvent` | Se emite cuando la instalación de una nueva versión falla. Puede utilizarse con fines de registro o monitoreo. |
+| `VersionFailedEvent` | Se emite cuando una versión encuentra una falla crítica (como errores de hashes rotos) que afecta a todas las personas usuarias que utilizan esa versión. Proporciona detalles del error para depuración y transparencia. |
-### Checking for updates
+### Verificar actualizaciones
-It's possible to ask the service worker to check if any updates have been deployed to the server.
-The service worker checks for updates during initialization and on each navigation request —that is, when the user navigates from a different address to your application.
-However, you might choose to manually check for updates if you have a site that changes frequently or want updates to happen on a schedule.
+Es posible pedirle al service worker que revise si se desplegó alguna actualización en el servidor.
+El service worker busca actualizaciones durante la inicialización y en cada solicitud de navegación—es decir, cuando la persona usuaria navega desde una dirección diferente hacia tu aplicación.
+Sin embargo, podrías optar por verificar las actualizaciones manualmente si tu sitio cambia con frecuencia o si quieres que las actualizaciones sucedan según un cronograma.
-Do this with the `checkForUpdate()` method:
+Hazlo con el método `checkForUpdate()`:
-This method returns a `Promise` which indicates if an update is available for activation.
-The check might fail, which will cause a rejection of the `Promise`.
+Este método devuelve un `Promise` que indica si hay una actualización disponible para activar.
+La verificación puede fallar, lo que provocará que la `Promise` se rechace.
-
-In order to avoid negatively affecting the initial rendering of the page, by default the Angular service worker service waits for up to 30 seconds for the application to stabilize before registering the ServiceWorker script.
+
+Para evitar que el renderizado inicial de la página se vea afectado de forma negativa, el servicio del service worker de Angular espera de manera predeterminada hasta 30 segundos a que la aplicación se estabilice antes de registrar el script del ServiceWorker.
-Constantly polling for updates, for example, with [setInterval()](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or RxJS' [interval()](https://rxjs.dev/api/index/function/interval), prevents the application from stabilizing and the ServiceWorker script is not registered with the browser until the 30 seconds upper limit is reached.
+Consultar constantemente si hay actualizaciones, por ejemplo, con [setInterval()](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) o con [interval()](https://rxjs.dev/api/index/function/interval) de RxJS, impide que la aplicación se estabilice y evita que el script del ServiceWorker se registre en el navegador hasta que se alcanza el límite máximo de 30 segundos.
-This is true for any kind of polling done by your application.
-Check the [isStable](api/core/ApplicationRef#isStable) documentation for more information.
+Esto aplica a cualquier tipo de sondeo que haga tu aplicación.
+Consulta la documentación de [isStable](api/core/ApplicationRef#isStable) para obtener más información.
-Avoid that delay by waiting for the application to stabilize first, before starting to poll for updates, as shown in the preceding example.
-Alternatively, you might want to define a different [registration strategy](api/service-worker/SwRegistrationOptions#registrationStrategy) for the ServiceWorker.
+Evita ese retraso esperando primero a que la aplicación se estabilice antes de comenzar a consultar por actualizaciones, como se muestra en el ejemplo anterior.
+Como alternativa, puedes definir una [estrategia de registro](api/service-worker/SwRegistrationOptions#registrationStrategy) diferente para el ServiceWorker.
-### Updating to the latest version
+### Actualizar a la versión más reciente
-You can update an existing tab to the latest version by reloading the page as soon as a new version is ready.
-To avoid disrupting the user's progress, it is generally a good idea to prompt the user and let them confirm that it is OK to reload the page and update to the latest version:
+Puedes actualizar una pestaña existente a la versión más reciente recargando la página tan pronto como una nueva versión esté lista.
+Para evitar interrumpir el progreso de la persona usuaria, en general es recomendable mostrar un aviso y pedir que confirme si desea recargar la página y actualizar a la versión más reciente:
-
-Calling `activateUpdate()` updates a tab to the latest version without reloading the page, but this could break the application.
+
+Llamar a `activateUpdate()` actualiza una pestaña a la versión más reciente sin recargar la página, pero esto podría romper la aplicación.
-Updating without reloading can create a version mismatch between the application shell and other page resources, such as lazy-loaded chunks, whose filenames may change between versions.
+Actualizar sin recargar puede crear una discrepancia de versiones entre el shell de la aplicación y otros recursos de la página, como los chunks cargados de forma diferida, cuyos nombres de archivo pueden cambiar entre versiones.
-You should only use `activateUpdate()`, if you are certain it is safe for your specific use case.
+Debes usar `activateUpdate()` solo si estás seguro de que es seguro para tu caso específico.
-### Handling an unrecoverable state
+### Manejar un estado irrecuperable
-In some cases, the version of the application used by the service worker to serve a client might be in a broken state that cannot be recovered from without a full page reload.
+En algunos casos, la versión de la aplicación que el service worker usa para atender a una persona usuaria puede quedar en un estado roto que no se puede recuperar sin recargar completamente la página.
-For example, imagine the following scenario:
+Por ejemplo, imagina el siguiente escenario:
-1. A user opens the application for the first time and the service worker caches the latest version of the application.
- Assume the application's cached assets include `index.html`, `main..js` and `lazy-chunk..js`.
+1. Una persona usuaria abre la aplicación por primera vez y el service worker almacena en caché la versión más reciente de la aplicación.
+ Supón que los recursos cacheados de la aplicación incluyen `index.html`, `main..js` y `lazy-chunk..js`.
+1. La persona usuaria cierra la aplicación y no la abre durante un tiempo.
+1. Después de un tiempo, se despliega en el servidor una nueva versión de la aplicación.
+ Esta versión más reciente incluye los archivos `index.html`, `main..js` y `lazy-chunk..js`.
+IMPORTANTE: Los hashes ahora son diferentes porque el contenido de los archivos cambió. La versión anterior ya no está disponible en el servidor.
+1. Mientras tanto, el navegador de la persona usuaria decide expulsar `lazy-chunk..js` de su caché.
+ Los navegadores pueden decidir expulsar recursos específicos (o todos) de una caché para recuperar espacio en disco.
+1. La persona usuaria vuelve a abrir la aplicación.
+ El service worker sirve la última versión que conoce en ese momento, es decir, la versión anterior (`index.html` y `main..js`).
+1. En algún momento posterior, la aplicación solicita el bundle diferido `lazy-chunk..js`.
+1. El service worker no puede encontrar el recurso en la caché (recuerda que el navegador lo expulsó).
+ Tampoco puede obtenerlo del servidor (porque el servidor ahora solo tiene `lazy-chunk..js` de la versión más reciente).
-1. The user closes the application and does not open it for a while.
-1. After some time, a new version of the application is deployed to the server.
- This newer version includes the files `index.html`, `main..js` and `lazy-chunk..js`.
-
-IMPORTANT: The hashes are different now, because the content of the files changed. The old version is no longer available on the server.
-
-1. In the meantime, the user's browser decides to evict `lazy-chunk..js` from its cache.
- Browsers might decide to evict specific (or all) resources from a cache in order to reclaim disk space.
-
-1. The user opens the application again.
- The service worker serves the latest version known to it at this point, namely the old version (`index.html` and `main..js`).
-
-1. At some later point, the application requests the lazy bundle, `lazy-chunk..js`.
-1. The service worker is unable to find the asset in the cache (remember that the browser evicted it).
- Nor is it able to retrieve it from the server (because the server now only has `lazy-chunk..js` from the newer version).
-
-In the preceding scenario, the service worker is not able to serve an asset that would normally be cached.
-That particular application version is broken and there is no way to fix the state of the client without reloading the page.
-In such cases, the service worker notifies the client by sending an `UnrecoverableStateEvent` event.
-Subscribe to `SwUpdate#unrecoverable` to be notified and handle these errors.
+En el escenario anterior, el service worker no puede servir un recurso que normalmente estaría en caché.
+Esa versión particular de la aplicación está rota y no hay forma de corregir el estado del cliente sin recargar la página.
+En esos casos, el service worker notifica al cliente enviando un evento `UnrecoverableStateEvent`.
+Suscríbete a `SwUpdate#unrecoverable` para recibir la notificación y manejar estos errores.
-## More on Angular service workers
+## Más sobre los service workers de Angular
-You might also be interested in the following:
+También podría interesarte lo siguiente:
-
+
diff --git a/adev-es/src/content/ecosystem/service-workers/config.en.md b/adev-es/src/content/ecosystem/service-workers/config.en.md
new file mode 100644
index 0000000..1cdf056
--- /dev/null
+++ b/adev-es/src/content/ecosystem/service-workers/config.en.md
@@ -0,0 +1,397 @@
+# Service Worker configuration file
+
+This topic describes the properties of the service worker configuration file.
+
+## Modifying the configuration
+
+The `ngsw-config.json` JSON configuration file specifies which files and data URLs the Angular service worker should cache and how it should update the cached files and data.
+The [Angular CLI](tools/cli) processes this configuration file during `ng build`.
+
+All file paths must begin with `/`, which corresponds to the deployment directory — usually `dist/` in CLI projects.
+
+Unless otherwise commented, patterns use a **limited*** glob format that internally will be converted into regex:
+
+| Glob formats | Details |
+|:--- |:--- |
+| `**` | Matches 0 or more path segments |
+| `*` | Matches 0 or more characters excluding `/` |
+| `?` | Matches exactly one character excluding `/` |
+| `!` prefix | Marks the pattern as being negative, meaning that only files that don't match the pattern are included |
+
+
+Pay attention that some characters with a special meaning in a regular expression are not escaped and also the pattern is not wrapped in `^`/`$` in the internal glob to regex conversion.
+
+`$` is a special character in regex that matches the end of the string and will not be automatically escaped when converting the glob pattern to a regular expression.
+
+If you want to literally match the `$` character, you have to escape it yourself (with `\\$`). For example, the glob pattern `/foo/bar/$value` results in an unmatchable expression, because it is impossible to have a string that has any characters after it has ended.
+
+The pattern will not be automatically wrapped in `^` and `$` when converting it to a regular expression. Therefore, the patterns will partially match the request URLs.
+
+If you want your patterns to match the beginning and/or end of URLs, you can add `^`/`$` yourself. For example, the glob pattern `/foo/bar/*.js` will match both `.js` and `.json` files. If you want to only match `.js` files, use `/foo/bar/*.js$`.
+
+
+Example patterns:
+
+| Patterns | Details |
+|:--- |:--- |
+| `/**/*.html` | Specifies all HTML files |
+| `/*.html` | Specifies only HTML files in the root |
+| `!/**/*.map` | Exclude all sourcemaps |
+
+## Service worker configuration properties
+
+The following sections describe each property of the configuration file.
+
+### `appData`
+
+This section enables you to pass any data you want that describes this particular version of the application.
+The `SwUpdate` service includes that data in the update notifications.
+Many applications use this section to provide additional information for the display of UI popups, notifying users of the available update.
+
+### `index`
+
+Specifies the file that serves as the index page to satisfy navigation requests.
+Usually this is `/index.html`.
+
+### `assetGroups`
+
+*Assets* are resources that are part of the application version that update along with the application.
+They can include resources loaded from the page's origin as well as third-party resources loaded from CDNs and other external URLs.
+As not all such external URLs might be known at build time, URL patterns can be matched.
+
+HELPFUL: For the service worker to handle resources that are loaded from different origins, make sure that [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) is correctly configured on each origin's server.
+
+This field contains an array of asset groups, each of which defines a set of asset resources and the policy by which they are cached.
+
+
+
+{
+ "assetGroups": [
+ {
+ …
+ },
+ {
+ …
+ }
+ ]
+}
+
+
+
+HELPFUL: When the ServiceWorker handles a request, it checks asset groups in the order in which they appear in `ngsw-config.json`.
+The first asset group that matches the requested resource handles the request.
+
+It is recommended that you put the more specific asset groups higher in the list.
+For example, an asset group that matches `/foo.js` should appear before one that matches `*.js`.
+
+Each asset group specifies both a group of resources and a policy that governs them.
+This policy determines when the resources are fetched and what happens when changes are detected.
+
+Asset groups follow the Typescript interface shown here:
+
+
+
+interface AssetGroup {
+ name: string;
+ installMode?: 'prefetch' | 'lazy';
+ updateMode?: 'prefetch' | 'lazy';
+ resources: {
+ files?: string[];
+ urls?: string[];
+ };
+ cacheQueryOptions?: {
+ ignoreSearch?: boolean;
+ };
+}
+
+
+
+Each `AssetGroup` is defined by the following asset group properties.
+
+#### `name`
+
+A `name` is mandatory.
+It identifies this particular group of assets between versions of the configuration.
+
+#### `installMode`
+
+The `installMode` determines how these resources are initially cached.
+The `installMode` can be either of two values:
+
+| Values | Details |
+|:--- |:--- |
+| `prefetch` | Tells the Angular service worker to fetch every single listed resource while it's caching the current version of the application. This is bandwidth-intensive but ensures resources are available whenever they're requested, even if the browser is currently offline. |
+| `lazy` | Does not cache any of the resources up front. Instead, the Angular service worker only caches resources for which it receives requests. This is an on-demand caching mode. Resources that are never requested are not cached. This is useful for things like images at different resolutions, so the service worker only caches the correct assets for the particular screen and orientation. |
+
+Defaults to `prefetch`.
+
+#### `updateMode`
+
+For resources already in the cache, the `updateMode` determines the caching behavior when a new version of the application is discovered.
+Any resources in the group that have changed since the previous version are updated in accordance with `updateMode`.
+
+| Values | Details |
+|:--- |:--- |
+| `prefetch` | Tells the service worker to download and cache the changed resources immediately. |
+| `lazy` | Tells the service worker to not cache those resources. Instead, it treats them as unrequested and waits until they're requested again before updating them. An `updateMode` of `lazy` is only valid if the `installMode` is also `lazy`. |
+
+Defaults to the value `installMode` is set to.
+
+#### `resources`
+
+This section describes the resources to cache, broken up into the following groups:
+
+| Resource groups | Details |
+|:--- |:--- |
+| `files` | Lists patterns that match files in the distribution directory. These can be single files or glob-like patterns that match a number of files. |
+| `urls` | Includes both URLs and URL patterns that are matched at runtime. These resources are not fetched directly and do not have content hashes, but they are cached according to their HTTP headers. This is most useful for CDNs such as the Google Fonts service.
*(Negative glob patterns are not supported and `?` will be matched literally; that is, it will not match any character other than `?`.)* |
+
+#### `cacheQueryOptions`
+
+These options are used to modify the matching behavior of requests.
+They are passed to the browsers `Cache#match` function.
+See [MDN](https://developer.mozilla.org/docs/Web/API/Cache/match) for details.
+Currently, only the following options are supported:
+
+| Options | Details |
+|:--- |:--- |
+| `ignoreSearch` | Ignore query parameters. Defaults to `false`. |
+
+### `dataGroups`
+
+Unlike asset resources, data requests are not versioned along with the application.
+They're cached according to manually-configured policies that are more useful for situations such as API requests and other data dependencies.
+
+This field contains an array of data groups, each of which defines a set of data resources and the policy by which they are cached.
+
+
+
+{
+ "dataGroups": [
+ {
+ …
+ },
+ {
+ …
+ }
+ ]
+}
+
+
+
+HELPFUL: When the ServiceWorker handles a request, it checks data groups in the order in which they appear in `ngsw-config.json`.
+The first data group that matches the requested resource handles the request.
+
+It is recommended that you put the more specific data groups higher in the list.
+For example, a data group that matches `/api/foo.json` should appear before one that matches `/api/*.json`.
+
+Data groups follow this Typescript interface:
+
+
+
+export interface DataGroup {
+ name: string;
+ urls: string[];
+ version?: number;
+ cacheConfig: {
+ maxSize: number;
+ maxAge: string;
+ timeout?: string;
+ refreshAhead?: string;
+ strategy?: 'freshness' | 'performance';
+ };
+ cacheQueryOptions?: {
+ ignoreSearch?: boolean;
+ };
+}
+
+
+
+Each `DataGroup` is defined by the following data group properties.
+
+#### `name`
+
+Similar to `assetGroups`, every data group has a `name` which uniquely identifies it.
+
+#### `urls`
+
+A list of URL patterns.
+URLs that match these patterns are cached according to this data group's policy.
+Only non-mutating requests (GET and HEAD) are cached.
+
+* Negative glob patterns are not supported
+* `?` is matched literally; that is, it matches *only* the character `?`
+
+#### `version`
+
+Occasionally APIs change formats in a way that is not backward-compatible.
+A new version of the application might not be compatible with the old API format and thus might not be compatible with existing cached resources from that API.
+
+`version` provides a mechanism to indicate that the resources being cached have been updated in a backwards-incompatible way, and that the old cache entries —those from previous versions— should be discarded.
+
+`version` is an integer field and defaults to `1`.
+
+#### `cacheConfig`
+
+The following properties define the policy by which matching requests are cached.
+
+##### `maxSize`
+
+The maximum number of entries, or responses, in the cache.
+
+CRITICAL: Open-ended caches can grow in unbounded ways and eventually exceed storage quotas, resulting in eviction.
+
+##### `maxAge`
+
+The `maxAge` parameter indicates how long responses are allowed to remain in the cache before being considered invalid and evicted. `maxAge` is a duration string, using the following unit suffixes:
+
+| Suffixes | Details |
+|:--- |:--- |
+| `d` | Days |
+| `h` | Hours |
+| `m` | Minutes |
+| `s` | Seconds |
+| `u` | Milliseconds |
+
+For example, the string `3d12h` caches content for up to three and a half days.
+
+##### `timeout`
+
+This duration string specifies the network timeout.
+The network timeout is how long the Angular service worker waits for the network to respond before using a cached response, if configured to do so.
+`timeout` is a duration string, using the following unit suffixes:
+
+| Suffixes | Details |
+|:--- |:--- |
+| `d` | Days |
+| `h` | Hours |
+| `m` | Minutes |
+| `s` | Seconds |
+| `u` | Milliseconds |
+
+For example, the string `5s30u` translates to five seconds and 30 milliseconds of network timeout.
+
+
+##### `refreshAhead`
+
+This duration string specifies the time ahead of the expiration of a cached resource when the Angular service worker should proactively attempt to refresh the resource from the network.
+The `refreshAhead` duration is an optional configuration that determines how much time before the expiration of a cached response the service worker should initiate a request to refresh the resource from the network.
+
+| Suffixes | Details |
+|:--- |:--- |
+| `d` | Days |
+| `h` | Hours |
+| `m` | Minutes |
+| `s` | Seconds |
+| `u` | Milliseconds |
+
+For example, the string `1h30m` translates to one hour and 30 minutes ahead of the expiration time.
+
+##### `strategy`
+
+The Angular service worker can use either of two caching strategies for data resources.
+
+| Caching strategies | Details |
+|:--- |:--- |
+| `performance` | The default, optimizes for responses that are as fast as possible. If a resource exists in the cache, the cached version is used, and no network request is made. This allows for some staleness, depending on the `maxAge`, in exchange for better performance. This is suitable for resources that don't change often; for example, user avatar images. |
+| `freshness` | Optimizes for currency of data, preferentially fetching requested data from the network. Only if the network times out, according to `timeout`, does the request fall back to the cache. This is useful for resources that change frequently; for example, account balances. |
+
+HELPFUL: You can also emulate a third strategy, [staleWhileRevalidate](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate), which returns cached data if it is available, but also fetches fresh data from the network in the background for next time.
+To use this strategy set `strategy` to `freshness` and `timeout` to `0u` in `cacheConfig`.
+
+This essentially does the following:
+
+1. Try to fetch from the network first.
+2. If the network request does not complete immediately, that is after a timeout of 0 ms, ignore the cache age and fall back to the cached value.
+3. Once the network request completes, update the cache for future requests.
+4. If the resource does not exist in the cache, wait for the network request anyway.
+
+##### `cacheOpaqueResponses`
+
+Whether the Angular service worker should cache opaque responses or not.
+
+If not specified, the default value depends on the data group's configured strategy:
+
+| Strategies | Details |
+|:--- |:--- |
+| Groups with the `freshness` strategy | The default value is `true` and the service worker caches opaque responses. These groups will request the data every time and only fall back to the cached response when offline or on a slow network. Therefore, it doesn't matter if the service worker caches an error response. |
+| Groups with the `performance` strategy | The default value is `false` and the service worker doesn't cache opaque responses. These groups would continue to return a cached response until `maxAge` expires, even if the error was due to a temporary network or server issue. Therefore, it would be problematic for the service worker to cache an error response. |
+
+
+
+In case you are not familiar, an [opaque response](https://fetch.spec.whatwg.org#concept-filtered-response-opaque) is a special type of response returned when requesting a resource that is on a different origin which doesn't return CORS headers.
+One of the characteristics of an opaque response is that the service worker is not allowed to read its status, meaning it can't check if the request was successful or not.
+See [Introduction to `fetch()`](https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types) for more details.
+
+If you are not able to implement CORS — for example, if you don't control the origin — prefer using the `freshness` strategy for resources that result in opaque responses.
+
+
+
+#### `cacheQueryOptions`
+
+See [assetGroups](#assetgroups) for details.
+
+### `navigationUrls`
+
+This optional section enables you to specify a custom list of URLs that will be redirected to the index file.
+
+#### Handling navigation requests
+
+The ServiceWorker redirects navigation requests that don't match any `asset` or `data` group to the specified [index file](#index).
+A request is considered to be a navigation request if:
+
+* Its [method](https://developer.mozilla.org/docs/Web/API/Request/method) is `GET`
+* Its [mode](https://developer.mozilla.org/docs/Web/API/Request/mode) is `navigation`
+* It accepts a `text/html` response as determined by the value of the `Accept` header
+* Its URL matches the following criteria:
+ * The URL must not contain a file extension (that is, a `.`) in the last path segment
+ * The URL must not contain `__`
+
+HELPFUL: To configure whether navigation requests are sent through to the network or not, see the [navigationRequestStrategy](#navigationrequeststrategy) section and [applicationMaxAge](#application-max-age) sections.
+
+#### Matching navigation request URLs
+
+While these default criteria are fine in most cases, it is sometimes desirable to configure different rules.
+For example, you might want to ignore specific routes, such as those that are not part of the Angular app, and pass them through to the server.
+
+This field contains an array of URLs and [glob-like](#modifying-the-configuration) URL patterns that are matched at runtime.
+It can contain both negative patterns (that is, patterns starting with `!`) and non-negative patterns and URLs.
+
+Only requests whose URLs match *any* of the non-negative URLs/patterns and *none* of the negative ones are considered navigation requests.
+The URL query is ignored when matching.
+
+If the field is omitted, it defaults to:
+
+
+
+[
+ '/**', // Include all URLs.
+ '!/**/*.*', // Exclude URLs to files (containing a file extension in the last segment).
+ '!/**/*__*', // Exclude URLs containing `__` in the last segment.
+ '!/**/*__*/**', // Exclude URLs containing `__` in any other segment.
+]
+
+
+
+### `navigationRequestStrategy`
+
+This optional property enables you to configure how the service worker handles navigation requests:
+
+
+
+{
+ "navigationRequestStrategy": "freshness"
+}
+
+
+
+| Possible values | Details |
+|:--- |:--- |
+| `'performance'` | The default setting. Serves the specified [index file](#index-file), which is typically cached. |
+| `'freshness'` | Passes the requests through to the network and falls back to the `performance` behavior when offline. This value is useful when the server redirects the navigation requests elsewhere using a `3xx` HTTP redirect status code. Reasons for using this value include: - Redirecting to an authentication website when authentication is not handled by the application
- Redirecting specific URLs to avoid breaking existing links/bookmarks after a website redesign
- Redirecting to a different website, such as a server-status page, while a page is temporarily down
|
+
+IMPORTANT: The `freshness` strategy usually results in more requests sent to the server, which can increase response latency. It is recommended that you use the default performance strategy whenever possible.
+
+### `applicationMaxAge`
+
+This optional property enables you to configure how long the service worker will cache any requests. Within the `maxAge`, files will be served from cache. Beyond it, all requests will only be served from the network, including asset and data requests.
diff --git a/adev-es/src/content/ecosystem/service-workers/config.md b/adev-es/src/content/ecosystem/service-workers/config.md
index 1cdf056..8318e64 100644
--- a/adev-es/src/content/ecosystem/service-workers/config.md
+++ b/adev-es/src/content/ecosystem/service-workers/config.md
@@ -1,67 +1,67 @@
-# Service Worker configuration file
+# Archivo de configuración del Service Worker
-This topic describes the properties of the service worker configuration file.
+Este tema describe las propiedades del archivo de configuración del service worker.
-## Modifying the configuration
+## Modificar la configuración
-The `ngsw-config.json` JSON configuration file specifies which files and data URLs the Angular service worker should cache and how it should update the cached files and data.
-The [Angular CLI](tools/cli) processes this configuration file during `ng build`.
+El archivo de configuración JSON `ngsw-config.json` especifica qué archivos y URL de datos debe almacenar en caché el service worker de Angular y cómo debe actualizar los archivos y datos almacenados.
+La [Angular CLI](tools/cli) procesa este archivo de configuración durante `ng build`.
-All file paths must begin with `/`, which corresponds to the deployment directory — usually `dist/` in CLI projects.
+Todas las rutas de archivo deben comenzar con `/`, que corresponde al directorio de despliegue (generalmente `dist/` en proyectos creados con la CLI).
-Unless otherwise commented, patterns use a **limited*** glob format that internally will be converted into regex:
+A menos que se indique lo contrario, los patrones utilizan un formato de glob **limitado*** que internamente se convierte en expresiones regulares:
-| Glob formats | Details |
-|:--- |:--- |
-| `**` | Matches 0 or more path segments |
-| `*` | Matches 0 or more characters excluding `/` |
-| `?` | Matches exactly one character excluding `/` |
-| `!` prefix | Marks the pattern as being negative, meaning that only files that don't match the pattern are included |
+| Formatos de glob | Detalles |
+|:--- |:--- |
+| `**` | Coincide con 0 o más segmentos de ruta |
+| `*` | Coincide con 0 o más caracteres excluyendo `/` |
+| `?` | Coincide con exactamente un carácter excluyendo `/` |
+| Prefijo `!` | Marca el patrón como negativo, lo que significa que solo se incluyen los archivos que no coincidan con el patrón |
-
-Pay attention that some characters with a special meaning in a regular expression are not escaped and also the pattern is not wrapped in `^`/`$` in the internal glob to regex conversion.
+
+Ten en cuenta que algunos caracteres con significado especial en una expresión regular no se escapan y que el patrón tampoco se envuelve en `^`/`$` durante la conversión interna de glob a regex.
-`$` is a special character in regex that matches the end of the string and will not be automatically escaped when converting the glob pattern to a regular expression.
+`$` es un carácter especial en regex que coincide con el final de la cadena y no se escapará automáticamente al convertir el patrón glob a expresión regular.
-If you want to literally match the `$` character, you have to escape it yourself (with `\\$`). For example, the glob pattern `/foo/bar/$value` results in an unmatchable expression, because it is impossible to have a string that has any characters after it has ended.
+Si quieres coincidir literalmente con el carácter `$`, debes escaparlo manualmente (con `\$`). Por ejemplo, el patrón glob `/foo/bar/$value` produce una expresión imposible de hacer coincidir, porque no puede existir ninguna cadena después del final de la cadena.
-The pattern will not be automatically wrapped in `^` and `$` when converting it to a regular expression. Therefore, the patterns will partially match the request URLs.
+El patrón tampoco se envolverá automáticamente en `^` y `$` al convertirlo en una expresión regular. Por lo tanto, los patrones coincidirán parcialmente con las URL de solicitud.
-If you want your patterns to match the beginning and/or end of URLs, you can add `^`/`$` yourself. For example, the glob pattern `/foo/bar/*.js` will match both `.js` and `.json` files. If you want to only match `.js` files, use `/foo/bar/*.js$`.
+Si deseas que tus patrones coincidan con el inicio y/o el final de las URL, puedes agregar `^`/`$` manualmente. Por ejemplo, el patrón glob `/foo/bar/*.js` coincidirá tanto con archivos `.js` como `.json`. Si quieres coincidir únicamente con archivos `.js`, usa `/foo/bar/*.js$`.
-Example patterns:
+Ejemplos de patrones:
-| Patterns | Details |
-|:--- |:--- |
-| `/**/*.html` | Specifies all HTML files |
-| `/*.html` | Specifies only HTML files in the root |
-| `!/**/*.map` | Exclude all sourcemaps |
+| Patrones | Detalles |
+|:--- |:--- |
+| `/**/*.html` | Especifica todos los archivos HTML |
+| `/*.html` | Especifica solo los archivos HTML en la raíz |
+| `!/**/*.map` | Excluye todos los sourcemaps |
-## Service worker configuration properties
+## Propiedades de configuración del service worker
-The following sections describe each property of the configuration file.
+Las siguientes secciones describen cada propiedad del archivo de configuración.
### `appData`
-This section enables you to pass any data you want that describes this particular version of the application.
-The `SwUpdate` service includes that data in the update notifications.
-Many applications use this section to provide additional information for the display of UI popups, notifying users of the available update.
+Esta sección te permite pasar cualquier dato que describa esta versión particular de la aplicación.
+El servicio `SwUpdate` incluye esos datos en las notificaciones de actualización.
+Muchas aplicaciones usan esta sección para proporcionar información adicional que se muestra en pop-ups de la interfaz de usuario cuando se notifica a las personas usuarias sobre una actualización disponible.
### `index`
-Specifies the file that serves as the index page to satisfy navigation requests.
-Usually this is `/index.html`.
+Especifica el archivo que actúa como página de índice para atender las solicitudes de navegación.
+Por lo general, es `/index.html`.
### `assetGroups`
-*Assets* are resources that are part of the application version that update along with the application.
-They can include resources loaded from the page's origin as well as third-party resources loaded from CDNs and other external URLs.
-As not all such external URLs might be known at build time, URL patterns can be matched.
+Los *assets* son recursos que forman parte de la versión de la aplicación y se actualizan junto con ella.
+Pueden incluir recursos cargados desde el origen de la página, así como recursos de terceros cargados desde CDNs y otras URLs externas.
+Como no todas esas URL externas pueden conocerse en tiempo de compilación, se pueden usar patrones de URL.
-HELPFUL: For the service worker to handle resources that are loaded from different origins, make sure that [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) is correctly configured on each origin's server.
+ÚTIL: Para que el service worker pueda manejar recursos cargados desde distintos orígenes, asegúrate de que [CORS](https://developer.mozilla.org/es/docs/Web/HTTP/Guides/CORS) esté configurado correctamente en el servidor de cada origen.
-This field contains an array of asset groups, each of which defines a set of asset resources and the policy by which they are cached.
+Este campo contiene un arreglo de grupos de assets; cada uno define un conjunto de recursos y la política mediante la cual se almacenan en caché.
@@ -78,16 +78,16 @@ This field contains an array of asset groups, each of which defines a set of ass
-HELPFUL: When the ServiceWorker handles a request, it checks asset groups in the order in which they appear in `ngsw-config.json`.
-The first asset group that matches the requested resource handles the request.
+ÚTIL: Cuando el ServiceWorker gestiona una solicitud, revisa los grupos de assets en el orden en que aparecen en `ngsw-config.json`.
+El primer grupo de assets que coincide con el recurso solicitado se encarga de la solicitud.
-It is recommended that you put the more specific asset groups higher in the list.
-For example, an asset group that matches `/foo.js` should appear before one that matches `*.js`.
+Es recomendable colocar los grupos de assets más específicos en la parte superior de la lista.
+Por ejemplo, un grupo de assets que coincide con `/foo.js` debería aparecer antes que uno que coincida con `*.js`.
-Each asset group specifies both a group of resources and a policy that governs them.
-This policy determines when the resources are fetched and what happens when changes are detected.
+Cada grupo de assets especifica tanto un conjunto de recursos como la política que los rige.
+Esta política determina cuándo se obtienen los recursos y qué sucede cuando se detectan cambios.
-Asset groups follow the Typescript interface shown here:
+Los grupos de assets siguen la interfaz de TypeScript que se muestra aquí:
@@ -106,63 +106,63 @@ interface AssetGroup {
-Each `AssetGroup` is defined by the following asset group properties.
+Cada `AssetGroup` se define mediante las siguientes propiedades.
#### `name`
-A `name` is mandatory.
-It identifies this particular group of assets between versions of the configuration.
+`name` es obligatorio.
+Identifica este grupo de assets en particular entre versiones de la configuración.
#### `installMode`
-The `installMode` determines how these resources are initially cached.
-The `installMode` can be either of two values:
+`installMode` determina cómo se almacenan inicialmente estos recursos en caché.
+`installMode` puede tomar uno de dos valores:
-| Values | Details |
-|:--- |:--- |
-| `prefetch` | Tells the Angular service worker to fetch every single listed resource while it's caching the current version of the application. This is bandwidth-intensive but ensures resources are available whenever they're requested, even if the browser is currently offline. |
-| `lazy` | Does not cache any of the resources up front. Instead, the Angular service worker only caches resources for which it receives requests. This is an on-demand caching mode. Resources that are never requested are not cached. This is useful for things like images at different resolutions, so the service worker only caches the correct assets for the particular screen and orientation. |
+| Valores | Detalles |
+|:--- |:--- |
+| `prefetch` | Indica al service worker de Angular que obtenga cada recurso listado mientras almacena en caché la versión actual de la aplicación. Esto consume mucho ancho de banda, pero garantiza que los recursos estén disponibles siempre que se soliciten, incluso si el navegador está sin conexión. |
+| `lazy` | No almacena ninguno de los recursos por adelantado. En su lugar, el service worker de Angular solo guarda en caché los recursos que recibe en las solicitudes. Es un modo de caché bajo demanda. Los recursos que nunca se solicitan no se almacenan. Es útil para elementos como imágenes en distintas resoluciones, de modo que el service worker solo almacena en caché los assets correctos para la pantalla y orientación específicas. |
-Defaults to `prefetch`.
+El valor predeterminado es `prefetch`.
#### `updateMode`
-For resources already in the cache, the `updateMode` determines the caching behavior when a new version of the application is discovered.
-Any resources in the group that have changed since the previous version are updated in accordance with `updateMode`.
+Para los recursos que ya están en caché, `updateMode` determina el comportamiento de caché cuando se descubre una nueva versión de la aplicación.
+Cualquier recurso del grupo que haya cambiado desde la versión anterior se actualiza según `updateMode`.
-| Values | Details |
-|:--- |:--- |
-| `prefetch` | Tells the service worker to download and cache the changed resources immediately. |
-| `lazy` | Tells the service worker to not cache those resources. Instead, it treats them as unrequested and waits until they're requested again before updating them. An `updateMode` of `lazy` is only valid if the `installMode` is also `lazy`. |
+| Valores | Detalles |
+|:--- |:--- |
+| `prefetch` | Indica al service worker que descargue y almacene en caché los recursos modificados de inmediato. |
+| `lazy` | Indica al service worker que no almacene esos recursos en caché. En su lugar, los trata como si no se hubieran solicitado y espera hasta que vuelvan a pedirse para actualizarlos. Un `updateMode` de `lazy` solo es válido si `installMode` también es `lazy`. |
-Defaults to the value `installMode` is set to.
+El valor predeterminado es el que se defina en `installMode`.
#### `resources`
-This section describes the resources to cache, broken up into the following groups:
+Esta sección describe los recursos que se almacenarán en caché, divididos en los siguientes grupos:
-| Resource groups | Details |
-|:--- |:--- |
-| `files` | Lists patterns that match files in the distribution directory. These can be single files or glob-like patterns that match a number of files. |
-| `urls` | Includes both URLs and URL patterns that are matched at runtime. These resources are not fetched directly and do not have content hashes, but they are cached according to their HTTP headers. This is most useful for CDNs such as the Google Fonts service.
*(Negative glob patterns are not supported and `?` will be matched literally; that is, it will not match any character other than `?`.)* |
+| Grupos de recursos | Detalles |
+|:--- |:--- |
+| `files` | Lista patrones que coinciden con archivos en el directorio de distribución. Estos pueden ser archivos individuales o patrones de tipo glob que coincidan con varios archivos. |
+| `urls` | Incluye tanto URL como patrones de URL que se comparan en tiempo de ejecución. Estos recursos no se obtienen directamente y no tienen hashes de contenido, pero se almacenan en caché de acuerdo con sus encabezados HTTP. Es especialmente útil para CDNs como el servicio de Google Fonts.
*(No se admiten patrones glob negativos y `?` se compara literalmente; es decir, no coincide con ningún carácter que no sea `?`).* |
#### `cacheQueryOptions`
-These options are used to modify the matching behavior of requests.
-They are passed to the browsers `Cache#match` function.
-See [MDN](https://developer.mozilla.org/docs/Web/API/Cache/match) for details.
-Currently, only the following options are supported:
+Estas opciones se usan para modificar el comportamiento de coincidencia de las solicitudes.
+Se pasan a la función `Cache#match` de los navegadores.
+Consulta [MDN](https://developer.mozilla.org/docs/Web/API/Cache/match) para obtener detalles.
+Actualmente, solo se admiten las siguientes opciones:
-| Options | Details |
-|:--- |:--- |
-| `ignoreSearch` | Ignore query parameters. Defaults to `false`. |
+| Opciones | Detalles |
+|:--- |:--- |
+| `ignoreSearch` | Ignora los parámetros de consulta. El valor predeterminado es `false`. |
### `dataGroups`
-Unlike asset resources, data requests are not versioned along with the application.
-They're cached according to manually-configured policies that are more useful for situations such as API requests and other data dependencies.
+A diferencia de los recursos de tipo asset, las solicitudes de datos no se versionan junto con la aplicación.
+Se almacenan en caché según políticas configuradas manualmente que resultan más útiles en situaciones como solicitudes a APIs y otras dependencias de datos.
-This field contains an array of data groups, each of which defines a set of data resources and the policy by which they are cached.
+Este campo contiene un arreglo de grupos de datos; cada uno define un conjunto de recursos de datos y la política con la que se almacenan en caché.
@@ -179,13 +179,13 @@ This field contains an array of data groups, each of which defines a set of data
-HELPFUL: When the ServiceWorker handles a request, it checks data groups in the order in which they appear in `ngsw-config.json`.
-The first data group that matches the requested resource handles the request.
+ÚTIL: Cuando el ServiceWorker gestiona una solicitud, revisa los grupos de datos en el orden en que aparecen en `ngsw-config.json`.
+El primer grupo de datos que coincide con el recurso solicitado se encarga de la solicitud.
-It is recommended that you put the more specific data groups higher in the list.
-For example, a data group that matches `/api/foo.json` should appear before one that matches `/api/*.json`.
+Se recomienda colocar los grupos de datos más específicos en la parte superior de la lista.
+Por ejemplo, un grupo que coincida con `/api/foo.json` debería aparecer antes que uno que coincida con `/api/*.json`.
-Data groups follow this Typescript interface:
+Los grupos de datos siguen la siguiente interfaz de TypeScript:
@@ -207,175 +207,172 @@ export interface DataGroup {
-Each `DataGroup` is defined by the following data group properties.
+Cada `DataGroup` se define mediante las siguientes propiedades.
#### `name`
-Similar to `assetGroups`, every data group has a `name` which uniquely identifies it.
+De forma similar a `assetGroups`, cada grupo de datos tiene un `name` que lo identifica de manera única.
#### `urls`
-A list of URL patterns.
-URLs that match these patterns are cached according to this data group's policy.
-Only non-mutating requests (GET and HEAD) are cached.
+Una lista de patrones de URL.
+Las URL que coinciden con estos patrones se almacenan en caché según la política de este grupo de datos.
+Solo se almacenan en caché las solicitudes no mutables (GET y HEAD).
-* Negative glob patterns are not supported
-* `?` is matched literally; that is, it matches *only* the character `?`
+* No se admiten patrones glob negativos
+* `?` se compara literalmente; es decir, coincide *solo* con el carácter `?`
#### `version`
-Occasionally APIs change formats in a way that is not backward-compatible.
-A new version of the application might not be compatible with the old API format and thus might not be compatible with existing cached resources from that API.
+Ocasionalmente, las APIs cambian de formato de una manera que no es retrocompatible.
+Una nueva versión de la aplicación podría no ser compatible con el formato antiguo de la API y, por lo tanto, no ser compatible con los recursos existentes almacenados en caché de esa API.
-`version` provides a mechanism to indicate that the resources being cached have been updated in a backwards-incompatible way, and that the old cache entries —those from previous versions— should be discarded.
+`version` ofrece un mecanismo para indicar que los recursos almacenados en caché se actualizaron de forma no retrocompatible y que las entradas antiguas de la caché—es decir, las versiones anteriores—deben descartarse.
-`version` is an integer field and defaults to `1`.
+`version` es un campo entero y el valor predeterminado es `1`.
#### `cacheConfig`
-The following properties define the policy by which matching requests are cached.
+Las siguientes propiedades definen la política según la cual las solicitudes coincidentes se almacenan en caché.
##### `maxSize`
-The maximum number of entries, or responses, in the cache.
+El número máximo de entradas o respuestas en la caché.
-CRITICAL: Open-ended caches can grow in unbounded ways and eventually exceed storage quotas, resulting in eviction.
+CRÍTICO: Las cachés sin límites pueden crecer indefinidamente y, finalmente, exceder las cuotas de almacenamiento, lo que se traduce en expulsiones.
##### `maxAge`
-The `maxAge` parameter indicates how long responses are allowed to remain in the cache before being considered invalid and evicted. `maxAge` is a duration string, using the following unit suffixes:
+El parámetro `maxAge` indica cuánto tiempo pueden permanecer las respuestas en la caché antes de considerarse inválidas y ser expulsadas. `maxAge` es una cadena de duración con los siguientes sufijos de unidad:
-| Suffixes | Details |
-|:--- |:--- |
-| `d` | Days |
-| `h` | Hours |
-| `m` | Minutes |
-| `s` | Seconds |
-| `u` | Milliseconds |
+| Sufijos | Detalles |
+|:--- |:--- |
+| `d` | Días |
+| `h` | Horas |
+| `m` | Minutos |
+| `s` | Segundos |
+| `u` | Milisegundos |
-For example, the string `3d12h` caches content for up to three and a half days.
+Por ejemplo, la cadena `3d12h` almacena contenido hasta por tres días y medio.
##### `timeout`
-This duration string specifies the network timeout.
-The network timeout is how long the Angular service worker waits for the network to respond before using a cached response, if configured to do so.
-`timeout` is a duration string, using the following unit suffixes:
-
-| Suffixes | Details |
-|:--- |:--- |
-| `d` | Days |
-| `h` | Hours |
-| `m` | Minutes |
-| `s` | Seconds |
-| `u` | Milliseconds |
+Esta cadena de duración especifica el tiempo de espera de red.
+Es el tiempo que el service worker de Angular espera la respuesta de la red antes de usar una respuesta en caché, si está configurado para hacerlo.
+`timeout` es una cadena de duración con los siguientes sufijos:
-For example, the string `5s30u` translates to five seconds and 30 milliseconds of network timeout.
+| Sufijos | Detalles |
+|:--- |:--- |
+| `d` | Días |
+| `h` | Horas |
+| `m` | Minutos |
+| `s` | Segundos |
+| `u` | Milisegundos |
+Por ejemplo, la cadena `5s30u` equivale a cinco segundos y 30 milisegundos de tiempo de espera de red.
##### `refreshAhead`
-This duration string specifies the time ahead of the expiration of a cached resource when the Angular service worker should proactively attempt to refresh the resource from the network.
-The `refreshAhead` duration is an optional configuration that determines how much time before the expiration of a cached response the service worker should initiate a request to refresh the resource from the network.
+Esta cadena de duración especifica cuánto tiempo antes de que expire un recurso almacenado en caché debe intentar el service worker de Angular actualizarlo proactivamente desde la red.
+`refreshAhead` es opcional y determina cuánto antes de la expiración de la respuesta almacenada el service worker debe iniciar una solicitud para actualizar el recurso desde la red.
-| Suffixes | Details |
-|:--- |:--- |
-| `d` | Days |
-| `h` | Hours |
-| `m` | Minutes |
-| `s` | Seconds |
-| `u` | Milliseconds |
+| Sufijos | Detalles |
+|:--- |:--- |
+| `d` | Días |
+| `h` | Horas |
+| `m` | Minutos |
+| `s` | Segundos |
+| `u` | Milisegundos |
-For example, the string `1h30m` translates to one hour and 30 minutes ahead of the expiration time.
+Por ejemplo, la cadena `1h30m` significa una hora y 30 minutos antes del tiempo de expiración.
##### `strategy`
-The Angular service worker can use either of two caching strategies for data resources.
+El service worker de Angular puede usar una de dos estrategias de caché para los recursos de datos.
-| Caching strategies | Details |
-|:--- |:--- |
-| `performance` | The default, optimizes for responses that are as fast as possible. If a resource exists in the cache, the cached version is used, and no network request is made. This allows for some staleness, depending on the `maxAge`, in exchange for better performance. This is suitable for resources that don't change often; for example, user avatar images. |
-| `freshness` | Optimizes for currency of data, preferentially fetching requested data from the network. Only if the network times out, according to `timeout`, does the request fall back to the cache. This is useful for resources that change frequently; for example, account balances. |
+| Estrategias de caché | Detalles |
+|:--- |:--- |
+| `performance` | Es la opción predeterminada y optimiza para respuestas lo más rápidas posible. Si existe un recurso en la caché, se usa la versión almacenada y no se realiza ninguna solicitud de red. Esto permite cierta obsolescencia, según `maxAge`, a cambio de un mejor rendimiento. Es adecuada para recursos que no cambian con frecuencia, como imágenes de avatar de usuario. |
+| `freshness` | Optimiza para la frescura de los datos, priorizando la obtención de la información solicitada desde la red. Solo si la red excede el tiempo de espera definido en `timeout` la solicitud recurre a la caché. Es útil para recursos que cambian con frecuencia, como saldos de cuentas. |
-HELPFUL: You can also emulate a third strategy, [staleWhileRevalidate](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate), which returns cached data if it is available, but also fetches fresh data from the network in the background for next time.
-To use this strategy set `strategy` to `freshness` and `timeout` to `0u` in `cacheConfig`.
+ÚTIL: También puedes emular una tercera estrategia, [staleWhileRevalidate](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate), que devuelve datos cacheados si están disponibles, pero también obtiene datos frescos de la red en segundo plano para la próxima vez.
+Para usar esta estrategia, establece `strategy` en `freshness` y `timeout` en `0u` dentro de `cacheConfig`.
-This essentially does the following:
+Esto, en esencia, realiza lo siguiente:
-1. Try to fetch from the network first.
-2. If the network request does not complete immediately, that is after a timeout of 0 ms, ignore the cache age and fall back to the cached value.
-3. Once the network request completes, update the cache for future requests.
-4. If the resource does not exist in the cache, wait for the network request anyway.
+1. Intenta obtener los datos desde la red primero.
+2. Si la solicitud de red no se completa inmediatamente (es decir, después de un tiempo de espera de 0 ms), ignora la antigüedad de la caché y recurre al valor almacenado.
+3. Una vez que la solicitud de red finaliza, actualiza la caché para futuras solicitudes.
+4. Si el recurso no existe en la caché, espera igualmente la respuesta de la red.
##### `cacheOpaqueResponses`
-Whether the Angular service worker should cache opaque responses or not.
+Indica si el service worker de Angular debe almacenar o no respuestas opacas.
-If not specified, the default value depends on the data group's configured strategy:
+Si no se especifica, el valor predeterminado depende de la estrategia configurada para el grupo de datos:
-| Strategies | Details |
-|:--- |:--- |
-| Groups with the `freshness` strategy | The default value is `true` and the service worker caches opaque responses. These groups will request the data every time and only fall back to the cached response when offline or on a slow network. Therefore, it doesn't matter if the service worker caches an error response. |
-| Groups with the `performance` strategy | The default value is `false` and the service worker doesn't cache opaque responses. These groups would continue to return a cached response until `maxAge` expires, even if the error was due to a temporary network or server issue. Therefore, it would be problematic for the service worker to cache an error response. |
+| Estrategias | Detalles |
+|:--- |:--- |
+| Grupos con la estrategia `freshness` | El valor predeterminado es `true` y el service worker almacena respuestas opacas. Estos grupos solicitarán los datos cada vez y solo recurrirán a la respuesta en caché cuando estén sin conexión o en una red lenta. Por lo tanto, no importa si el service worker almacena una respuesta de error. |
+| Grupos con la estrategia `performance`| El valor predeterminado es `false` y el service worker no almacena respuestas opacas. Estos grupos seguirían devolviendo una respuesta cacheada hasta que `maxAge` expire, incluso si el error se debe a un problema temporal de red o del servidor. Por ello, sería problemático que el service worker almacenara una respuesta de error. |
-
-
-In case you are not familiar, an [opaque response](https://fetch.spec.whatwg.org#concept-filtered-response-opaque) is a special type of response returned when requesting a resource that is on a different origin which doesn't return CORS headers.
-One of the characteristics of an opaque response is that the service worker is not allowed to read its status, meaning it can't check if the request was successful or not.
-See [Introduction to `fetch()`](https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types) for more details.
-
-If you are not able to implement CORS — for example, if you don't control the origin — prefer using the `freshness` strategy for resources that result in opaque responses.
+
+Si no estás familiarizado, una [respuesta opaca](https://fetch.spec.whatwg.org#concept-filtered-response-opaque) es un tipo especial de respuesta que se devuelve cuando se solicita un recurso en un origen distinto que no retorna encabezados CORS.
+Una de las características de una respuesta opaca es que al service worker no se le permite leer su estado, es decir, no puede verificar si la solicitud se realizó correctamente.
+Consulta [Introduction to `fetch()`](https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types) para más detalles.
+Si no puedes implementar CORS—por ejemplo, si no controlas el origen—prefiere usar la estrategia `freshness` para los recursos que resulten en respuestas opacas.
#### `cacheQueryOptions`
-See [assetGroups](#assetgroups) for details.
+Consulta [assetGroups](#assetgroups) para obtener detalles.
### `navigationUrls`
-This optional section enables you to specify a custom list of URLs that will be redirected to the index file.
+Esta sección opcional te permite especificar una lista personalizada de URL que se redirigirán al archivo de índice.
-#### Handling navigation requests
+#### Manejo de solicitudes de navegación
-The ServiceWorker redirects navigation requests that don't match any `asset` or `data` group to the specified [index file](#index).
-A request is considered to be a navigation request if:
+El ServiceWorker redirige las solicitudes de navegación que no coinciden con ningún grupo de `asset` o `data` al [archivo de índice](#index) especificado.
+Una solicitud se considera de navegación si:
-* Its [method](https://developer.mozilla.org/docs/Web/API/Request/method) is `GET`
-* Its [mode](https://developer.mozilla.org/docs/Web/API/Request/mode) is `navigation`
-* It accepts a `text/html` response as determined by the value of the `Accept` header
-* Its URL matches the following criteria:
- * The URL must not contain a file extension (that is, a `.`) in the last path segment
- * The URL must not contain `__`
+* Su [método](https://developer.mozilla.org/docs/Web/API/Request/method) es `GET`
+* Su [modo](https://developer.mozilla.org/docs/Web/API/Request/mode) es `navigation`
+* Acepta una respuesta `text/html`, según el valor del encabezado `Accept`
+* Su URL cumple con los siguientes criterios:
+ * La URL no debe contener una extensión de archivo (es decir, un `.`) en el último segmento del path
+ * La URL no debe contener `__`
-HELPFUL: To configure whether navigation requests are sent through to the network or not, see the [navigationRequestStrategy](#navigationrequeststrategy) section and [applicationMaxAge](#application-max-age) sections.
+ÚTIL: Para configurar si las solicitudes de navegación se envían o no a la red, consulta las secciones [navigationRequestStrategy](#navigationrequeststrategy) y [applicationMaxAge](#application-max-age).
-#### Matching navigation request URLs
+#### Coincidencias de URL de navegación
-While these default criteria are fine in most cases, it is sometimes desirable to configure different rules.
-For example, you might want to ignore specific routes, such as those that are not part of the Angular app, and pass them through to the server.
+Aunque estos criterios predeterminados funcionan en la mayoría de los casos, a veces es conveniente configurar reglas diferentes.
+Por ejemplo, podrías querer ignorar rutas específicas, como las que no forman parte de la aplicación Angular, y dejarlas pasar al servidor.
-This field contains an array of URLs and [glob-like](#modifying-the-configuration) URL patterns that are matched at runtime.
-It can contain both negative patterns (that is, patterns starting with `!`) and non-negative patterns and URLs.
+Este campo contiene un arreglo de URL y patrones de URL (tipo glob, [como se describió anteriormente](#modificar-la-configuración)) que se comparan en tiempo de ejecución.
+Puede contener patrones y URL negativos (es decir, patrones que comienzan con `!`) y no negativos.
-Only requests whose URLs match *any* of the non-negative URLs/patterns and *none* of the negative ones are considered navigation requests.
-The URL query is ignored when matching.
+Solo las solicitudes cuyas URL coincidan con *alguno* de los patrones o URL no negativos y *ninguno* de los negativos se consideran solicitudes de navegación.
+La query de la URL se ignora al hacer esta comparación.
-If the field is omitted, it defaults to:
+Si se omite el campo, el valor predeterminado es:
[
- '/**', // Include all URLs.
- '!/**/*.*', // Exclude URLs to files (containing a file extension in the last segment).
- '!/**/*__*', // Exclude URLs containing `__` in the last segment.
- '!/**/*__*/**', // Exclude URLs containing `__` in any other segment.
+ '/**', // Incluir todas las URL.
+ '!/**/*.*', // Excluir URL de archivos (que contienen una extensión en el último segmento).
+ '!/**/*__*', // Excluir URL que contienen `__` en el último segmento.
+ '!/**/*__*/**', // Excluir URL que contienen `__` en cualquier otro segmento.
]
### `navigationRequestStrategy`
-This optional property enables you to configure how the service worker handles navigation requests:
+Esta propiedad opcional te permite configurar cómo el service worker maneja las solicitudes de navegación:
@@ -385,13 +382,13 @@ This optional property enables you to configure how the service worker handles n
-| Possible values | Details |
-|:--- |:--- |
-| `'performance'` | The default setting. Serves the specified [index file](#index-file), which is typically cached. |
-| `'freshness'` | Passes the requests through to the network and falls back to the `performance` behavior when offline. This value is useful when the server redirects the navigation requests elsewhere using a `3xx` HTTP redirect status code. Reasons for using this value include: - Redirecting to an authentication website when authentication is not handled by the application
- Redirecting specific URLs to avoid breaking existing links/bookmarks after a website redesign
- Redirecting to a different website, such as a server-status page, while a page is temporarily down
|
+| Posibles valores | Detalles |
+|:--- |:--- |
+| `'performance'` | El valor predeterminado. Sirve el [archivo de índice](#index) especificado, que normalmente está almacenado en caché. |
+| `'freshness'` | Envía las solicitudes a la red y recurre al comportamiento de `performance` cuando se está sin conexión. Este valor es útil cuando el servidor redirige las solicitudes de navegación a otro lugar usando un código de estado HTTP `3xx`. Algunas razones para usar este valor incluyen: - Redirigir a un sitio de autenticación cuando la autenticación no la gestiona la aplicación
- Redirigir URL específicas para evitar romper enlaces o marcadores existentes después de un rediseño
- Redirigir a un sitio diferente, como una página de estado del servidor, mientras una página está temporalmente caída
|
-IMPORTANT: The `freshness` strategy usually results in more requests sent to the server, which can increase response latency. It is recommended that you use the default performance strategy whenever possible.
+IMPORTANTE: La estrategia `freshness` suele resultar en más solicitudes al servidor, lo que puede aumentar la latencia de respuesta. Se recomienda usar la estrategia predeterminada `performance` siempre que sea posible.
### `applicationMaxAge`
-This optional property enables you to configure how long the service worker will cache any requests. Within the `maxAge`, files will be served from cache. Beyond it, all requests will only be served from the network, including asset and data requests.
+Esta propiedad opcional te permite configurar cuánto tiempo el service worker almacenará en caché cualquier solicitud. Dentro de `maxAge`, los archivos se entregan desde la caché. Después de ese tiempo, todas las solicitudes se atienden exclusivamente desde la red, incluidos los assets y los datos.
diff --git a/adev-es/src/content/ecosystem/service-workers/custom-service-worker-scripts.en.md b/adev-es/src/content/ecosystem/service-workers/custom-service-worker-scripts.en.md
new file mode 100644
index 0000000..8bafac8
--- /dev/null
+++ b/adev-es/src/content/ecosystem/service-workers/custom-service-worker-scripts.en.md
@@ -0,0 +1,111 @@
+# Custom service worker scripts
+
+While the Angular service worker provides excellent capabilities, you may need to add custom functionality such as handling push notifications, background sync, or other service worker events. You can create a custom service worker script that imports and extends the Angular service worker.
+
+## Creating a custom service worker
+
+To create a custom service worker that extends Angular's functionality:
+
+1. Create a custom service worker file (e.g., `custom-sw.js`) in your `src` directory:
+
+
+
+// Import the Angular service worker
+importScripts('./ngsw-worker.js');
+
+(function () {
+ 'use strict';
+
+ // Add custom notification click handler
+ self.addEventListener('notificationclick', (event) => {
+ console.log('Custom notification click handler');
+ console.log('Notification details:', event.notification);
+
+ // Handle notification click - open URL if provided
+ if (clients.openWindow && event.notification.data.url) {
+ event.waitUntil(clients.openWindow(event.notification.data.url));
+ console.log('Opening URL:', event.notification.data.url);
+ }
+ });
+
+ // Add custom background sync handler
+ self.addEventListener('sync', (event) => {
+ console.log('Custom background sync handler');
+
+ if (event.tag === 'background-sync') {
+ event.waitUntil(doBackgroundSync());
+ }
+ });
+
+ function doBackgroundSync() {
+ // Implement your background sync logic here
+ return fetch('https://example.com/api/sync')
+ .then(response => response.json())
+ .then(data => console.log('Background sync completed:', data))
+ .catch(error => console.error('Background sync failed:', error));
+ }
+})();
+
+
+
+2. Update your `angular.json` file to use the custom service worker:
+
+
+
+{
+ "projects": {
+ "your-app": {
+ "architect": {
+ "build": {
+ "options": {
+ "assets": [
+ {
+ "glob": "**/*",
+ "input": "public"
+ },
+ "app/src/custom-sw.js"
+ ]
+ },
+ }
+ }
+ }
+ }
+}
+
+
+
+3. Configure the service worker registration to use your custom script:
+
+
+
+import { ApplicationConfig, isDevMode } from '@angular/core';
+import { provideServiceWorker } from '@angular/service-worker';
+
+export const appConfig: ApplicationConfig = {
+ providers: [
+ provideServiceWorker('custom-sw.js', {
+ enabled: !isDevMode(),
+ registrationStrategy: 'registerWhenStable:30000'
+ }),
+ ],
+};
+
+
+
+### Best practices for custom service workers
+
+When extending the Angular service worker:
+
+- **Always import the Angular service worker first** using `importScripts('./ngsw-worker.js')` to ensure you get all the caching and update functionality
+- **Wrap your custom code in an IIFE** (Immediately Invoked Function Expression) to avoid polluting the global scope
+- **Use `event.waitUntil()`** for asynchronous operations to ensure they complete before the service worker is terminated
+- **Test thoroughly** in both development and production environments
+- **Handle errors gracefully** to prevent your custom code from breaking the Angular service worker functionality
+
+### Common use cases
+
+Custom service workers are commonly used for:
+
+- **Push notifications**: Handle incoming push messages and display notifications
+- **Background sync**: Sync data when the network connection is restored
+- **Custom navigation**: Handle special routing or offline page scenarios
diff --git a/adev-es/src/content/ecosystem/service-workers/custom-service-worker-scripts.md b/adev-es/src/content/ecosystem/service-workers/custom-service-worker-scripts.md
index 8bafac8..d0c040a 100644
--- a/adev-es/src/content/ecosystem/service-workers/custom-service-worker-scripts.md
+++ b/adev-es/src/content/ecosystem/service-workers/custom-service-worker-scripts.md
@@ -1,36 +1,36 @@
-# Custom service worker scripts
+# Scripts personalizados de service worker
-While the Angular service worker provides excellent capabilities, you may need to add custom functionality such as handling push notifications, background sync, or other service worker events. You can create a custom service worker script that imports and extends the Angular service worker.
+Aunque el service worker de Angular ofrece excelentes capacidades, es posible que necesites agregar funcionalidad personalizada, como manejar notificaciones push, sincronización en segundo plano u otros eventos de service worker. Puedes crear un script de service worker personalizado que importe y amplíe el service worker de Angular.
-## Creating a custom service worker
+## Crear un service worker personalizado
-To create a custom service worker that extends Angular's functionality:
+Para crear un service worker personalizado que extienda la funcionalidad de Angular:
-1. Create a custom service worker file (e.g., `custom-sw.js`) in your `src` directory:
+1. Crea un archivo de service worker personalizado (por ejemplo, `custom-sw.js`) en tu directorio `src`:
-// Import the Angular service worker
+// Importa el service worker de Angular
importScripts('./ngsw-worker.js');
(function () {
'use strict';
- // Add custom notification click handler
+ // Agrega un manejador personalizado para el clic en notificaciones
self.addEventListener('notificationclick', (event) => {
- console.log('Custom notification click handler');
- console.log('Notification details:', event.notification);
+ console.log('Manejador personalizado de clic en notificaciones');
+ console.log('Detalles de la notificación:', event.notification);
- // Handle notification click - open URL if provided
+ // Gestiona el clic en la notificación: abre la URL si está disponible
if (clients.openWindow && event.notification.data.url) {
event.waitUntil(clients.openWindow(event.notification.data.url));
- console.log('Opening URL:', event.notification.data.url);
+ console.log('Abriendo URL:', event.notification.data.url);
}
});
- // Add custom background sync handler
+ // Agrega un manejador personalizado para sincronización en segundo plano
self.addEventListener('sync', (event) => {
- console.log('Custom background sync handler');
+ console.log('Manejador personalizado de sincronización en segundo plano');
if (event.tag === 'background-sync') {
event.waitUntil(doBackgroundSync());
@@ -38,17 +38,17 @@ importScripts('./ngsw-worker.js');
});
function doBackgroundSync() {
- // Implement your background sync logic here
+ // Implementa aquí la lógica de sincronización en segundo plano
return fetch('https://example.com/api/sync')
.then(response => response.json())
- .then(data => console.log('Background sync completed:', data))
- .catch(error => console.error('Background sync failed:', error));
+ .then(data => console.log('Sincronización en segundo plano completa:', data))
+ .catch(error => console.error('La sincronización en segundo plano falló:', error));
}
})();
-2. Update your `angular.json` file to use the custom service worker:
+2. Actualiza tu archivo `angular.json` para usar el service worker personalizado:
@@ -74,7 +74,7 @@ importScripts('./ngsw-worker.js');
-3. Configure the service worker registration to use your custom script:
+3. Configura el registro del service worker para usar tu script personalizado:
@@ -92,20 +92,20 @@ export const appConfig: ApplicationConfig = {
-### Best practices for custom service workers
+### Mejores prácticas para service workers personalizados
-When extending the Angular service worker:
+Al extender el service worker de Angular:
-- **Always import the Angular service worker first** using `importScripts('./ngsw-worker.js')` to ensure you get all the caching and update functionality
-- **Wrap your custom code in an IIFE** (Immediately Invoked Function Expression) to avoid polluting the global scope
-- **Use `event.waitUntil()`** for asynchronous operations to ensure they complete before the service worker is terminated
-- **Test thoroughly** in both development and production environments
-- **Handle errors gracefully** to prevent your custom code from breaking the Angular service worker functionality
+- **Importa siempre primero el service worker de Angular** mediante `importScripts('./ngsw-worker.js')` para asegurarte de conservar toda la funcionalidad de caché y actualización.
+- **Envuelve tu código personalizado en un IIFE** (Immediately Invoked Function Expression) para evitar contaminar el ámbito global.
+- **Usa `event.waitUntil()`** en las operaciones asíncronas para garantizar que finalicen antes de que el service worker se termine.
+- **Prueba exhaustivamente** en entornos de desarrollo y producción.
+- **Maneja los errores con cuidado** para evitar que tu código personalizado rompa la funcionalidad del service worker de Angular.
-### Common use cases
+### Casos de uso comunes
-Custom service workers are commonly used for:
+Los service workers personalizados se utilizan con frecuencia para:
-- **Push notifications**: Handle incoming push messages and display notifications
-- **Background sync**: Sync data when the network connection is restored
-- **Custom navigation**: Handle special routing or offline page scenarios
+- **Notificaciones push**: manejar mensajes push entrantes y mostrar notificaciones
+- **Sincronización en segundo plano**: sincronizar datos cuando se restablece la conexión de red
+- **Navegación personalizada**: gestionar escenarios especiales de routing o páginas offline
diff --git a/adev-es/src/content/ecosystem/service-workers/devops.en.md b/adev-es/src/content/ecosystem/service-workers/devops.en.md
new file mode 100644
index 0000000..4aea23e
--- /dev/null
+++ b/adev-es/src/content/ecosystem/service-workers/devops.en.md
@@ -0,0 +1,315 @@
+# Service worker devops
+
+This page is a reference for deploying and supporting production applications that use the Angular service worker.
+It explains how the Angular service worker fits into the larger production environment, the service worker's behavior under various conditions, and available resources and fail-safes.
+
+## Service worker and caching of application resources
+
+Imagine the Angular service worker as a forward cache or a Content Delivery Network (CDN) edge that is installed in the end user's web browser.
+The service worker responds to requests made by the Angular application for resources or data from a local cache, without needing to wait for the network.
+Like any cache, it has rules for how content is expired and updated.
+
+### Application versions
+
+In the context of an Angular service worker, a "version" is a collection of resources that represent a specific build of the Angular application.
+Whenever a new build of the application is deployed, the service worker treats that build as a new version of the application.
+This is true even if only a single file is updated.
+At any given time, the service worker might have multiple versions of the application in its cache and it might be serving them simultaneously.
+For more information, see the [Application tabs](#application-tabs) section.
+
+To preserve application integrity, the Angular service worker groups all files into a version together.
+The files grouped into a version usually include HTML, JS, and CSS files.
+Grouping of these files is essential for integrity because HTML, JS, and CSS files frequently refer to each other and depend on specific content.
+For example, an `index.html` file might have a `