refactor: establish workspaces and extract db and dtos packages

This commit is contained in:
yiling
2026-06-01 23:08:58 +08:00
parent d10c92133d
commit 2362a7f373
210 changed files with 81275 additions and 265 deletions
+21
View File
@@ -145,6 +145,23 @@
"vitest": "^4.1.4",
},
},
"packages/db": {
"name": "@shumai/db",
"version": "0.1.0",
"dependencies": {
"@prisma/client": "^7.7.0",
},
"devDependencies": {
"prisma": "^7.7.0",
},
},
"packages/dtos": {
"name": "@shumai/dtos",
"version": "0.1.0",
"dependencies": {
"zod": "^4.4.3",
},
},
},
"packages": {
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
@@ -925,6 +942,10 @@
"@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
"@shumai/db": ["@shumai/db@workspace:packages/db"],
"@shumai/dtos": ["@shumai/dtos@workspace:packages/dtos"],
"@sinclair/typebox": ["@sinclair/typebox@0.34.49", "", {}, "sha512-brySQQs7Jtn0joV8Xh9ZV/hZb9Ozb0pmazDIASBkYKCjXrXU3mpcFahmK/z4YDhGkQvP9mWJbVyahdtU5wQA+A=="],
"@smithy/chunked-blob-reader": ["@smithy/chunked-blob-reader@5.2.2", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-St+kVicSyayWQca+I1rGitaOEH6uKgE8IUWoYnnEX26SWdWQcL6LvMSD19Lg+vYHKdT9B2Zuu7rd3i6Wnyb/iw=="],
+3
View File
@@ -3,6 +3,9 @@
"version": "0.1.0",
"private": true,
"type": "module",
"workspaces": [
"packages/*"
],
"scripts": {
"dev": "bun run --hot src/index.ts serve",
"typecheck": "tsc --noEmit",
+14
View File
@@ -0,0 +1,14 @@
{
"name": "@shumai/db",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"dependencies": {
"@prisma/client": "^7.7.0"
},
"devDependencies": {
"prisma": "^7.7.0"
}
}
@@ -1,5 +1,5 @@
import { afterEach, beforeEach } from 'vitest'
import { getPrismaTestingHelper } from '@/db'
import { getPrismaTestingHelper } from './index'
export function setupTestDbHooks() {
beforeEach(async () => {
+178
View File
@@ -0,0 +1,178 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file should be your main import to use Prisma-related types and utilities in a browser.
* Use it to get access to models, enums, and input types.
*
* This file does not contain a `PrismaClient` class, nor several other helpers that are intended as server-side only.
* See `client.ts` for the standard, server-side entry point.
*
* 🟢 You can import this file directly.
*/
import * as Prisma from './internal/prismaNamespaceBrowser.ts'
export { Prisma }
export * as $Enums from './enums.ts'
export * from './enums.ts'
/**
* Model User
*
*/
export type User = Prisma.UserModel
/**
* Model Session
*
*/
export type Session = Prisma.SessionModel
/**
* Model Account
*
*/
export type Account = Prisma.AccountModel
/**
* Model Verification
*
*/
export type Verification = Prisma.VerificationModel
/**
* Model AuthToken
*
*/
export type AuthToken = Prisma.AuthTokenModel
/**
* Model Team
*
*/
export type Team = Prisma.TeamModel
/**
* Model Sandbox
*
*/
export type Sandbox = Prisma.SandboxModel
/**
* Model Skill
*
*/
export type Skill = Prisma.SkillModel
/**
* Model TeamMember
*
*/
export type TeamMember = Prisma.TeamMemberModel
/**
* Model Project
*
*/
export type Project = Prisma.ProjectModel
/**
* Model ProjectMember
*
*/
export type ProjectMember = Prisma.ProjectMemberModel
/**
* Model ShareLink
*
*/
export type ShareLink = Prisma.ShareLinkModel
/**
* Model Asset
*
*/
export type Asset = Prisma.AssetModel
/**
* Model StorageKey
*
*/
export type StorageKey = Prisma.StorageKeyModel
/**
* Model AssetMetadataValue
*
*/
export type AssetMetadataValue = Prisma.AssetMetadataValueModel
/**
* Model AssetComment
*
*/
export type AssetComment = Prisma.AssetCommentModel
/**
* Model AssetCommentAttachment
*
*/
export type AssetCommentAttachment = Prisma.AssetCommentAttachmentModel
/**
* Model AssetEmbedding
*
*/
export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model Invite
*
*/
export type Invite = Prisma.InviteModel
/**
* Model MetadataField
*
*/
export type MetadataField = Prisma.MetadataFieldModel
/**
* Model Notification
*
*/
export type Notification = Prisma.NotificationModel
/**
* Model SystemSettings
*
*/
export type SystemSettings = Prisma.SystemSettingsModel
/**
* Model Task
*
*/
export type Task = Prisma.TaskModel
/**
* Model WorkflowTask
*
*/
export type WorkflowTask = Prisma.WorkflowTaskModel
/**
* Model Agent
*
*/
export type Agent = Prisma.AgentModel
/**
* Model AgentSkill
*
*/
export type AgentSkill = Prisma.AgentSkillModel
/**
* Model AgentSession
*
*/
export type AgentSession = Prisma.AgentSessionModel
/**
* Model AgentSessionEntry
*
*/
export type AgentSessionEntry = Prisma.AgentSessionEntryModel
/**
* Model UserMetadata
*
*/
export type UserMetadata = Prisma.UserMetadataModel
/**
* Model Model
*
*/
export type Model = Prisma.ModelModel
/**
* Model Provider
*
*/
export type Provider = Prisma.ProviderModel
/**
* Model Collection
*
*/
export type Collection = Prisma.CollectionModel
+206
View File
@@ -0,0 +1,206 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file should be your main import to use Prisma. Through it you get access to all the models, enums, and input types.
* If you're looking for something you can import in the client-side of your application, please refer to the `browser.ts` file instead.
*
* 🟢 You can import this file directly.
*/
import * as process from 'node:process'
import * as path from 'node:path'
import { fileURLToPath } from 'node:url'
globalThis['__dirname'] = path.dirname(fileURLToPath(import.meta.url))
import * as runtime from '@prisma/client/runtime/client'
import * as $Enums from './enums.ts'
import * as $Class from './internal/class.ts'
import * as Prisma from './internal/prismaNamespace.ts'
export * as $Enums from './enums.ts'
export * from './enums.ts'
/**
* ## Prisma Client
*
* Type-safe database client for TypeScript
* @example
* ```
* const prisma = new PrismaClient({
* adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL })
* })
* // Fetch zero or more Users
* const users = await prisma.user.findMany()
* ```
*
* Read more in our [docs](https://pris.ly/d/client).
*/
export const PrismaClient = $Class.getPrismaClientClass()
export type PrismaClient<
LogOpts extends Prisma.LogLevel = never,
OmitOpts extends Prisma.PrismaClientOptions['omit'] = Prisma.PrismaClientOptions['omit'],
ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs,
> = $Class.PrismaClient<LogOpts, OmitOpts, ExtArgs>
export { Prisma }
/**
* Model User
*
*/
export type User = Prisma.UserModel
/**
* Model Session
*
*/
export type Session = Prisma.SessionModel
/**
* Model Account
*
*/
export type Account = Prisma.AccountModel
/**
* Model Verification
*
*/
export type Verification = Prisma.VerificationModel
/**
* Model AuthToken
*
*/
export type AuthToken = Prisma.AuthTokenModel
/**
* Model Team
*
*/
export type Team = Prisma.TeamModel
/**
* Model Sandbox
*
*/
export type Sandbox = Prisma.SandboxModel
/**
* Model Skill
*
*/
export type Skill = Prisma.SkillModel
/**
* Model TeamMember
*
*/
export type TeamMember = Prisma.TeamMemberModel
/**
* Model Project
*
*/
export type Project = Prisma.ProjectModel
/**
* Model ProjectMember
*
*/
export type ProjectMember = Prisma.ProjectMemberModel
/**
* Model ShareLink
*
*/
export type ShareLink = Prisma.ShareLinkModel
/**
* Model Asset
*
*/
export type Asset = Prisma.AssetModel
/**
* Model StorageKey
*
*/
export type StorageKey = Prisma.StorageKeyModel
/**
* Model AssetMetadataValue
*
*/
export type AssetMetadataValue = Prisma.AssetMetadataValueModel
/**
* Model AssetComment
*
*/
export type AssetComment = Prisma.AssetCommentModel
/**
* Model AssetCommentAttachment
*
*/
export type AssetCommentAttachment = Prisma.AssetCommentAttachmentModel
/**
* Model AssetEmbedding
*
*/
export type AssetEmbedding = Prisma.AssetEmbeddingModel
/**
* Model Invite
*
*/
export type Invite = Prisma.InviteModel
/**
* Model MetadataField
*
*/
export type MetadataField = Prisma.MetadataFieldModel
/**
* Model Notification
*
*/
export type Notification = Prisma.NotificationModel
/**
* Model SystemSettings
*
*/
export type SystemSettings = Prisma.SystemSettingsModel
/**
* Model Task
*
*/
export type Task = Prisma.TaskModel
/**
* Model WorkflowTask
*
*/
export type WorkflowTask = Prisma.WorkflowTaskModel
/**
* Model Agent
*
*/
export type Agent = Prisma.AgentModel
/**
* Model AgentSkill
*
*/
export type AgentSkill = Prisma.AgentSkillModel
/**
* Model AgentSession
*
*/
export type AgentSession = Prisma.AgentSessionModel
/**
* Model AgentSessionEntry
*
*/
export type AgentSessionEntry = Prisma.AgentSessionEntryModel
/**
* Model UserMetadata
*
*/
export type UserMetadata = Prisma.UserMetadataModel
/**
* Model Model
*
*/
export type Model = Prisma.ModelModel
/**
* Model Provider
*
*/
export type Provider = Prisma.ProviderModel
/**
* Model Collection
*
*/
export type Collection = Prisma.CollectionModel
File diff suppressed because it is too large Load Diff
+140
View File
@@ -0,0 +1,140 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This file exports all enum related types from the schema.
*
* 🟢 You can import this file directly.
*/
export const UserType = {
human: 'human',
agent: 'agent',
} as const
export type UserType = (typeof UserType)[keyof typeof UserType]
export const AssetType = {
folder: 'folder',
file: 'file',
share: 'share',
root: 'root',
attachment: 'attachment',
version_stack: 'version_stack',
share_root: 'share_root',
symlink: 'symlink',
} as const
export type AssetType = (typeof AssetType)[keyof typeof AssetType]
export const AssetStatus = {
uploading: 'uploading',
uploaded: 'uploaded',
processing: 'processing',
processed: 'processed',
trashed: 'trashed',
pending_purge: 'pending_purge',
} as const
export type AssetStatus = (typeof AssetStatus)[keyof typeof AssetStatus]
export const StorageKeyStatus = {
active: 'active',
purging: 'purging',
} as const
export type StorageKeyStatus = (typeof StorageKeyStatus)[keyof typeof StorageKeyStatus]
export const InviteRole = {
editor: 'editor',
reviewer: 'reviewer',
} as const
export type InviteRole = (typeof InviteRole)[keyof typeof InviteRole]
export const MetadataFieldScope = {
SYSTEM: 'SYSTEM',
TEAM: 'TEAM',
PROJECT: 'PROJECT',
} as const
export type MetadataFieldScope = (typeof MetadataFieldScope)[keyof typeof MetadataFieldScope]
export const NotificationType = {
comment_created: 'comment_created',
reply_created: 'reply_created',
mention: 'mention',
successful_file_uploaded: 'successful_file_uploaded',
metadata_field_updated_status: 'metadata_field_updated_status',
new_user_join_team: 'new_user_join_team',
new_user_join_project: 'new_user_join_project',
} as const
export type NotificationType = (typeof NotificationType)[keyof typeof NotificationType]
export const ProjectMemberRole = {
owner: 'owner',
editor: 'editor',
reviewer: 'reviewer',
} as const
export type ProjectMemberRole = (typeof ProjectMemberRole)[keyof typeof ProjectMemberRole]
export const TaskType = {
upload: 'upload',
} as const
export type TaskType = (typeof TaskType)[keyof typeof TaskType]
export const TaskStatus = {
pending: 'pending',
uploading: 'uploading',
completed: 'completed',
failed: 'failed',
} as const
export type TaskStatus = (typeof TaskStatus)[keyof typeof TaskStatus]
export const TeamMemberRole = {
owner: 'owner',
editor: 'editor',
reviewer: 'reviewer',
} as const
export type TeamMemberRole = (typeof TeamMemberRole)[keyof typeof TeamMemberRole]
export const TeamMemberScope = {
team: 'team',
project: 'project',
} as const
export type TeamMemberScope = (typeof TeamMemberScope)[keyof typeof TeamMemberScope]
export const WorkflowTaskType = {
transcode: 'transcode',
ai_metadata_autofill: 'ai_metadata_autofill',
chat: 'chat',
ai_embedding: 'ai_embedding',
query_embedding_for_search: 'query_embedding_for_search',
agent_tool_call: 'agent_tool_call',
} as const
export type WorkflowTaskType = (typeof WorkflowTaskType)[keyof typeof WorkflowTaskType]
export const WorkflowTaskStatus = {
pending: 'pending',
processing: 'processing',
completed: 'completed',
failed: 'failed',
} as const
export type WorkflowTaskStatus = (typeof WorkflowTaskStatus)[keyof typeof WorkflowTaskStatus]
export const AgentType = {
chat: 'chat',
autofill: 'autofill',
embedding: 'embedding',
} as const
export type AgentType = (typeof AgentType)[keyof typeof AgentType]
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,586 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* WARNING: This is an internal file that is subject to change!
*
* 🛑 Under no circumstances should you import this file directly! 🛑
*
* All exports from this file are wrapped under a `Prisma` namespace object in the browser.ts file.
* While this enables partial backward compatibility, it is not part of the stable public API.
*
* If you are looking for your Models, Enums, and Input Types, please import them from the respective
* model files in the `model` directory!
*/
import * as runtime from '@prisma/client/runtime/index-browser'
export type * from '../models.ts'
export type * from './prismaNamespace.ts'
export const Decimal = runtime.Decimal
export const NullTypes = {
DbNull: runtime.NullTypes.DbNull as new (secret: never) => typeof runtime.DbNull,
JsonNull: runtime.NullTypes.JsonNull as new (secret: never) => typeof runtime.JsonNull,
AnyNull: runtime.NullTypes.AnyNull as new (secret: never) => typeof runtime.AnyNull,
}
/**
* Helper for filtering JSON entries that have `null` on the database (empty on the db)
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const DbNull = runtime.DbNull
/**
* Helper for filtering JSON entries that have JSON `null` values (not empty on the db)
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const JsonNull = runtime.JsonNull
/**
* Helper for filtering JSON entries that are `Prisma.DbNull` or `Prisma.JsonNull`
*
* @see https://www.prisma.io/docs/concepts/components/prisma-client/working-with-fields/working-with-json-fields#filtering-on-a-json-field
*/
export const AnyNull = runtime.AnyNull
export const ModelName = {
User: 'User',
Session: 'Session',
Account: 'Account',
Verification: 'Verification',
AuthToken: 'AuthToken',
Team: 'Team',
Sandbox: 'Sandbox',
Skill: 'Skill',
TeamMember: 'TeamMember',
Project: 'Project',
ProjectMember: 'ProjectMember',
ShareLink: 'ShareLink',
Asset: 'Asset',
StorageKey: 'StorageKey',
AssetMetadataValue: 'AssetMetadataValue',
AssetComment: 'AssetComment',
AssetCommentAttachment: 'AssetCommentAttachment',
AssetEmbedding: 'AssetEmbedding',
Invite: 'Invite',
MetadataField: 'MetadataField',
Notification: 'Notification',
SystemSettings: 'SystemSettings',
Task: 'Task',
WorkflowTask: 'WorkflowTask',
Agent: 'Agent',
AgentSkill: 'AgentSkill',
AgentSession: 'AgentSession',
AgentSessionEntry: 'AgentSessionEntry',
UserMetadata: 'UserMetadata',
Model: 'Model',
Provider: 'Provider',
Collection: 'Collection',
} as const
export type ModelName = (typeof ModelName)[keyof typeof ModelName]
/*
* Enums
*/
export const TransactionIsolationLevel = runtime.makeStrictEnum({
ReadUncommitted: 'ReadUncommitted',
ReadCommitted: 'ReadCommitted',
RepeatableRead: 'RepeatableRead',
Serializable: 'Serializable',
} as const)
export type TransactionIsolationLevel =
(typeof TransactionIsolationLevel)[keyof typeof TransactionIsolationLevel]
export const UserScalarFieldEnum = {
id: 'id',
type: 'type',
name: 'name',
email: 'email',
emailVerified: 'emailVerified',
image: 'image',
password: 'password',
agentSettings: 'agentSettings',
guestEmail: 'guestEmail',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type UserScalarFieldEnum = (typeof UserScalarFieldEnum)[keyof typeof UserScalarFieldEnum]
export const SessionScalarFieldEnum = {
id: 'id',
expiresAt: 'expiresAt',
token: 'token',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
ipAddress: 'ipAddress',
userAgent: 'userAgent',
userId: 'userId',
} as const
export type SessionScalarFieldEnum =
(typeof SessionScalarFieldEnum)[keyof typeof SessionScalarFieldEnum]
export const AccountScalarFieldEnum = {
id: 'id',
accountId: 'accountId',
providerId: 'providerId',
userId: 'userId',
accessToken: 'accessToken',
refreshToken: 'refreshToken',
idToken: 'idToken',
accessTokenExpiresAt: 'accessTokenExpiresAt',
refreshTokenExpiresAt: 'refreshTokenExpiresAt',
scope: 'scope',
password: 'password',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type AccountScalarFieldEnum =
(typeof AccountScalarFieldEnum)[keyof typeof AccountScalarFieldEnum]
export const VerificationScalarFieldEnum = {
id: 'id',
identifier: 'identifier',
value: 'value',
expiresAt: 'expiresAt',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type VerificationScalarFieldEnum =
(typeof VerificationScalarFieldEnum)[keyof typeof VerificationScalarFieldEnum]
export const AuthTokenScalarFieldEnum = {
id: 'id',
accessToken: 'accessToken',
refreshToken: 'refreshToken',
accessTokenExpiresAt: 'accessTokenExpiresAt',
refreshTokenExpiresAt: 'refreshTokenExpiresAt',
userId: 'userId',
} as const
export type AuthTokenScalarFieldEnum =
(typeof AuthTokenScalarFieldEnum)[keyof typeof AuthTokenScalarFieldEnum]
export const TeamScalarFieldEnum = {
id: 'id',
name: 'name',
settings: 'settings',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
rootFolderId: 'rootFolderId',
} as const
export type TeamScalarFieldEnum = (typeof TeamScalarFieldEnum)[keyof typeof TeamScalarFieldEnum]
export const SandboxScalarFieldEnum = {
id: 'id',
allowedDomains: 'allowedDomains',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
} as const
export type SandboxScalarFieldEnum =
(typeof SandboxScalarFieldEnum)[keyof typeof SandboxScalarFieldEnum]
export const SkillScalarFieldEnum = {
id: 'id',
name: 'name',
description: 'description',
config: 'config',
assetId: 'assetId',
hash: 'hash',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
} as const
export type SkillScalarFieldEnum = (typeof SkillScalarFieldEnum)[keyof typeof SkillScalarFieldEnum]
export const TeamMemberScalarFieldEnum = {
id: 'id',
role: 'role',
scope: 'scope',
teamId: 'teamId',
userId: 'userId',
lastReadNotificationId: 'lastReadNotificationId',
} as const
export type TeamMemberScalarFieldEnum =
(typeof TeamMemberScalarFieldEnum)[keyof typeof TeamMemberScalarFieldEnum]
export const ProjectScalarFieldEnum = {
id: 'id',
name: 'name',
coverImageKey: 'coverImageKey',
metadataOverrides: 'metadataOverrides',
enableNotification: 'enableNotification',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
rootFolderId: 'rootFolderId',
shareRootId: 'shareRootId',
} as const
export type ProjectScalarFieldEnum =
(typeof ProjectScalarFieldEnum)[keyof typeof ProjectScalarFieldEnum]
export const ProjectMemberScalarFieldEnum = {
id: 'id',
role: 'role',
projectId: 'projectId',
teamMemberId: 'teamMemberId',
} as const
export type ProjectMemberScalarFieldEnum =
(typeof ProjectMemberScalarFieldEnum)[keyof typeof ProjectMemberScalarFieldEnum]
export const ShareLinkScalarFieldEnum = {
id: 'id',
name: 'name',
expireAt: 'expireAt',
password: 'password',
isDisabled: 'isDisabled',
defaultSortOrder: 'defaultSortOrder',
fieldVisibility: 'fieldVisibility',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
projectId: 'projectId',
rootFolderId: 'rootFolderId',
} as const
export type ShareLinkScalarFieldEnum =
(typeof ShareLinkScalarFieldEnum)[keyof typeof ShareLinkScalarFieldEnum]
export const AssetScalarFieldEnum = {
id: 'id',
name: 'name',
nameNgram: 'nameNgram',
type: 'type',
mediaType: 'mediaType',
fileCount: 'fileCount',
sizeByte: 'sizeByte',
status: 'status',
transcodeTaskId: 'transcodeTaskId',
media: 'media',
isDeleted: 'isDeleted',
deletedAt: 'deletedAt',
sortIndex: 'sortIndex',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
parentId: 'parentId',
targetId: 'targetId',
storageKeyId: 'storageKeyId',
creatorId: 'creatorId',
taskId: 'taskId',
projectId: 'projectId',
} as const
export type AssetScalarFieldEnum = (typeof AssetScalarFieldEnum)[keyof typeof AssetScalarFieldEnum]
export const StorageKeyScalarFieldEnum = {
id: 'id',
key: 'key',
status: 'status',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type StorageKeyScalarFieldEnum =
(typeof StorageKeyScalarFieldEnum)[keyof typeof StorageKeyScalarFieldEnum]
export const AssetMetadataValueScalarFieldEnum = {
id: 'id',
assetId: 'assetId',
fieldKey: 'fieldKey',
stringValue: 'stringValue',
numberValue: 'numberValue',
booleanValue: 'booleanValue',
jsonValue: 'jsonValue',
dateValue: 'dateValue',
} as const
export type AssetMetadataValueScalarFieldEnum =
(typeof AssetMetadataValueScalarFieldEnum)[keyof typeof AssetMetadataValueScalarFieldEnum]
export const AssetCommentScalarFieldEnum = {
id: 'id',
message: 'message',
annotation: 'annotation',
second: 'second',
sessionId: 'sessionId',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
assetId: 'assetId',
creatorId: 'creatorId',
replyToId: 'replyToId',
} as const
export type AssetCommentScalarFieldEnum =
(typeof AssetCommentScalarFieldEnum)[keyof typeof AssetCommentScalarFieldEnum]
export const AssetCommentAttachmentScalarFieldEnum = {
id: 'id',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
commentId: 'commentId',
assetId: 'assetId',
} as const
export type AssetCommentAttachmentScalarFieldEnum =
(typeof AssetCommentAttachmentScalarFieldEnum)[keyof typeof AssetCommentAttachmentScalarFieldEnum]
export const AssetEmbeddingScalarFieldEnum = {
id: 'id',
startTime: 'startTime',
endTime: 'endTime',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
assetId: 'assetId',
} as const
export type AssetEmbeddingScalarFieldEnum =
(typeof AssetEmbeddingScalarFieldEnum)[keyof typeof AssetEmbeddingScalarFieldEnum]
export const InviteScalarFieldEnum = {
id: 'id',
code: 'code',
role: 'role',
used: 'used',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
projectId: 'projectId',
inviterId: 'inviterId',
} as const
export type InviteScalarFieldEnum =
(typeof InviteScalarFieldEnum)[keyof typeof InviteScalarFieldEnum]
export const MetadataFieldScalarFieldEnum = {
id: 'id',
key: 'key',
scope: 'scope',
config: 'config',
readOnly: 'readOnly',
aiAutofill: 'aiAutofill',
description: 'description',
teamId: 'teamId',
projectId: 'projectId',
} as const
export type MetadataFieldScalarFieldEnum =
(typeof MetadataFieldScalarFieldEnum)[keyof typeof MetadataFieldScalarFieldEnum]
export const NotificationScalarFieldEnum = {
id: 'id',
type: 'type',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
projectId: 'projectId',
creatorId: 'creatorId',
assetId: 'assetId',
taskId: 'taskId',
userId: 'userId',
} as const
export type NotificationScalarFieldEnum =
(typeof NotificationScalarFieldEnum)[keyof typeof NotificationScalarFieldEnum]
export const SystemSettingsScalarFieldEnum = {
id: 'id',
key: 'key',
value: 'value',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type SystemSettingsScalarFieldEnum =
(typeof SystemSettingsScalarFieldEnum)[keyof typeof SystemSettingsScalarFieldEnum]
export const TaskScalarFieldEnum = {
id: 'id',
type: 'type',
status: 'status',
name: 'name',
total: 'total',
uploaded: 'uploaded',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
creatorId: 'creatorId',
} as const
export type TaskScalarFieldEnum = (typeof TaskScalarFieldEnum)[keyof typeof TaskScalarFieldEnum]
export const WorkflowTaskScalarFieldEnum = {
id: 'id',
uid: 'uid',
teamId: 'teamId',
projectId: 'projectId',
assetId: 'assetId',
type: 'type',
status: 'status',
payload: 'payload',
output: 'output',
heartbeat: 'heartbeat',
inputTokens: 'inputTokens',
outputTokens: 'outputTokens',
model: 'model',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type WorkflowTaskScalarFieldEnum =
(typeof WorkflowTaskScalarFieldEnum)[keyof typeof WorkflowTaskScalarFieldEnum]
export const AgentScalarFieldEnum = {
id: 'id',
type: 'type',
enabled: 'enabled',
soul: 'soul',
providerId: 'providerId',
modelId: 'modelId',
teamId: 'teamId',
config: 'config',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type AgentScalarFieldEnum = (typeof AgentScalarFieldEnum)[keyof typeof AgentScalarFieldEnum]
export const AgentSkillScalarFieldEnum = {
id: 'id',
agentId: 'agentId',
skillId: 'skillId',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type AgentSkillScalarFieldEnum =
(typeof AgentSkillScalarFieldEnum)[keyof typeof AgentSkillScalarFieldEnum]
export const AgentSessionScalarFieldEnum = {
id: 'id',
agentId: 'agentId',
userId: 'userId',
cwd: 'cwd',
leafId: 'leafId',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
} as const
export type AgentSessionScalarFieldEnum =
(typeof AgentSessionScalarFieldEnum)[keyof typeof AgentSessionScalarFieldEnum]
export const AgentSessionEntryScalarFieldEnum = {
id: 'id',
sessionId: 'sessionId',
entry: 'entry',
} as const
export type AgentSessionEntryScalarFieldEnum =
(typeof AgentSessionEntryScalarFieldEnum)[keyof typeof AgentSessionEntryScalarFieldEnum]
export const UserMetadataScalarFieldEnum = {
id: 'id',
key: 'key',
value: 'value',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
userId: 'userId',
teamId: 'teamId',
} as const
export type UserMetadataScalarFieldEnum =
(typeof UserMetadataScalarFieldEnum)[keyof typeof UserMetadataScalarFieldEnum]
export const ModelScalarFieldEnum = {
id: 'id',
modelId: 'modelId',
name: 'name',
config: 'config',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
providerId: 'providerId',
} as const
export type ModelScalarFieldEnum = (typeof ModelScalarFieldEnum)[keyof typeof ModelScalarFieldEnum]
export const ProviderScalarFieldEnum = {
id: 'id',
name: 'name',
isBuiltin: 'isBuiltin',
config: 'config',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
teamId: 'teamId',
} as const
export type ProviderScalarFieldEnum =
(typeof ProviderScalarFieldEnum)[keyof typeof ProviderScalarFieldEnum]
export const CollectionScalarFieldEnum = {
id: 'id',
name: 'name',
filter: 'filter',
createdAt: 'createdAt',
updatedAt: 'updatedAt',
projectId: 'projectId',
} as const
export type CollectionScalarFieldEnum =
(typeof CollectionScalarFieldEnum)[keyof typeof CollectionScalarFieldEnum]
export const SortOrder = {
asc: 'asc',
desc: 'desc',
} as const
export type SortOrder = (typeof SortOrder)[keyof typeof SortOrder]
export const NullableJsonNullValueInput = {
DbNull: DbNull,
JsonNull: JsonNull,
} as const
export type NullableJsonNullValueInput =
(typeof NullableJsonNullValueInput)[keyof typeof NullableJsonNullValueInput]
export const JsonNullValueInput = {
JsonNull: JsonNull,
} as const
export type JsonNullValueInput = (typeof JsonNullValueInput)[keyof typeof JsonNullValueInput]
export const QueryMode = {
default: 'default',
insensitive: 'insensitive',
} as const
export type QueryMode = (typeof QueryMode)[keyof typeof QueryMode]
export const JsonNullValueFilter = {
DbNull: DbNull,
JsonNull: JsonNull,
AnyNull: AnyNull,
} as const
export type JsonNullValueFilter = (typeof JsonNullValueFilter)[keyof typeof JsonNullValueFilter]
export const NullsOrder = {
first: 'first',
last: 'last',
} as const
export type NullsOrder = (typeof NullsOrder)[keyof typeof NullsOrder]
@@ -0,0 +1,42 @@
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
/* eslint-disable */
// biome-ignore-all lint: generated file
// @ts-nocheck
/*
* This is a barrel export file for all models and their related types.
*
* 🟢 You can import this file directly.
*/
export type * from './models/User.ts'
export type * from './models/Session.ts'
export type * from './models/Account.ts'
export type * from './models/Verification.ts'
export type * from './models/AuthToken.ts'
export type * from './models/Team.ts'
export type * from './models/Sandbox.ts'
export type * from './models/Skill.ts'
export type * from './models/TeamMember.ts'
export type * from './models/Project.ts'
export type * from './models/ProjectMember.ts'
export type * from './models/ShareLink.ts'
export type * from './models/Asset.ts'
export type * from './models/StorageKey.ts'
export type * from './models/AssetMetadataValue.ts'
export type * from './models/AssetComment.ts'
export type * from './models/AssetCommentAttachment.ts'
export type * from './models/AssetEmbedding.ts'
export type * from './models/Invite.ts'
export type * from './models/MetadataField.ts'
export type * from './models/Notification.ts'
export type * from './models/SystemSettings.ts'
export type * from './models/Task.ts'
export type * from './models/WorkflowTask.ts'
export type * from './models/Agent.ts'
export type * from './models/AgentSkill.ts'
export type * from './models/AgentSession.ts'
export type * from './models/AgentSessionEntry.ts'
export type * from './models/UserMetadata.ts'
export type * from './models/Model.ts'
export type * from './models/Provider.ts'
export type * from './models/Collection.ts'
export type * from './commonInputTypes.ts'
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+183
View File
@@ -0,0 +1,183 @@
import * as Prisma from './internal/prismaNamespace'
declare global {
namespace PrismaJson {
// This namespace will always be empty. Definitions should be done by
// you manually, and merged automatically by typescript. Make sure that
// your declaration merging file is included in your tsconfig.json
//
// Learn more: https://github.com/arthurfiorette/prisma-json-types-generator/issues/143
// Declaration Merging: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
}
}
/** A filter to be used against nullable List types. */
export type NullableListFilter<T> = {
equals?: T | T[] | null
has?: T | null
hasEvery?: T[]
hasSome?: T[]
isEmpty?: boolean
}
/** A type to determine how to update a json field */
export type UpdateInput<T> = T extends object ? { [P in keyof T]?: UpdateInput<T[P]> } : T
/** A type to determine how to update a json[] field */
export type UpdateManyInput<T> = T | T[] | { set?: T[]; push?: T | T[] }
/** A type to determine how to create a json[] input */
export type CreateManyInput<T> = T | T[] | { set?: T[] }
/**
* A typed version of NestedStringFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedNestedStringFilter<S extends string> =
//@ts-ignore - When Prisma.StringFilter is not present, this type is not used
Prisma.StringFilter & {
equals?: S
in?: S[]
notIn?: S[]
not?: TypedNestedStringFilter<S> | S
}
/**
* A typed version of StringFilter, allowing narrowing of string types to discriminated
* unions.
*/
export type TypedStringFilter<S extends string> =
//@ts-ignore - When Prisma.StringFilter is not present, this type is not used
Prisma.StringFilter & {
equals?: S
in?: S[]
notIn?: S[]
not?: TypedNestedStringFilter<S> | S
}
/**
* A typed version of NestedStringNullableFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedNestedStringNullableFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableFilter is not present, this type is not used
Prisma.StringNullableFilter & {
equals?: S | null
in?: S[] | null
notIn?: S[] | null
not?: TypedNestedStringNullableFilter<S> | S | null
}
/**
* A typed version of StringNullableFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedStringNullableFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableFilter is not present, this type is not used
Prisma.StringNullableFilter & {
equals?: S | null
in?: S[] | null
notIn?: S[] | null
not?: TypedNestedStringNullableFilter<S> | S | null
}
/**
* A typed version of NestedStringWithAggregatesFilter, allowing narrowing of string types
* to discriminated unions.
*/
export type TypedNestedStringWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.NestedStringWithAggregatesFilter is not present, this type is not used
Prisma.NestedStringWithAggregatesFilter & {
equals?: S
in?: S[]
notIn?: S[]
not?: TypedNestedStringWithAggregatesFilter<S> | S
}
/**
* A typed version of StringWithAggregatesFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedStringWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.StringWithAggregatesFilter is not present, this type is not used
Prisma.StringWithAggregatesFilter & {
equals?: S
in?: S[]
notIn?: S[]
not?: TypedNestedStringWithAggregatesFilter<S> | S
}
/**
* A typed version of NestedStringNullableWithAggregatesFilter, allowing narrowing of
* string types to discriminated unions.
*/
export type TypedNestedStringNullableWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.NestedStringNullableWithAggregatesFilter is not present, this type is not used
Prisma.NestedStringNullableWithAggregatesFilter & {
equals?: S | null
in?: S[] | null
notIn?: S[] | null
not?: TypedNestedStringNullableWithAggregatesFilter<S> | S | null
}
/**
* A typed version of StringNullableWithAggregatesFilter, allowing narrowing of string
* types to discriminated unions.
*/
export type TypedStringNullableWithAggregatesFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableWithAggregatesFilter is not present, this type is not used
Prisma.StringNullableWithAggregatesFilter & {
equals?: S | null
in?: S[] | null
notIn?: S[] | null
not?: TypedNestedStringNullableWithAggregatesFilter<S> | S | null
}
/**
* A typed version of StringFieldUpdateOperationsInput, allowing narrowing of string types
* to discriminated unions.
*/
export type TypedStringFieldUpdateOperationsInput<S extends string> =
//@ts-ignore - When Prisma.StringFieldUpdateOperationsInput is not present, this type is not used
Prisma.StringFieldUpdateOperationsInput & {
set?: S
}
/**
* A typed version of NullableStringFieldUpdateOperationsInput, allowing narrowing of
* string types to discriminated unions.
*/
export type TypedNullableStringFieldUpdateOperationsInput<S extends string> =
//@ts-ignore - When Prisma.NullableStringFieldUpdateOperationsInput is not present, this type is not used
Prisma.NullableStringFieldUpdateOperationsInput & {
set?: S | null
}
/**
* A typed version of StringNullableListFilter, allowing narrowing of string types to
* discriminated unions.
*/
export type TypedStringNullableListFilter<S extends string> =
//@ts-ignore - When Prisma.StringNullableListFilter is not present, this type is not used
Prisma.StringNullableListFilter & {
equals?: S[] | null
has?: S | null
hasEvery?: S[]
hasSome?: S[]
}
/**
* A typed version of the input type to update a string[] field, allowing narrowing of
* string types to discriminated unions.
*/
export type UpdateStringArrayInput<S extends string> = {
set?: S[]
push?: S | S[]
}
/**
* A typed version of the input type to create a string[] field, allowing narrowing of
* string types to discriminated unions.
*/
export type CreateStringArrayInput<S extends string> = {
set?: S[]
}
+20 -13
View File
@@ -1,8 +1,16 @@
import { PrismaClient } from '@/generated/prisma/client'
import { PrismaTestingHelper } from '@/test-utils'
import { PrismaClient, WorkflowTask } from './generated/prisma/client'
import { PrismaTestingHelper } from './prisma-testing-helper'
import { PrismaPg } from '@prisma/adapter-pg'
import { Pool } from 'pg'
import { generateNgrams } from '@/utils/ngram'
import { generateNgrams } from './utils/ngram'
// Global callback for workflow task creation (decouples db package from workflow engine)
type WorkflowTriggerCallback = (task: WorkflowTask) => Promise<void>
let onWorkflowTaskCreated: WorkflowTriggerCallback | null = null
export function registerWorkflowTrigger(cb: WorkflowTriggerCallback) {
onWorkflowTaskCreated = cb
}
const isTest = process.env.NODE_ENV === 'test'
@@ -10,7 +18,6 @@ const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
// We use any here because PrismaTestingHelper is generic and the extended client type is complex
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let prismaTestingHelper: PrismaTestingHelper<any> | null = null
@@ -24,16 +31,9 @@ function createPrismaClient() {
workflowTask: {
async create({ args, query }) {
const result = await query(args)
// Lazy load workflowService to avoid circular dependency
import('@/workflow/workflow').then((mod) => {
const service = mod?.workflowService
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const task = result as any
if (service && task.status === 'pending') {
// result is the created task, but the extension types are complex
service.submit(task).catch(console.error)
if (onWorkflowTaskCreated && (result as WorkflowTask).status === 'pending') {
onWorkflowTaskCreated(result as WorkflowTask).catch(console.error)
}
})
return result
},
},
@@ -94,3 +94,10 @@ export function getPrismaTestingHelper() {
}
return prismaTestingHelper
}
export * from './utils/ngram'
export * from './db-test-hooks'
export * from './prisma-testing-helper'
export * from './generated/prisma/models'
export * from './generated/prisma/enums'
export { PrismaClient } from './generated/prisma/client'
@@ -51,7 +51,7 @@ declare global {
// ----------------------------------------------------------------------
// Collection Filter
// ----------------------------------------------------------------------
export type CollectionFilter = import('./dtos/collection').CollectionFilter
export type CollectionFilter = import('@shumai/dtos').CollectionFilter
export interface TranscodeSettings {
videoStrategy: VideoTranscodeStrategy
@@ -231,9 +231,9 @@ declare global {
// Provider Config
// ----------------------------------------------------------------------
export type ModelConfig = import('zod').z.infer<
typeof import('@/dtos/provider').providerModelConfigSchema
typeof import('@shumai/dtos').providerModelConfigSchema
>
export type ProviderConfig = import('@/dtos/provider').ProviderConfigSerializable
export type ProviderConfig = import('@shumai/dtos').ProviderConfigSerializable
// ----------------------------------------------------------------------
// Workflow Task Payload
@@ -284,13 +284,7 @@ declare global {
// ----------------------------------------------------------------------
// Skill Config
// ----------------------------------------------------------------------
export interface SkillEnvironmentVariable {
name: string
default?: string
}
export interface SkillConfig {
environmentVariables: SkillEnvironmentVariable[]
}
export type SkillEnvironmentVariable = import('@shumai/dtos').SkillEnvironmentVariable
export type SkillConfig = import('@shumai/dtos').SkillConfig
}
}
+255
View File
@@ -0,0 +1,255 @@
import { AsyncLocalStorage } from 'node:async_hooks'
import { Prisma } from './generated/prisma/client'
type PromiseResolveFunction = (value: void | PromiseLike<void>) => void
const internalRollbackErrorSymbol = Symbol(
'Internal transactional-prisma-testing rollback error symbol',
)
const MAX_ACTIVE_SAVEPOINTS = 56
export class PrismaTestingHelper<
T extends {
$transaction(arg: unknown[], options?: unknown): Promise<unknown>
$transaction<TR>(fn: (client: unknown) => Promise<TR>, options?: unknown): Promise<TR>
},
> {
private readonly proxyClient: T
private currentPrismaTransactionClient?: Prisma.TransactionClient
private endCurrentTransactionPromise?: (value?: unknown) => void
private savepointId = 0
private transactionLock: Promise<void> | null = null
private readonly asyncLocalStorage = new AsyncLocalStorage<{
transactionSavepoint: string
}>()
constructor(private readonly prismaClient: T) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const prismaTestingHelper = this
this.proxyClient = new Proxy(prismaClient, {
get(target, prop, receiver) {
if (prismaTestingHelper.currentPrismaTransactionClient == null) {
return Reflect.get(target, prop, receiver)
}
const descriptor = Object.getOwnPropertyDescriptor(target, prop)
if (descriptor && !descriptor.configurable && !descriptor.writable) {
return Reflect.get(target, prop, receiver)
}
if (prop === '$transaction') {
return prismaTestingHelper.transactionProxyFunction.bind(prismaTestingHelper)
}
// accessing arbitrary properties on transaction client requires any cast
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((prismaTestingHelper.currentPrismaTransactionClient as any)[prop] != null) {
const ret = Reflect.get(
prismaTestingHelper.currentPrismaTransactionClient,
prop,
receiver,
)
if (
typeof ret === 'object' &&
ret !== null &&
'findFirst' in ret &&
typeof ret.findFirst === 'function'
) {
return prismaTestingHelper.getPrismaDelegateProxy(ret)
}
return ret
}
return Reflect.get(target, prop, receiver)
},
})
}
private getPrismaDelegateProxy<TU extends object>(original: TU): TU {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const prismaTestingHelper = this
const prismaDelegateProxy = new Proxy(original, {
get(_, prop, receiver) {
const originalReturnValue = Reflect.get(original, prop, receiver)
if (typeof originalReturnValue !== 'function') {
return originalReturnValue
}
const originalFunction = originalReturnValue as (...args: unknown[]) => Promise<unknown>
return (...args: unknown[]) => {
const catchCallbacks: Array<(reason: unknown) => unknown> = []
const finallyCallbacks: Array<() => unknown> = []
const returnedPromise = {
// reject must be any per Promise signature
// eslint-disable-next-line @typescript-eslint/no-explicit-any
then: async (resolve: PromiseResolveFunction, reject: any) => {
try {
const isInTransaction =
prismaTestingHelper.asyncLocalStorage.getStore()?.transactionSavepoint != null
if (!isInTransaction) {
const value = await prismaTestingHelper.wrapInSavepoint(() =>
originalFunction.apply(prismaDelegateProxy, args),
)
// resolve requires any cast to match expected type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return resolve(value as any)
}
const value = await originalFunction.apply(prismaDelegateProxy, args)
// resolve requires any cast to match expected type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return resolve(value as any)
} catch (e) {
try {
let error = e
for (const catchCallback of catchCallbacks) {
error = await catchCallback(error)
}
if (reject) {
reject(error)
} else {
return Promise.reject(error)
}
} catch (innerError) {
if (reject) {
reject(innerError)
} else {
return Promise.reject(innerError)
}
}
} finally {
finallyCallbacks.forEach((c) => c())
}
},
catch: (callback: (reason: unknown) => unknown) => {
catchCallbacks.push(callback)
return returnedPromise
},
finally: (callback: () => unknown) => {
finallyCallbacks.push(callback)
return returnedPromise
},
}
return returnedPromise
}
},
})
return prismaDelegateProxy
}
private async transactionProxyFunction(args: unknown): Promise<unknown> {
return this.wrapInSavepoint(async () => {
if (Array.isArray(args)) {
const ret = []
for (const query of args) {
ret.push(await query)
}
return ret
} else if (typeof args === 'function') {
return args(this.currentPrismaTransactionClient)
} else {
throw new Error(
'[transactional-prisma-testing] Invalid $transaction call. Argument must be an array or a callback function.',
)
}
})
}
private async wrapInSavepoint<T>(func: () => Promise<T>): Promise<T> {
const transactionClient = this.currentPrismaTransactionClient
const isInTransaction = this.asyncLocalStorage.getStore()?.transactionSavepoint != null
let lockResolve = undefined
if (!isInTransaction) {
lockResolve = await this.acquireTransactionLock()
}
try {
if (transactionClient == null) {
throw new Error(
'[transactional-prisma-testing] Invalid call to $transaction while no transaction is active.',
)
}
if (transactionClient !== this.currentPrismaTransactionClient) {
throw new Error(
'[transactional-prisma-testing] Transaction client changed (and old transaction rollbacked) before query could be executed.',
)
}
const savepointIdToRelease = this.savepointId - MAX_ACTIVE_SAVEPOINTS
if (savepointIdToRelease >= 0 && savepointIdToRelease % MAX_ACTIVE_SAVEPOINTS === 0) {
try {
await transactionClient.$executeRawUnsafe(
`RELEASE SAVEPOINT trnsctl_tst_${savepointIdToRelease}`,
)
} catch {
// ignore release errors
}
}
const savepointName = `trnsctl_tst_${this.savepointId++}`
try {
await transactionClient.$executeRawUnsafe(`SAVEPOINT ${savepointName}`)
return await this.asyncLocalStorage.run({ transactionSavepoint: savepointName }, func)
} catch (err) {
await transactionClient?.$executeRawUnsafe(`ROLLBACK TO SAVEPOINT ${savepointName}`)
throw err
}
} finally {
this.transactionLock = null
lockResolve?.()
}
}
private async acquireTransactionLock(): Promise<PromiseResolveFunction> {
while (this.transactionLock != null) {
await this.transactionLock
}
let lockResolve!: PromiseResolveFunction
this.transactionLock = new Promise((resolve) => {
lockResolve = resolve
})
return lockResolve
}
public getProxyClient(): T {
return this.proxyClient
}
public async startNewTransaction(opts?: { timeout?: number; maxWait?: number }): Promise<void> {
if (this.endCurrentTransactionPromise != null) {
throw new Error(
'[transactional-prisma-testing] rollbackCurrentTransaction must be called before starting a new transaction',
)
}
this.savepointId = 0
return new Promise((resolve) => {
this.prismaClient
.$transaction(
async (prisma) => {
this.currentPrismaTransactionClient = prisma as Prisma.TransactionClient | undefined
await new Promise((innerResolve) => {
this.endCurrentTransactionPromise = innerResolve
resolve()
})
throw internalRollbackErrorSymbol
},
{ ...opts, timeout: 30000 },
)
.catch((error) => {
if (error !== internalRollbackErrorSymbol) {
throw error
}
})
})
}
public rollbackCurrentTransaction(): void {
if (this.endCurrentTransactionPromise == null) {
throw new Error('[transactional-prisma-testing] No transaction currently active')
}
this.endCurrentTransactionPromise()
this.endCurrentTransactionPromise = undefined
}
}
+61
View File
@@ -0,0 +1,61 @@
/**
* Generates 1-gram, 2-gram, and 3-gram tokens for a given text.
* Used for optimizing substring searches (especially for CJK characters).
*
* Examples:
* "apple" -> a, p, l, e, ap, pp, pl, le, app, ppl, ple
* "foo-bar" -> f, o, -, b, a, r, fo, oo, o-, -b, ba, ar, foo, oo-, o-b, -ba, bar
*/
export function generateNgrams(text: string): string[] {
if (!text) return []
const normalized = text.toLowerCase()
const tokens = new Set<string>()
const chars = Array.from(normalized) // Unicode-aware character splitting
for (let i = 0; i < chars.length; i++) {
// 1-gram
tokens.add(chars[i])
// 2-gram
if (i + 1 < chars.length) {
tokens.add(chars[i] + chars[i + 1])
}
// 3-gram
if (i + 2 < chars.length) {
tokens.add(chars[i] + chars[i + 1] + chars[i + 2])
}
}
return Array.from(tokens)
}
/**
* Generates only the longest possible n-grams for a search query.
* If the word is 3+ chars, only return 3-grams.
* If 2 chars, return 2-grams.
* If 1 char, return 1-grams.
*
* This significantly improves search performance by reducing GIN index intersection overhead.
*/
export function generateSearchNgrams(text: string): string[] {
if (!text) return []
const normalized = text.toLowerCase()
const tokens = new Set<string>()
const chars = Array.from(normalized)
const len = chars.length
if (len >= 3) {
for (let i = 0; i <= len - 3; i++) {
tokens.add(chars[i] + chars[i + 1] + chars[i + 2])
}
} else if (len === 2) {
tokens.add(chars[0] + chars[1])
} else if (len === 1) {
tokens.add(chars[0])
}
return Array.from(tokens)
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"ignoreDeprecations": "6.0"
},
"include": ["src/**/*"]
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@shumai/dtos",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"dependencies": {
"zod": "^4.4.3"
}
}
@@ -22,11 +22,11 @@ export const childPreviewSchema = z.object({
})
export type ChildPreview = z.infer<typeof childPreviewSchema>
export const userInfoSchema = z.object({
export const assetUserInfoSchema = z.object({
id: z.string(),
name: z.string(),
})
export type UserInfo = z.infer<typeof userInfoSchema>
export type AssetUserInfo = z.infer<typeof assetUserInfoSchema>
export const fieldValueInfoSchema = z.object({
fieldId: z.string(),
@@ -63,7 +63,7 @@ export const assetInfoSchema = z.object({
createdAt: z.string(),
updatedAt: z.string(),
deletedAt: z.string().nullable().optional(),
creator: userInfoSchema.nullable().optional(),
creator: assetUserInfoSchema.nullable().optional(),
fieldValues: z.array(fieldValueInfoSchema).optional(),
sortIndex: z.string().optional().nullable(),
startTime: z.number().optional().nullable(),
@@ -192,10 +192,10 @@ export type CommentInfo = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
annotations: any
second: number | null
creator: UserInfo
creator: AssetUserInfo
replies: CommentInfo[]
attachments: AttachmentInfo[]
mentions: UserInfo[]
mentions: AssetUserInfo[]
createdAt: string
updatedAt: string
sessionId: string | null
@@ -208,10 +208,10 @@ export const commentInfoSchema: z.ZodType<CommentInfo> = z.object({
annotations: z.any(),
second: z.number().nullable(),
creator: userInfoSchema,
creator: assetUserInfoSchema,
replies: z.array(z.lazy(() => commentInfoSchema)),
attachments: z.array(attachmentInfoSchema),
mentions: z.array(userInfoSchema),
mentions: z.array(assetUserInfoSchema),
createdAt: z.string(),
updatedAt: z.string(),
sessionId: z.string().nullable(),
+20
View File
@@ -0,0 +1,20 @@
export * from './agent'
export * from './ai'
export * from './asset'
export * from './auth'
export * from './collection'
export * from './folder'
export * from './invite'
export * from './metadata'
export * from './notification'
export * from './pagination'
export * from './project'
export * from './provider'
export * from './s3'
export * from './search'
export * from './share'
export * from './skill'
export * from './team'
export * from './upload'
export * from './user-metadata'
export * from './versionStack'
@@ -1,10 +1,19 @@
import { z } from 'zod'
export interface SkillEnvironmentVariable {
name: string
default?: string
}
export interface SkillConfig {
environmentVariables: SkillEnvironmentVariable[]
}
export interface SkillInfo {
id: string
name: string
description: string | null
config: PrismaJson.SkillConfig | null
config: SkillConfig | null
assetId: string
hash: string
createdAt: string
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"ignoreDeprecations": "6.0"
},
"include": ["src/**/*"]
}
+2 -2
View File
@@ -4,9 +4,9 @@ import { loadEnvConfig } from './src/env-loader'
loadEnvConfig(process.cwd())
export default defineConfig({
schema: 'prisma/schema.prisma',
schema: 'packages/db/prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
path: 'packages/db/prisma/migrations',
},
datasource: {
url: process.env.DATABASE_URL,
+2 -2
View File
@@ -1,9 +1,9 @@
import { defineConfig } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
schema: 'packages/db/prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
path: 'packages/db/prisma/migrations',
},
datasource: {
url: process.env.DATABASE_URL,
+2 -2
View File
@@ -1,5 +1,5 @@
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { s3Service } from '@/services/s3/s3'
import { type SessionTreeEntry } from '@earendil-works/pi-agent-core'
import { describe, expect, it, vi } from 'vitest'
+1 -1
View File
@@ -1,4 +1,4 @@
import { prisma } from '@/db'
import { prisma } from '@shumai/db'
import { s3Service } from '@/services/s3/s3'
import { ulid } from 'ulid'
import {
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { prisma } from '@/db'
import { setupTestDbHooks } from '@/db-test-hooks'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db'
import { createReadSkillTool } from './read-skill'
import { s3Service } from '@/services/s3/s3'
import * as fs from 'fs'
+1 -1
View File
@@ -1,4 +1,4 @@
import { prisma } from '@/db'
import { prisma } from '@shumai/db'
import { Type } from '@sinclair/typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { agentService } from '@/services/agent/agent'
+1 -1
View File
@@ -1,4 +1,4 @@
import { prisma } from '@/db'
import { prisma } from '@shumai/db'
import { workflowService } from '@/workflow/workflow'
import { WorkflowTaskType, WorkflowTaskStatus } from '@/generated/prisma/client'
+1 -1
View File
@@ -7,7 +7,7 @@ import {
updateAgentRequestSchema,
AgentInfo,
AgentType,
} from '@/dtos/agent'
} from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
+1 -1
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { postAttachmentRequestSchema } from '@/dtos/asset'
import { postAttachmentRequestSchema } from '@shumai/dtos'
import { assetService } from '@/services/asset/asset'
import { s3Service } from '@/services/s3/s3'
import { AssetType } from '@/generated/prisma/client'
+1 -1
View File
@@ -3,7 +3,7 @@ import { teamService } from '@/services/team/team'
import { auth } from '@/services/auth/auth'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { prisma } from '@/db'
import { prisma } from '@shumai/db'
import { ulid } from 'ulid'
const app = new Hono()
+1 -1
View File
@@ -8,7 +8,7 @@ import {
listCollectionsRequestSchema,
CollectionInfo,
CollectionFilter,
} from '@/dtos/collection'
} from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import { prisma } from '@/db'
import { prisma } from '@shumai/db'
import fileRoute from './file'
import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata'
+4 -4
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { prisma } from '@/db'
import { prisma } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { assetService } from '@/services/asset/asset'
import { metadataService } from '@/services/metadata/metadata'
@@ -13,9 +13,9 @@ import {
restoreFilesRequestSchema,
createCommentRequestSchema,
uploadFileRequestSchema,
} from '@/dtos/asset'
import { updateAssetMetadataRequestSchema } from '@/dtos/metadata'
import { paginationParamsSchema } from '@/dtos/pagination'
} from '@shumai/dtos'
import { updateAssetMetadataRequestSchema } from '@shumai/dtos'
import { paginationParamsSchema } from '@shumai/dtos'
import { ulid } from 'ulid'
import { z } from 'zod'
import type { Prisma } from '@/generated/prisma/client'
+3 -3
View File
@@ -8,9 +8,9 @@ import {
updateFolderRequestSchema,
deleteFoldersRequestSchema,
restoreFoldersRequestSchema,
} from '@/dtos/folder'
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@/dtos/asset'
import { searchRequestSchema } from '@/dtos/search'
} from '@shumai/dtos'
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@shumai/dtos'
import { searchRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -5,7 +5,7 @@ import {
createTeamInviteRequestSchema,
joinRequestSchema,
InviteInfo,
} from '@/dtos/invite'
} from '@shumai/dtos'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { inviteService } from '@/services/invite/invite'
import { notificationService } from '@/services/notification/notification'
+1 -1
View File
@@ -7,7 +7,7 @@ import {
updateFieldRequestSchema,
updateProjectFieldsOrderRequestSchema,
FieldInfo,
} from '@/dtos/metadata'
} from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -1,6 +1,6 @@
import type { Prisma } from '@/generated/prisma/client'
import { auth } from '@/services/auth/auth'
import { prisma } from '@/db'
import { prisma } from '@shumai/db'
import { createMiddleware } from 'hono/factory'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -6,7 +6,7 @@ import {
listNotificationsRequestSchema,
markNotificationReadRequestSchema,
notificationSettingsSchema,
} from '@/dtos/notification'
} from '@shumai/dtos'
import { userMetadataService } from '@/services/user-metadata/user-metadata'
import type { Prisma } from '@/generated/prisma/client'
+3 -3
View File
@@ -3,14 +3,14 @@ import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { projectService } from '@/services/project/project'
import { assetService } from '@/services/asset/asset'
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@/dtos/asset'
import { reparentAssetsRequestSchema, copyAssetsRequestSchema } from '@shumai/dtos'
import {
createProjectRequestSchema,
updateProjectRequestSchema,
listProjectsRequestSchema,
recentlyDeletedRequestSchema,
} from '@/dtos/project'
import { listMembersQuerySchema } from '@/dtos/team'
} from '@shumai/dtos'
import { listMembersQuerySchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -2,7 +2,7 @@ import { zValidator } from '@hono/zod-validator'
import { Hono } from 'hono'
import { authzService, Permission, ResourceType } from '@/services/authz/authz'
import { providerService } from '@/services/provider/provider'
import { createProviderRequestSchema, updateProviderRequestSchema } from '@/dtos/provider'
import { createProviderRequestSchema, updateProviderRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@/generated/prisma/client'
type User = Prisma.UserGetPayload<Record<string, never>>
+1 -1
View File
@@ -1,6 +1,6 @@
import { Hono } from 'hono'
import { inviteService } from '@/services/invite/invite'
import { InviteInfo } from '@/dtos/invite'
import { InviteInfo } from '@shumai/dtos'
const app = new Hono()

Some files were not shown because too many files have changed in this diff Show More