fix: type import (#2715)

This commit is contained in:
Himself65 2023-06-07 22:47:02 +08:00 committed by GitHub
parent 008a05a470
commit 7f2006488e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 60 additions and 91 deletions

View File

@ -1,6 +0,0 @@
/* eslint-disable @typescript-eslint/consistent-type-imports */
declare interface Window {
apis: import('./src/affine-apis').PreloadHandlers;
events: import('./src/affine-apis').MainIPCEventMap;
}

View File

@ -1,26 +1,6 @@
// NOTE: we will generate preload types from this file // NOTE: we will generate preload types from this file
import { ipcRenderer } from 'electron'; import { ipcRenderer } from 'electron';
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
import type {
MainIPCEventMap,
MainIPCHandlerMap,
} from '../../main/src/exposed';
type WithoutFirstParameter<T> = T extends (_: any, ...args: infer P) => infer R
? (...args: P) => R
: T;
type HandlersMap<N extends keyof MainIPCHandlerMap> = {
[K in keyof MainIPCHandlerMap[N]]: WithoutFirstParameter<
MainIPCHandlerMap[N][K]
>;
};
export type PreloadHandlers = {
[N in keyof MainIPCHandlerMap]: HandlersMap<N>;
};
type MainExposedMeta = { type MainExposedMeta = {
handlers: [namespace: string, handlerNames: string[]][]; handlers: [namespace: string, handlerNames: string[]][];
events: [namespace: string, eventNames: string[]][]; events: [namespace: string, eventNames: string[]][];
@ -35,7 +15,7 @@ const meta: MainExposedMeta = (() => {
})(); })();
// main handlers that can be invoked from the renderer process // main handlers that can be invoked from the renderer process
const apis: PreloadHandlers = (() => { const apis: any = (() => {
const { handlers: handlersMeta } = meta; const { handlers: handlersMeta } = meta;
const all = handlersMeta.map(([namespace, functionNames]) => { const all = handlersMeta.map(([namespace, functionNames]) => {
@ -55,7 +35,7 @@ const apis: PreloadHandlers = (() => {
})(); })();
// main events that can be listened to from the renderer process // main events that can be listened to from the renderer process
const events: MainIPCEventMap = (() => { const events: any = (() => {
const { events: eventsMeta } = meta; const { events: eventsMeta } = meta;
// NOTE: ui may try to listen to a lot of the same events, so we increase the limit... // NOTE: ui may try to listen to a lot of the same events, so we increase the limit...

View File

@ -1,6 +1,3 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../layers/preload/preload.d.ts" />
/* eslint-disable no-empty-pattern */ /* eslint-disable no-empty-pattern */
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import { join, resolve } from 'node:path'; import { join, resolve } from 'node:path';
@ -45,6 +42,7 @@ export const test = base.extend<{
}); });
} }
const logFilePath = await page.evaluate(async () => { const logFilePath = await page.evaluate(async () => {
// @ts-expect-error
return window.apis?.debug.logFilePath(); return window.apis?.debug.logFilePath();
}); });
// wat for blocksuite to be loaded // wat for blocksuite to be loaded

View File

@ -27,6 +27,7 @@ test('move workspace db file', async ({ page, appInfo, workspace }) => {
// move db file to tmp folder // move db file to tmp folder
await page.evaluate(tmpPath => { await page.evaluate(tmpPath => {
// @ts-expect-error
window.apis?.dialog.setFakeDialogResult({ window.apis?.dialog.setFakeDialogResult({
filePath: tmpPath, filePath: tmpPath,
}); });
@ -61,6 +62,7 @@ test('export then add', async ({ page, appInfo, workspace }) => {
// export db file to tmp folder // export db file to tmp folder
await page.evaluate(tmpPath => { await page.evaluate(tmpPath => {
// @ts-expect-error
window.apis?.dialog.setFakeDialogResult({ window.apis?.dialog.setFakeDialogResult({
filePath: tmpPath, filePath: tmpPath,
}); });
@ -79,6 +81,7 @@ test('export then add', async ({ page, appInfo, workspace }) => {
await page.getByTestId('add-or-new-workspace').click(); await page.getByTestId('add-or-new-workspace').click();
await page.evaluate(tmpPath => { await page.evaluate(tmpPath => {
// @ts-expect-error
window.apis?.dialog.setFakeDialogResult({ window.apis?.dialog.setFakeDialogResult({
filePath: tmpPath, filePath: tmpPath,
}); });

View File

@ -50,8 +50,10 @@ rootWorkspacesMetadataAtom.onMount = setAtom => {
}, 0); }, 0);
if (environment.isDesktop) { if (environment.isDesktop) {
// @ts-expect-error
window.apis?.workspace.list().then(workspaceIDs => { window.apis?.workspace.list().then(workspaceIDs => {
if (abortController.signal.aborted) return; if (abortController.signal.aborted) return;
// @ts-expect-error
const newMetadata = workspaceIDs.map(w => ({ const newMetadata = workspaceIDs.map(w => ({
id: w[0], id: w[0],
flavour: WorkspaceFlavour.LOCAL, flavour: WorkspaceFlavour.LOCAL,
@ -59,6 +61,7 @@ rootWorkspacesMetadataAtom.onMount = setAtom => {
setAtom(metadata => { setAtom(metadata => {
return [ return [
...metadata, ...metadata,
// @ts-expect-error
...newMetadata.filter(m => !metadata.find(m2 => m2.id === m.id)), ...newMetadata.filter(m => !metadata.find(m2 => m2.id === m.id)),
]; ];
}); });

View File

@ -122,6 +122,7 @@ const useDefaultDBLocation = () => {
const [defaultDBLocation, setDefaultDBLocation] = useState(''); const [defaultDBLocation, setDefaultDBLocation] = useState('');
useEffect(() => { useEffect(() => {
// @ts-expect-error
window.apis?.db.getDefaultStorageLocation().then(dir => { window.apis?.db.getDefaultStorageLocation().then(dir => {
setDefaultDBLocation(dir); setDefaultDBLocation(dir);
}); });
@ -147,6 +148,7 @@ const SetDBLocationContent = ({
if (result?.filePath) { if (result?.filePath) {
onConfirmLocation(result.filePath); onConfirmLocation(result.filePath);
} else if (result?.error) { } else if (result?.error) {
// @ts-expect-error
toast(t[result.error]()); toast(t[result.error]());
} }
}; };
@ -277,6 +279,7 @@ export const CreateWorkspaceModal = ({
setStep('set-syncing-mode'); setStep('set-syncing-mode');
} else if (result.error || result.canceled) { } else if (result.error || result.canceled) {
if (result.error) { if (result.error) {
// @ts-expect-error
toast(t[result.error]()); toast(t[result.error]());
} }
onClose(); onClose();

View File

@ -18,6 +18,7 @@ export const ExportPanel = () => {
if (id) { if (id) {
const result = await window.apis?.dialog.saveDBFileAs(id); const result = await window.apis?.dialog.saveDBFileAs(id);
if (result?.error) { if (result?.error) {
// @ts-expect-error
toast(t[result.error]()); toast(t[result.error]());
} else if (!result?.canceled) { } else if (!result?.canceled) {
toast(t['Export success']()); toast(t['Export success']());

View File

@ -27,9 +27,11 @@ const useShowOpenDBFile = (workspaceId: string) => {
const [show, setShow] = useState(false); const [show, setShow] = useState(false);
useEffect(() => { useEffect(() => {
if (window.apis && window.events && environment.isDesktop) { if (window.apis && window.events && environment.isDesktop) {
// @ts-expect-error
window.apis.workspace.getMeta(workspaceId).then(meta => { window.apis.workspace.getMeta(workspaceId).then(meta => {
setShow(!!meta.secondaryDBPath); setShow(!!meta.secondaryDBPath);
}); });
// @ts-expect-error
return window.events.workspace.onMetaChange(newMeta => { return window.events.workspace.onMetaChange(newMeta => {
if (newMeta.workspaceId === workspaceId) { if (newMeta.workspaceId === workspaceId) {
const meta = newMeta.meta; const meta = newMeta.meta;
@ -73,6 +75,7 @@ export const GeneralPanel: React.FC<PanelProps> = ({
if (!result?.error && !result?.canceled) { if (!result?.error && !result?.canceled) {
toast(t['Move folder success']()); toast(t['Move folder success']());
} else if (result?.error) { } else if (result?.error) {
// @ts-expect-error
toast(t[result.error]()); toast(t[result.error]());
} }
} catch (err) { } catch (err) {

View File

@ -35,22 +35,14 @@ function rpcToObservable<
}); });
} }
type InferTFromEvent<E> = E extends (
callback: (t: infer T) => void
) => () => void
? T
: never;
type UpdateMeta = InferTFromEvent<typeof window.events.updater.onUpdateReady>;
export const updateReadyAtom = atomWithObservable(() => { export const updateReadyAtom = atomWithObservable(() => {
return rpcToObservable(null as UpdateMeta | null, { return rpcToObservable(null as any | null, {
event: window.events?.updater.onUpdateReady, event: window.events?.updater.onUpdateReady,
}); });
}); });
export const updateAvailableAtom = atomWithObservable(() => { export const updateAvailableAtom = atomWithObservable(() => {
return rpcToObservable(null as UpdateMeta | null, { return rpcToObservable(null as any | null, {
event: window.events?.updater.onUpdateAvailable, event: window.events?.updater.onUpdateAvailable,
onSubscribe: () => { onSubscribe: () => {
window.apis?.updater.checkForUpdatesAndNotify(); window.apis?.updater.checkForUpdatesAndNotify();

View File

@ -1,6 +1,3 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../../../apps/electron/layers/preload/preload.d.ts" />
export * from './components/list-skeleton'; export * from './components/list-skeleton';
export * from './styles'; export * from './styles';
export * from './ui/breadcrumbs'; export * from './ui/breadcrumbs';

View File

@ -1,12 +1,20 @@
/// <reference types="@blocksuite/global" /> /// <reference types="@blocksuite/global" />
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="./global.d.ts" />
import { assertEquals } from '@blocksuite/global/utils'; import { assertEquals } from '@blocksuite/global/utils';
import getConfig from 'next/config'; import getConfig from 'next/config';
import { z } from 'zod'; import { z } from 'zod';
import { UaHelper } from './ua-helper'; import { UaHelper } from './ua-helper';
declare global {
interface Window {
appInfo: {
electron: boolean;
};
apis: any;
events: any;
}
}
export const buildFlagsSchema = z.object({ export const buildFlagsSchema = z.object({
/** /**
* todo: remove this build flag when filter feature is ready. * todo: remove this build flag when filter feature is ready.

View File

@ -1,5 +0,0 @@
interface Window {
appInfo: {
electron: bool;
};
}

View File

@ -1,10 +1,9 @@
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"include": ["./src"],
"compilerOptions": { "compilerOptions": {
"noEmit": false,
"composite": true, "composite": true,
"noEmit": false,
"outDir": "lib" "outDir": "lib"
}, }
"include": ["./src", "env.d.ts", "./src/global.d.ts"],
"exclude": ["lib"]
} }

View File

@ -1,10 +1,9 @@
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"include": ["./src"],
"compilerOptions": { "compilerOptions": {
"target": "ESNext", "composite": true,
"module": "ESNext", "noEmit": false,
"rootDir": "./src", "outDir": "lib"
"noEmit": true }
},
"include": ["src"]
} }

View File

@ -1,10 +1,10 @@
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "lib",
"composite": true,
"noEmit": false
},
"include": ["./src"], "include": ["./src"],
"compilerOptions": {
"composite": true,
"noEmit": false,
"outDir": "lib"
},
"references": [{ "path": "../env" }, { "path": "../y-indexeddb" }] "references": [{ "path": "../env" }, { "path": "../y-indexeddb" }]
} }

View File

@ -1,14 +1,10 @@
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"compilerOptions": {
"module": "ESNext",
"target": "ESNext",
"sourceMap": true,
"noEmit": false,
"outDir": "lib",
"composite": true
},
"include": ["./src"], "include": ["./src"],
"exclude": ["node_modules"], "compilerOptions": {
"composite": true,
"noEmit": false,
"outDir": "lib"
},
"references": [{ "path": "../env" }] "references": [{ "path": "../env" }]
} }

View File

@ -1,6 +1,11 @@
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"include": ["./src"], "include": ["./src"],
"compilerOptions": {
"composite": true,
"noEmit": false,
"outDir": "lib"
},
"references": [ "references": [
{ {
"path": "../component" "path": "../component"
@ -8,10 +13,5 @@
{ {
"path": "../workspace" "path": "../workspace"
} }
], ]
"compilerOptions": {
"noEmit": false,
"composite": true,
"outDir": "lib"
}
} }

View File

@ -1,7 +1,6 @@
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"exclude": ["lib"], "include": ["./src"],
"include": ["src"],
"compilerOptions": { "compilerOptions": {
"composite": true, "composite": true,
"noEmit": false, "noEmit": false,

View File

@ -102,9 +102,11 @@ export const CRUD: WorkspaceCRUD<WorkspaceFlavour.LOCAL> = {
// workspaces in desktop // workspaces in desktop
if (window.apis && environment.isDesktop) { if (window.apis && environment.isDesktop) {
// @ts-expect-error
const desktopIds = (await window.apis.workspace.list()).map(([id]) => id); const desktopIds = (await window.apis.workspace.list()).map(([id]) => id);
// the ids maybe a subset of the local storage // the ids maybe a subset of the local storage
const moreWorkspaces = desktopIds.filter( const moreWorkspaces = desktopIds.filter(
// @ts-expect-error
id => !allWorkspaceIDs.includes(id) id => !allWorkspaceIDs.includes(id)
); );
allWorkspaceIDs = [...allWorkspaceIDs, ...moreWorkspaces]; allWorkspaceIDs = [...allWorkspaceIDs, ...moreWorkspaces];

View File

@ -39,6 +39,7 @@ vi.stubGlobal('window', {
}, },
events: { events: {
db: { db: {
// @ts-expect-error
onExternalUpdate: fn => { onExternalUpdate: fn => {
triggerDBUpdate = fn; triggerDBUpdate = fn;
return () => { return () => {
@ -113,6 +114,7 @@ describe('SQLite download provider', () => {
offlineYdoc.getText('text').insert(0, 'sqlite-world'); offlineYdoc.getText('text').insert(0, 'sqlite-world');
// @ts-expect-error
triggerDBUpdate?.({ triggerDBUpdate?.({
workspaceId: id + '-another-id', workspaceId: id + '-another-id',
update: Y.encodeStateAsUpdate(offlineYdoc), update: Y.encodeStateAsUpdate(offlineYdoc),
@ -121,6 +123,7 @@ describe('SQLite download provider', () => {
// not yet updated (because the workspace id is different) // not yet updated (because the workspace id is different)
expect(workspace.doc.getText('text').toString()).toBe(''); expect(workspace.doc.getText('text').toString()).toBe('');
// @ts-expect-error
triggerDBUpdate?.({ triggerDBUpdate?.({
workspaceId: id, workspaceId: id,
update: Y.encodeStateAsUpdate(offlineYdoc), update: Y.encodeStateAsUpdate(offlineYdoc),

View File

@ -183,6 +183,7 @@ const createSQLiteProvider = (
const connect = () => { const connect = () => {
logger.info('connecting sqlite provider', blockSuiteWorkspace.id); logger.info('connecting sqlite provider', blockSuiteWorkspace.id);
blockSuiteWorkspace.doc.on('update', handleUpdate); blockSuiteWorkspace.doc.on('update', handleUpdate);
// @ts-expect-error
unsubscribe = events.db.onExternalUpdate(({ update, workspaceId }) => { unsubscribe = events.db.onExternalUpdate(({ update, workspaceId }) => {
if (workspaceId === blockSuiteWorkspace.id) { if (workspaceId === blockSuiteWorkspace.id) {
Y.applyUpdate(blockSuiteWorkspace.doc, update, sqliteOrigin); Y.applyUpdate(blockSuiteWorkspace.doc, update, sqliteOrigin);

View File

@ -1,17 +1,11 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../../../apps/electron/layers/preload/preload.d.ts" />
import type { View } from '@affine/component/page-list/filter/shared-types'; import type { View } from '@affine/component/page-list/filter/shared-types';
import type { EditorContainer } from '@blocksuite/editor'; import type { EditorContainer } from '@blocksuite/editor';
import type { Page } from '@blocksuite/store'; import type { Page } from '@blocksuite/store';
import type { Workspace as BlockSuiteWorkspace } from '@blocksuite/store'; import type { Workspace as BlockSuiteWorkspace } from '@blocksuite/store';
import type { createStore } from 'jotai';
import type { FC, PropsWithChildren } from 'react'; import type { FC, PropsWithChildren } from 'react';
import type { Workspace as RemoteWorkspace } from './affine/api'; import type { Workspace as RemoteWorkspace } from './affine/api';
export type JotaiStore = ReturnType<typeof createStore>;
export enum WorkspaceSubPath { export enum WorkspaceSubPath {
ALL = 'all', ALL = 'all',
SETTING = 'setting', SETTING = 'setting',

View File

@ -1,12 +1,11 @@
{ {
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"include": ["./src"],
"compilerOptions": { "compilerOptions": {
"composite": true, "composite": true,
"noEmit": false, "noEmit": false,
"outDir": "lib" "outDir": "lib"
}, },
"include": ["./src", "./src/affine/api"],
"exclude": ["lib"],
"references": [ "references": [
{ "path": "../../tests/fixtures" }, { "path": "../../tests/fixtures" },
{ "path": "../y-indexeddb" }, { "path": "../y-indexeddb" },