Skip to content

Commit

Permalink
Allow more flexibility in choosing which requests get the COI workaro…
Browse files Browse the repository at this point in the history
…und.
  • Loading branch information
rblank committed Sep 19, 2024
1 parent 335fc0b commit 2f836ec
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 35 deletions.
27 changes: 0 additions & 27 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"@codemirror/view": "^6.33.0",
"@rollup/plugin-node-resolve": "^15.2.3",
"@sqlite.org/sqlite-wasm": "^3.46.1-build1",
"mini-coi": "^0.4.2",
"rollup": "^4.21.2",
"rollup-plugin-license": "^3.5.2"
},
Expand Down
12 changes: 6 additions & 6 deletions tdoc/common/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def on_builder_inited(app):

# The file must be at the root of the website, to avoid limiting the scope
# of the service worker to _static.
fileutil.copy_asset_file(_common / 'static.gen' / 'mini-coi.js',
fileutil.copy_asset_file(_common / 'static' / 'tdoc-coi.js',
app.builder.outdir, force=True)


Expand All @@ -106,15 +106,15 @@ def on_html_page_context(app, page, template, context, doctree):
license_url = app.config.license_url
if license_url: context['license_url'] = license_url

# Work around Cross-Origin Isoaltion issues when the corresponding headers
# cannot be set server-side.
app.add_js_file('../mini-coi.js', priority=0)
# Work around Cross-Origin Isolation issues when the relevant headers cannot
# be set server-side.
app.add_js_file('../tdoc-coi.js', priority=0,
scope=context['pathto']('', resource=True))

# Add language-specific .js files.
if doctree:
for lang in sorted(Exec.find_nodes(doctree)):
app.add_js_file(f'tdoc-{lang}.js', type='module')
# TODO: Add Cross-Origin-*-Policy headers in the dev server
# TODO: Work around inability to specify headers on GitHub Pages


def add_reload_js(app, page, template, context, doctree):
Expand Down
54 changes: 54 additions & 0 deletions tdoc/common/static/tdoc-coi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright 2024 Remy Blank <[email protected]>
// SPDX-License-Identifier: MIT

(({document: doc, navigator: {serviceWorker: workers}}) => {
if (!doc) {
// Running in the service worker. Capture fetch() requests and add the
// relevant headers.
addEventListener('install', () => skipWaiting());
addEventListener('activate', e => e.waitUntil(clients.claim()));
addEventListener('fetch', e => {
const req = e.request;
if (req.cache === 'only-if-cached' && req.mode !== 'same-origin') {
return;
}
e.respondWith((async () => {
const resp = await fetch(req);
const {status, statusText, body} = resp;
if (!status || status >= 400) return resp;
const headers = new Headers(resp.headers);
headers.set('Cross-Origin-Embedder-Policy', 'require-corp');
headers.set('Cross-Origin-Opener-Policy', 'same-origin');
headers.set('Cross-Origin-Resource-Policy', 'cross-origin');
return new Response(resp.body, {status, statusText, headers});
})());
});
return;
}

// Running in the main thread. Register the service worker if necessary.
if (crossOriginIsolated) {
console.info("[t-doc] Already cross-origin isolated");
return;
}
if (!isSecureContext) {
console.warn("[t-doc] Not a secure context; COI workaround disabled");
return;
}
if (!workers) {
console.warn(
"[t-doc] No service worker container; COI workaround disabled");
return;
}
const script = doc.currentScript;
workers.register(script.src, {scope: script.getAttribute('scope')})
.then(reg => {
console.info('[t-doc] COI service worker registered');
reg.addEventListener('updatefound', () => location.reload());
if (reg.active && !workers.controller) location.reload();
})
.catch(e => {
console.error(
`[t-doc] Failed to register COI service worker: ${e}`);
});
})(self);
1 change: 0 additions & 1 deletion tools/hatch_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ def initialize(self, version, build_data):
self.app.display_info("Generating files")
os.makedirs(static_gen, exist_ok=True)
node_modules = root / 'node_modules'
shutil.copy2(node_modules / 'mini-coi' / 'mini-coi.js', static_gen)
shutil.copytree(node_modules / '@sqlite.org' / 'sqlite-wasm'
/ 'sqlite-wasm' / 'jswasm',
static_gen, symlinks=True, dirs_exist_ok=True)
Expand Down

0 comments on commit 2f836ec

Please sign in to comment.