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,18 @@
/** @type { import('@storybook/react-vite').StorybookConfig } */
const config = {
stories: ['../stories/**/*.mdx', '../stories/**/*.stories.tsx'],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials',
'@storybook/addon-onboarding',
'@storybook/addon-interactions',
],
framework: {
name: '@storybook/react-vite',
options: {},
},
docs: {
autodocs: 'tag',
},
};
export default config;

View File

@@ -0,0 +1,14 @@
/** @type { import('@storybook/react').Preview } */
const preview = {
parameters: {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
};
export default preview;

View File

@@ -0,0 +1,5 @@
const { defineConfig } = require('@coze-arch/stylelint-config');
module.exports = defineConfig({
extends: [],
});

View File

@@ -0,0 +1,16 @@
# @coze-data/reporter
> Project template for react component with storybook and supports publish independently.
## Features
- [x] eslint & ts
- [x] esm bundle
- [x] umd bundle
- [x] storybook
## Commands
- init: `rush update`
- dev: `npm run dev`
- build: `npm run build`

View File

@@ -0,0 +1,76 @@
/*
* 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 { expect, describe, test, vi } from 'vitest';
import { dataReporter } from '../src/reporter/data-reporter';
import { DataNamespace } from '../src/constants';
const global = vi.hoisted(() => ({
reportFn: vi.fn(),
}));
vi.stubGlobal('location', {
pathname:
'/space/7313840473481936940/knowledge/7327619796571734060/7347658103988715564',
});
vi.mock('../src/reporter/utils.ts', () => ({
reporterFun: global.reportFn,
}));
vi.mock('@coze-arch/logger', () => ({}));
describe('test report func', () => {
test('errorEvent', () => {
dataReporter.errorEvent(DataNamespace.KNOWLEDGE, {
error: {},
level: 'error',
eventName: 'test',
} as any);
expect(global.reportFn).toHaveBeenCalledWith({
event: {
error: {},
eventName: 'test',
level: 'error',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
namespace: 'knowledge',
type: 'error',
});
});
test('event', () => {
dataReporter.event(DataNamespace.KNOWLEDGE, {
eventName: 'test',
});
expect(global.reportFn).toHaveBeenCalledWith({
event: {
eventName: 'test',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
namespace: 'knowledge',
type: 'custom',
});
});
});

View File

@@ -0,0 +1,122 @@
/*
* 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.
*/
/* eslint-disable @typescript-eslint/naming-convention */
import React, { useState } from 'react';
import { expect, describe, test, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import { DataErrorBoundary } from '../src/components/error-boundary/error-boundary';
import { DataNamespace } from '../src';
class MyErrorBoundary extends React.Component<
{
children: React.ReactElement;
FallbackComponent: () => React.ReactElement;
onError: (...args: any[]) => void;
},
{ hasError: boolean }
> {
constructor(props) {
super(props);
this.state = {
hasError: false,
};
}
static getDerivedStateFromError(_error) {
// Update state so next render shows fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log error to an error reporting service
this.props.onError(error, errorInfo);
}
render() {
const { children, FallbackComponent } = this.props;
if (this.state.hasError) {
return <FallbackComponent />;
}
return children;
}
}
export function ErrorButton() {
const [clicked, setClicked] = useState(false);
if (clicked) {
throw new Error('test');
}
return <button onClick={() => setClicked(true)}>test</button>;
}
const globalFlag = vi.hoisted(() => ({
persistError: vi.fn(),
}));
vi.mock('@coze-arch/logger', () => ({
ErrorBoundary: props => <MyErrorBoundary {...props} />,
logger: {
persist: {
error: globalFlag.persistError,
},
},
}));
vi.mock('@coze-arch/i18n', () => ({
I18n: {
t: vi.fn().mockImplementation((title: string) => title),
},
}));
describe('test DataErrorBoundary', () => {
test('render children', async () => {
await render(
<DataErrorBoundary namespace={DataNamespace.KNOWLEDGE}>
<button>test</button>
</DataErrorBoundary>,
);
const testButton = await screen.queryByText('test');
expect(testButton).not.toBeNull();
});
test('on error callback', async () => {
await render(
<DataErrorBoundary namespace={DataNamespace.KNOWLEDGE}>
<ErrorButton />
</DataErrorBoundary>,
);
const testButton = await screen.queryByText('test');
expect(testButton).not.toBeNull();
await fireEvent.click(testButton);
expect(globalFlag.persistError).toBeCalled();
});
test('fallback render', async () => {
await render(
<DataErrorBoundary namespace={DataNamespace.KNOWLEDGE}>
<ErrorButton />
</DataErrorBoundary>,
);
const testButton = await screen.queryByText('test');
expect(testButton).not.toBeNull();
await fireEvent.click(testButton);
const fallbackComp = await screen.queryByText('data_error_title');
expect(fallbackComp).not.toBeNull();
});
});

View File

@@ -0,0 +1,95 @@
/*
* 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 { expect, describe, test, vi } from 'vitest';
import { reporterFun } from '../src/reporter/utils';
import { DataNamespace } from '../src/constants';
const global = vi.hoisted(() => ({
reporter: {
errorEvent: vi.fn(),
event: vi.fn(),
},
}));
vi.mock('@coze-arch/logger', () => ({
reporter: global.reporter,
}));
describe('reporter utils test', () => {
test('reporterFun test errorEvent', () => {
reporterFun({
event: {
error: {
name: 'test',
message: 'test',
},
meta: {
spaceId: '2333',
},
eventName: 'test',
level: 'error',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
type: 'error',
namespace: DataNamespace.KNOWLEDGE,
});
expect(global.reporter.errorEvent).toHaveBeenCalledWith({
error: {
message: 'test',
name: 'test',
},
eventName: 'test',
level: 'error',
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '2333',
},
namespace: 'knowledge',
});
expect(global.reporter.event).not.toBeCalled();
});
test('reporterFun test event', () => {
reporterFun({
event: {
eventName: 'test',
},
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
type: 'custom',
namespace: DataNamespace.KNOWLEDGE,
});
expect(global.reporter.event).toHaveBeenCalledWith({
eventName: 'test',
meta: {
documentId: '7347658103988715564',
knowledgeId: '7327619796571734060',
spaceId: '7313840473481936940',
},
namespace: 'knowledge',
});
});
});

View File

@@ -0,0 +1,12 @@
{
"operationSettings": [
{
"operationName": "test:cov",
"outputFolderNames": ["coverage"]
},
{
"operationName": "ts-check",
"outputFolderNames": ["./dist"]
}
]
}

View File

@@ -0,0 +1,6 @@
{
"codecov": {
"coverage": 0,
"incrementCoverage": 0
}
}

View File

@@ -0,0 +1,7 @@
const { defineConfig } = require('@coze-arch/eslint-config');
module.exports = defineConfig({
packageRoot: __dirname,
preset: 'web',
rules: {},
});

View File

@@ -0,0 +1,65 @@
{
"name": "@coze-data/reporter",
"version": "0.0.1",
"description": "coze knowledge reporter",
"license": "Apache-2.0",
"author": "rosefang.123@bytedance.com",
"maintainers": [],
"main": "src/index.ts",
"unpkg": "./dist/umd/index.js",
"module": "./dist/esm/index.js",
"types": "./src/index.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "exit 0",
"dev": "storybook dev -p 6006",
"lint": "eslint ./ --cache",
"test": "vitest --run --passWithNoTests",
"test:cov": "npm run test -- --coverage"
},
"dependencies": {
"@coze-arch/i18n": "workspace:*",
"@coze-arch/logger": "workspace:*",
"@douyinfe/semi-illustrations": "^2.36.0",
"lodash-es": "^4.17.21"
},
"devDependencies": {
"@coze-arch/eslint-config": "workspace:*",
"@coze-arch/stylelint-config": "workspace:*",
"@coze-arch/ts-config": "workspace:*",
"@coze-arch/vitest-config": "workspace:*",
"@storybook/addon-essentials": "^7.6.7",
"@storybook/addon-interactions": "^7.6.7",
"@storybook/addon-links": "^7.6.7",
"@storybook/addon-onboarding": "^1.0.10",
"@storybook/blocks": "^7.6.7",
"@storybook/react": "^7.6.7",
"@storybook/react-vite": "^7.6.7",
"@storybook/test": "^7.6.7",
"@swc/core": "^1.3.35",
"@swc/helpers": "^0.4.12",
"@testing-library/jest-dom": "^6.1.5",
"@testing-library/react": "^14.1.2",
"@testing-library/react-hooks": "^8.0.1",
"@types/lodash-es": "^4.17.10",
"@types/react": "18.2.37",
"@types/react-dom": "18.2.15",
"@vitest/coverage-v8": "~3.0.5",
"autoprefixer": "^10.4.16",
"less-loader": "~11.1.3",
"postcss": "^8.4.32",
"react": "~18.2.0",
"react-dom": "~18.2.0",
"storybook": "^7.6.7",
"tailwindcss": "~3.3.3",
"vitest": "~3.0.5"
},
"peerDependencies": {
"react": ">=18.2.0",
"react-dom": ">=18.2.0"
}
}

View File

@@ -0,0 +1,62 @@
/*
* 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 React, { type FC, type PropsWithChildren } from 'react';
import { logger, ErrorBoundary } from '@coze-arch/logger';
import { I18n } from '@coze-arch/i18n';
import { IllustrationNoAccess } from '@douyinfe/semi-illustrations';
import { type DataNamespace } from '../../constants';
import s from './index.module.less';
interface FallbackComponentProps {
namespace: DataNamespace;
}
export const ErrorFallbackComponent: FC<FallbackComponentProps> = ({
namespace,
}) => (
<div className={s.wrapper}>
<div className={s.content}>
<IllustrationNoAccess width={140} height={140} />
<div className={s.title}>
{I18n.t('data_error_title', { module: namespace })}
</div>
<div className={s.paragraph}>{I18n.t('data_error_msg')}</div>
</div>
</div>
);
export interface DataErrorBoundaryProps {
namespace: DataNamespace;
}
export const DataErrorBoundary: FC<
PropsWithChildren<DataErrorBoundaryProps>
> = ({ children, namespace }) => (
<ErrorBoundary
onError={error => {
logger.persist.error({
eventName: `${namespace}_error_boundary`,
error,
});
}}
errorBoundaryName={`${namespace}-error-boundary`}
FallbackComponent={() => <ErrorFallbackComponent namespace={namespace} />}
>
{children}
</ErrorBoundary>
);

View File

@@ -0,0 +1,30 @@
/* stylelint-disable declaration-no-important */
.wrapper {
width: 100%;
height: 100%;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
margin: auto;
padding-top: 35.39vh;
}
.title {
margin-top: 24px !important;
margin-bottom: 4px !important;
font-size: 16px !important;
font-weight: 600 !important;
line-height: 22px !important;
}
.paragraph {
margin-bottom: 24px !important;
font-size: 12px !important;
line-height: 16px !important;
color: #1d1c2399 !important;
}

View File

@@ -0,0 +1,24 @@
/*
* 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 enum DataNamespace {
KNOWLEDGE = 'knowledge',
DATABASE = 'database',
FILEBOX = 'filebox',
VARIABLE = 'variable',
TIMECAPSULE = 'timeCapsule',
MEMORY = 'memory',
}

View File

@@ -0,0 +1,24 @@
/*
* 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 {
DataErrorBoundary,
ErrorFallbackComponent,
type DataErrorBoundaryProps,
} from './components/error-boundary/error-boundary';
export { DataNamespace } from './constants';
export { dataReporter } from './reporter';

View File

@@ -0,0 +1,78 @@
/*
* 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 { get } from 'lodash-es';
import type { ErrorEvent, CustomEvent } from '@coze-arch/logger';
import { type DataNamespace } from '../constants';
import { reporterFun } from './utils';
enum ParamsIndex {
SPACE_ID = 1,
KNOWLEDGE_ID = 3,
DOCUMENT_ID = 5,
}
/**
* 与use-data-reporter区分使用
* use-data-reporter用于组件场景
* data-reporter用于ts/js场景
*/
class DataReporter {
/**
* 获取公共的meta信息
*/
getMeta() {
const pathName = window.location.pathname;
const reg = /\/space\/(\d+)\/knowledge(\/(\d+)(\/(\d+))?)?/gi;
const regRes = reg.exec(pathName);
const meta = {
spaceId: get(regRes, ParamsIndex.SPACE_ID),
knowledgeId: get(regRes, ParamsIndex.KNOWLEDGE_ID),
documentId: get(regRes, ParamsIndex.DOCUMENT_ID),
};
return meta;
}
/**
* 错误事件上报
* @param namespace
* @param event
*/
errorEvent<EventEnum extends string>(
namespace: DataNamespace,
event: ErrorEvent<EventEnum>,
) {
const meta = this.getMeta();
reporterFun({ type: 'error', namespace, event, meta });
}
/**
* 自定义事件上报
* @param namespace
* @param event
*/
event<EventEnum extends string>(
namespace: DataNamespace,
event: CustomEvent<EventEnum>,
) {
const meta = this.getMeta();
reporterFun({ type: 'custom', namespace, event, meta });
}
}
export const dataReporter = new DataReporter();

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.
*/
export { dataReporter } from './data-reporter';

View File

@@ -0,0 +1,55 @@
/*
* 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 {
reporter,
type CustomEvent,
type ErrorEvent,
} from '@coze-arch/logger';
import { type DataNamespace } from '../constants';
export const reporterFun = <EventEnum extends string>(
params: {
namespace: DataNamespace;
meta: { [key: string]: unknown };
} & (
| {
type: 'error';
event: ErrorEvent<EventEnum>;
}
| {
type: 'custom';
event: CustomEvent<EventEnum>;
}
),
) => {
const { type, namespace, event, meta } = params;
const { meta: inputMeta, ...rest } = event;
const eventParams = {
namespace,
meta: {
...meta,
...inputMeta,
},
...rest,
};
if (type === 'error') {
reporter.errorEvent(eventParams as ErrorEvent<EventEnum>);
} else {
reporter.event(eventParams);
}
};

View File

@@ -0,0 +1,20 @@
/*
* 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.
*/
declare module '*.less' {
const resource: { [key: string]: string };
export = resource;
}

View File

@@ -0,0 +1,37 @@
/*
* 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 { DataErrorBoundary, DataNamespace } from '../src';
export default {
title: 'DataErrorBoundary',
component: DataErrorBoundary,
parameters: {
namespace: DataNamespace.KNOWLEDGE,
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {},
};
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const Base = {
args: {
name: 'tecvan',
},
};

View File

@@ -0,0 +1,31 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"compilerOptions": {
"types": [],
"rootDir": "./src",
"outDir": "./dist",
"tsBuildInfoFile": "dist/tsconfig.build.tsbuildinfo"
},
"include": ["src"],
"references": [
{
"path": "../../../arch/i18n/tsconfig.build.json"
},
{
"path": "../../../arch/logger/tsconfig.build.json"
},
{
"path": "../../../../config/eslint-config/tsconfig.build.json"
},
{
"path": "../../../../config/stylelint-config/tsconfig.build.json"
},
{
"path": "../../../../config/ts-config/tsconfig.build.json"
},
{
"path": "../../../../config/vitest-config/tsconfig.build.json"
}
]
}

View File

@@ -0,0 +1,15 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"composite": true
},
"references": [
{
"path": "./tsconfig.build.json"
},
{
"path": "./tsconfig.misc.json"
}
],
"exclude": ["**/*"]
}

View File

@@ -0,0 +1,16 @@
{
"extends": "@coze-arch/ts-config/tsconfig.web.json",
"$schema": "https://json.schemastore.org/tsconfig",
"include": ["__tests__", "stories", "vitest.config.ts", "tailwind.config.ts"],
"exclude": ["./dist"],
"references": [
{
"path": "./tsconfig.build.json"
}
],
"compilerOptions": {
"rootDir": "./",
"outDir": "./dist",
"types": ["vitest/globals"]
}
}

View File

@@ -0,0 +1,27 @@
/*
* 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 { defineConfig } from '@coze-arch/vitest-config';
export default defineConfig({
dirname: __dirname,
preset: 'web',
test: {
coverage: {
all: true,
},
},
});