Service Workerのビルドにesbuildを使うようにする

This commit is contained in:
tamaina 2022-01-25 13:03:13 +00:00
parent 154e7c2e59
commit e8ca4785e8
9 changed files with 361 additions and 945 deletions

View file

@ -49,14 +49,8 @@ gulp.task('build:backend:style', () => {
.pipe(gulp.dest('./packages/backend/built/server/web/'));
});
gulp.task('build:sw', () => {
return gulp.src(['./packages/sw/src/sw.js'])
.pipe(replace('VERSION', meta.version))
.pipe(gulp.dest('./built/_sw_dist_/'));
});
gulp.task('build', gulp.parallel(
'copy:client:locales', 'copy:backend:views', 'build:backend:script', 'build:backend:style', 'copy:client:fonts', 'build:sw'
'copy:client:locales', 'copy:backend:views', 'build:backend:script', 'build:backend:style', 'copy:client:fonts',
));
gulp.task('default', gulp.task('build'));

View file

@ -104,11 +104,6 @@ router.get(`/sw.${config.version}.js`, async ctx => {
root: swAssets,
});
});
router.get(`/sw-lib.${config.version}.js`, async ctx => {
await send(ctx as any, `/sw-lib.js`, {
root: swAssets,
});
});
// Manifest
router.get('/manifest.json', require('./manifest'));

37
packages/sw/build.js Normal file
View file

@ -0,0 +1,37 @@
const esbuild = require('esbuild');
const locales = require('../../locales');
const meta = require('../../package.json');
const watch = process.argv[2]?.includes('watch');
console.log('Starting SW building...');
esbuild.build({
entryPoints: [ `${__dirname}/src/sw.ts` ],
bundle: true,
format: 'esm',
treeShaking: true,
minify: process.env.NODE_ENV === 'production',
absWorkingDir: __dirname,
outbase: `${__dirname}/src`,
outdir: `${__dirname}/../../built/_sw_dist_`,
loader: {
'.ts': 'ts'
},
tsconfig: `${__dirname}/tsconfig.json`,
define: {
_VERSION_: JSON.stringify(meta.version),
_LANGS_: JSON.stringify(Object.entries(locales).map(([k, v]) => [k, v._lang_])),
_ENV_: JSON.stringify(process.env.NODE_ENV),
_DEV_: process.env.NODE_ENV !== 'production',
_PERF_PREFIX_: JSON.stringify('Misskey:'),
},
watch: watch ? {
onRebuild(error, result) {
if (error) console.error('SW: watch build failed:', error);
else console.log('SW: watch build succeeded:', result);
},
} : false,
}).then(result => {
if (watch) console.log('watching...');
else console.log('done,', JSON.stringify(result));
});

View file

