feat: manually mirror opencoze's code from bytedance

Change-Id: I09a73aadda978ad9511264a756b2ce51f5761adf
This commit is contained in:
fanlv
2025-07-20 17:36:12 +08:00
commit 890153324f
14811 changed files with 1923430 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { type LocalStorageCacheConfig } from './types';
// 统一维护 key 定义避免出现冲突
export const LOCAL_STORAGE_CACHE_KEYS = [
'coachmark',
'workspace-spaceId',
'workspace-subMenu',
'workspace-develop-filters',
'workspace-library-filters',
'workspace-ocean-project-filters',
'coze-home-session-area-hidden-key',
'template-purchase-agreement-checked',
'coze-promptkit-recommend-pannel-hidden-key',
'workflow-toolbar-role-onboarding-hidden',
'coze-project-entity-hidden-key',
'enterpriseId',
'resourceCopyTaskIds',
'coze-create-enterprise-success',
'coze-show-product-matrix-tips',
] as const satisfies readonly string[];
export type LocalStorageCacheKey = (typeof LOCAL_STORAGE_CACHE_KEYS)[number];
export type LocalStorageCacheConfigMap = {
[key in LocalStorageCacheKey]?: LocalStorageCacheConfig;
};
export const cacheConfig: LocalStorageCacheConfigMap = {
coachmark: {
bindAccount: true,
},
'workspace-spaceId': {
bindAccount: true,
},
'workspace-subMenu': {
bindAccount: true,
},
'template-purchase-agreement-checked': {
bindAccount: true,
},
enterpriseId: {
bindAccount: true,
},
resourceCopyTaskIds: {
bindAccount: true,
},
};

View File

@@ -0,0 +1,154 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { throttle } from 'lodash-es';
import EventEmitter from 'eventemitter3';
import { filterCacheData, paseLocalStorageValue } from '../utils/parse';
import { type LocalStorageCacheData } from '../types';
import { cacheConfig, type LocalStorageCacheKey } from '../config';
const LOCAL_STORAGE_KEY = '__coz_biz_cache__';
const throttleWait = 300;
class LocalStorageService extends EventEmitter {
#state: LocalStorageCacheData = {};
#userId: string | undefined;
#saveState: () => void;
constructor() {
super();
this.#saveState = throttle(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.#state));
}, throttleWait);
document.addEventListener('visibilitychange', () => {
/**
* 页签进入后台后,通过操作其它页签,可能导致 #state 状态不是最新的
* 所以页签重新激活后需要同步一次 localStorage 的数据
*/
if (document.visibilityState === 'visible') {
this.#initState();
}
});
this.#initState();
}
#initState() {
this.#state = filterCacheData(
paseLocalStorageValue(localStorage.getItem(LOCAL_STORAGE_KEY)),
);
this.emit('change');
}
#setPermanent(key: LocalStorageCacheKey, value?: string) {
if (value) {
this.#state.permanent = {
...this.#state.permanent,
[key]: value,
};
} else if (this.#state.permanent) {
delete this.#state.permanent[key];
}
this.#saveState();
}
#setUserRelated(key: LocalStorageCacheKey, value?: string) {
if (!this.#userId) {
return;
}
if (value) {
this.#state.userRelated = {
...this.#state.userRelated,
[this.#userId]: {
...this.#state.userRelated?.[this.#userId],
[key]: value,
},
};
} else if (this.#state.userRelated?.[this.#userId]?.[key]) {
delete this.#state.userRelated?.[this.#userId]?.[key];
}
this.#saveState();
}
#getPermanent(key: LocalStorageCacheKey) {
return this.#state.permanent?.[key];
}
#getUserRelated(key: LocalStorageCacheKey) {
if (!this.#userId) {
if (IS_DEV_MODE) {
throw Error(
'需要确保在 userId 初始化后再调用此方法 或者使用 getValueSync',
);
}
return undefined;
}
return this.#state.userRelated?.[this.#userId]?.[key];
}
#waitUserId() {
return new Promise<string | undefined>(r => {
const callback = (userId: string) => {
if (userId) {
r(this.#userId);
this.off('setUserId', callback);
}
};
this.on('setUserId', callback);
});
}
setUserId(userId?: string) {
this.#userId = userId;
this.emit('change');
this.emit('setUserId', userId);
}
setValue(key: LocalStorageCacheKey, value?: string) {
const { bindAccount } = cacheConfig[key] ?? {};
if (bindAccount) {
if (!this.#userId) {
return;
}
this.#setUserRelated(key, value);
} else {
this.#setPermanent(key, value);
}
this.emit('change');
}
getValue(key: LocalStorageCacheKey): string | undefined {
const { bindAccount } = cacheConfig[key] ?? {};
if (bindAccount) {
return this.#getUserRelated(key);
}
return this.#getPermanent(key);
}
async getValueSync(key: LocalStorageCacheKey): Promise<string | undefined> {
const { bindAccount } = cacheConfig[key] ?? {};
if (bindAccount) {
if (!this.#userId) {
await this.#waitUserId();
}
return this.#getUserRelated(key);
}
return this.#getPermanent(key);
}
}
export const localStorageService = new LocalStorageService();

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { useEffect, useState } from 'react';
import { localStorageService } from '../core';
import { type LocalStorageCacheKey } from '../config';
export const useValue = (key: LocalStorageCacheKey): string | undefined => {
const [value, setValue] = useState(() => localStorageService.getValue(key));
useEffect(() => {
const callback = () => {
setValue(localStorageService.getValue(key));
};
localStorageService.on('change', callback);
return () => {
localStorageService.off('change', callback);
};
}, [key]);
return value;
};

