@uiwwsw/workbox 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AI-TRAINING-NOTICE.md +11 -0
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/package.json +16 -4
- package/src/cli.js +16 -0
- package/src/index.d.ts +13 -0
- package/src/index.js +104 -0
- package/src/register.d.ts +1 -0
- package/src/register.js +16 -0
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# AI training and data collection notice / AI 학습·수집 반대 고지
|
|
2
|
+
|
|
3
|
+
이 프로젝트의 관리자는 자신이 권리를 보유한 코드, 문서, 웹사이트, 앱, 데모, 패키지, 이미지와 기타 콘텐츠를 사전 서면 동의 없이 AI·머신러닝 모델의 학습·미세조정 또는 학습용 데이터셋 구축을 위해 수집·저장·이용하는 것에 명시적으로 반대합니다. 해당 목적의 이용 전 권리자의 서면 동의를 받으세요.
|
|
4
|
+
|
|
5
|
+
The maintainer expressly objects to collecting, storing or using maintainer-controlled code, documentation, websites, apps, demos, packages, images and other content for AI or machine-learning training, fine-tuning or training datasets without prior written consent. Obtain the rights holder's written consent before such use.
|
|
6
|
+
|
|
7
|
+
이 고지는 권리자의 의사 표시입니다. 기존 오픈소스·콘텐츠 라이선스를 수정하거나 이미 부여된 권리 및 법령상 허용되는 이용을 제한하지 않습니다. 제삼자 자료와 사용자가 작성한 콘텐츠에는 각 권리자의 조건이 적용됩니다. 서비스 이용자가 요청한 개별 AI 기능의 실행과 학습용 무단 수집은 구분합니다.
|
|
8
|
+
|
|
9
|
+
This notice states the rights holder's preference. It does not amend existing software or content licenses, restrict rights already granted, or override uses permitted by law. Third-party materials and user-created content remain subject to their own rights and terms. User-authorized AI features are distinct from unauthorized collection for training.
|
|
10
|
+
|
|
11
|
+
robots.txt expresses crawler preferences; it does not guarantee compliance or remove previously collected data.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 uiwwsw
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @uiwwsw/workbox
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
기존 방문자에게 서버 장애 시 미리 저장한 안내 페이지를 보여주는 작은 서비스워커 패키지입니다. Google Workbox와 별개의 프로젝트입니다.
|
|
4
|
+
|
|
5
|
+
A navigation-only outage fallback for returning visitors. It does not cache application pages, API responses, credentials, or personal data.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @uiwwsw/workbox
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Create a public, self-contained static HTML page at `public/unavailable.html`. Use inline CSS or declare its public dependencies in `assets`. Avoid remote fonts, scripts and authenticated resources: they may be unreachable during an outage.
|
|
14
|
+
|
|
15
|
+
Create `outage.config.json`:
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
{
|
|
19
|
+
"fallback": "/unavailable.html",
|
|
20
|
+
"outDir": "public"
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Generate before the application's build:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npx outage-worker outage.config.json
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Register from the browser entry point:
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
import { registerOutageWorker } from '@uiwwsw/workbox/register';
|
|
34
|
+
|
|
35
|
+
registerOutageWorker().catch(console.error);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
For static sites without a bundler, copy `src/register.js` from the installed package into the site's static assets and import it locally. Serve the generated worker from the same origin as the site, with a JavaScript content type and `Cache-Control: no-cache`. Exclude the worker from SPA HTML rewrites. Keep registration failures observable without blocking application startup.
|
|
39
|
+
|
|
40
|
+
## Options
|
|
41
|
+
|
|
42
|
+
| Option | Default | Meaning |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| `fallback` | required | Same-origin absolute path to public static HTML |
|
|
45
|
+
| `outDir` | required for CLI | Public output directory, relative to working directory |
|
|
46
|
+
| `worker` | `/outage-sw.js` | Generated worker pathname |
|
|
47
|
+
| `scope` | `/` | Controlled pathname prefix, ending with `/` |
|
|
48
|
+
| `assets` | `[]` | Public CSS, font or image paths required by the fallback |
|
|
49
|
+
| `timeoutMs` | `8000` | Navigation timeout, 100–120000 milliseconds |
|
|
50
|
+
| `namespace` | `outage` | Cache isolation identifier |
|
|
51
|
+
| `version` | `1` | Optional release identifier; CLI also hashes local HTML/assets |
|
|
52
|
+
|
|
53
|
+
For a subpath deployment, set `scope` and `fallback` to that subpath and pass matching `scope` and `worker` options to registration. Place the worker at or above the scope directory.
|
|
54
|
+
|
|
55
|
+
The CLI validates that declared public files exist and automatically revisions their cache when their contents change.
|
|
56
|
+
|
|
57
|
+
The Node API exports `createWorker(options)` and `writeWorker(options)` for build integrations. Browser registration is a separate export, so Node built-ins never enter the client bundle.
|
|
58
|
+
|
|
59
|
+
## Behavior and limits
|
|
60
|
+
|
|
61
|
+
- Only same-origin GET navigations inside scope receive outage fallback on network failure, timeout or HTTP 500–599. Original 401/403/404/429 responses are preserved.
|
|
62
|
+
- Only the fallback and explicitly listed public assets are cached. Initial caching omits credentials and rejects redirects and unsuccessful responses. The fallback must be HTML.
|
|
63
|
+
- HTTPS and a successful prior installation are required. First visits, cleared/evicted storage, private browsing restrictions and disabled service workers cannot be protected.
|
|
64
|
+
- Existing pages' API errors and client-side router transitions need application UI handling. This package does not replace that handling or provide attack protection.
|
|
65
|
+
- Registration refuses overlapping existing workers. Integrate with an existing PWA worker rather than replacing it; do not add a second competing worker.
|
|
66
|
+
- Updates follow the standard waiting lifecycle. No forced `skipWaiting`, mass unregister or deletion of other packages' caches occurs. Close old tabs to finish activating a waiting update.
|
|
67
|
+
- Retry the original URL from the fallback (for example, a normal reload button). Avoid automatic reload loops or redirecting to the fallback URL.
|
|
68
|
+
- Removing registration code does not uninstall an existing worker. Roll back by serving a network-only worker at the same URL and releasing it through the normal update lifecycle before removing that URL.
|
|
69
|
+
|
|
70
|
+
## Development
|
|
71
|
+
|
|
72
|
+
Node.js 20 or newer; no runtime dependencies.
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
npm test
|
|
76
|
+
npm pack --dry-run
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Releases
|
|
80
|
+
|
|
81
|
+
The `Publish npm` GitHub Actions workflow publishes from `main` using npm Trusted Publishing (OIDC). It requires no stored npm publishing token. Configure the package's trusted publisher with the repository owner and name, workflow filename `publish.yml`, and direct publishing permission. The workflow uses no GitHub environment binding.
|
|
82
|
+
|
|
83
|
+
For a new package, first use npm staged publishing and approve the initial version on npmjs.com. Once the package exists, configure its trusted publisher. Commit a new package version, then manually run the workflow from `main`. The workflow checks the package, inspects its contents and publishes with provenance. Run its first OIDC release within two days of configuring the trust relationship.
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
MIT. See [LICENSE](LICENSE).
|
|
88
|
+
|
|
89
|
+
<!-- ai-training-notice -->
|
|
90
|
+
## AI 학습·수집 반대 / AI training notice
|
|
91
|
+
|
|
92
|
+
사전 서면 동의 없는 AI 학습·미세조정 및 학습용 데이터 수집에 반대합니다. No AI training, fine-tuning or training-data collection without prior written consent.
|
|
93
|
+
|
|
94
|
+
[전문 / Full notice](AI-TRAINING-NOTICE.md). Existing licenses and third-party/user rights remain unchanged.
|
package/package.json
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uiwwsw/workbox",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
}
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Navigation-only service worker fallback for returning visitors during server outages",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": { "node": ">=20" },
|
|
7
|
+
"exports": {
|
|
8
|
+
".": { "types": "./src/index.d.ts", "import": "./src/index.js" },
|
|
9
|
+
"./register": { "types": "./src/register.d.ts", "import": "./src/register.js" }
|
|
10
|
+
},
|
|
11
|
+
"bin": { "outage-worker": "src/cli.js" },
|
|
12
|
+
"files": ["src", "README.md", "LICENSE", "AI-TRAINING-NOTICE.md"],
|
|
13
|
+
"scripts": { "test": "node --test", "check": "node --test && python3 .github/scripts/check-ai-notice.py", "prepublishOnly": "npm run check" },
|
|
14
|
+
"publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
|
|
15
|
+
"repository": { "type": "git", "url": "git+https://github.com/uiwwsw/workbox.git" },
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"keywords": ["service-worker", "offline", "outage", "fallback"]
|
|
18
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { writeWorker } from './index.js';
|
|
4
|
+
const args = process.argv.slice(2);
|
|
5
|
+
if (args.length !== 1 || args[0] === '--help') {
|
|
6
|
+
console.log('Usage: outage-worker <config.json>\nConfig: { "fallback": "/unavailable.html", "outDir": "public" }');
|
|
7
|
+
process.exit(args[0] === '--help' ? 0 : 1);
|
|
8
|
+
}
|
|
9
|
+
try {
|
|
10
|
+
const config = JSON.parse(await readFile(args[0], 'utf8'));
|
|
11
|
+
if (typeof config.outDir !== 'string' || !config.outDir) throw new TypeError('outDir is required');
|
|
12
|
+
console.log(await writeWorker(config));
|
|
13
|
+
} catch (error) {
|
|
14
|
+
console.error(`outage-worker: ${error.message}`);
|
|
15
|
+
process.exitCode = 1;
|
|
16
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface WorkerOptions {
|
|
2
|
+
/** Public static HTML; no login or personal data. */
|
|
3
|
+
fallback: string;
|
|
4
|
+
scope?: string;
|
|
5
|
+
/** Public CSS, fonts or images required by the fallback. */
|
|
6
|
+
assets?: string[];
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
namespace?: string;
|
|
9
|
+
/** Change when fallback content changes to refresh its cache. */
|
|
10
|
+
version?: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function createWorker(options: WorkerOptions): string;
|
|
13
|
+
export declare function writeWorker(options: WorkerOptions & { outDir: string; worker?: string }): Promise<string>;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
function path(value, name) {
|
|
6
|
+
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') || /[\\?#\s]/.test(value)) {
|
|
7
|
+
throw new TypeError(`${name} must be a same-origin absolute pathname`);
|
|
8
|
+
}
|
|
9
|
+
const url = new URL(value, 'https://example.invalid');
|
|
10
|
+
if (url.pathname !== value || /%2f|%5c|%2e/i.test(value)) throw new TypeError(`${name} must be a normalized pathname`);
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Generate a self-contained classic service worker. No runtime CDN dependency. */
|
|
15
|
+
export function createWorker(options) {
|
|
16
|
+
const fallback = path(options?.fallback, 'fallback');
|
|
17
|
+
const scope = path(options.scope ?? '/', 'scope');
|
|
18
|
+
if (!scope.endsWith('/')) throw new TypeError('scope must end with /');
|
|
19
|
+
if (!fallback.startsWith(scope)) throw new TypeError('fallback must be inside scope');
|
|
20
|
+
const assets = [...new Set((options.assets ?? []).map(value => path(value, 'asset')))];
|
|
21
|
+
const timeoutMs = options.timeoutMs ?? 8000;
|
|
22
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 120000) throw new TypeError('timeoutMs must be 100–120000');
|
|
23
|
+
const namespace = options.namespace ?? 'outage';
|
|
24
|
+
if (!/^[a-zA-Z0-9_-]{1,64}$/.test(namespace)) throw new TypeError('invalid namespace');
|
|
25
|
+
const config = { fallback, scope, assets, timeoutMs };
|
|
26
|
+
const revision = createHash('sha256').update(JSON.stringify({ config, version: options.version ?? '1', runtime: '0.1.0' })).digest('hex').slice(0, 16);
|
|
27
|
+
const prefix = `uiwwsw-workbox:${namespace}:${scope}:`;
|
|
28
|
+
return `/* @uiwwsw/workbox — navigation fallback only */\n(${runtime.toString()})(${JSON.stringify({ ...config, prefix, cacheName: prefix + revision })});\n`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function runtime(config) {
|
|
32
|
+
const absolute = value => new URL(value, self.location.origin).href;
|
|
33
|
+
self.addEventListener('install', event => {
|
|
34
|
+
event.waitUntil((async () => {
|
|
35
|
+
// Fetch and validate everything before writing; failed updates preserve the active worker.
|
|
36
|
+
const entries = await Promise.all([config.fallback, ...config.assets].map(async value => {
|
|
37
|
+
const response = await fetch(new Request(absolute(value), { cache: 'reload', credentials: 'omit', redirect: 'error' }));
|
|
38
|
+
if (!response.ok || response.type === 'opaque' || (value === config.fallback && !response.headers.get('content-type')?.includes('text/html'))) {
|
|
39
|
+
throw new Error('Fallback assets must be public, successful responses; fallback must be HTML');
|
|
40
|
+
}
|
|
41
|
+
return [absolute(value), response];
|
|
42
|
+
}));
|
|
43
|
+
const cache = await caches.open(config.cacheName);
|
|
44
|
+
await Promise.all(entries.map(([url, response]) => cache.put(url, response)));
|
|
45
|
+
// Intentionally no skipWaiting: keep the standard service-worker update lifecycle.
|
|
46
|
+
})());
|
|
47
|
+
});
|
|
48
|
+
self.addEventListener('activate', event => {
|
|
49
|
+
event.waitUntil((async () => {
|
|
50
|
+
await Promise.all((await caches.keys()).filter(name => name.startsWith(config.prefix) && name !== config.cacheName).map(name => caches.delete(name)));
|
|
51
|
+
await self.clients.claim();
|
|
52
|
+
})());
|
|
53
|
+
});
|
|
54
|
+
self.addEventListener('fetch', event => {
|
|
55
|
+
const request = event.request;
|
|
56
|
+
const url = new URL(request.url);
|
|
57
|
+
if (request.method !== 'GET' || url.origin !== self.location.origin || url.pathname === '/api' || url.pathname.startsWith('/api/')) return;
|
|
58
|
+
if (request.mode !== 'navigate') {
|
|
59
|
+
// Only explicitly declared public fallback assets may be served from this cache.
|
|
60
|
+
if (!url.search && config.assets.includes(url.pathname)) {
|
|
61
|
+
event.respondWith(caches.open(config.cacheName).then(async cache => (await cache.match(request.url)) ?? fetch(request)));
|
|
62
|
+
}
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (!url.pathname.startsWith(config.scope)) return;
|
|
66
|
+
event.respondWith((async () => {
|
|
67
|
+
const controller = new AbortController();
|
|
68
|
+
let timer;
|
|
69
|
+
try {
|
|
70
|
+
const timeout = new Promise((_, reject) => {
|
|
71
|
+
timer = setTimeout(() => { controller.abort(); reject(new Error('Navigation timeout')); }, config.timeoutMs);
|
|
72
|
+
});
|
|
73
|
+
const response = await Promise.race([fetch(request, { signal: controller.signal }), timeout]);
|
|
74
|
+
if (response.status < 500 || response.status > 599) return response;
|
|
75
|
+
const cache = await caches.open(config.cacheName);
|
|
76
|
+
return (await cache.match(absolute(config.fallback))) ?? response;
|
|
77
|
+
} catch {
|
|
78
|
+
const cache = await caches.open(config.cacheName);
|
|
79
|
+
return (await cache.match(absolute(config.fallback))) ?? Response.error();
|
|
80
|
+
} finally {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
}
|
|
83
|
+
})());
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Write the generated worker to a site's public directory. */
|
|
88
|
+
export async function writeWorker({ outDir, worker = '/outage-sw.js', ...options }) {
|
|
89
|
+
path(worker, 'worker');
|
|
90
|
+
if (!worker.endsWith('.js')) throw new TypeError('worker must end with .js');
|
|
91
|
+
const scope = options.scope ?? '/';
|
|
92
|
+
if (!scope.startsWith(worker.slice(0, worker.lastIndexOf('/') + 1))) throw new TypeError('worker directory must contain scope');
|
|
93
|
+
createWorker(options); // Validate paths before reading any declared public files.
|
|
94
|
+
if (typeof outDir !== 'string' || !outDir) throw new TypeError('outDir is required');
|
|
95
|
+
const digest = createHash('sha256');
|
|
96
|
+
for (const asset of [options.fallback, ...(options.assets ?? [])]) {
|
|
97
|
+
digest.update(asset).update(await readFile(resolve(outDir, '.' + asset)));
|
|
98
|
+
}
|
|
99
|
+
const source = createWorker({ ...options, version: `${options.version ?? '1'}:${digest.digest('hex')}` });
|
|
100
|
+
const output = resolve(outDir, '.' + worker);
|
|
101
|
+
await mkdir(resolve(output, '..'), { recursive: true });
|
|
102
|
+
await writeFile(output, source);
|
|
103
|
+
return output;
|
|
104
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function registerOutageWorker(options?: { worker?: string; scope?: string }): Promise<ServiceWorkerRegistration | null>;
|
package/src/register.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Register only when supported; refuse to replace another worker in the same scope. */
|
|
2
|
+
export async function registerOutageWorker({ worker = '/outage-sw.js', scope = '/' } = {}) {
|
|
3
|
+
if (typeof window === 'undefined' || !window.isSecureContext || !('serviceWorker' in navigator)) return null;
|
|
4
|
+
const script = new URL(worker, location.origin);
|
|
5
|
+
const scopeUrl = new URL(scope, location.origin);
|
|
6
|
+
if (script.origin !== location.origin || scopeUrl.origin !== location.origin) throw new TypeError('Worker and scope must be same-origin');
|
|
7
|
+
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
8
|
+
for (const registration of registrations) {
|
|
9
|
+
const existing = registration.installing ?? registration.waiting ?? registration.active;
|
|
10
|
+
const overlaps = scopeUrl.href.startsWith(registration.scope) || registration.scope.startsWith(scopeUrl.href);
|
|
11
|
+
if (overlaps && existing && existing.scriptURL !== script.href) {
|
|
12
|
+
throw new Error('Existing service worker overlaps this scope; integrate fallback into that worker instead');
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return navigator.serviceWorker.register(script.href, { scope: scopeUrl.href, updateViaCache: 'none' });
|
|
16
|
+
}
|