@ -1,17 +1,16 @@
{
"private": true,
"scripts": {
"watch": "webpack --watch",
"build": "webpack",
"watch": "node build.js watch",
"build": "node build.js",
"lint": "eslint --quiet src/**/*.{ts}"
},
"resolutions": {},
"dependencies": {
"esbuild": "0.14.13",
"idb-keyval": "6.0.3",
"misskey-js": "0.0.10",
"ts-loader": "9.2.6",
"webpack": "5.64.1",
"webpack-cli": "4.9.1"
"ts-loader": "9.2.6"
},
"devDependencies": {
"eslint": "8.2.0"

View file

@ -1,226 +0,0 @@
/**
* Service Worker
*/
declare var self: ServiceWorkerGlobalScope & {
lib: {
oninstall: (ev: ServiceWorkerGlobalScopeEventMap['install']) => void;
onactivate: (ev: ServiceWorkerGlobalScopeEventMap['activate']) => void;
onfetch: (ev: ServiceWorkerGlobalScopeEventMap['fetch']) => void;
onpush: (ev: ServiceWorkerGlobalScopeEventMap['push']) => void;
onnotificationclick: (ev: ServiceWorkerGlobalScopeEventMap['notificationclick']) => void;
onnotificationclose: (ev: ServiceWorkerGlobalScopeEventMap['notificationclose']) => void;
onmessage: (ev: ServiceWorkerGlobalScopeEventMap['message']) => void;
};
};
import { createEmptyNotification, createNotification } from '@/scripts/create-notification';
import { swLang } from '@/scripts/lang';
import { swNotificationRead } from '@/scripts/notification-read';
import { pushNotificationDataMap } from '@/types';
import * as swos from '@/scripts/operations';
import { acct as getAcct } from '@/filters/user';
self.lib = {} as any;
//#region Lifecycle: Install
self.lib.oninstall = (ev: ServiceWorkerGlobalScopeEventMap['install']) => {
ev.waitUntil(self.skipWaiting());
}
//#region Lifecycle: Activate
self.lib.onactivate = (ev: ServiceWorkerGlobalScopeEventMap['activate']) => {
ev.waitUntil(
caches.keys()
.then(cacheNames => Promise.all(
cacheNames
.filter((v) => v !== swLang.cacheName)
.map(name => caches.delete(name))
))
.then(() => self.clients.claim())
);
}
//#endregion
//#region When: Fetching
self.lib.onfetch = (ev: ServiceWorkerGlobalScopeEventMap['fetch']) => {
ev.respondWith(
fetch(ev.request)
.catch(() => new Response(`Offline. Service Worker @${_VERSION_}`, { status: 200 }))
);
}
//#endregion
//#region When: Caught Notification
self.lib.onpush = (ev: ServiceWorkerGlobalScopeEventMap['push']) => {
// クライアント取得
ev.waitUntil(self.clients.matchAll({
includeUncontrolled: true,
type: 'window'
}).then(async <K extends keyof pushNotificationDataMap>(clients: readonly WindowClient[]) => {
const data: pushNotificationDataMap[K] = ev.data?.json();
switch (data.type) {
// case 'driveFileCreated':
case 'notification':
case 'unreadMessagingMessage':
// クライアントがあったらストリームに接続しているということなので通知しない
if (clients.length != 0) return;
return createNotification(data);
case 'readAllNotifications':
for (const n of await self.registration.getNotifications()) {
if (n?.data?.type === 'notification') n.close();
}
break;
case 'readAllMessagingMessages':
for (const n of await self.registration.getNotifications()) {
if (n?.data?.type === 'unreadMessagingMessage') n.close();
}
break;
case 'readNotifications':
for (const n of await self.registration.getNotifications()) {
if (data.body?.notificationIds?.includes(n.data.body.id)) {
n.close();
}
}
break;
case 'readAllMessagingMessagesOfARoom':
for (const n of await self.registration.getNotifications()) {
if (n.data.type === 'unreadMessagingMessage'
&& ('userId' in data.body
? data.body.userId === n.data.body.userId
: data.body.groupId === n.data.body.groupId)
) {
n.close();
}
}
break;
}
createEmptyNotification();
}));
}
//#endregion
//#region Notification
self.lib.onnotificationclick = <K extends keyof pushNotificationDataMap>(ev: ServiceWorkerGlobalScopeEventMap['notificationclick']) => {
ev.waitUntil((async () => {
if (_DEV_) {
console.log('notificationclick', ev.action, ev.notification.data);
}
const { action, notification } = ev;
const data: pushNotificationDataMap[K] = notification.data;
const { userId: id } = data;
let client: WindowClient | null = null;
switch (data.type) {
case 'notification':
switch (action) {
case 'follow':
if ('userId' in data.body) await swos.api('following/create', id, { userId: data.body.userId });
break;
case 'showUser':
if ('user' in data.body) client = await swos.openUser(getAcct(data.body.user), id);
break;
case 'reply':
if ('note' in data.body) client = await swos.openPost({ reply: data.body.note }, id);
break;
case 'renote':
if ('note' in data.body) await swos.api('notes/create', id, { renoteId: data.body.note.id });
break;
case 'accept':
switch (data.body.type) {
case 'receiveFollowRequest':
await swos.api('following/requests/accept', id, { userId: data.body.userId });
break;
case 'groupInvited':
await swos.api('users/groups/invitations/accept', id, { invitationId: data.body.invitation.id });
break;
}
break;
case 'reject':
switch (data.body.type) {
case 'receiveFollowRequest':
await swos.api('following/requests/reject', id, { userId: data.body.userId });
break;
case 'groupInvited':
await swos.api('users/groups/invitations/reject', id, { invitationId: data.body.invitation.id });
break;
}
break;
case 'showFollowRequests':
client = await swos.openClient('push', '/my/follow-requests', id);
break;
default:
switch (data.body.type) {
case 'receiveFollowRequest':
client = await swos.openClient('push', '/my/follow-requests', id);
break;
case 'groupInvited':
client = await swos.openClient('push', '/my/groups', id);
break;
case 'reaction':
client = await swos.openNote(data.body.note.id, id);
break;
default:
if ('note' in data.body) {
client = await swos.openNote(data.body.note.id, id);
} else if ('user' in data.body) {
client = await swos.openUser(getAcct(data.body.user), id);
}
break;
}
}
break;
case 'unreadMessagingMessage':
client = await swos.openChat(data.body, id);
break;
}
if (client) {
client.focus();
}
if (data.type === 'notification') {
swNotificationRead.then(that => that.read(data));
}
notification.close();
})());
}
self.lib.onnotificationclose = <K extends keyof pushNotificationDataMap>(ev: ServiceWorkerGlobalScopeEventMap['notificationclose']) => {
const data: pushNotificationDataMap[K] = ev.notification.data;
if (data.type === 'notification') {
swNotificationRead.then(that => that.read(data));
}
}
//#endregion
//#region When: Caught a message from the client
self.lib.onmessage = (ev: ServiceWorkerGlobalScopeEventMap['message']) => {
ev.waitUntil((async () => {
switch (ev.data) {
case 'clear':
// Cache Storage全削除
await caches.keys()
.then(cacheNames => Promise.all(
cacheNames.map(name => caches.delete(name))
));
return; // TODO
}
if (typeof ev.data === 'object') {
// E.g. '[object Array]' → 'array'
const otype = Object.prototype.toString.call(ev.data).slice(8, -1).toLowerCase();
if (otype === 'object') {
if (ev.data.msg === 'initialize') {
swLang.setLang(ev.data.lang);
}
}
}
})());
}
//#endregion

View file

@ -1,15 +0,0 @@
self.importScripts('/sw-lib.VERSION.js');
self.addEventListener('install', self.lib.oninstall);
self.addEventListener('activate', self.lib.onactivate);
self.addEventListener('fetch', self.lib.onfetch);
self.addEventListener('push', self.lib.onpush);
self.addEventListener('notificationclick', self.lib.onnotificationclick);
self.addEventListener('notificationclose', self.lib.onnotificationclose);
self.addEventListener('message', self.lib.onmessage);

200
packages/sw/src/sw.ts Normal file
View file

@ -0,0 +1,200 @@
declare var self: ServiceWorkerGlobalScope;
import { createEmptyNotification, createNotification } from '@/scripts/create-notification';
import { swLang } from '@/scripts/lang';
import { swNotificationRead } from '@/scripts/notification-read';
import { pushNotificationDataMap } from '@/types';
import * as swos from '@/scripts/operations';
import { acct as getAcct } from '@/filters/user';
self.addEventListener('install', ev => {
ev.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', ev => {
ev.waitUntil(
caches.keys()
.then(cacheNames => Promise.all(
cacheNames
.filter((v) => v !== swLang.cacheName)
.map(name => caches.delete(name))
))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', ev => {
ev.respondWith(
fetch(ev.request)
.catch(() => new Response(`Offline. Service Worker @${_VERSION_}`, { status: 200 }))
);
});
self.addEventListener('push', ev => {
// クライアント取得
ev.waitUntil(self.clients.matchAll({
includeUncontrolled: true,
type: 'window'
}).then(async <K extends keyof pushNotificationDataMap>(clients: readonly WindowClient[]) => {
const data: pushNotificationDataMap[K] = ev.data?.json();
switch (data.type) {
// case 'driveFileCreated':
case 'notification':
case 'unreadMessagingMessage':
// クライアントがあったらストリームに接続しているということなので通知しない
if (clients.length != 0) return;
return createNotification(data);
case 'readAllNotifications':
for (const n of await self.registration.getNotifications()) {
if (n?.data?.type === 'notification') n.close();
}
break;
case 'readAllMessagingMessages':
for (const n of await self.registration.getNotifications()) {
if (n?.data?.type === 'unreadMessagingMessage') n.close();
}
break;
case 'readNotifications':
for (const n of await self.registration.getNotifications()) {
if (data.body?.notificationIds?.includes(n.data.body.id)) {
n.close();
}
}
break;
case 'readAllMessagingMessagesOfARoom':
for (const n of await self.registration.getNotifications()) {
if (n.data.type === 'unreadMessagingMessage'
&& ('userId' in data.body
? data.body.userId === n.data.body.userId
: data.body.groupId === n.data.body.groupId)
) {
n.close();
}
}
break;
}
createEmptyNotification();
}));
});
self.addEventListener('notificationclick', <K extends keyof pushNotificationDataMap>(ev: ServiceWorkerGlobalScopeEventMap['notificationclick']) => {
ev.waitUntil((async () => {
if (_DEV_) {
console.log('notificationclick', ev.action, ev.notification.data);
}
const { action, notification } = ev;
const data: pushNotificationDataMap[K] = notification.data;
const { userId: id } = data;
let client: WindowClient | null = null;
switch (data.type) {
case 'notification':
switch (action) {
case 'follow':
if ('userId' in data.body) await swos.api('following/create', id, { userId: data.body.userId });
break;
case 'showUser':
if ('user' in data.body) client = await swos.openUser(getAcct(data.body.user), id);
break;
case 'reply':
if ('note' in data.body) client = await swos.openPost({ reply: data.body.note }, id);
break;
case 'renote':
if ('note' in data.body) await swos.api('notes/create', id, { renoteId: data.body.note.id });
break;
case 'accept':
switch (data.body.type) {
case 'receiveFollowRequest':
await swos.api('following/requests/accept', id, { userId: data.body.userId });
break;
case 'groupInvited':
await swos.api('users/groups/invitations/accept', id, { invitationId: data.body.invitation.id });
break;
}
break;
case 'reject':
switch (data.body.type) {
case 'receiveFollowRequest':
await swos.api('following/requests/reject', id, { userId: data.body.userId });
break;
case 'groupInvited':
await swos.api('users/groups/invitations/reject', id, { invitationId: data.body.invitation.id });
break;
}
break;
case 'showFollowRequests':
client = await swos.openClient('push', '/my/follow-requests', id);
break;
default:
switch (data.body.type) {
case 'receiveFollowRequest':
client = await swos.openClient('push', '/my/follow-requests', id);
break;
case 'groupInvited':
client = await swos.openClient('push', '/my/groups', id);
break;
case 'reaction':
client = await swos.openNote(data.body.note.id, id);
break;
default:
if ('note' in data.body) {
client = await swos.openNote(data.body.note.id, id);
} else if ('user' in data.body) {
client = await swos.openUser(getAcct(data.body.user), id);
}
break;
}
}
break;
case 'unreadMessagingMessage':
client = await swos.openChat(data.body, id);
break;
}
if (client) {
client.focus();
}
if (data.type === 'notification') {
swNotificationRead.then(that => that.read(data));
}
notification.close();
})());
});
self.addEventListener('notificationclose', <K extends keyof pushNotificationDataMap>(ev: ServiceWorkerGlobalScopeEventMap['notificationclose']) => {
const data: pushNotificationDataMap[K] = ev.notification.data;
if (data.type === 'notification') {
swNotificationRead.then(that => that.read(data));
}
});
self.addEventListener('message', (ev: ServiceWorkerGlobalScopeEventMap['message']) => {
ev.waitUntil((async () => {
switch (ev.data) {
case 'clear':
// Cache Storage全削除
await caches.keys()
.then(cacheNames => Promise.all(
cacheNames.map(name => caches.delete(name))
));
return; // TODO
}
if (typeof ev.data === 'object') {
// E.g. '[object Array]' → 'array'
const otype = Object.prototype.toString.call(ev.data).slice(8, -1).toLowerCase();
if (otype === 'object') {
if (ev.data.msg === 'initialize') {
swLang.setLang(ev.data.lang);
}
}
}
})());
});

View file

@ -18,6 +18,7 @@
"strictNullChecks": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"isolatedModules": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],

File diff suppressed because it is too large Load diff