View File

@@ -0,0 +1,19 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { localStorageService } from './core';
export { useValue as useLocalStorageValue } from './hooks/use-value';

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface LocalStorageCacheConfig {
bindAccount?: boolean;
}
export interface CacheDataItems {
[key: string]: string;
}
export interface LocalStorageCacheData {
permanent?: CacheDataItems;
userRelated?: Record<string, CacheDataItems>;
}

View File

@@ -0,0 +1,17 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <reference types='@coze-arch/bot-typings' />

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { type CacheDataItems, type LocalStorageCacheData } from '../types';
import { LOCAL_STORAGE_CACHE_KEYS } from '../config';
const isValidDataItem = (data: unknown): data is CacheDataItems => {
if (!data || typeof data !== 'object') {
return false;
}
return Object.values(data).every(value => typeof value === 'string');
};
const isObject = (value: unknown): value is object =>
!!value && typeof value === 'object' && value !== null;
// 判断本地缓存中的值是否与 LocalStorageCacheData 类型定义匹配
const isValidCacheData = (value: unknown): value is LocalStorageCacheData => {
if (!isObject(value)) {
return false;
}
if ('permanent' in value && !isValidDataItem(value.permanent)) {
return false;
}
if ('userRelated' in value) {
const { userRelated } = value;
if (!isObject(userRelated)) {
return false;
}
if (
Object.values(userRelated).some(dateItem => !isValidDataItem(dateItem))
) {
return false;
}
}
return true;
};
export const paseLocalStorageValue = (value: string | null) => {
if (!value) {
return {};
}
try {
const raw = JSON.parse(value);
return isValidCacheData(raw) ? raw : ({} satisfies LocalStorageCacheData);
} catch (e) {
return {} satisfies LocalStorageCacheData;
}
};
const filterDataItems = (data: CacheDataItems): CacheDataItems =>
Object.entries(data).reduce((res, [key, item]) => {
if ((LOCAL_STORAGE_CACHE_KEYS as unknown as string[]).includes(key)) {
return {
...res,
[key]: item,
};
}
return res;
}, {});
export const filterCacheData = (
cacheData: LocalStorageCacheData,
): LocalStorageCacheData => {
if (cacheData.permanent) {
cacheData.permanent = filterDataItems(cacheData.permanent);
}
if (cacheData.userRelated) {
cacheData.userRelated = Object.entries(cacheData.userRelated).reduce(
(res, [key, value]) => ({
...res,
[key]: filterDataItems(value),
}),
{},
);
}
return cacheData;
};