mirror of
https://github.com/simstudioai/sim.git
synced 2026-02-05 12:14:59 -05:00
Compare commits
7 Commits
fix/onedri
...
fix/traces
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ac79b0443 | ||
|
|
47cb0a2cc9 | ||
|
|
a529db112e | ||
|
|
c69d6bf976 | ||
|
|
567f39267c | ||
|
|
12409f5eb5 | ||
|
|
7386d227eb |
@@ -183,109 +183,6 @@ export const {ServiceName}Block: BlockConfig = {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## File Input Handling
|
|
||||||
|
|
||||||
When your block accepts file uploads, use the basic/advanced mode pattern with `normalizeFileInput`.
|
|
||||||
|
|
||||||
### Basic/Advanced File Pattern
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Basic mode: Visual file upload
|
|
||||||
{
|
|
||||||
id: 'uploadFile',
|
|
||||||
title: 'File',
|
|
||||||
type: 'file-upload',
|
|
||||||
canonicalParamId: 'file', // Both map to 'file' param
|
|
||||||
placeholder: 'Upload file',
|
|
||||||
mode: 'basic',
|
|
||||||
multiple: false,
|
|
||||||
required: true,
|
|
||||||
condition: { field: 'operation', value: 'upload' },
|
|
||||||
},
|
|
||||||
// Advanced mode: Reference from other blocks
|
|
||||||
{
|
|
||||||
id: 'fileRef',
|
|
||||||
title: 'File',
|
|
||||||
type: 'short-input',
|
|
||||||
canonicalParamId: 'file', // Both map to 'file' param
|
|
||||||
placeholder: 'Reference file (e.g., {{file_block.output}})',
|
|
||||||
mode: 'advanced',
|
|
||||||
required: true,
|
|
||||||
condition: { field: 'operation', value: 'upload' },
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
**Critical constraints:**
|
|
||||||
- `canonicalParamId` must NOT match any subblock's `id` in the same block
|
|
||||||
- Values are stored under subblock `id`, not `canonicalParamId`
|
|
||||||
|
|
||||||
### Normalizing File Input in tools.config
|
|
||||||
|
|
||||||
Use `normalizeFileInput` to handle all input variants:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { normalizeFileInput } from '@/blocks/utils'
|
|
||||||
|
|
||||||
tools: {
|
|
||||||
access: ['service_upload'],
|
|
||||||
config: {
|
|
||||||
tool: (params) => {
|
|
||||||
// Check all field IDs: uploadFile (basic), fileRef (advanced), fileContent (legacy)
|
|
||||||
const normalizedFile = normalizeFileInput(
|
|
||||||
params.uploadFile || params.fileRef || params.fileContent,
|
|
||||||
{ single: true }
|
|
||||||
)
|
|
||||||
if (normalizedFile) {
|
|
||||||
params.file = normalizedFile
|
|
||||||
}
|
|
||||||
return `service_${params.operation}`
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Why this pattern?**
|
|
||||||
- Values come through as `params.uploadFile` or `params.fileRef` (the subblock IDs)
|
|
||||||
- `canonicalParamId` only controls UI/schema mapping, not runtime values
|
|
||||||
- `normalizeFileInput` handles JSON strings from advanced mode template resolution
|
|
||||||
|
|
||||||
### File Input Types in `inputs`
|
|
||||||
|
|
||||||
Use `type: 'json'` for file inputs:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
inputs: {
|
|
||||||
uploadFile: { type: 'json', description: 'Uploaded file (UserFile)' },
|
|
||||||
fileRef: { type: 'json', description: 'File reference from previous block' },
|
|
||||||
// Legacy field for backwards compatibility
|
|
||||||
fileContent: { type: 'string', description: 'Legacy: base64 encoded content' },
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Multiple Files
|
|
||||||
|
|
||||||
For multiple file uploads:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
{
|
|
||||||
id: 'attachments',
|
|
||||||
title: 'Attachments',
|
|
||||||
type: 'file-upload',
|
|
||||||
multiple: true, // Allow multiple files
|
|
||||||
maxSize: 25, // Max size in MB per file
|
|
||||||
acceptedTypes: 'image/*,application/pdf,.doc,.docx',
|
|
||||||
}
|
|
||||||
|
|
||||||
// In tools.config:
|
|
||||||
const normalizedFiles = normalizeFileInput(
|
|
||||||
params.attachments || params.attachmentRefs,
|
|
||||||
// No { single: true } - returns array
|
|
||||||
)
|
|
||||||
if (normalizedFiles) {
|
|
||||||
params.files = normalizedFiles
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Condition Syntax
|
## Condition Syntax
|
||||||
|
|
||||||
Controls when a field is shown based on other field values.
|
Controls when a field is shown based on other field values.
|
||||||
|
|||||||
@@ -206,15 +206,10 @@ export const {Service}Block: BlockConfig = {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Critical Canonical Param Rules:**
|
**Critical:**
|
||||||
- `canonicalParamId` must NOT match any subblock's `id` in the block
|
- `canonicalParamId` must NOT match any other subblock's `id`, must be unique per block, and should only be used to link basic/advanced alternatives for the same parameter.
|
||||||
- `canonicalParamId` must be unique per operation/condition context
|
- `mode` only controls UI visibility, NOT serialization. Without `canonicalParamId`, both basic and advanced field values would be sent.
|
||||||
- Only use `canonicalParamId` to link basic/advanced alternatives for the same logical parameter
|
- Every subblock `id` must be unique within the block. Duplicate IDs cause conflicts even with different conditions.
|
||||||
- `mode` only controls UI visibility, NOT serialization. Without `canonicalParamId`, both basic and advanced field values would be sent
|
|
||||||
- Every subblock `id` must be unique within the block. Duplicate IDs cause conflicts even with different conditions
|
|
||||||
- **Required consistency:** If one subblock in a canonical group has `required: true`, ALL subblocks in that group must have `required: true` (prevents bypassing validation by switching modes)
|
|
||||||
- **Inputs section:** Must list canonical param IDs (e.g., `fileId`), NOT raw subblock IDs (e.g., `fileSelector`, `manualFileId`)
|
|
||||||
- **Params function:** Must use canonical param IDs, NOT raw subblock IDs (raw IDs are deleted after canonical transformation)
|
|
||||||
|
|
||||||
## Step 4: Add Icon
|
## Step 4: Add Icon
|
||||||
|
|
||||||
@@ -462,230 +457,7 @@ You can usually find this in the service's brand/press kit page, or copy it from
|
|||||||
Paste the SVG code here and I'll convert it to a React component.
|
Paste the SVG code here and I'll convert it to a React component.
|
||||||
```
|
```
|
||||||
|
|
||||||
## File Handling
|
## Common Gotchas
|
||||||
|
|
||||||
When your integration handles file uploads or downloads, follow these patterns to work with `UserFile` objects consistently.
|
|
||||||
|
|
||||||
### What is a UserFile?
|
|
||||||
|
|
||||||
A `UserFile` is the standard file representation in Sim:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
interface UserFile {
|
|
||||||
id: string // Unique identifier
|
|
||||||
name: string // Original filename
|
|
||||||
url: string // Presigned URL for download
|
|
||||||
size: number // File size in bytes
|
|
||||||
type: string // MIME type (e.g., 'application/pdf')
|
|
||||||
base64?: string // Optional base64 content (if small file)
|
|
||||||
key?: string // Internal storage key
|
|
||||||
context?: object // Storage context metadata
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### File Input Pattern (Uploads)
|
|
||||||
|
|
||||||
For tools that accept file uploads, **always route through an internal API endpoint** rather than calling external APIs directly. This ensures proper file content retrieval.
|
|
||||||
|
|
||||||
#### 1. Block SubBlocks for File Input
|
|
||||||
|
|
||||||
Use the basic/advanced mode pattern:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Basic mode: File upload UI
|
|
||||||
{
|
|
||||||
id: 'uploadFile',
|
|
||||||
title: 'File',
|
|
||||||
type: 'file-upload',
|
|
||||||
canonicalParamId: 'file', // Maps to 'file' param
|
|
||||||
placeholder: 'Upload file',
|
|
||||||
mode: 'basic',
|
|
||||||
multiple: false,
|
|
||||||
required: true,
|
|
||||||
condition: { field: 'operation', value: 'upload' },
|
|
||||||
},
|
|
||||||
// Advanced mode: Reference from previous block
|
|
||||||
{
|
|
||||||
id: 'fileRef',
|
|
||||||
title: 'File',
|
|
||||||
type: 'short-input',
|
|
||||||
canonicalParamId: 'file', // Same canonical param
|
|
||||||
placeholder: 'Reference file (e.g., {{file_block.output}})',
|
|
||||||
mode: 'advanced',
|
|
||||||
required: true,
|
|
||||||
condition: { field: 'operation', value: 'upload' },
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
**Critical:** `canonicalParamId` must NOT match any subblock `id`.
|
|
||||||
|
|
||||||
#### 2. Normalize File Input in Block Config
|
|
||||||
|
|
||||||
In `tools.config.tool`, use `normalizeFileInput` to handle all input variants:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { normalizeFileInput } from '@/blocks/utils'
|
|
||||||
|
|
||||||
tools: {
|
|
||||||
config: {
|
|
||||||
tool: (params) => {
|
|
||||||
// Normalize file from basic (uploadFile), advanced (fileRef), or legacy (fileContent)
|
|
||||||
const normalizedFile = normalizeFileInput(
|
|
||||||
params.uploadFile || params.fileRef || params.fileContent,
|
|
||||||
{ single: true }
|
|
||||||
)
|
|
||||||
if (normalizedFile) {
|
|
||||||
params.file = normalizedFile
|
|
||||||
}
|
|
||||||
return `{service}_${params.operation}`
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 3. Create Internal API Route
|
|
||||||
|
|
||||||
Create `apps/sim/app/api/tools/{service}/{action}/route.ts`:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { NextResponse, type NextRequest } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
|
||||||
import { FileInputSchema, type RawFileInput } from '@/lib/uploads/utils/file-schemas'
|
|
||||||
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
|
||||||
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
|
||||||
|
|
||||||
const logger = createLogger('{Service}UploadAPI')
|
|
||||||
|
|
||||||
const RequestSchema = z.object({
|
|
||||||
accessToken: z.string(),
|
|
||||||
file: FileInputSchema.optional().nullable(),
|
|
||||||
// Legacy field for backwards compatibility
|
|
||||||
fileContent: z.string().optional().nullable(),
|
|
||||||
// ... other params
|
|
||||||
})
|
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
const requestId = generateRequestId()
|
|
||||||
|
|
||||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
|
||||||
if (!authResult.success) {
|
|
||||||
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const data = RequestSchema.parse(body)
|
|
||||||
|
|
||||||
let fileBuffer: Buffer
|
|
||||||
let fileName: string
|
|
||||||
|
|
||||||
// Prefer UserFile input, fall back to legacy base64
|
|
||||||
if (data.file) {
|
|
||||||
const userFiles = processFilesToUserFiles([data.file as RawFileInput], requestId, logger)
|
|
||||||
if (userFiles.length === 0) {
|
|
||||||
return NextResponse.json({ success: false, error: 'Invalid file' }, { status: 400 })
|
|
||||||
}
|
|
||||||
const userFile = userFiles[0]
|
|
||||||
fileBuffer = await downloadFileFromStorage(userFile, requestId, logger)
|
|
||||||
fileName = userFile.name
|
|
||||||
} else if (data.fileContent) {
|
|
||||||
// Legacy: base64 string (backwards compatibility)
|
|
||||||
fileBuffer = Buffer.from(data.fileContent, 'base64')
|
|
||||||
fileName = 'file'
|
|
||||||
} else {
|
|
||||||
return NextResponse.json({ success: false, error: 'File required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now call external API with fileBuffer
|
|
||||||
const response = await fetch('https://api.{service}.com/upload', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { Authorization: `Bearer ${data.accessToken}` },
|
|
||||||
body: new Uint8Array(fileBuffer), // Convert Buffer for fetch
|
|
||||||
})
|
|
||||||
|
|
||||||
// ... handle response
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 4. Update Tool to Use Internal Route
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
export const {service}UploadTool: ToolConfig<Params, Response> = {
|
|
||||||
id: '{service}_upload',
|
|
||||||
// ...
|
|
||||||
params: {
|
|
||||||
file: { type: 'file', required: false, visibility: 'user-or-llm' },
|
|
||||||
fileContent: { type: 'string', required: false, visibility: 'hidden' }, // Legacy
|
|
||||||
},
|
|
||||||
request: {
|
|
||||||
url: '/api/tools/{service}/upload', // Internal route
|
|
||||||
method: 'POST',
|
|
||||||
body: (params) => ({
|
|
||||||
accessToken: params.accessToken,
|
|
||||||
file: params.file,
|
|
||||||
fileContent: params.fileContent,
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### File Output Pattern (Downloads)
|
|
||||||
|
|
||||||
For tools that return files, use `FileToolProcessor` to store files and return `UserFile` objects.
|
|
||||||
|
|
||||||
#### In Tool transformResponse
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { FileToolProcessor } from '@/executor/utils/file-tool-processor'
|
|
||||||
|
|
||||||
transformResponse: async (response, context) => {
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
// Process file outputs to UserFile objects
|
|
||||||
const fileProcessor = new FileToolProcessor(context)
|
|
||||||
const file = await fileProcessor.processFileData({
|
|
||||||
data: data.content, // base64 or buffer
|
|
||||||
mimeType: data.mimeType,
|
|
||||||
filename: data.filename,
|
|
||||||
})
|
|
||||||
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
output: { file },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### In API Route (for complex file handling)
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Return file data that FileToolProcessor can handle
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
output: {
|
|
||||||
file: {
|
|
||||||
data: base64Content,
|
|
||||||
mimeType: 'application/pdf',
|
|
||||||
filename: 'document.pdf',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
### Key Helpers Reference
|
|
||||||
|
|
||||||
| Helper | Location | Purpose |
|
|
||||||
|--------|----------|---------|
|
|
||||||
| `normalizeFileInput` | `@/blocks/utils` | Normalize file params in block config |
|
|
||||||
| `processFilesToUserFiles` | `@/lib/uploads/utils/file-utils` | Convert raw inputs to UserFile[] |
|
|
||||||
| `downloadFileFromStorage` | `@/lib/uploads/utils/file-utils.server` | Get file Buffer from UserFile |
|
|
||||||
| `FileToolProcessor` | `@/executor/utils/file-tool-processor` | Process tool output files |
|
|
||||||
| `isUserFile` | `@/lib/core/utils/user-file` | Type guard for UserFile objects |
|
|
||||||
| `FileInputSchema` | `@/lib/uploads/utils/file-schemas` | Zod schema for file validation |
|
|
||||||
|
|
||||||
### Common Gotchas
|
|
||||||
|
|
||||||
1. **OAuth serviceId must match** - The `serviceId` in oauth-input must match the OAuth provider configuration
|
1. **OAuth serviceId must match** - The `serviceId` in oauth-input must match the OAuth provider configuration
|
||||||
2. **Tool IDs are snake_case** - `stripe_create_payment`, not `stripeCreatePayment`
|
2. **Tool IDs are snake_case** - `stripe_create_payment`, not `stripeCreatePayment`
|
||||||
@@ -693,5 +465,3 @@ return NextResponse.json({
|
|||||||
4. **Alphabetical ordering** - Keep imports and registry entries alphabetically sorted
|
4. **Alphabetical ordering** - Keep imports and registry entries alphabetically sorted
|
||||||
5. **Required can be conditional** - Use `required: { field: 'op', value: 'create' }` instead of always true
|
5. **Required can be conditional** - Use `required: { field: 'op', value: 'create' }` instead of always true
|
||||||
6. **DependsOn clears options** - When a dependency changes, selector options are refetched
|
6. **DependsOn clears options** - When a dependency changes, selector options are refetched
|
||||||
7. **Never pass Buffer directly to fetch** - Convert to `new Uint8Array(buffer)` for TypeScript compatibility
|
|
||||||
8. **Always handle legacy file params** - Keep hidden `fileContent` params for backwards compatibility
|
|
||||||
|
|||||||
@@ -157,36 +157,6 @@ dependsOn: { all: ['authMethod'], any: ['credential', 'botToken'] }
|
|||||||
- `'both'` - Show in both modes (default)
|
- `'both'` - Show in both modes (default)
|
||||||
- `'trigger'` - Only when block is used as trigger
|
- `'trigger'` - Only when block is used as trigger
|
||||||
|
|
||||||
### `canonicalParamId` - Link basic/advanced alternatives
|
|
||||||
|
|
||||||
Use to map multiple UI inputs to a single logical parameter:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Basic mode: Visual selector
|
|
||||||
{
|
|
||||||
id: 'fileSelector',
|
|
||||||
type: 'file-selector',
|
|
||||||
mode: 'basic',
|
|
||||||
canonicalParamId: 'fileId',
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
// Advanced mode: Manual input
|
|
||||||
{
|
|
||||||
id: 'manualFileId',
|
|
||||||
type: 'short-input',
|
|
||||||
mode: 'advanced',
|
|
||||||
canonicalParamId: 'fileId',
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
**Critical Rules:**
|
|
||||||
- `canonicalParamId` must NOT match any subblock's `id`
|
|
||||||
- `canonicalParamId` must be unique per operation/condition context
|
|
||||||
- **Required consistency:** All subblocks in a canonical group must have the same `required` status
|
|
||||||
- **Inputs section:** Must list canonical param IDs (e.g., `fileId`), NOT raw subblock IDs
|
|
||||||
- **Params function:** Must use canonical param IDs (raw IDs are deleted after canonical transformation)
|
|
||||||
|
|
||||||
**Register in `blocks/registry.ts`:**
|
**Register in `blocks/registry.ts`:**
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@@ -225,52 +195,6 @@ import { {service}WebhookTrigger } from '@/triggers/{service}'
|
|||||||
{service}_webhook: {service}WebhookTrigger,
|
{service}_webhook: {service}WebhookTrigger,
|
||||||
```
|
```
|
||||||
|
|
||||||
## File Handling
|
|
||||||
|
|
||||||
When integrations handle file uploads/downloads, use `UserFile` objects consistently.
|
|
||||||
|
|
||||||
### File Input (Uploads)
|
|
||||||
|
|
||||||
1. **Block subBlocks:** Use basic/advanced mode pattern with `canonicalParamId`
|
|
||||||
2. **Normalize in block config:** Use `normalizeFileInput` from `@/blocks/utils`
|
|
||||||
3. **Internal API route:** Create route that uses `downloadFileFromStorage` to get file content
|
|
||||||
4. **Tool routes to internal API:** Don't call external APIs directly with files
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// In block tools.config:
|
|
||||||
import { normalizeFileInput } from '@/blocks/utils'
|
|
||||||
|
|
||||||
const normalizedFile = normalizeFileInput(
|
|
||||||
params.uploadFile || params.fileRef || params.fileContent,
|
|
||||||
{ single: true }
|
|
||||||
)
|
|
||||||
if (normalizedFile) params.file = normalizedFile
|
|
||||||
```
|
|
||||||
|
|
||||||
### File Output (Downloads)
|
|
||||||
|
|
||||||
Use `FileToolProcessor` in tool `transformResponse` to store files:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { FileToolProcessor } from '@/executor/utils/file-tool-processor'
|
|
||||||
|
|
||||||
const processor = new FileToolProcessor(context)
|
|
||||||
const file = await processor.processFileData({
|
|
||||||
data: base64Content,
|
|
||||||
mimeType: 'application/pdf',
|
|
||||||
filename: 'doc.pdf',
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
### Key Helpers
|
|
||||||
|
|
||||||
| Helper | Location | Purpose |
|
|
||||||
|--------|----------|---------|
|
|
||||||
| `normalizeFileInput` | `@/blocks/utils` | Normalize file params in block config |
|
|
||||||
| `processFilesToUserFiles` | `@/lib/uploads/utils/file-utils` | Convert raw inputs to UserFile[] |
|
|
||||||
| `downloadFileFromStorage` | `@/lib/uploads/utils/file-utils.server` | Get Buffer from UserFile |
|
|
||||||
| `FileToolProcessor` | `@/executor/utils/file-tool-processor` | Process tool output files |
|
|
||||||
|
|
||||||
## Checklist
|
## Checklist
|
||||||
|
|
||||||
- [ ] Look up API docs for the service
|
- [ ] Look up API docs for the service
|
||||||
@@ -283,5 +207,3 @@ const file = await processor.processFileData({
|
|||||||
- [ ] Register block in `blocks/registry.ts`
|
- [ ] Register block in `blocks/registry.ts`
|
||||||
- [ ] (Optional) Create triggers in `triggers/{service}/`
|
- [ ] (Optional) Create triggers in `triggers/{service}/`
|
||||||
- [ ] (Optional) Register triggers in `triggers/registry.ts`
|
- [ ] (Optional) Register triggers in `triggers/registry.ts`
|
||||||
- [ ] (If file uploads) Create internal API route with `downloadFileFromStorage`
|
|
||||||
- [ ] (If file uploads) Use `normalizeFileInput` in block config
|
|
||||||
|
|||||||
@@ -155,36 +155,6 @@ dependsOn: { all: ['authMethod'], any: ['credential', 'botToken'] }
|
|||||||
- `'both'` - Show in both modes (default)
|
- `'both'` - Show in both modes (default)
|
||||||
- `'trigger'` - Only when block is used as trigger
|
- `'trigger'` - Only when block is used as trigger
|
||||||
|
|
||||||
### `canonicalParamId` - Link basic/advanced alternatives
|
|
||||||
|
|
||||||
Use to map multiple UI inputs to a single logical parameter:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Basic mode: Visual selector
|
|
||||||
{
|
|
||||||
id: 'fileSelector',
|
|
||||||
type: 'file-selector',
|
|
||||||
mode: 'basic',
|
|
||||||
canonicalParamId: 'fileId',
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
// Advanced mode: Manual input
|
|
||||||
{
|
|
||||||
id: 'manualFileId',
|
|
||||||
type: 'short-input',
|
|
||||||
mode: 'advanced',
|
|
||||||
canonicalParamId: 'fileId',
|
|
||||||
required: true,
|
|
||||||
},
|
|
||||||
```
|
|
||||||
|
|
||||||
**Critical Rules:**
|
|
||||||
- `canonicalParamId` must NOT match any subblock's `id`
|
|
||||||
- `canonicalParamId` must be unique per operation/condition context
|
|
||||||
- **Required consistency:** All subblocks in a canonical group must have the same `required` status
|
|
||||||
- **Inputs section:** Must list canonical param IDs (e.g., `fileId`), NOT raw subblock IDs
|
|
||||||
- **Params function:** Must use canonical param IDs (raw IDs are deleted after canonical transformation)
|
|
||||||
|
|
||||||
**Register in `blocks/registry.ts`:**
|
**Register in `blocks/registry.ts`:**
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@@ -223,52 +193,6 @@ import { {service}WebhookTrigger } from '@/triggers/{service}'
|
|||||||
{service}_webhook: {service}WebhookTrigger,
|
{service}_webhook: {service}WebhookTrigger,
|
||||||
```
|
```
|
||||||
|
|
||||||
## File Handling
|
|
||||||
|
|
||||||
When integrations handle file uploads/downloads, use `UserFile` objects consistently.
|
|
||||||
|
|
||||||
### File Input (Uploads)
|
|
||||||
|
|
||||||
1. **Block subBlocks:** Use basic/advanced mode pattern with `canonicalParamId`
|
|
||||||
2. **Normalize in block config:** Use `normalizeFileInput` from `@/blocks/utils`
|
|
||||||
3. **Internal API route:** Create route that uses `downloadFileFromStorage` to get file content
|
|
||||||
4. **Tool routes to internal API:** Don't call external APIs directly with files
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// In block tools.config:
|
|
||||||
import { normalizeFileInput } from '@/blocks/utils'
|
|
||||||
|
|
||||||
const normalizedFile = normalizeFileInput(
|
|
||||||
params.uploadFile || params.fileRef || params.fileContent,
|
|
||||||
{ single: true }
|
|
||||||
)
|
|
||||||
if (normalizedFile) params.file = normalizedFile
|
|
||||||
```
|
|
||||||
|
|
||||||
### File Output (Downloads)
|
|
||||||
|
|
||||||
Use `FileToolProcessor` in tool `transformResponse` to store files:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { FileToolProcessor } from '@/executor/utils/file-tool-processor'
|
|
||||||
|
|
||||||
const processor = new FileToolProcessor(context)
|
|
||||||
const file = await processor.processFileData({
|
|
||||||
data: base64Content,
|
|
||||||
mimeType: 'application/pdf',
|
|
||||||
filename: 'doc.pdf',
|
|
||||||
})
|
|
||||||
```
|
|
||||||
|
|
||||||
### Key Helpers
|
|
||||||
|
|
||||||
| Helper | Location | Purpose |
|
|
||||||
|--------|----------|---------|
|
|
||||||
| `normalizeFileInput` | `@/blocks/utils` | Normalize file params in block config |
|
|
||||||
| `processFilesToUserFiles` | `@/lib/uploads/utils/file-utils` | Convert raw inputs to UserFile[] |
|
|
||||||
| `downloadFileFromStorage` | `@/lib/uploads/utils/file-utils.server` | Get Buffer from UserFile |
|
|
||||||
| `FileToolProcessor` | `@/executor/utils/file-tool-processor` | Process tool output files |
|
|
||||||
|
|
||||||
## Checklist
|
## Checklist
|
||||||
|
|
||||||
- [ ] Look up API docs for the service
|
- [ ] Look up API docs for the service
|
||||||
@@ -281,5 +205,3 @@ const file = await processor.processFileData({
|
|||||||
- [ ] Register block in `blocks/registry.ts`
|
- [ ] Register block in `blocks/registry.ts`
|
||||||
- [ ] (Optional) Create triggers in `triggers/{service}/`
|
- [ ] (Optional) Create triggers in `triggers/{service}/`
|
||||||
- [ ] (Optional) Register triggers in `triggers/registry.ts`
|
- [ ] (Optional) Register triggers in `triggers/registry.ts`
|
||||||
- [ ] (If file uploads) Create internal API route with `downloadFileFromStorage`
|
|
||||||
- [ ] (If file uploads) Use `normalizeFileInput` in block config
|
|
||||||
|
|||||||
19
CLAUDE.md
19
CLAUDE.md
@@ -265,23 +265,6 @@ Register in `blocks/registry.ts` (alphabetically).
|
|||||||
|
|
||||||
**dependsOn:** `['field']` or `{ all: ['a'], any: ['b', 'c'] }`
|
**dependsOn:** `['field']` or `{ all: ['a'], any: ['b', 'c'] }`
|
||||||
|
|
||||||
**File Input Pattern (basic/advanced mode):**
|
|
||||||
```typescript
|
|
||||||
// Basic: file-upload UI
|
|
||||||
{ id: 'uploadFile', type: 'file-upload', canonicalParamId: 'file', mode: 'basic' },
|
|
||||||
// Advanced: reference from other blocks
|
|
||||||
{ id: 'fileRef', type: 'short-input', canonicalParamId: 'file', mode: 'advanced' },
|
|
||||||
```
|
|
||||||
|
|
||||||
In `tools.config.tool`, normalize with:
|
|
||||||
```typescript
|
|
||||||
import { normalizeFileInput } from '@/blocks/utils'
|
|
||||||
const file = normalizeFileInput(params.uploadFile || params.fileRef, { single: true })
|
|
||||||
if (file) params.file = file
|
|
||||||
```
|
|
||||||
|
|
||||||
For file uploads, create an internal API route (`/api/tools/{service}/upload`) that uses `downloadFileFromStorage` to get file content from `UserFile` objects.
|
|
||||||
|
|
||||||
### 3. Icon (`components/icons.tsx`)
|
### 3. Icon (`components/icons.tsx`)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@@ -310,5 +293,3 @@ Register in `triggers/registry.ts`.
|
|||||||
- [ ] Create block in `blocks/blocks/{service}.ts`
|
- [ ] Create block in `blocks/blocks/{service}.ts`
|
||||||
- [ ] Register block in `blocks/registry.ts`
|
- [ ] Register block in `blocks/registry.ts`
|
||||||
- [ ] (Optional) Create and register triggers
|
- [ ] (Optional) Create and register triggers
|
||||||
- [ ] (If file uploads) Create internal API route with `downloadFileFromStorage`
|
|
||||||
- [ ] (If file uploads) Use `normalizeFileInput` in block config
|
|
||||||
|
|||||||
@@ -163,9 +163,9 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
|||||||
elevenlabs: ElevenLabsIcon,
|
elevenlabs: ElevenLabsIcon,
|
||||||
enrich: EnrichSoIcon,
|
enrich: EnrichSoIcon,
|
||||||
exa: ExaAIIcon,
|
exa: ExaAIIcon,
|
||||||
file_v3: DocumentIcon,
|
file_v2: DocumentIcon,
|
||||||
firecrawl: FirecrawlIcon,
|
firecrawl: FirecrawlIcon,
|
||||||
fireflies_v2: FirefliesIcon,
|
fireflies: FirefliesIcon,
|
||||||
github_v2: GithubIcon,
|
github_v2: GithubIcon,
|
||||||
gitlab: GitLabIcon,
|
gitlab: GitLabIcon,
|
||||||
gmail_v2: GmailIcon,
|
gmail_v2: GmailIcon,
|
||||||
@@ -177,7 +177,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
|||||||
google_maps: GoogleMapsIcon,
|
google_maps: GoogleMapsIcon,
|
||||||
google_search: GoogleIcon,
|
google_search: GoogleIcon,
|
||||||
google_sheets_v2: GoogleSheetsIcon,
|
google_sheets_v2: GoogleSheetsIcon,
|
||||||
google_slides_v2: GoogleSlidesIcon,
|
google_slides: GoogleSlidesIcon,
|
||||||
google_vault: GoogleVaultIcon,
|
google_vault: GoogleVaultIcon,
|
||||||
grafana: GrafanaIcon,
|
grafana: GrafanaIcon,
|
||||||
grain: GrainIcon,
|
grain: GrainIcon,
|
||||||
@@ -206,7 +206,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
|||||||
microsoft_excel_v2: MicrosoftExcelIcon,
|
microsoft_excel_v2: MicrosoftExcelIcon,
|
||||||
microsoft_planner: MicrosoftPlannerIcon,
|
microsoft_planner: MicrosoftPlannerIcon,
|
||||||
microsoft_teams: MicrosoftTeamsIcon,
|
microsoft_teams: MicrosoftTeamsIcon,
|
||||||
mistral_parse_v3: MistralIcon,
|
mistral_parse_v2: MistralIcon,
|
||||||
mongodb: MongoDBIcon,
|
mongodb: MongoDBIcon,
|
||||||
mysql: MySQLIcon,
|
mysql: MySQLIcon,
|
||||||
neo4j: Neo4jIcon,
|
neo4j: Neo4jIcon,
|
||||||
@@ -221,11 +221,11 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
|||||||
polymarket: PolymarketIcon,
|
polymarket: PolymarketIcon,
|
||||||
postgresql: PostgresIcon,
|
postgresql: PostgresIcon,
|
||||||
posthog: PosthogIcon,
|
posthog: PosthogIcon,
|
||||||
pulse_v2: PulseIcon,
|
pulse: PulseIcon,
|
||||||
qdrant: QdrantIcon,
|
qdrant: QdrantIcon,
|
||||||
rds: RDSIcon,
|
rds: RDSIcon,
|
||||||
reddit: RedditIcon,
|
reddit: RedditIcon,
|
||||||
reducto_v2: ReductoIcon,
|
reducto: ReductoIcon,
|
||||||
resend: ResendIcon,
|
resend: ResendIcon,
|
||||||
s3: S3Icon,
|
s3: S3Icon,
|
||||||
salesforce: SalesforceIcon,
|
salesforce: SalesforceIcon,
|
||||||
@@ -244,11 +244,11 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
|||||||
ssh: SshIcon,
|
ssh: SshIcon,
|
||||||
stagehand: StagehandIcon,
|
stagehand: StagehandIcon,
|
||||||
stripe: StripeIcon,
|
stripe: StripeIcon,
|
||||||
stt_v2: STTIcon,
|
stt: STTIcon,
|
||||||
supabase: SupabaseIcon,
|
supabase: SupabaseIcon,
|
||||||
tavily: TavilyIcon,
|
tavily: TavilyIcon,
|
||||||
telegram: TelegramIcon,
|
telegram: TelegramIcon,
|
||||||
textract_v2: TextractIcon,
|
textract: TextractIcon,
|
||||||
tinybird: TinybirdIcon,
|
tinybird: TinybirdIcon,
|
||||||
translate: TranslateIcon,
|
translate: TranslateIcon,
|
||||||
trello: TrelloIcon,
|
trello: TrelloIcon,
|
||||||
@@ -257,7 +257,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
|||||||
twilio_voice: TwilioIcon,
|
twilio_voice: TwilioIcon,
|
||||||
typeform: TypeformIcon,
|
typeform: TypeformIcon,
|
||||||
video_generator_v2: VideoIcon,
|
video_generator_v2: VideoIcon,
|
||||||
vision_v2: EyeIcon,
|
vision: EyeIcon,
|
||||||
wealthbox: WealthboxIcon,
|
wealthbox: WealthboxIcon,
|
||||||
webflow: WebflowIcon,
|
webflow: WebflowIcon,
|
||||||
whatsapp: WhatsAppIcon,
|
whatsapp: WhatsAppIcon,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Mehrere Dateien lesen und parsen
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="file_v3"
|
type="file"
|
||||||
color="#40916C"
|
color="#40916C"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Interagieren Sie mit Fireflies.ai-Besprechungstranskripten und -auf
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="fireflies_v2"
|
type="fireflies"
|
||||||
color="#100730"
|
color="#100730"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Text aus PDF-Dokumenten extrahieren
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="mistral_parse_v3"
|
type="mistral_parse"
|
||||||
color="#000000"
|
color="#000000"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -213,25 +213,6 @@ Different subscription plans have different usage limits:
|
|||||||
| **Team** | $40/seat (pooled, adjustable) | 300 sync, 2,500 async |
|
| **Team** | $40/seat (pooled, adjustable) | 300 sync, 2,500 async |
|
||||||
| **Enterprise** | Custom | Custom |
|
| **Enterprise** | Custom | Custom |
|
||||||
|
|
||||||
## Execution Time Limits
|
|
||||||
|
|
||||||
Workflows have maximum execution time limits based on your subscription plan:
|
|
||||||
|
|
||||||
| Plan | Sync Execution | Async Execution |
|
|
||||||
|------|----------------|-----------------|
|
|
||||||
| **Free** | 5 minutes | 10 minutes |
|
|
||||||
| **Pro** | 50 minutes | 90 minutes |
|
|
||||||
| **Team** | 50 minutes | 90 minutes |
|
|
||||||
| **Enterprise** | 50 minutes | 90 minutes |
|
|
||||||
|
|
||||||
**Sync executions** run immediately and return results directly. These are triggered via the API with `async: false` (default) or through the UI.
|
|
||||||
**Async executions** (triggered via API with `async: true`, webhooks, or schedules) run in the background. Async time limits are up to 2x the sync limit, capped at 90 minutes.
|
|
||||||
|
|
||||||
|
|
||||||
<Callout type="info">
|
|
||||||
If a workflow exceeds its time limit, it will be terminated and marked as failed with a timeout error. Design long-running workflows to use async execution or break them into smaller workflows.
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
## Billing Model
|
## Billing Model
|
||||||
|
|
||||||
Sim uses a **base subscription + overage** billing model:
|
Sim uses a **base subscription + overage** billing model:
|
||||||
|
|||||||
@@ -1,168 +0,0 @@
|
|||||||
---
|
|
||||||
title: Passing Files
|
|
||||||
---
|
|
||||||
|
|
||||||
import { Callout } from 'fumadocs-ui/components/callout'
|
|
||||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
|
||||||
|
|
||||||
Sim makes it easy to work with files throughout your workflows. Blocks can receive files, process them, and pass them to other blocks seamlessly.
|
|
||||||
|
|
||||||
## File Objects
|
|
||||||
|
|
||||||
When blocks output files (like Gmail attachments, generated images, or parsed documents), they return a standardized file object:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"name": "report.pdf",
|
|
||||||
"url": "https://...",
|
|
||||||
"base64": "JVBERi0xLjQK...",
|
|
||||||
"type": "application/pdf",
|
|
||||||
"size": 245678
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
You can access any of these properties when referencing files from previous blocks.
|
|
||||||
|
|
||||||
## The File Block
|
|
||||||
|
|
||||||
The **File block** is the universal entry point for files in your workflows. It accepts files from any source and outputs standardized file objects that work with all integrations.
|
|
||||||
|
|
||||||
**Inputs:**
|
|
||||||
- **Uploaded files** - Drag and drop or select files directly
|
|
||||||
- **External URLs** - Any publicly accessible file URL
|
|
||||||
- **Files from other blocks** - Pass files from Gmail attachments, Slack downloads, etc.
|
|
||||||
|
|
||||||
**Outputs:**
|
|
||||||
- A list of `UserFile` objects with consistent structure (`name`, `url`, `base64`, `type`, `size`)
|
|
||||||
- `combinedContent` - Extracted text content from all files (for documents)
|
|
||||||
|
|
||||||
**Example usage:**
|
|
||||||
|
|
||||||
```
|
|
||||||
// Get all files from the File block
|
|
||||||
<file.files>
|
|
||||||
|
|
||||||
// Get the first file
|
|
||||||
<file.files[0]>
|
|
||||||
|
|
||||||
// Get combined text content from parsed documents
|
|
||||||
<file.combinedContent>
|
|
||||||
```
|
|
||||||
|
|
||||||
The File block automatically:
|
|
||||||
- Detects file types from URLs and extensions
|
|
||||||
- Extracts text from PDFs, CSVs, and documents
|
|
||||||
- Generates base64 encoding for binary files
|
|
||||||
- Creates presigned URLs for secure access
|
|
||||||
|
|
||||||
Use the File block when you need to normalize files from different sources before passing them to other blocks like Vision, STT, or email integrations.
|
|
||||||
|
|
||||||
## Passing Files Between Blocks
|
|
||||||
|
|
||||||
Reference files from previous blocks using the tag dropdown. Click in any file input field and type `<` to see available outputs.
|
|
||||||
|
|
||||||
**Common patterns:**
|
|
||||||
|
|
||||||
```
|
|
||||||
// Single file from a block
|
|
||||||
<gmail.attachments[0]>
|
|
||||||
|
|
||||||
// Pass the whole file object
|
|
||||||
<file_parser.files[0]>
|
|
||||||
|
|
||||||
// Access specific properties
|
|
||||||
<gmail.attachments[0].name>
|
|
||||||
<gmail.attachments[0].base64>
|
|
||||||
```
|
|
||||||
|
|
||||||
Most blocks accept the full file object and extract what they need automatically. You don't need to manually extract `base64` or `url` in most cases.
|
|
||||||
|
|
||||||
## Triggering Workflows with Files
|
|
||||||
|
|
||||||
When calling a workflow via API that expects file input, include files in your request:
|
|
||||||
|
|
||||||
<Tabs items={['Base64', 'URL']}>
|
|
||||||
<Tab value="Base64">
|
|
||||||
```bash
|
|
||||||
curl -X POST "https://sim.ai/api/workflows/YOUR_WORKFLOW_ID/execute" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "x-api-key: YOUR_API_KEY" \
|
|
||||||
-d '{
|
|
||||||
"document": {
|
|
||||||
"name": "report.pdf",
|
|
||||||
"base64": "JVBERi0xLjQK...",
|
|
||||||
"type": "application/pdf"
|
|
||||||
}
|
|
||||||
}'
|
|
||||||
```
|
|
||||||
</Tab>
|
|
||||||
<Tab value="URL">
|
|
||||||
```bash
|
|
||||||
curl -X POST "https://sim.ai/api/workflows/YOUR_WORKFLOW_ID/execute" \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "x-api-key: YOUR_API_KEY" \
|
|
||||||
-d '{
|
|
||||||
"document": {
|
|
||||||
"name": "report.pdf",
|
|
||||||
"url": "https://example.com/report.pdf",
|
|
||||||
"type": "application/pdf"
|
|
||||||
}
|
|
||||||
}'
|
|
||||||
```
|
|
||||||
</Tab>
|
|
||||||
</Tabs>
|
|
||||||
|
|
||||||
The workflow's Start block should have an input field configured to receive the file parameter.
|
|
||||||
|
|
||||||
## Receiving Files in API Responses
|
|
||||||
|
|
||||||
When a workflow outputs files, they're included in the response:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"success": true,
|
|
||||||
"output": {
|
|
||||||
"generatedFile": {
|
|
||||||
"name": "output.png",
|
|
||||||
"url": "https://...",
|
|
||||||
"base64": "iVBORw0KGgo...",
|
|
||||||
"type": "image/png",
|
|
||||||
"size": 34567
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Use `url` for direct downloads or `base64` for inline processing.
|
|
||||||
|
|
||||||
## Blocks That Work with Files
|
|
||||||
|
|
||||||
**File inputs:**
|
|
||||||
- **File** - Parse documents, images, and text files
|
|
||||||
- **Vision** - Analyze images with AI models
|
|
||||||
- **Mistral Parser** - Extract text from PDFs
|
|
||||||
|
|
||||||
**File outputs:**
|
|
||||||
- **Gmail** - Email attachments
|
|
||||||
- **Slack** - Downloaded files
|
|
||||||
- **TTS** - Generated audio files
|
|
||||||
- **Video Generator** - Generated videos
|
|
||||||
- **Image Generator** - Generated images
|
|
||||||
|
|
||||||
**File storage:**
|
|
||||||
- **Supabase** - Upload/download from storage
|
|
||||||
- **S3** - AWS S3 operations
|
|
||||||
- **Google Drive** - Drive file operations
|
|
||||||
- **Dropbox** - Dropbox file operations
|
|
||||||
|
|
||||||
<Callout type="info">
|
|
||||||
Files are automatically available to downstream blocks. The execution engine handles all file transfer and format conversion.
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
## Best Practices
|
|
||||||
|
|
||||||
1. **Use file objects directly** - Pass the full file object rather than extracting individual properties. Blocks handle the conversion automatically.
|
|
||||||
|
|
||||||
2. **Check file types** - Ensure the file type matches what the receiving block expects. The Vision block needs images, the File block handles documents.
|
|
||||||
|
|
||||||
3. **Consider file size** - Large files increase execution time. For very large files, consider using storage blocks (S3, Supabase) for intermediate storage.
|
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
{
|
{
|
||||||
"pages": ["index", "basics", "files", "api", "logging", "costs"]
|
"pages": ["index", "basics", "api", "logging", "costs"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -180,11 +180,6 @@ A quick lookup for everyday actions in the Sim workflow editor. For keyboard sho
|
|||||||
<td>Right-click → **Enable/Disable**</td>
|
<td>Right-click → **Enable/Disable**</td>
|
||||||
<td><ActionImage src="/static/quick-reference/disable-block.png" alt="Disable block" /></td>
|
<td><ActionImage src="/static/quick-reference/disable-block.png" alt="Disable block" /></td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr>
|
|
||||||
<td>Lock/Unlock a block</td>
|
|
||||||
<td>Hover block → Click lock icon (Admin only)</td>
|
|
||||||
<td><ActionImage src="/static/quick-reference/lock-block.png" alt="Lock block" /></td>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
<tr>
|
||||||
<td>Toggle handle orientation</td>
|
<td>Toggle handle orientation</td>
|
||||||
<td>Right-click → **Toggle Handles**</td>
|
<td>Right-click → **Toggle Handles**</td>
|
||||||
|
|||||||
@@ -49,25 +49,10 @@ Retrieve content from Confluence pages using the Confluence API.
|
|||||||
|
|
||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
| `ts` | string | Timestamp of retrieval |
|
||||||
| `pageId` | string | Confluence page ID |
|
| `pageId` | string | Confluence page ID |
|
||||||
| `title` | string | Page title |
|
|
||||||
| `content` | string | Page content with HTML tags stripped |
|
| `content` | string | Page content with HTML tags stripped |
|
||||||
| `status` | string | Page status \(current, archived, trashed, draft\) |
|
| `title` | string | Page title |
|
||||||
| `spaceId` | string | ID of the space containing the page |
|
|
||||||
| `parentId` | string | ID of the parent page |
|
|
||||||
| `authorId` | string | Account ID of the page author |
|
|
||||||
| `createdAt` | string | ISO 8601 timestamp when the page was created |
|
|
||||||
| `url` | string | URL to view the page in Confluence |
|
|
||||||
| `body` | object | Raw page body content in storage format |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| `version` | object | Page version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
|
|
||||||
### `confluence_update`
|
### `confluence_update`
|
||||||
|
|
||||||
@@ -91,25 +76,6 @@ Update a Confluence page using the Confluence API.
|
|||||||
| `ts` | string | Timestamp of update |
|
| `ts` | string | Timestamp of update |
|
||||||
| `pageId` | string | Confluence page ID |
|
| `pageId` | string | Confluence page ID |
|
||||||
| `title` | string | Updated page title |
|
| `title` | string | Updated page title |
|
||||||
| `status` | string | Page status |
|
|
||||||
| `spaceId` | string | Space ID |
|
|
||||||
| `body` | object | Page body content in storage format |
|
|
||||||
| ↳ `storage` | object | Body in storage format \(Confluence markup\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `view` | object | Body in view format \(rendered HTML\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `atlas_doc_format` | object | Body in Atlassian Document Format \(ADF\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| `version` | object | Page version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| `url` | string | URL to view the page in Confluence |
|
|
||||||
| `success` | boolean | Update operation success status |
|
| `success` | boolean | Update operation success status |
|
||||||
|
|
||||||
### `confluence_create_page`
|
### `confluence_create_page`
|
||||||
@@ -134,30 +100,11 @@ Create a new page in a Confluence space.
|
|||||||
| `ts` | string | Timestamp of creation |
|
| `ts` | string | Timestamp of creation |
|
||||||
| `pageId` | string | Created page ID |
|
| `pageId` | string | Created page ID |
|
||||||
| `title` | string | Page title |
|
| `title` | string | Page title |
|
||||||
| `status` | string | Page status |
|
|
||||||
| `spaceId` | string | Space ID |
|
|
||||||
| `parentId` | string | Parent page ID |
|
|
||||||
| `body` | object | Page body content |
|
|
||||||
| ↳ `storage` | object | Body in storage format \(Confluence markup\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `view` | object | Body in view format \(rendered HTML\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `atlas_doc_format` | object | Body in Atlassian Document Format \(ADF\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| `version` | object | Page version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| `url` | string | Page URL |
|
| `url` | string | Page URL |
|
||||||
|
|
||||||
### `confluence_delete_page`
|
### `confluence_delete_page`
|
||||||
|
|
||||||
Delete a Confluence page. By default moves to trash; use purge=true to permanently delete.
|
Delete a Confluence page (moves it to trash where it can be restored).
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
@@ -165,7 +112,6 @@ Delete a Confluence page. By default moves to trash; use purge=true to permanent
|
|||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
||||||
| `pageId` | string | Yes | Confluence page ID to delete |
|
| `pageId` | string | Yes | Confluence page ID to delete |
|
||||||
| `purge` | boolean | No | If true, permanently deletes the page instead of moving to trash \(default: false\) |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
@@ -176,229 +122,6 @@ Delete a Confluence page. By default moves to trash; use purge=true to permanent
|
|||||||
| `pageId` | string | Deleted page ID |
|
| `pageId` | string | Deleted page ID |
|
||||||
| `deleted` | boolean | Deletion status |
|
| `deleted` | boolean | Deletion status |
|
||||||
|
|
||||||
### `confluence_list_pages_in_space`
|
|
||||||
|
|
||||||
List all pages within a specific Confluence space. Supports pagination and filtering by status.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `spaceId` | string | Yes | The ID of the Confluence space to list pages from |
|
|
||||||
| `limit` | number | No | Maximum number of pages to return \(default: 50, max: 250\) |
|
|
||||||
| `status` | string | No | Filter pages by status: current, archived, trashed, or draft |
|
|
||||||
| `bodyFormat` | string | No | Format for page body content: storage, atlas_doc_format, or view. If not specified, body is not included. |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response to get the next page of results |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `pages` | array | Array of pages in the space |
|
|
||||||
| ↳ `id` | string | Unique page identifier |
|
|
||||||
| ↳ `title` | string | Page title |
|
|
||||||
| ↳ `status` | string | Page status \(e.g., current, archived, trashed, draft\) |
|
|
||||||
| ↳ `spaceId` | string | ID of the space containing the page |
|
|
||||||
| ↳ `parentId` | string | ID of the parent page \(null if top-level\) |
|
|
||||||
| ↳ `authorId` | string | Account ID of the page author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp when the page was created |
|
|
||||||
| ↳ `version` | object | Page version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| ↳ `body` | object | Page body content \(if bodyFormat was specified\) |
|
|
||||||
| ↳ `storage` | object | Body in storage format \(Confluence markup\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `view` | object | Body in view format \(rendered HTML\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `atlas_doc_format` | object | Body in Atlassian Document Format \(ADF\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `webUrl` | string | URL to view the page in Confluence |
|
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_get_page_children`
|
|
||||||
|
|
||||||
Get all child pages of a specific Confluence page. Useful for navigating page hierarchies.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `pageId` | string | Yes | The ID of the parent page to get children from |
|
|
||||||
| `limit` | number | No | Maximum number of child pages to return \(default: 50, max: 250\) |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response to get the next page of results |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `parentId` | string | ID of the parent page |
|
|
||||||
| `children` | array | Array of child pages |
|
|
||||||
| ↳ `id` | string | Child page ID |
|
|
||||||
| ↳ `title` | string | Child page title |
|
|
||||||
| ↳ `status` | string | Page status |
|
|
||||||
| ↳ `spaceId` | string | Space ID |
|
|
||||||
| ↳ `childPosition` | number | Position among siblings |
|
|
||||||
| ↳ `webUrl` | string | URL to view the page |
|
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_get_page_ancestors`
|
|
||||||
|
|
||||||
Get the ancestor (parent) pages of a specific Confluence page. Returns the full hierarchy from the page up to the root.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `pageId` | string | Yes | The ID of the page to get ancestors for |
|
|
||||||
| `limit` | number | No | Maximum number of ancestors to return \(default: 25, max: 250\) |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `pageId` | string | ID of the page whose ancestors were retrieved |
|
|
||||||
| `ancestors` | array | Array of ancestor pages, ordered from direct parent to root |
|
|
||||||
| ↳ `id` | string | Ancestor page ID |
|
|
||||||
| ↳ `title` | string | Ancestor page title |
|
|
||||||
| ↳ `status` | string | Page status |
|
|
||||||
| ↳ `spaceId` | string | Space ID |
|
|
||||||
| ↳ `webUrl` | string | URL to view the page |
|
|
||||||
|
|
||||||
### `confluence_list_page_versions`
|
|
||||||
|
|
||||||
List all versions (revision history) of a Confluence page.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `pageId` | string | Yes | The ID of the page to get versions for |
|
|
||||||
| `limit` | number | No | Maximum number of versions to return \(default: 50, max: 250\) |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `pageId` | string | ID of the page |
|
|
||||||
| `versions` | array | Array of page versions |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_get_page_version`
|
|
||||||
|
|
||||||
Get details about a specific version of a Confluence page.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `pageId` | string | Yes | The ID of the page |
|
|
||||||
| `versionNumber` | number | Yes | The version number to retrieve \(e.g., 1, 2, 3\) |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `pageId` | string | ID of the page |
|
|
||||||
| `version` | object | Detailed version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| ↳ `contentTypeModified` | boolean | Whether the content type was modified in this version |
|
|
||||||
| ↳ `collaborators` | array | List of collaborator account IDs for this version |
|
|
||||||
| ↳ `prevVersion` | number | Previous version number |
|
|
||||||
| ↳ `nextVersion` | number | Next version number |
|
|
||||||
|
|
||||||
### `confluence_list_page_properties`
|
|
||||||
|
|
||||||
List all custom properties (metadata) attached to a Confluence page.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `pageId` | string | Yes | The ID of the page to list properties from |
|
|
||||||
| `limit` | number | No | Maximum number of properties to return \(default: 50, max: 250\) |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `pageId` | string | ID of the page |
|
|
||||||
| `properties` | array | Array of content properties |
|
|
||||||
| ↳ `id` | string | Property ID |
|
|
||||||
| ↳ `key` | string | Property key |
|
|
||||||
| ↳ `value` | json | Property value \(can be any JSON\) |
|
|
||||||
| ↳ `version` | object | Version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_create_page_property`
|
|
||||||
|
|
||||||
Create a new custom property (metadata) on a Confluence page.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `pageId` | string | Yes | The ID of the page to add the property to |
|
|
||||||
| `key` | string | Yes | The key/name for the property |
|
|
||||||
| `value` | json | Yes | The value for the property \(can be any JSON value\) |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `pageId` | string | ID of the page |
|
|
||||||
| `propertyId` | string | ID of the created property |
|
|
||||||
| `key` | string | Property key |
|
|
||||||
| `value` | json | Property value |
|
|
||||||
| `version` | object | Version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
|
|
||||||
### `confluence_search`
|
### `confluence_search`
|
||||||
|
|
||||||
Search for content across Confluence pages, blog posts, and other content.
|
Search for content across Confluence pages, blog posts, and other content.
|
||||||
@@ -432,211 +155,6 @@ Search for content across Confluence pages, blog posts, and other content.
|
|||||||
| ↳ `lastModified` | string | ISO 8601 timestamp of last modification |
|
| ↳ `lastModified` | string | ISO 8601 timestamp of last modification |
|
||||||
| ↳ `entityType` | string | Entity type identifier \(e.g., content, space\) |
|
| ↳ `entityType` | string | Entity type identifier \(e.g., content, space\) |
|
||||||
|
|
||||||
### `confluence_search_in_space`
|
|
||||||
|
|
||||||
Search for content within a specific Confluence space. Optionally filter by text query and content type.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `spaceKey` | string | Yes | The key of the Confluence space to search in \(e.g., "ENG", "HR"\) |
|
|
||||||
| `query` | string | No | Text search query. If not provided, returns all content in the space. |
|
|
||||||
| `contentType` | string | No | Filter by content type: page, blogpost, attachment, or comment |
|
|
||||||
| `limit` | number | No | Maximum number of results to return \(default: 25, max: 250\) |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `spaceKey` | string | The space key that was searched |
|
|
||||||
| `totalSize` | number | Total number of matching results |
|
|
||||||
| `results` | array | Array of search results |
|
|
||||||
| ↳ `id` | string | Unique content identifier |
|
|
||||||
| ↳ `title` | string | Content title |
|
|
||||||
| ↳ `type` | string | Content type \(e.g., page, blogpost, attachment, comment\) |
|
|
||||||
| ↳ `status` | string | Content status \(e.g., current\) |
|
|
||||||
| ↳ `url` | string | URL to view the content in Confluence |
|
|
||||||
| ↳ `excerpt` | string | Text excerpt matching the search query |
|
|
||||||
| ↳ `spaceKey` | string | Key of the space containing the content |
|
|
||||||
| ↳ `space` | object | Space information for the content |
|
|
||||||
| ↳ `id` | string | Space identifier |
|
|
||||||
| ↳ `key` | string | Space key |
|
|
||||||
| ↳ `name` | string | Space name |
|
|
||||||
| ↳ `lastModified` | string | ISO 8601 timestamp of last modification |
|
|
||||||
| ↳ `entityType` | string | Entity type identifier \(e.g., content, space\) |
|
|
||||||
|
|
||||||
### `confluence_list_blogposts`
|
|
||||||
|
|
||||||
List all blog posts across all accessible Confluence spaces.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `limit` | number | No | Maximum number of blog posts to return \(default: 25, max: 250\) |
|
|
||||||
| `status` | string | No | Filter by status: current, archived, trashed, or draft |
|
|
||||||
| `sort` | string | No | Sort order: created-date, -created-date, modified-date, -modified-date, title, -title |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `blogPosts` | array | Array of blog posts |
|
|
||||||
| ↳ `id` | string | Blog post ID |
|
|
||||||
| ↳ `title` | string | Blog post title |
|
|
||||||
| ↳ `status` | string | Blog post status |
|
|
||||||
| ↳ `spaceId` | string | Space ID |
|
|
||||||
| ↳ `authorId` | string | Author account ID |
|
|
||||||
| ↳ `createdAt` | string | Creation timestamp |
|
|
||||||
| ↳ `version` | object | Version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| ↳ `webUrl` | string | URL to view the blog post |
|
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_get_blogpost`
|
|
||||||
|
|
||||||
Get a specific Confluence blog post by ID, including its content.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `blogPostId` | string | Yes | The ID of the blog post to retrieve |
|
|
||||||
| `bodyFormat` | string | No | Format for blog post body: storage, atlas_doc_format, or view |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `id` | string | Blog post ID |
|
|
||||||
| `title` | string | Blog post title |
|
|
||||||
| `status` | string | Blog post status |
|
|
||||||
| `spaceId` | string | Space ID |
|
|
||||||
| `authorId` | string | Author account ID |
|
|
||||||
| `createdAt` | string | Creation timestamp |
|
|
||||||
| `version` | object | Version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| `body` | object | Blog post body content in requested format\(s\) |
|
|
||||||
| ↳ `storage` | object | Body in storage format \(Confluence markup\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `view` | object | Body in view format \(rendered HTML\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `atlas_doc_format` | object | Body in Atlassian Document Format \(ADF\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| `webUrl` | string | URL to view the blog post |
|
|
||||||
|
|
||||||
### `confluence_create_blogpost`
|
|
||||||
|
|
||||||
Create a new blog post in a Confluence space.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `spaceId` | string | Yes | The ID of the space to create the blog post in |
|
|
||||||
| `title` | string | Yes | Title of the blog post |
|
|
||||||
| `content` | string | Yes | Blog post content in Confluence storage format \(HTML\) |
|
|
||||||
| `status` | string | No | Blog post status: current \(default\) or draft |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `id` | string | Created blog post ID |
|
|
||||||
| `title` | string | Blog post title |
|
|
||||||
| `status` | string | Blog post status |
|
|
||||||
| `spaceId` | string | Space ID |
|
|
||||||
| `authorId` | string | Author account ID |
|
|
||||||
| `body` | object | Blog post body content |
|
|
||||||
| ↳ `storage` | object | Body in storage format \(Confluence markup\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `view` | object | Body in view format \(rendered HTML\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `atlas_doc_format` | object | Body in Atlassian Document Format \(ADF\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| `version` | object | Blog post version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| `webUrl` | string | URL to view the blog post |
|
|
||||||
|
|
||||||
### `confluence_list_blogposts_in_space`
|
|
||||||
|
|
||||||
List all blog posts within a specific Confluence space.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `spaceId` | string | Yes | The ID of the Confluence space to list blog posts from |
|
|
||||||
| `limit` | number | No | Maximum number of blog posts to return \(default: 25, max: 250\) |
|
|
||||||
| `status` | string | No | Filter by status: current, archived, trashed, or draft |
|
|
||||||
| `bodyFormat` | string | No | Format for blog post body: storage, atlas_doc_format, or view |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `blogPosts` | array | Array of blog posts in the space |
|
|
||||||
| ↳ `id` | string | Blog post ID |
|
|
||||||
| ↳ `title` | string | Blog post title |
|
|
||||||
| ↳ `status` | string | Blog post status |
|
|
||||||
| ↳ `spaceId` | string | Space ID |
|
|
||||||
| ↳ `authorId` | string | Author account ID |
|
|
||||||
| ↳ `createdAt` | string | Creation timestamp |
|
|
||||||
| ↳ `version` | object | Version information |
|
|
||||||
| ↳ `number` | number | Version number |
|
|
||||||
| ↳ `message` | string | Version message |
|
|
||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
|
||||||
| ↳ `body` | object | Blog post body content |
|
|
||||||
| ↳ `storage` | object | Body in storage format \(Confluence markup\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `view` | object | Body in view format \(rendered HTML\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `atlas_doc_format` | object | Body in Atlassian Document Format \(ADF\) |
|
|
||||||
| ↳ `value` | string | The content value in the specified format |
|
|
||||||
| ↳ `representation` | string | Content representation type |
|
|
||||||
| ↳ `webUrl` | string | URL to view the blog post |
|
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_create_comment`
|
### `confluence_create_comment`
|
||||||
|
|
||||||
Add a comment to a Confluence page.
|
Add a comment to a Confluence page.
|
||||||
@@ -669,8 +187,6 @@ List all comments on a Confluence page.
|
|||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
||||||
| `pageId` | string | Yes | Confluence page ID to list comments from |
|
| `pageId` | string | Yes | Confluence page ID to list comments from |
|
||||||
| `limit` | number | No | Maximum number of comments to return \(default: 25\) |
|
| `limit` | number | No | Maximum number of comments to return \(default: 25\) |
|
||||||
| `bodyFormat` | string | No | Format for the comment body: storage, atlas_doc_format, view, or export_view \(default: storage\) |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
@@ -696,7 +212,6 @@ List all comments on a Confluence page.
|
|||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
| ↳ `authorId` | string | Account ID of the version author |
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_update_comment`
|
### `confluence_update_comment`
|
||||||
|
|
||||||
@@ -776,8 +291,7 @@ List all attachments on a Confluence page.
|
|||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
||||||
| `pageId` | string | Yes | Confluence page ID to list attachments from |
|
| `pageId` | string | Yes | Confluence page ID to list attachments from |
|
||||||
| `limit` | number | No | Maximum number of attachments to return \(default: 50, max: 250\) |
|
| `limit` | number | No | Maximum number of attachments to return \(default: 25\) |
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
@@ -802,7 +316,6 @@ List all attachments on a Confluence page.
|
|||||||
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
| ↳ `minorEdit` | boolean | Whether this is a minor edit |
|
||||||
| ↳ `authorId` | string | Account ID of the version author |
|
| ↳ `authorId` | string | Account ID of the version author |
|
||||||
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
| ↳ `createdAt` | string | ISO 8601 timestamp of version creation |
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_delete_attachment`
|
### `confluence_delete_attachment`
|
||||||
|
|
||||||
@@ -834,8 +347,6 @@ List all labels on a Confluence page.
|
|||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
||||||
| `pageId` | string | Yes | Confluence page ID to list labels from |
|
| `pageId` | string | Yes | Confluence page ID to list labels from |
|
||||||
| `limit` | number | No | Maximum number of labels to return \(default: 25, max: 250\) |
|
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
@@ -847,30 +358,6 @@ List all labels on a Confluence page.
|
|||||||
| ↳ `id` | string | Unique label identifier |
|
| ↳ `id` | string | Unique label identifier |
|
||||||
| ↳ `name` | string | Label name |
|
| ↳ `name` | string | Label name |
|
||||||
| ↳ `prefix` | string | Label prefix/type \(e.g., global, my, team\) |
|
| ↳ `prefix` | string | Label prefix/type \(e.g., global, my, team\) |
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
### `confluence_add_label`
|
|
||||||
|
|
||||||
Add a label to a Confluence page for organization and categorization.
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `pageId` | string | Yes | Confluence page ID to add the label to |
|
|
||||||
| `labelName` | string | Yes | Name of the label to add |
|
|
||||||
| `prefix` | string | No | Label prefix: global \(default\), my, team, or system |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
|
||||||
| `pageId` | string | Page ID that the label was added to |
|
|
||||||
| `labelName` | string | Name of the added label |
|
|
||||||
| `labelId` | string | ID of the added label |
|
|
||||||
|
|
||||||
### `confluence_get_space`
|
### `confluence_get_space`
|
||||||
|
|
||||||
@@ -888,19 +375,13 @@ Get details about a specific Confluence space.
|
|||||||
|
|
||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `ts` | string | ISO 8601 timestamp of the operation |
|
| `ts` | string | Timestamp of retrieval |
|
||||||
| `spaceId` | string | Space ID |
|
| `spaceId` | string | Space ID |
|
||||||
| `name` | string | Space name |
|
| `name` | string | Space name |
|
||||||
| `key` | string | Space key |
|
| `key` | string | Space key |
|
||||||
| `type` | string | Space type \(global, personal\) |
|
| `type` | string | Space type |
|
||||||
| `status` | string | Space status \(current, archived\) |
|
| `status` | string | Space status |
|
||||||
| `url` | string | URL to view the space in Confluence |
|
| `url` | string | Space URL |
|
||||||
| `authorId` | string | Account ID of the space creator |
|
|
||||||
| `createdAt` | string | ISO 8601 timestamp when the space was created |
|
|
||||||
| `homepageId` | string | ID of the space homepage |
|
|
||||||
| `description` | object | Space description content |
|
|
||||||
| ↳ `value` | string | Description text content |
|
|
||||||
| ↳ `representation` | string | Content representation format \(e.g., plain, view, storage\) |
|
|
||||||
|
|
||||||
### `confluence_list_spaces`
|
### `confluence_list_spaces`
|
||||||
|
|
||||||
@@ -911,8 +392,7 @@ List all Confluence spaces accessible to the user.
|
|||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
| `domain` | string | Yes | Your Confluence domain \(e.g., yourcompany.atlassian.net\) |
|
||||||
| `limit` | number | No | Maximum number of spaces to return \(default: 25, max: 250\) |
|
| `limit` | number | No | Maximum number of spaces to return \(default: 25\) |
|
||||||
| `cursor` | string | No | Pagination cursor from previous response |
|
|
||||||
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
| `cloudId` | string | No | Confluence Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
@@ -932,6 +412,5 @@ List all Confluence spaces accessible to the user.
|
|||||||
| ↳ `description` | object | Space description |
|
| ↳ `description` | object | Space description |
|
||||||
| ↳ `value` | string | Description text content |
|
| ↳ `value` | string | Description text content |
|
||||||
| ↳ `representation` | string | Content representation format \(e.g., plain, view, storage\) |
|
| ↳ `representation` | string | Content representation format \(e.g., plain, view, storage\) |
|
||||||
| `nextCursor` | string | Cursor for fetching the next page of results |
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -63,7 +63,6 @@ Send a message to a Discord channel
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `message` | string | Success or error message |
|
| `message` | string | Success or error message |
|
||||||
| `files` | file[] | Files attached to the message |
|
|
||||||
| `data` | object | Discord message data |
|
| `data` | object | Discord message data |
|
||||||
| ↳ `id` | string | Message ID |
|
| ↳ `id` | string | Message ID |
|
||||||
| ↳ `content` | string | Message content |
|
| ↳ `content` | string | Message content |
|
||||||
|
|||||||
@@ -43,8 +43,7 @@ Upload a file to Dropbox
|
|||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `path` | string | Yes | The path in Dropbox where the file should be saved \(e.g., /folder/document.pdf\) |
|
| `path` | string | Yes | The path in Dropbox where the file should be saved \(e.g., /folder/document.pdf\) |
|
||||||
| `file` | file | No | The file to upload \(UserFile object\) |
|
| `fileContent` | string | Yes | The base64 encoded content of the file to upload |
|
||||||
| `fileContent` | string | No | Legacy: base64 encoded file content |
|
|
||||||
| `fileName` | string | No | Optional filename \(used if path is a folder\) |
|
| `fileName` | string | No | Optional filename \(used if path is a folder\) |
|
||||||
| `mode` | string | No | Write mode: add \(default\) or overwrite |
|
| `mode` | string | No | Write mode: add \(default\) or overwrite |
|
||||||
| `autorename` | boolean | No | If true, rename the file if there is a conflict |
|
| `autorename` | boolean | No | If true, rename the file if there is a conflict |
|
||||||
@@ -67,7 +66,7 @@ Upload a file to Dropbox
|
|||||||
|
|
||||||
### `dropbox_download`
|
### `dropbox_download`
|
||||||
|
|
||||||
Download a file from Dropbox with metadata and content
|
Download a file from Dropbox and get a temporary link
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
@@ -79,8 +78,11 @@ Download a file from Dropbox with metadata and content
|
|||||||
|
|
||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `file` | file | Downloaded file stored in execution files |
|
| `file` | object | The file metadata |
|
||||||
| `metadata` | json | The file metadata |
|
| ↳ `id` | string | Unique identifier for the file |
|
||||||
|
| ↳ `name` | string | Name of the file |
|
||||||
|
| ↳ `path_display` | string | Display path of the file |
|
||||||
|
| ↳ `size` | number | Size of the file in bytes |
|
||||||
| `temporaryLink` | string | Temporary link to download the file \(valid for ~4 hours\) |
|
| `temporaryLink` | string | Temporary link to download the file \(valid for ~4 hours\) |
|
||||||
| `content` | string | Base64 encoded file content \(if fetched\) |
|
| `content` | string | Base64 encoded file content \(if fetched\) |
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Read and parse multiple files
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="file_v3"
|
type="file_v2"
|
||||||
color="#40916C"
|
color="#40916C"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ The File Parser tool is particularly useful for scenarios where your agents need
|
|||||||
|
|
||||||
## Usage Instructions
|
## Usage Instructions
|
||||||
|
|
||||||
Upload files directly or import from external URLs to get UserFile objects for use in other blocks.
|
Integrate File into the workflow. Can upload a file manually or insert a file url.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -41,15 +41,14 @@ Parse one or more uploaded files or files from URLs (text, PDF, CSV, images, etc
|
|||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `filePath` | string | No | Path to the file\(s\). Can be a single path, URL, or an array of paths. |
|
| `filePath` | string | Yes | Path to the file\(s\). Can be a single path, URL, or an array of paths. |
|
||||||
| `file` | file | No | Uploaded file\(s\) to parse |
|
|
||||||
| `fileType` | string | No | Type of file to parse \(auto-detected if not specified\) |
|
| `fileType` | string | No | Type of file to parse \(auto-detected if not specified\) |
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `files` | file[] | Parsed files as UserFile objects |
|
| `files` | array | Array of parsed files with content, metadata, and file properties |
|
||||||
| `combinedContent` | string | Combined content of all parsed files |
|
| `combinedContent` | string | All file contents merged into a single text string |
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Interact with Fireflies.ai meeting transcripts and recordings
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="fireflies_v2"
|
type="fireflies"
|
||||||
color="#100730"
|
color="#100730"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -692,7 +692,6 @@ Get the content of a file from a GitHub repository. Supports files up to 1MB. Co
|
|||||||
| `download_url` | string | Direct download URL |
|
| `download_url` | string | Direct download URL |
|
||||||
| `git_url` | string | Git blob API URL |
|
| `git_url` | string | Git blob API URL |
|
||||||
| `_links` | json | Related links |
|
| `_links` | json | Related links |
|
||||||
| `file` | file | Downloaded file stored in execution files |
|
|
||||||
|
|
||||||
### `github_create_file`
|
### `github_create_file`
|
||||||
|
|
||||||
|
|||||||
@@ -291,7 +291,11 @@ Download a file from Google Drive with complete metadata (exports Google Workspa
|
|||||||
|
|
||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `file` | file | Downloaded file stored in execution files |
|
| `file` | object | Downloaded file data |
|
||||||
|
| ↳ `name` | string | File name |
|
||||||
|
| ↳ `mimeType` | string | MIME type of the file |
|
||||||
|
| ↳ `data` | string | File content as base64-encoded string |
|
||||||
|
| ↳ `size` | number | File size in bytes |
|
||||||
| `metadata` | object | Complete file metadata from Google Drive |
|
| `metadata` | object | Complete file metadata from Google Drive |
|
||||||
| ↳ `id` | string | Google Drive file ID |
|
| ↳ `id` | string | Google Drive file ID |
|
||||||
| ↳ `kind` | string | Resource type identifier |
|
| ↳ `kind` | string | Resource type identifier |
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Read, write, and create presentations
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="google_slides_v2"
|
type="google_slides"
|
||||||
color="#E0E0E0"
|
color="#E0E0E0"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -333,28 +333,6 @@ Get all attachments from a Jira issue
|
|||||||
| `issueKey` | string | Issue key |
|
| `issueKey` | string | Issue key |
|
||||||
| `attachments` | array | Array of attachments with id, filename, size, mimeType, created, author |
|
| `attachments` | array | Array of attachments with id, filename, size, mimeType, created, author |
|
||||||
|
|
||||||
### `jira_add_attachment`
|
|
||||||
|
|
||||||
Add attachments to a Jira issue
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `domain` | string | Yes | Your Jira domain \(e.g., yourcompany.atlassian.net\) |
|
|
||||||
| `issueKey` | string | Yes | Jira issue key to add attachments to \(e.g., PROJ-123\) |
|
|
||||||
| `files` | file[] | Yes | Files to attach to the Jira issue |
|
|
||||||
| `cloudId` | string | No | Jira Cloud ID for the instance. If not provided, it will be fetched using the domain. |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `ts` | string | Timestamp of the operation |
|
|
||||||
| `issueKey` | string | Issue key |
|
|
||||||
| `attachmentIds` | json | IDs of uploaded attachments |
|
|
||||||
| `files` | file[] | Uploaded attachment files |
|
|
||||||
|
|
||||||
### `jira_delete_attachment`
|
### `jira_delete_attachment`
|
||||||
|
|
||||||
Delete an attachment from a Jira issue
|
Delete an attachment from a Jira issue
|
||||||
|
|||||||
@@ -1022,8 +1022,7 @@ Add an attachment to an issue in Linear
|
|||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `issueId` | string | Yes | Issue ID to attach to |
|
| `issueId` | string | Yes | Issue ID to attach to |
|
||||||
| `url` | string | No | URL of the attachment |
|
| `url` | string | Yes | URL of the attachment |
|
||||||
| `file` | file | No | File to attach |
|
|
||||||
| `title` | string | Yes | Attachment title |
|
| `title` | string | Yes | Attachment title |
|
||||||
| `subtitle` | string | No | Attachment subtitle/description |
|
| `subtitle` | string | No | Attachment subtitle/description |
|
||||||
|
|
||||||
|
|||||||
@@ -81,7 +81,6 @@ Write or update content in a Microsoft Teams chat
|
|||||||
| `createdTime` | string | Timestamp when message was created |
|
| `createdTime` | string | Timestamp when message was created |
|
||||||
| `url` | string | Web URL to the message |
|
| `url` | string | Web URL to the message |
|
||||||
| `updatedContent` | boolean | Whether content was successfully updated |
|
| `updatedContent` | boolean | Whether content was successfully updated |
|
||||||
| `files` | file[] | Files attached to the message |
|
|
||||||
|
|
||||||
### `microsoft_teams_read_channel`
|
### `microsoft_teams_read_channel`
|
||||||
|
|
||||||
@@ -133,7 +132,6 @@ Write or send a message to a Microsoft Teams channel
|
|||||||
| `createdTime` | string | Timestamp when message was created |
|
| `createdTime` | string | Timestamp when message was created |
|
||||||
| `url` | string | Web URL to the message |
|
| `url` | string | Web URL to the message |
|
||||||
| `updatedContent` | boolean | Whether content was successfully updated |
|
| `updatedContent` | boolean | Whether content was successfully updated |
|
||||||
| `files` | file[] | Files attached to the message |
|
|
||||||
|
|
||||||
### `microsoft_teams_update_chat_message`
|
### `microsoft_teams_update_chat_message`
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Extract text from PDF documents
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="mistral_parse_v3"
|
type="mistral_parse_v2"
|
||||||
color="#000000"
|
color="#000000"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -35,12 +35,13 @@ Integrate Mistral Parse into the workflow. Can extract text from uploaded PDF do
|
|||||||
|
|
||||||
### `mistral_parser`
|
### `mistral_parser`
|
||||||
|
|
||||||
|
Parse PDF documents using Mistral OCR API
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `filePath` | string | No | URL to a PDF document to be processed |
|
| `filePath` | string | Yes | URL to a PDF document to be processed |
|
||||||
| `file` | file | No | Document file to be processed |
|
|
||||||
| `fileUpload` | object | No | File upload data from file-upload component |
|
| `fileUpload` | object | No | File upload data from file-upload component |
|
||||||
| `resultType` | string | No | Type of parsed result \(markdown, text, or json\). Defaults to markdown. |
|
| `resultType` | string | No | Type of parsed result \(markdown, text, or json\). Defaults to markdown. |
|
||||||
| `includeImageBase64` | boolean | No | Include base64-encoded images in the response |
|
| `includeImageBase64` | boolean | No | Include base64-encoded images in the response |
|
||||||
@@ -54,8 +55,27 @@ Integrate Mistral Parse into the workflow. Can extract text from uploaded PDF do
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `pages` | array | Array of page objects from Mistral OCR |
|
| `pages` | array | Array of page objects from Mistral OCR |
|
||||||
| `model` | string | Mistral OCR model identifier |
|
| ↳ `index` | number | Page index \(zero-based\) |
|
||||||
| `usage_info` | json | Usage statistics from the API |
|
| ↳ `markdown` | string | Extracted markdown content |
|
||||||
| `document_annotation` | string | Structured annotation data |
|
| ↳ `images` | array | Images extracted from this page with bounding boxes |
|
||||||
|
| ↳ `id` | string | Image identifier \(e.g., img-0.jpeg\) |
|
||||||
|
| ↳ `top_left_x` | number | Top-left X coordinate in pixels |
|
||||||
|
| ↳ `top_left_y` | number | Top-left Y coordinate in pixels |
|
||||||
|
| ↳ `bottom_right_x` | number | Bottom-right X coordinate in pixels |
|
||||||
|
| ↳ `bottom_right_y` | number | Bottom-right Y coordinate in pixels |
|
||||||
|
| ↳ `image_base64` | string | Base64-encoded image data \(when include_image_base64=true\) |
|
||||||
|
| ↳ `dimensions` | object | Page dimensions |
|
||||||
|
| ↳ `dpi` | number | Dots per inch |
|
||||||
|
| ↳ `height` | number | Page height in pixels |
|
||||||
|
| ↳ `width` | number | Page width in pixels |
|
||||||
|
| ↳ `tables` | array | Extracted tables as HTML/markdown \(when table_format is set\). Referenced via placeholders like \[tbl-0.html\] |
|
||||||
|
| ↳ `hyperlinks` | array | Array of URL strings detected in the page \(e.g., \["https://...", "mailto:..."\]\) |
|
||||||
|
| ↳ `header` | string | Page header content \(when extract_header=true\) |
|
||||||
|
| ↳ `footer` | string | Page footer content \(when extract_footer=true\) |
|
||||||
|
| `model` | string | Mistral OCR model identifier \(e.g., mistral-ocr-latest\) |
|
||||||
|
| `usage_info` | object | Usage and processing statistics |
|
||||||
|
| ↳ `pages_processed` | number | Total number of pages processed |
|
||||||
|
| ↳ `doc_size_bytes` | number | Document file size in bytes |
|
||||||
|
| `document_annotation` | string | Structured annotation data as JSON string \(when applicable\) |
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -113,26 +113,6 @@ Create a new page in Notion
|
|||||||
| `last_edited_time` | string | ISO 8601 last edit timestamp |
|
| `last_edited_time` | string | ISO 8601 last edit timestamp |
|
||||||
| `title` | string | Page title |
|
| `title` | string | Page title |
|
||||||
|
|
||||||
### `notion_update_page`
|
|
||||||
|
|
||||||
Update properties of a Notion page
|
|
||||||
|
|
||||||
#### Input
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
| --------- | ---- | -------- | ----------- |
|
|
||||||
| `pageId` | string | Yes | The UUID of the Notion page to update |
|
|
||||||
| `properties` | json | Yes | JSON object of properties to update |
|
|
||||||
|
|
||||||
#### Output
|
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
|
||||||
| --------- | ---- | ----------- |
|
|
||||||
| `id` | string | Page UUID |
|
|
||||||
| `url` | string | Notion page URL |
|
|
||||||
| `last_edited_time` | string | ISO 8601 last edit timestamp |
|
|
||||||
| `title` | string | Page title |
|
|
||||||
|
|
||||||
### `notion_query_database`
|
### `notion_query_database`
|
||||||
|
|
||||||
Query and filter Notion database entries with advanced filtering
|
Query and filter Notion database entries with advanced filtering
|
||||||
|
|||||||
@@ -152,7 +152,6 @@ Retrieve files from Pipedrive with optional filters
|
|||||||
| `person_id` | string | No | Filter files by person ID \(e.g., "456"\) |
|
| `person_id` | string | No | Filter files by person ID \(e.g., "456"\) |
|
||||||
| `org_id` | string | No | Filter files by organization ID \(e.g., "789"\) |
|
| `org_id` | string | No | Filter files by organization ID \(e.g., "789"\) |
|
||||||
| `limit` | string | No | Number of results to return \(e.g., "50", default: 100, max: 500\) |
|
| `limit` | string | No | Number of results to return \(e.g., "50", default: 100, max: 500\) |
|
||||||
| `downloadFiles` | boolean | No | Download file contents into file outputs |
|
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
@@ -169,7 +168,6 @@ Retrieve files from Pipedrive with optional filters
|
|||||||
| ↳ `person_id` | number | Associated person ID |
|
| ↳ `person_id` | number | Associated person ID |
|
||||||
| ↳ `org_id` | number | Associated organization ID |
|
| ↳ `org_id` | number | Associated organization ID |
|
||||||
| ↳ `url` | string | File download URL |
|
| ↳ `url` | string | File download URL |
|
||||||
| `downloadedFiles` | file[] | Downloaded files from Pipedrive |
|
|
||||||
| `total_items` | number | Total number of files returned |
|
| `total_items` | number | Total number of files returned |
|
||||||
| `success` | boolean | Operation success status |
|
| `success` | boolean | Operation success status |
|
||||||
|
|
||||||
|
|||||||
@@ -6,12 +6,12 @@ description: Extract text from documents using Pulse OCR
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="pulse_v2"
|
type="pulse"
|
||||||
color="#E0E0E0"
|
color="#E0E0E0"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* MANUAL-CONTENT-START:intro */}
|
{/* MANUAL-CONTENT-START:intro */}
|
||||||
The [Pulse](https://www.runpulse.com) tool enables seamless extraction of text and structured content from a wide variety of documents—including PDFs, images, and Office files—using state-of-the-art OCR (Optical Character Recognition) powered by Pulse. Designed for automated agentic workflows, Pulse Parser makes it easy to unlock valuable information trapped in unstructured documents and integrate the extracted content directly into your workflow.
|
The [Pulse](https://www.pulseapi.com/) tool enables seamless extraction of text and structured content from a wide variety of documents—including PDFs, images, and Office files—using state-of-the-art OCR (Optical Character Recognition) powered by Pulse. Designed for automated agentic workflows, Pulse Parser makes it easy to unlock valuable information trapped in unstructured documents and integrate the extracted content directly into your workflow.
|
||||||
|
|
||||||
With Pulse, you can:
|
With Pulse, you can:
|
||||||
|
|
||||||
@@ -31,7 +31,7 @@ If you need accurate, scalable, and developer-friendly document parsing capabili
|
|||||||
|
|
||||||
## Usage Instructions
|
## Usage Instructions
|
||||||
|
|
||||||
Integrate Pulse into the workflow. Extract text from PDF documents, images, and Office files via upload or file references.
|
Integrate Pulse into the workflow. Extract text from PDF documents, images, and Office files via URL or upload.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -39,12 +39,13 @@ Integrate Pulse into the workflow. Extract text from PDF documents, images, and
|
|||||||
|
|
||||||
### `pulse_parser`
|
### `pulse_parser`
|
||||||
|
|
||||||
|
Parse documents (PDF, images, Office docs) using Pulse OCR API
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `filePath` | string | No | URL to a document to be processed |
|
| `filePath` | string | Yes | URL to a document to be processed |
|
||||||
| `file` | file | No | Document file to be processed |
|
|
||||||
| `fileUpload` | object | No | File upload data from file-upload component |
|
| `fileUpload` | object | No | File upload data from file-upload component |
|
||||||
| `pages` | string | No | Page range to process \(1-indexed, e.g., "1-2,5"\) |
|
| `pages` | string | No | Page range to process \(1-indexed, e.g., "1-2,5"\) |
|
||||||
| `extractFigure` | boolean | No | Enable figure extraction from the document |
|
| `extractFigure` | boolean | No | Enable figure extraction from the document |
|
||||||
@@ -56,6 +57,16 @@ Integrate Pulse into the workflow. Extract text from PDF documents, images, and
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `markdown` | string | Extracted content in markdown format |
|
||||||
|
| `page_count` | number | Number of pages in the document |
|
||||||
|
| `job_id` | string | Unique job identifier |
|
||||||
|
| `bounding_boxes` | json | Bounding box layout information |
|
||||||
|
| `extraction_url` | string | URL for extraction results \(for large documents\) |
|
||||||
|
| `html` | string | HTML content if requested |
|
||||||
|
| `structured_output` | json | Structured output if schema was provided |
|
||||||
|
| `chunks` | json | Chunked content if chunking was enabled |
|
||||||
|
| `figures` | json | Extracted figures if figure extraction was enabled |
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Extract text from PDF documents
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="reducto_v2"
|
type="reducto"
|
||||||
color="#5c0c5c"
|
color="#5c0c5c"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@ Looking for reliable and scalable PDF parsing? Reducto is optimized for develope
|
|||||||
|
|
||||||
## Usage Instructions
|
## Usage Instructions
|
||||||
|
|
||||||
Integrate Reducto Parse into the workflow. Can extract text from uploaded PDF documents or file references.
|
Integrate Reducto Parse into the workflow. Can extract text from uploaded PDF documents, or from a URL.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -37,12 +37,13 @@ Integrate Reducto Parse into the workflow. Can extract text from uploaded PDF do
|
|||||||
|
|
||||||
### `reducto_parser`
|
### `reducto_parser`
|
||||||
|
|
||||||
|
Parse PDF documents using Reducto OCR API
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
| --------- | ---- | -------- | ----------- |
|
| --------- | ---- | -------- | ----------- |
|
||||||
| `filePath` | string | No | URL to a PDF document to be processed |
|
| `filePath` | string | Yes | URL to a PDF document to be processed |
|
||||||
| `file` | file | No | Document file to be processed |
|
|
||||||
| `fileUpload` | object | No | File upload data from file-upload component |
|
| `fileUpload` | object | No | File upload data from file-upload component |
|
||||||
| `pages` | array | No | Specific pages to process \(1-indexed page numbers\) |
|
| `pages` | array | No | Specific pages to process \(1-indexed page numbers\) |
|
||||||
| `tableOutputFormat` | string | No | Table output format \(html or markdown\). Defaults to markdown. |
|
| `tableOutputFormat` | string | No | Table output format \(html or markdown\). Defaults to markdown. |
|
||||||
@@ -50,6 +51,13 @@ Integrate Reducto Parse into the workflow. Can extract text from uploaded PDF do
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `job_id` | string | Unique identifier for the processing job |
|
||||||
|
| `duration` | number | Processing time in seconds |
|
||||||
|
| `usage` | json | Resource consumption data |
|
||||||
|
| `result` | json | Parsed document content with chunks and blocks |
|
||||||
|
| `pdf_url` | string | Storage URL of converted PDF |
|
||||||
|
| `studio_link` | string | Link to Reducto studio interface |
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -78,7 +78,6 @@ Retrieve an object from an AWS S3 bucket
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `url` | string | Pre-signed URL for downloading the S3 object |
|
| `url` | string | Pre-signed URL for downloading the S3 object |
|
||||||
| `file` | file | Downloaded file stored in execution files |
|
|
||||||
| `metadata` | object | File metadata including type, size, name, and last modified date |
|
| `metadata` | object | File metadata including type, size, name, and last modified date |
|
||||||
|
|
||||||
### `s3_list_objects`
|
### `s3_list_objects`
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ Send an email using SendGrid API
|
|||||||
| `bcc` | string | No | BCC email address |
|
| `bcc` | string | No | BCC email address |
|
||||||
| `replyTo` | string | No | Reply-to email address |
|
| `replyTo` | string | No | Reply-to email address |
|
||||||
| `replyToName` | string | No | Reply-to name |
|
| `replyToName` | string | No | Reply-to name |
|
||||||
| `attachments` | file[] | No | Files to attach to the email \(UserFile objects\) |
|
| `attachments` | file[] | No | Files to attach to the email as an array of attachment objects |
|
||||||
| `templateId` | string | No | SendGrid template ID to use |
|
| `templateId` | string | No | SendGrid template ID to use |
|
||||||
| `dynamicTemplateData` | json | No | JSON object of dynamic template data |
|
| `dynamicTemplateData` | json | No | JSON object of dynamic template data |
|
||||||
|
|
||||||
|
|||||||
@@ -97,7 +97,6 @@ Download a file from a remote SFTP server
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `success` | boolean | Whether the download was successful |
|
| `success` | boolean | Whether the download was successful |
|
||||||
| `file` | file | Downloaded file stored in execution files |
|
|
||||||
| `fileName` | string | Name of the downloaded file |
|
| `fileName` | string | Name of the downloaded file |
|
||||||
| `content` | string | File content \(text or base64 encoded\) |
|
| `content` | string | File content \(text or base64 encoded\) |
|
||||||
| `size` | number | File size in bytes |
|
| `size` | number | File size in bytes |
|
||||||
|
|||||||
@@ -144,7 +144,6 @@ Send messages to Slack channels or direct messages. Supports Slack mrkdwn format
|
|||||||
| `ts` | string | Message timestamp |
|
| `ts` | string | Message timestamp |
|
||||||
| `channel` | string | Channel ID where message was sent |
|
| `channel` | string | Channel ID where message was sent |
|
||||||
| `fileCount` | number | Number of files uploaded \(when files are attached\) |
|
| `fileCount` | number | Number of files uploaded \(when files are attached\) |
|
||||||
| `files` | file[] | Files attached to the message |
|
|
||||||
|
|
||||||
### `slack_canvas`
|
### `slack_canvas`
|
||||||
|
|
||||||
|
|||||||
@@ -170,7 +170,6 @@ Download a file from a remote SSH server
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `downloaded` | boolean | Whether the file was downloaded successfully |
|
| `downloaded` | boolean | Whether the file was downloaded successfully |
|
||||||
| `file` | file | Downloaded file stored in execution files |
|
|
||||||
| `fileContent` | string | File content \(base64 encoded for binary files\) |
|
| `fileContent` | string | File content \(base64 encoded for binary files\) |
|
||||||
| `fileName` | string | Name of the downloaded file |
|
| `fileName` | string | Name of the downloaded file |
|
||||||
| `remotePath` | string | Source path on the remote server |
|
| `remotePath` | string | Source path on the remote server |
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Convert speech to text using AI
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="stt_v2"
|
type="stt"
|
||||||
color="#181C1E"
|
color="#181C1E"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -50,6 +50,8 @@ Transcribe audio and video files to text using leading AI providers. Supports mu
|
|||||||
|
|
||||||
### `stt_whisper`
|
### `stt_whisper`
|
||||||
|
|
||||||
|
Transcribe audio to text using OpenAI Whisper
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
@@ -69,10 +71,22 @@ Transcribe audio and video files to text using leading AI providers. Supports mu
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `transcript` | string | Full transcribed text |
|
||||||
|
| `segments` | array | Timestamped segments |
|
||||||
|
| ↳ `text` | string | Transcribed text for this segment |
|
||||||
|
| ↳ `start` | number | Start time in seconds |
|
||||||
|
| ↳ `end` | number | End time in seconds |
|
||||||
|
| ↳ `speaker` | string | Speaker identifier \(if diarization enabled\) |
|
||||||
|
| ↳ `confidence` | number | Confidence score \(0-1\) |
|
||||||
|
| `language` | string | Detected or specified language |
|
||||||
|
| `duration` | number | Audio duration in seconds |
|
||||||
|
|
||||||
### `stt_deepgram`
|
### `stt_deepgram`
|
||||||
|
|
||||||
|
Transcribe audio to text using Deepgram
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
@@ -89,10 +103,23 @@ This tool does not produce any outputs.
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `transcript` | string | Full transcribed text |
|
||||||
|
| `segments` | array | Timestamped segments with speaker labels |
|
||||||
|
| ↳ `text` | string | Transcribed text for this segment |
|
||||||
|
| ↳ `start` | number | Start time in seconds |
|
||||||
|
| ↳ `end` | number | End time in seconds |
|
||||||
|
| ↳ `speaker` | string | Speaker identifier \(if diarization enabled\) |
|
||||||
|
| ↳ `confidence` | number | Confidence score \(0-1\) |
|
||||||
|
| `language` | string | Detected or specified language |
|
||||||
|
| `duration` | number | Audio duration in seconds |
|
||||||
|
| `confidence` | number | Overall confidence score |
|
||||||
|
|
||||||
### `stt_elevenlabs`
|
### `stt_elevenlabs`
|
||||||
|
|
||||||
|
Transcribe audio to text using ElevenLabs
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
@@ -108,10 +135,18 @@ This tool does not produce any outputs.
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `transcript` | string | Full transcribed text |
|
||||||
|
| `segments` | array | Timestamped segments |
|
||||||
|
| `language` | string | Detected or specified language |
|
||||||
|
| `duration` | number | Audio duration in seconds |
|
||||||
|
| `confidence` | number | Overall confidence score |
|
||||||
|
|
||||||
### `stt_assemblyai`
|
### `stt_assemblyai`
|
||||||
|
|
||||||
|
Transcribe audio to text using AssemblyAI with advanced NLP features
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
@@ -132,10 +167,35 @@ This tool does not produce any outputs.
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `transcript` | string | Full transcribed text |
|
||||||
|
| `segments` | array | Timestamped segments with speaker labels |
|
||||||
|
| ↳ `text` | string | Transcribed text for this segment |
|
||||||
|
| ↳ `start` | number | Start time in seconds |
|
||||||
|
| ↳ `end` | number | End time in seconds |
|
||||||
|
| ↳ `speaker` | string | Speaker identifier \(if diarization enabled\) |
|
||||||
|
| ↳ `confidence` | number | Confidence score \(0-1\) |
|
||||||
|
| `language` | string | Detected or specified language |
|
||||||
|
| `duration` | number | Audio duration in seconds |
|
||||||
|
| `confidence` | number | Overall confidence score |
|
||||||
|
| `sentiment` | array | Sentiment analysis results |
|
||||||
|
| ↳ `text` | string | Text that was analyzed |
|
||||||
|
| ↳ `sentiment` | string | Sentiment \(POSITIVE, NEGATIVE, NEUTRAL\) |
|
||||||
|
| ↳ `confidence` | number | Confidence score |
|
||||||
|
| ↳ `start` | number | Start time in milliseconds |
|
||||||
|
| ↳ `end` | number | End time in milliseconds |
|
||||||
|
| `entities` | array | Detected entities |
|
||||||
|
| ↳ `entity_type` | string | Entity type \(e.g., person_name, location, organization\) |
|
||||||
|
| ↳ `text` | string | Entity text |
|
||||||
|
| ↳ `start` | number | Start time in milliseconds |
|
||||||
|
| ↳ `end` | number | End time in milliseconds |
|
||||||
|
| `summary` | string | Auto-generated summary |
|
||||||
|
|
||||||
### `stt_gemini`
|
### `stt_gemini`
|
||||||
|
|
||||||
|
Transcribe audio to text using Google Gemini with multimodal capabilities
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
@@ -151,6 +211,12 @@ This tool does not produce any outputs.
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `transcript` | string | Full transcribed text |
|
||||||
|
| `segments` | array | Timestamped segments |
|
||||||
|
| `language` | string | Detected or specified language |
|
||||||
|
| `duration` | number | Audio duration in seconds |
|
||||||
|
| `confidence` | number | Overall confidence score |
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -354,7 +354,6 @@ Send documents (PDF, ZIP, DOC, etc.) to Telegram channels or users through the T
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `message` | string | Success or error message |
|
| `message` | string | Success or error message |
|
||||||
| `files` | file[] | Files attached to the message |
|
|
||||||
| `data` | object | Telegram message data including document |
|
| `data` | object | Telegram message data including document |
|
||||||
| ↳ `message_id` | number | Unique Telegram message identifier |
|
| ↳ `message_id` | number | Unique Telegram message identifier |
|
||||||
| ↳ `from` | object | Information about the sender |
|
| ↳ `from` | object | Information about the sender |
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Extract text, tables, and forms from documents
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="textract_v2"
|
type="textract"
|
||||||
color="linear-gradient(135deg, #055F4E 0%, #56C0A7 100%)"
|
color="linear-gradient(135deg, #055F4E 0%, #56C0A7 100%)"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -35,6 +35,8 @@ Integrate AWS Textract into your workflow to extract text, tables, forms, and ke
|
|||||||
|
|
||||||
### `textract_parser`
|
### `textract_parser`
|
||||||
|
|
||||||
|
Parse documents using AWS Textract OCR and document analysis
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
@@ -44,8 +46,8 @@ Integrate AWS Textract into your workflow to extract text, tables, forms, and ke
|
|||||||
| `region` | string | Yes | AWS region for Textract service \(e.g., us-east-1\) |
|
| `region` | string | Yes | AWS region for Textract service \(e.g., us-east-1\) |
|
||||||
| `processingMode` | string | No | Document type: single-page or multi-page. Defaults to single-page. |
|
| `processingMode` | string | No | Document type: single-page or multi-page. Defaults to single-page. |
|
||||||
| `filePath` | string | No | URL to a document to be processed \(JPEG, PNG, or single-page PDF\). |
|
| `filePath` | string | No | URL to a document to be processed \(JPEG, PNG, or single-page PDF\). |
|
||||||
| `file` | file | No | Document file to be processed \(JPEG, PNG, or single-page PDF\). |
|
|
||||||
| `s3Uri` | string | No | S3 URI for multi-page processing \(s3://bucket/key\). |
|
| `s3Uri` | string | No | S3 URI for multi-page processing \(s3://bucket/key\). |
|
||||||
|
| `fileUpload` | object | No | File upload data from file-upload component |
|
||||||
| `featureTypes` | array | No | Feature types to detect: TABLES, FORMS, QUERIES, SIGNATURES, LAYOUT. If not specified, only text detection is performed. |
|
| `featureTypes` | array | No | Feature types to detect: TABLES, FORMS, QUERIES, SIGNATURES, LAYOUT. If not specified, only text detection is performed. |
|
||||||
| `items` | string | No | Feature type |
|
| `items` | string | No | Feature type |
|
||||||
| `queries` | array | No | Custom queries to extract specific information. Only used when featureTypes includes QUERIES. |
|
| `queries` | array | No | Custom queries to extract specific information. Only used when featureTypes includes QUERIES. |
|
||||||
@@ -56,6 +58,39 @@ Integrate AWS Textract into your workflow to extract text, tables, forms, and ke
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `blocks` | array | Array of Block objects containing detected text, tables, forms, and other elements |
|
||||||
|
| ↳ `BlockType` | string | Type of block \(PAGE, LINE, WORD, TABLE, CELL, KEY_VALUE_SET, etc.\) |
|
||||||
|
| ↳ `Id` | string | Unique identifier for the block |
|
||||||
|
| ↳ `Text` | string | The text content \(for LINE and WORD blocks\) |
|
||||||
|
| ↳ `TextType` | string | Type of text \(PRINTED or HANDWRITING\) |
|
||||||
|
| ↳ `Confidence` | number | Confidence score \(0-100\) |
|
||||||
|
| ↳ `Page` | number | Page number |
|
||||||
|
| ↳ `Geometry` | object | Location and bounding box information |
|
||||||
|
| ↳ `BoundingBox` | object | Height as ratio of document height |
|
||||||
|
| ↳ `Height` | number | Height as ratio of document height |
|
||||||
|
| ↳ `Left` | number | Left position as ratio of document width |
|
||||||
|
| ↳ `Top` | number | Top position as ratio of document height |
|
||||||
|
| ↳ `Width` | number | Width as ratio of document width |
|
||||||
|
| ↳ `Polygon` | array | Polygon coordinates |
|
||||||
|
| ↳ `X` | number | X coordinate |
|
||||||
|
| ↳ `Y` | number | Y coordinate |
|
||||||
|
| ↳ `Relationships` | array | Relationships to other blocks |
|
||||||
|
| ↳ `Type` | string | Relationship type \(CHILD, VALUE, ANSWER, etc.\) |
|
||||||
|
| ↳ `Ids` | array | IDs of related blocks |
|
||||||
|
| ↳ `EntityTypes` | array | Entity types for KEY_VALUE_SET \(KEY or VALUE\) |
|
||||||
|
| ↳ `SelectionStatus` | string | For checkboxes: SELECTED or NOT_SELECTED |
|
||||||
|
| ↳ `RowIndex` | number | Row index for table cells |
|
||||||
|
| ↳ `ColumnIndex` | number | Column index for table cells |
|
||||||
|
| ↳ `RowSpan` | number | Row span for merged cells |
|
||||||
|
| ↳ `ColumnSpan` | number | Column span for merged cells |
|
||||||
|
| ↳ `Query` | object | Query information for QUERY blocks |
|
||||||
|
| ↳ `Text` | string | Query text |
|
||||||
|
| ↳ `Alias` | string | Query alias |
|
||||||
|
| ↳ `Pages` | array | Pages to search |
|
||||||
|
| `documentMetadata` | object | Metadata about the analyzed document |
|
||||||
|
| ↳ `pages` | number | Number of pages in the document |
|
||||||
|
| `modelVersion` | string | Version of the Textract model used for processing |
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -122,7 +122,6 @@ Retrieve call recording information and transcription (if enabled via TwiML).
|
|||||||
| `channels` | number | Number of channels \(1 for mono, 2 for dual\) |
|
| `channels` | number | Number of channels \(1 for mono, 2 for dual\) |
|
||||||
| `source` | string | How the recording was created |
|
| `source` | string | How the recording was created |
|
||||||
| `mediaUrl` | string | URL to download the recording media file |
|
| `mediaUrl` | string | URL to download the recording media file |
|
||||||
| `file` | file | Downloaded recording media file |
|
|
||||||
| `price` | string | Cost of the recording |
|
| `price` | string | Cost of the recording |
|
||||||
| `priceUnit` | string | Currency of the price |
|
| `priceUnit` | string | Currency of the price |
|
||||||
| `uri` | string | Relative URI of the recording resource |
|
| `uri` | string | Relative URI of the recording resource |
|
||||||
|
|||||||
@@ -75,7 +75,6 @@ Download files uploaded in Typeform responses
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `fileUrl` | string | Direct download URL for the uploaded file |
|
| `fileUrl` | string | Direct download URL for the uploaded file |
|
||||||
| `file` | file | Downloaded file stored in execution files |
|
|
||||||
| `contentType` | string | MIME type of the uploaded file |
|
| `contentType` | string | MIME type of the uploaded file |
|
||||||
| `filename` | string | Original filename of the uploaded file |
|
| `filename` | string | Original filename of the uploaded file |
|
||||||
|
|
||||||
|
|||||||
@@ -57,14 +57,14 @@ Generate videos using Runway Gen-4 with world consistency and visual references
|
|||||||
| `duration` | number | No | Video duration in seconds \(5 or 10, default: 5\) |
|
| `duration` | number | No | Video duration in seconds \(5 or 10, default: 5\) |
|
||||||
| `aspectRatio` | string | No | Aspect ratio: 16:9 \(landscape\), 9:16 \(portrait\), or 1:1 \(square\) |
|
| `aspectRatio` | string | No | Aspect ratio: 16:9 \(landscape\), 9:16 \(portrait\), or 1:1 \(square\) |
|
||||||
| `resolution` | string | No | Video resolution \(720p output\). Note: Gen-4 Turbo outputs at 720p natively |
|
| `resolution` | string | No | Video resolution \(720p output\). Note: Gen-4 Turbo outputs at 720p natively |
|
||||||
| `visualReference` | file | Yes | Reference image REQUIRED for Gen-4 \(UserFile object\). Gen-4 only supports image-to-video, not text-only generation |
|
| `visualReference` | json | Yes | Reference image REQUIRED for Gen-4 \(UserFile object\). Gen-4 only supports image-to-video, not text-only generation |
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `videoUrl` | string | Generated video URL |
|
| `videoUrl` | string | Generated video URL |
|
||||||
| `videoFile` | file | Video file object with metadata |
|
| `videoFile` | json | Video file object with metadata |
|
||||||
| `duration` | number | Video duration in seconds |
|
| `duration` | number | Video duration in seconds |
|
||||||
| `width` | number | Video width in pixels |
|
| `width` | number | Video width in pixels |
|
||||||
| `height` | number | Video height in pixels |
|
| `height` | number | Video height in pixels |
|
||||||
@@ -93,7 +93,7 @@ Generate videos using Google Veo 3/3.1 with native audio generation
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `videoUrl` | string | Generated video URL |
|
| `videoUrl` | string | Generated video URL |
|
||||||
| `videoFile` | file | Video file object with metadata |
|
| `videoFile` | json | Video file object with metadata |
|
||||||
| `duration` | number | Video duration in seconds |
|
| `duration` | number | Video duration in seconds |
|
||||||
| `width` | number | Video width in pixels |
|
| `width` | number | Video width in pixels |
|
||||||
| `height` | number | Video height in pixels |
|
| `height` | number | Video height in pixels |
|
||||||
@@ -123,7 +123,7 @@ Generate videos using Luma Dream Machine with advanced camera controls
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `videoUrl` | string | Generated video URL |
|
| `videoUrl` | string | Generated video URL |
|
||||||
| `videoFile` | file | Video file object with metadata |
|
| `videoFile` | json | Video file object with metadata |
|
||||||
| `duration` | number | Video duration in seconds |
|
| `duration` | number | Video duration in seconds |
|
||||||
| `width` | number | Video width in pixels |
|
| `width` | number | Video width in pixels |
|
||||||
| `height` | number | Video height in pixels |
|
| `height` | number | Video height in pixels |
|
||||||
@@ -151,7 +151,7 @@ Generate videos using MiniMax Hailuo through MiniMax Platform API with advanced
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `videoUrl` | string | Generated video URL |
|
| `videoUrl` | string | Generated video URL |
|
||||||
| `videoFile` | file | Video file object with metadata |
|
| `videoFile` | json | Video file object with metadata |
|
||||||
| `duration` | number | Video duration in seconds |
|
| `duration` | number | Video duration in seconds |
|
||||||
| `width` | number | Video width in pixels |
|
| `width` | number | Video width in pixels |
|
||||||
| `height` | number | Video height in pixels |
|
| `height` | number | Video height in pixels |
|
||||||
@@ -181,7 +181,7 @@ Generate videos using Fal.ai platform with access to multiple models including V
|
|||||||
| Parameter | Type | Description |
|
| Parameter | Type | Description |
|
||||||
| --------- | ---- | ----------- |
|
| --------- | ---- | ----------- |
|
||||||
| `videoUrl` | string | Generated video URL |
|
| `videoUrl` | string | Generated video URL |
|
||||||
| `videoFile` | file | Video file object with metadata |
|
| `videoFile` | json | Video file object with metadata |
|
||||||
| `duration` | number | Video duration in seconds |
|
| `duration` | number | Video duration in seconds |
|
||||||
| `width` | number | Video width in pixels |
|
| `width` | number | Video width in pixels |
|
||||||
| `height` | number | Video height in pixels |
|
| `height` | number | Video height in pixels |
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Analyze images with vision models
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="vision_v2"
|
type="vision"
|
||||||
color="#4D5FFF"
|
color="#4D5FFF"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -35,6 +35,8 @@ Integrate Vision into the workflow. Can analyze images with vision models.
|
|||||||
|
|
||||||
### `vision_tool`
|
### `vision_tool`
|
||||||
|
|
||||||
|
Process and analyze images using advanced vision models. Capable of understanding image content, extracting text, identifying objects, and providing detailed visual descriptions.
|
||||||
|
|
||||||
#### Input
|
#### Input
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
@@ -47,6 +49,14 @@ Integrate Vision into the workflow. Can analyze images with vision models.
|
|||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
This tool does not produce any outputs.
|
| Parameter | Type | Description |
|
||||||
|
| --------- | ---- | ----------- |
|
||||||
|
| `content` | string | The analyzed content and description of the image |
|
||||||
|
| `model` | string | The vision model that was used for analysis |
|
||||||
|
| `tokens` | number | Total tokens used for the analysis |
|
||||||
|
| `usage` | object | Detailed token usage breakdown |
|
||||||
|
| ↳ `input_tokens` | number | Tokens used for input processing |
|
||||||
|
| ↳ `output_tokens` | number | Tokens used for response generation |
|
||||||
|
| ↳ `total_tokens` | number | Total tokens consumed |
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -335,7 +335,6 @@ Get all recordings for a specific Zoom meeting
|
|||||||
| `meetingId` | string | Yes | The meeting ID or meeting UUID \(e.g., "1234567890" or "4444AAABBBccccc12345=="\) |
|
| `meetingId` | string | Yes | The meeting ID or meeting UUID \(e.g., "1234567890" or "4444AAABBBccccc12345=="\) |
|
||||||
| `includeFolderItems` | boolean | No | Include items within a folder |
|
| `includeFolderItems` | boolean | No | Include items within a folder |
|
||||||
| `ttl` | number | No | Time to live for download URLs in seconds \(max 604800\) |
|
| `ttl` | number | No | Time to live for download URLs in seconds \(max 604800\) |
|
||||||
| `downloadFiles` | boolean | No | Download recording files into file outputs |
|
|
||||||
|
|
||||||
#### Output
|
#### Output
|
||||||
|
|
||||||
@@ -365,7 +364,6 @@ Get all recordings for a specific Zoom meeting
|
|||||||
| ↳ `download_url` | string | URL to download the recording |
|
| ↳ `download_url` | string | URL to download the recording |
|
||||||
| ↳ `status` | string | Recording status |
|
| ↳ `status` | string | Recording status |
|
||||||
| ↳ `recording_type` | string | Type of recording \(shared_screen, audio_only, etc.\) |
|
| ↳ `recording_type` | string | Type of recording \(shared_screen, audio_only, etc.\) |
|
||||||
| `files` | file[] | Downloaded recording files |
|
|
||||||
|
|
||||||
### `zoom_delete_recording`
|
### `zoom_delete_recording`
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Leer y analizar múltiples archivos
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="file_v3"
|
type="file"
|
||||||
color="#40916C"
|
color="#40916C"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Interactúa con transcripciones y grabaciones de reuniones de Firef
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="fireflies_v2"
|
type="fireflies"
|
||||||
color="#100730"
|
color="#100730"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Extraer texto de documentos PDF
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="mistral_parse_v3"
|
type="mistral_parse"
|
||||||
color="#000000"
|
color="#000000"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Lire et analyser plusieurs fichiers
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="file_v3"
|
type="file"
|
||||||
color="#40916C"
|
color="#40916C"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ description: Interagissez avec les transcriptions et enregistrements de réunion
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="fireflies_v2"
|
type="fireflies"
|
||||||
color="#100730"
|
color="#100730"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Extraire du texte à partir de documents PDF
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="mistral_parse_v3"
|
type="mistral_parse"
|
||||||
color="#000000"
|
color="#000000"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: 複数のファイルを読み込んで解析する
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="file_v3"
|
type="file"
|
||||||
color="#40916C"
|
color="#40916C"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: Fireflies.aiの会議文字起こしと録画を操作
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="fireflies_v2"
|
type="fireflies"
|
||||||
color="#100730"
|
color="#100730"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: PDFドキュメントからテキストを抽出する
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="mistral_parse_v3"
|
type="mistral_parse"
|
||||||
color="#000000"
|
color="#000000"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: 读取并解析多个文件
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="file_v3"
|
type="file"
|
||||||
color="#40916C"
|
color="#40916C"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: 与 Fireflies.ai 会议转录和录音进行交互
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="fireflies_v2"
|
type="fireflies"
|
||||||
color="#100730"
|
color="#100730"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ description: 从 PDF 文档中提取文本
|
|||||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||||
|
|
||||||
<BlockInfoCard
|
<BlockInfoCard
|
||||||
type="mistral_parse_v3"
|
type="mistral_parse"
|
||||||
color="#000000"
|
color="#000000"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 34 KiB |
@@ -1,7 +1,7 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
|
import { useBrandConfig } from '@/lib/branding/branding'
|
||||||
import { inter } from '@/app/_styles/fonts/inter/inter'
|
import { inter } from '@/app/_styles/fonts/inter/inter'
|
||||||
import { useBrandConfig } from '@/ee/whitelabeling'
|
|
||||||
|
|
||||||
export interface SupportFooterProps {
|
export interface SupportFooterProps {
|
||||||
/** Position style - 'fixed' for pages without AuthLayout, 'absolute' for pages with AuthLayout */
|
/** Position style - 'fixed' for pages without AuthLayout, 'absolute' for pages with AuthLayout */
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
Database,
|
Database,
|
||||||
DollarSign,
|
DollarSign,
|
||||||
HardDrive,
|
HardDrive,
|
||||||
Timer,
|
Workflow,
|
||||||
} from 'lucide-react'
|
} from 'lucide-react'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { cn } from '@/lib/core/utils/cn'
|
import { cn } from '@/lib/core/utils/cn'
|
||||||
@@ -44,7 +44,7 @@ interface PricingTier {
|
|||||||
const FREE_PLAN_FEATURES: PricingFeature[] = [
|
const FREE_PLAN_FEATURES: PricingFeature[] = [
|
||||||
{ icon: DollarSign, text: '$20 usage limit' },
|
{ icon: DollarSign, text: '$20 usage limit' },
|
||||||
{ icon: HardDrive, text: '5GB file storage' },
|
{ icon: HardDrive, text: '5GB file storage' },
|
||||||
{ icon: Timer, text: '5 min execution limit' },
|
{ icon: Workflow, text: 'Public template access' },
|
||||||
{ icon: Database, text: 'Limited log retention' },
|
{ icon: Database, text: 'Limited log retention' },
|
||||||
{ icon: Code2, text: 'CLI/SDK Access' },
|
{ icon: Code2, text: 'CLI/SDK Access' },
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ import Image from 'next/image'
|
|||||||
import Link from 'next/link'
|
import Link from 'next/link'
|
||||||
import { useRouter } from 'next/navigation'
|
import { useRouter } from 'next/navigation'
|
||||||
import { GithubIcon } from '@/components/icons'
|
import { GithubIcon } from '@/components/icons'
|
||||||
|
import { useBrandConfig } from '@/lib/branding/branding'
|
||||||
import { isHosted } from '@/lib/core/config/feature-flags'
|
import { isHosted } from '@/lib/core/config/feature-flags'
|
||||||
import { soehne } from '@/app/_styles/fonts/soehne/soehne'
|
import { soehne } from '@/app/_styles/fonts/soehne/soehne'
|
||||||
import { getFormattedGitHubStars } from '@/app/(landing)/actions/github'
|
import { getFormattedGitHubStars } from '@/app/(landing)/actions/github'
|
||||||
import { useBrandConfig } from '@/ee/whitelabeling'
|
|
||||||
import { useBrandedButtonClass } from '@/hooks/use-branded-button-class'
|
import { useBrandedButtonClass } from '@/hooks/use-branded-button-class'
|
||||||
|
|
||||||
const logger = createLogger('nav')
|
const logger = createLogger('nav')
|
||||||
|
|||||||
@@ -14,8 +14,9 @@ import {
|
|||||||
parseWorkflowSSEChunk,
|
parseWorkflowSSEChunk,
|
||||||
} from '@/lib/a2a/utils'
|
} from '@/lib/a2a/utils'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
|
import { getBrandConfig } from '@/lib/branding/branding'
|
||||||
import { acquireLock, getRedisClient, releaseLock } from '@/lib/core/config/redis'
|
import { acquireLock, getRedisClient, releaseLock } from '@/lib/core/config/redis'
|
||||||
import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server'
|
import { validateExternalUrl } from '@/lib/core/security/input-validation'
|
||||||
import { SSE_HEADERS } from '@/lib/core/utils/sse'
|
import { SSE_HEADERS } from '@/lib/core/utils/sse'
|
||||||
import { getBaseUrl } from '@/lib/core/utils/urls'
|
import { getBaseUrl } from '@/lib/core/utils/urls'
|
||||||
import { markExecutionCancelled } from '@/lib/execution/cancellation'
|
import { markExecutionCancelled } from '@/lib/execution/cancellation'
|
||||||
@@ -34,7 +35,6 @@ import {
|
|||||||
type PushNotificationSetParams,
|
type PushNotificationSetParams,
|
||||||
type TaskIdParams,
|
type TaskIdParams,
|
||||||
} from '@/app/api/a2a/serve/[agentId]/utils'
|
} from '@/app/api/a2a/serve/[agentId]/utils'
|
||||||
import { getBrandConfig } from '@/ee/whitelabeling'
|
|
||||||
|
|
||||||
const logger = createLogger('A2AServeAPI')
|
const logger = createLogger('A2AServeAPI')
|
||||||
|
|
||||||
@@ -1119,7 +1119,7 @@ async function handlePushNotificationSet(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const urlValidation = await validateUrlWithDNS(
|
const urlValidation = validateExternalUrl(
|
||||||
params.pushNotificationConfig.url,
|
params.pushNotificationConfig.url,
|
||||||
'Push notification URL'
|
'Push notification URL'
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ const UpdateCreatorProfileSchema = z.object({
|
|||||||
name: z.string().min(1, 'Name is required').max(100, 'Max 100 characters').optional(),
|
name: z.string().min(1, 'Name is required').max(100, 'Max 100 characters').optional(),
|
||||||
profileImageUrl: z.string().optional().or(z.literal('')),
|
profileImageUrl: z.string().optional().or(z.literal('')),
|
||||||
details: CreatorProfileDetailsSchema.optional(),
|
details: CreatorProfileDetailsSchema.optional(),
|
||||||
verified: z.boolean().optional(), // Verification status (super users only)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// Helper to check if user has permission to manage profile
|
// Helper to check if user has permission to manage profile
|
||||||
@@ -98,29 +97,11 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
|
|||||||
return NextResponse.json({ error: 'Profile not found' }, { status: 404 })
|
return NextResponse.json({ error: 'Profile not found' }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verification changes require super user permission
|
// Check permissions
|
||||||
if (data.verified !== undefined) {
|
const canEdit = await hasPermission(session.user.id, existing[0])
|
||||||
const { verifyEffectiveSuperUser } = await import('@/lib/templates/permissions')
|
if (!canEdit) {
|
||||||
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
|
logger.warn(`[${requestId}] User denied permission to update profile: ${id}`)
|
||||||
if (!effectiveSuperUser) {
|
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||||
logger.warn(`[${requestId}] Non-super user attempted to change creator verification: ${id}`)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Only super users can change verification status' },
|
|
||||||
{ status: 403 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// For non-verified updates, check regular permissions
|
|
||||||
const hasNonVerifiedUpdates =
|
|
||||||
data.name !== undefined || data.profileImageUrl !== undefined || data.details !== undefined
|
|
||||||
|
|
||||||
if (hasNonVerifiedUpdates) {
|
|
||||||
const canEdit = await hasPermission(session.user.id, existing[0])
|
|
||||||
if (!canEdit) {
|
|
||||||
logger.warn(`[${requestId}] User denied permission to update profile: ${id}`)
|
|
||||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateData: any = {
|
const updateData: any = {
|
||||||
@@ -130,7 +111,6 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
|
|||||||
if (data.name !== undefined) updateData.name = data.name
|
if (data.name !== undefined) updateData.name = data.name
|
||||||
if (data.profileImageUrl !== undefined) updateData.profileImageUrl = data.profileImageUrl
|
if (data.profileImageUrl !== undefined) updateData.profileImageUrl = data.profileImageUrl
|
||||||
if (data.details !== undefined) updateData.details = data.details
|
if (data.details !== undefined) updateData.details = data.details
|
||||||
if (data.verified !== undefined) updateData.verified = data.verified
|
|
||||||
|
|
||||||
const updated = await db
|
const updated = await db
|
||||||
.update(templateCreators)
|
.update(templateCreators)
|
||||||
|
|||||||
113
apps/sim/app/api/creators/[id]/verify/route.ts
Normal file
113
apps/sim/app/api/creators/[id]/verify/route.ts
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
import { db } from '@sim/db'
|
||||||
|
import { templateCreators } from '@sim/db/schema'
|
||||||
|
import { createLogger } from '@sim/logger'
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { getSession } from '@/lib/auth'
|
||||||
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
|
import { verifyEffectiveSuperUser } from '@/lib/templates/permissions'
|
||||||
|
|
||||||
|
const logger = createLogger('CreatorVerificationAPI')
|
||||||
|
|
||||||
|
export const revalidate = 0
|
||||||
|
|
||||||
|
// POST /api/creators/[id]/verify - Verify a creator (super users only)
|
||||||
|
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const requestId = generateRequestId()
|
||||||
|
const { id } = await params
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
logger.warn(`[${requestId}] Unauthorized verification attempt for creator: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user is a super user
|
||||||
|
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
|
||||||
|
if (!effectiveSuperUser) {
|
||||||
|
logger.warn(`[${requestId}] Non-super user attempted to verify creator: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Only super users can verify creators' }, { status: 403 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if creator exists
|
||||||
|
const existingCreator = await db
|
||||||
|
.select()
|
||||||
|
.from(templateCreators)
|
||||||
|
.where(eq(templateCreators.id, id))
|
||||||
|
.limit(1)
|
||||||
|
|
||||||
|
if (existingCreator.length === 0) {
|
||||||
|
logger.warn(`[${requestId}] Creator not found for verification: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Creator not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update creator verified status to true
|
||||||
|
await db
|
||||||
|
.update(templateCreators)
|
||||||
|
.set({ verified: true, updatedAt: new Date() })
|
||||||
|
.where(eq(templateCreators.id, id))
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Creator verified: ${id} by super user: ${session.user.id}`)
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Creator verified successfully',
|
||||||
|
creatorId: id,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`[${requestId}] Error verifying creator ${id}`, error)
|
||||||
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE /api/creators/[id]/verify - Unverify a creator (super users only)
|
||||||
|
export async function DELETE(
|
||||||
|
request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
const requestId = generateRequestId()
|
||||||
|
const { id } = await params
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
logger.warn(`[${requestId}] Unauthorized unverification attempt for creator: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if user is a super user
|
||||||
|
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
|
||||||
|
if (!effectiveSuperUser) {
|
||||||
|
logger.warn(`[${requestId}] Non-super user attempted to unverify creator: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Only super users can unverify creators' }, { status: 403 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if creator exists
|
||||||
|
const existingCreator = await db
|
||||||
|
.select()
|
||||||
|
.from(templateCreators)
|
||||||
|
.where(eq(templateCreators.id, id))
|
||||||
|
.limit(1)
|
||||||
|
|
||||||
|
if (existingCreator.length === 0) {
|
||||||
|
logger.warn(`[${requestId}] Creator not found for unverification: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Creator not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update creator verified status to false
|
||||||
|
await db
|
||||||
|
.update(templateCreators)
|
||||||
|
.set({ verified: false, updatedAt: new Date() })
|
||||||
|
.where(eq(templateCreators.id, id))
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Creator unverified: ${id} by super user: ${session.user.id}`)
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Creator unverified successfully',
|
||||||
|
creatorId: id,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`[${requestId}] Error unverifying creator ${id}`, error)
|
||||||
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,13 @@
|
|||||||
import { asyncJobs, db } from '@sim/db'
|
import { db } from '@sim/db'
|
||||||
import { workflowExecutionLogs } from '@sim/db/schema'
|
import { workflowExecutionLogs } from '@sim/db/schema'
|
||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { and, eq, inArray, lt, sql } from 'drizzle-orm'
|
import { and, eq, lt, sql } from 'drizzle-orm'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { verifyCronAuth } from '@/lib/auth/internal'
|
import { verifyCronAuth } from '@/lib/auth/internal'
|
||||||
import { JOB_RETENTION_HOURS, JOB_STATUS } from '@/lib/core/async-jobs'
|
|
||||||
import { getMaxExecutionTimeout } from '@/lib/core/execution-limits'
|
|
||||||
|
|
||||||
const logger = createLogger('CleanupStaleExecutions')
|
const logger = createLogger('CleanupStaleExecutions')
|
||||||
|
|
||||||
const STALE_THRESHOLD_MS = getMaxExecutionTimeout() + 5 * 60 * 1000
|
const STALE_THRESHOLD_MINUTES = 30
|
||||||
const STALE_THRESHOLD_MINUTES = Math.ceil(STALE_THRESHOLD_MS / 60000)
|
|
||||||
const MAX_INT32 = 2_147_483_647
|
const MAX_INT32 = 2_147_483_647
|
||||||
|
|
||||||
export async function GET(request: NextRequest) {
|
export async function GET(request: NextRequest) {
|
||||||
@@ -81,102 +78,12 @@ export async function GET(request: NextRequest) {
|
|||||||
|
|
||||||
logger.info(`Stale execution cleanup completed. Cleaned: ${cleaned}, Failed: ${failed}`)
|
logger.info(`Stale execution cleanup completed. Cleaned: ${cleaned}, Failed: ${failed}`)
|
||||||
|
|
||||||
// Clean up stale async jobs (stuck in processing)
|
|
||||||
let asyncJobsMarkedFailed = 0
|
|
||||||
|
|
||||||
try {
|
|
||||||
const staleAsyncJobs = await db
|
|
||||||
.update(asyncJobs)
|
|
||||||
.set({
|
|
||||||
status: JOB_STATUS.FAILED,
|
|
||||||
completedAt: new Date(),
|
|
||||||
error: `Job terminated: stuck in processing for more than ${STALE_THRESHOLD_MINUTES} minutes`,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(
|
|
||||||
and(eq(asyncJobs.status, JOB_STATUS.PROCESSING), lt(asyncJobs.startedAt, staleThreshold))
|
|
||||||
)
|
|
||||||
.returning({ id: asyncJobs.id })
|
|
||||||
|
|
||||||
asyncJobsMarkedFailed = staleAsyncJobs.length
|
|
||||||
if (asyncJobsMarkedFailed > 0) {
|
|
||||||
logger.info(`Marked ${asyncJobsMarkedFailed} stale async jobs as failed`)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Failed to clean up stale async jobs:', {
|
|
||||||
error: error instanceof Error ? error.message : String(error),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean up stale pending jobs (never started, e.g., due to server crash before startJob())
|
|
||||||
let stalePendingJobsMarkedFailed = 0
|
|
||||||
|
|
||||||
try {
|
|
||||||
const stalePendingJobs = await db
|
|
||||||
.update(asyncJobs)
|
|
||||||
.set({
|
|
||||||
status: JOB_STATUS.FAILED,
|
|
||||||
completedAt: new Date(),
|
|
||||||
error: `Job terminated: stuck in pending state for more than ${STALE_THRESHOLD_MINUTES} minutes (never started)`,
|
|
||||||
updatedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(
|
|
||||||
and(eq(asyncJobs.status, JOB_STATUS.PENDING), lt(asyncJobs.createdAt, staleThreshold))
|
|
||||||
)
|
|
||||||
.returning({ id: asyncJobs.id })
|
|
||||||
|
|
||||||
stalePendingJobsMarkedFailed = stalePendingJobs.length
|
|
||||||
if (stalePendingJobsMarkedFailed > 0) {
|
|
||||||
logger.info(`Marked ${stalePendingJobsMarkedFailed} stale pending jobs as failed`)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Failed to clean up stale pending jobs:', {
|
|
||||||
error: error instanceof Error ? error.message : String(error),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete completed/failed jobs older than retention period
|
|
||||||
const retentionThreshold = new Date(Date.now() - JOB_RETENTION_HOURS * 60 * 60 * 1000)
|
|
||||||
let asyncJobsDeleted = 0
|
|
||||||
|
|
||||||
try {
|
|
||||||
const deletedJobs = await db
|
|
||||||
.delete(asyncJobs)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
inArray(asyncJobs.status, [JOB_STATUS.COMPLETED, JOB_STATUS.FAILED]),
|
|
||||||
lt(asyncJobs.completedAt, retentionThreshold)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.returning({ id: asyncJobs.id })
|
|
||||||
|
|
||||||
asyncJobsDeleted = deletedJobs.length
|
|
||||||
if (asyncJobsDeleted > 0) {
|
|
||||||
logger.info(
|
|
||||||
`Deleted ${asyncJobsDeleted} old async jobs (retention: ${JOB_RETENTION_HOURS}h)`
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Failed to delete old async jobs:', {
|
|
||||||
error: error instanceof Error ? error.message : String(error),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
executions: {
|
found: staleExecutions.length,
|
||||||
found: staleExecutions.length,
|
cleaned,
|
||||||
cleaned,
|
failed,
|
||||||
failed,
|
thresholdMinutes: STALE_THRESHOLD_MINUTES,
|
||||||
thresholdMinutes: STALE_THRESHOLD_MINUTES,
|
|
||||||
},
|
|
||||||
asyncJobs: {
|
|
||||||
staleProcessingMarkedFailed: asyncJobsMarkedFailed,
|
|
||||||
stalePendingMarkedFailed: stalePendingJobsMarkedFailed,
|
|
||||||
oldDeleted: asyncJobsDeleted,
|
|
||||||
staleThresholdMinutes: STALE_THRESHOLD_MINUTES,
|
|
||||||
retentionHours: JOB_RETENTION_HOURS,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Error in stale execution cleanup job:', error)
|
logger.error('Error in stale execution cleanup job:', error)
|
||||||
|
|||||||
@@ -6,11 +6,7 @@ import { createLogger } from '@sim/logger'
|
|||||||
import binaryExtensionsList from 'binary-extensions'
|
import binaryExtensionsList from 'binary-extensions'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import {
|
import { secureFetchWithPinnedIP, validateUrlWithDNS } from '@/lib/core/security/input-validation'
|
||||||
secureFetchWithPinnedIP,
|
|
||||||
validateUrlWithDNS,
|
|
||||||
} from '@/lib/core/security/input-validation.server'
|
|
||||||
import { sanitizeUrlForLog } from '@/lib/core/utils/logging'
|
|
||||||
import { isSupportedFileType, parseFile } from '@/lib/file-parsers'
|
import { isSupportedFileType, parseFile } from '@/lib/file-parsers'
|
||||||
import { isUsingCloudStorage, type StorageContext, StorageService } from '@/lib/uploads'
|
import { isUsingCloudStorage, type StorageContext, StorageService } from '@/lib/uploads'
|
||||||
import { uploadExecutionFile } from '@/lib/uploads/contexts/execution'
|
import { uploadExecutionFile } from '@/lib/uploads/contexts/execution'
|
||||||
@@ -23,7 +19,6 @@ import {
|
|||||||
getMimeTypeFromExtension,
|
getMimeTypeFromExtension,
|
||||||
getViewerUrl,
|
getViewerUrl,
|
||||||
inferContextFromKey,
|
inferContextFromKey,
|
||||||
isInternalFileUrl,
|
|
||||||
} from '@/lib/uploads/utils/file-utils'
|
} from '@/lib/uploads/utils/file-utils'
|
||||||
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
|
import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils'
|
||||||
import { verifyFileAccess } from '@/app/api/files/authorization'
|
import { verifyFileAccess } from '@/app/api/files/authorization'
|
||||||
@@ -220,7 +215,7 @@ async function parseFileSingle(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isInternalFileUrl(filePath)) {
|
if (filePath.includes('/api/files/serve/')) {
|
||||||
return handleCloudFile(filePath, fileType, undefined, userId, executionContext)
|
return handleCloudFile(filePath, fileType, undefined, userId, executionContext)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,7 +246,7 @@ function validateFilePath(filePath: string): { isValid: boolean; error?: string
|
|||||||
return { isValid: false, error: 'Invalid path: tilde character not allowed' }
|
return { isValid: false, error: 'Invalid path: tilde character not allowed' }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (filePath.startsWith('/') && !isInternalFileUrl(filePath)) {
|
if (filePath.startsWith('/') && !filePath.startsWith('/api/files/serve/')) {
|
||||||
return { isValid: false, error: 'Path outside allowed directory' }
|
return { isValid: false, error: 'Path outside allowed directory' }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -425,7 +420,7 @@ async function handleExternalUrl(
|
|||||||
|
|
||||||
return parseResult
|
return parseResult
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Error handling external URL ${sanitizeUrlForLog(url)}:`, error)
|
logger.error(`Error handling external URL ${url}:`, error)
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: `Error fetching URL: ${(error as Error).message}`,
|
error: `Error fetching URL: ${(error as Error).message}`,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
|
import { runs } from '@trigger.dev/sdk'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import { getJobQueue, JOB_STATUS } from '@/lib/core/async-jobs'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { createErrorResponse } from '@/app/api/workflows/utils'
|
import { createErrorResponse } from '@/app/api/workflows/utils'
|
||||||
|
|
||||||
@@ -15,6 +15,8 @@ export async function GET(
|
|||||||
const requestId = generateRequestId()
|
const requestId = generateRequestId()
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
logger.debug(`[${requestId}] Getting status for task: ${taskId}`)
|
||||||
|
|
||||||
const authResult = await checkHybridAuth(request, { requireWorkflowId: false })
|
const authResult = await checkHybridAuth(request, { requireWorkflowId: false })
|
||||||
if (!authResult.success || !authResult.userId) {
|
if (!authResult.success || !authResult.userId) {
|
||||||
logger.warn(`[${requestId}] Unauthorized task status request`)
|
logger.warn(`[${requestId}] Unauthorized task status request`)
|
||||||
@@ -23,60 +25,76 @@ export async function GET(
|
|||||||
|
|
||||||
const authenticatedUserId = authResult.userId
|
const authenticatedUserId = authResult.userId
|
||||||
|
|
||||||
const jobQueue = await getJobQueue()
|
const run = await runs.retrieve(taskId)
|
||||||
const job = await jobQueue.getJob(taskId)
|
|
||||||
|
|
||||||
if (!job) {
|
logger.debug(`[${requestId}] Task ${taskId} status: ${run.status}`)
|
||||||
return createErrorResponse('Task not found', 404)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (job.metadata?.workflowId) {
|
const payload = run.payload as any
|
||||||
|
if (payload?.workflowId) {
|
||||||
const { verifyWorkflowAccess } = await import('@/socket/middleware/permissions')
|
const { verifyWorkflowAccess } = await import('@/socket/middleware/permissions')
|
||||||
const accessCheck = await verifyWorkflowAccess(
|
const accessCheck = await verifyWorkflowAccess(authenticatedUserId, payload.workflowId)
|
||||||
authenticatedUserId,
|
|
||||||
job.metadata.workflowId as string
|
|
||||||
)
|
|
||||||
if (!accessCheck.hasAccess) {
|
if (!accessCheck.hasAccess) {
|
||||||
logger.warn(`[${requestId}] Access denied to workflow ${job.metadata.workflowId}`)
|
logger.warn(`[${requestId}] User ${authenticatedUserId} denied access to task ${taskId}`, {
|
||||||
|
workflowId: payload.workflowId,
|
||||||
|
})
|
||||||
|
return createErrorResponse('Access denied', 403)
|
||||||
|
}
|
||||||
|
logger.debug(`[${requestId}] User ${authenticatedUserId} has access to task ${taskId}`)
|
||||||
|
} else {
|
||||||
|
if (payload?.userId && payload.userId !== authenticatedUserId) {
|
||||||
|
logger.warn(
|
||||||
|
`[${requestId}] User ${authenticatedUserId} attempted to access task ${taskId} owned by ${payload.userId}`
|
||||||
|
)
|
||||||
|
return createErrorResponse('Access denied', 403)
|
||||||
|
}
|
||||||
|
if (!payload?.userId) {
|
||||||
|
logger.warn(
|
||||||
|
`[${requestId}] Task ${taskId} has no ownership information in payload. Denying access for security.`
|
||||||
|
)
|
||||||
return createErrorResponse('Access denied', 403)
|
return createErrorResponse('Access denied', 403)
|
||||||
}
|
}
|
||||||
} else if (job.metadata?.userId && job.metadata.userId !== authenticatedUserId) {
|
|
||||||
logger.warn(`[${requestId}] Access denied to user ${job.metadata.userId}`)
|
|
||||||
return createErrorResponse('Access denied', 403)
|
|
||||||
} else if (!job.metadata?.userId && !job.metadata?.workflowId) {
|
|
||||||
logger.warn(`[${requestId}] Access denied to job ${taskId}`)
|
|
||||||
return createErrorResponse('Access denied', 403)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const mappedStatus = job.status === JOB_STATUS.PENDING ? 'queued' : job.status
|
const statusMap = {
|
||||||
|
QUEUED: 'queued',
|
||||||
|
WAITING_FOR_DEPLOY: 'queued',
|
||||||
|
EXECUTING: 'processing',
|
||||||
|
RESCHEDULED: 'processing',
|
||||||
|
FROZEN: 'processing',
|
||||||
|
COMPLETED: 'completed',
|
||||||
|
CANCELED: 'cancelled',
|
||||||
|
FAILED: 'failed',
|
||||||
|
CRASHED: 'failed',
|
||||||
|
INTERRUPTED: 'failed',
|
||||||
|
SYSTEM_FAILURE: 'failed',
|
||||||
|
EXPIRED: 'failed',
|
||||||
|
} as const
|
||||||
|
|
||||||
|
const mappedStatus = statusMap[run.status as keyof typeof statusMap] || 'unknown'
|
||||||
|
|
||||||
const response: any = {
|
const response: any = {
|
||||||
success: true,
|
success: true,
|
||||||
taskId,
|
taskId,
|
||||||
status: mappedStatus,
|
status: mappedStatus,
|
||||||
metadata: {
|
metadata: {
|
||||||
startedAt: job.startedAt,
|
startedAt: run.startedAt,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if (job.status === JOB_STATUS.COMPLETED) {
|
if (mappedStatus === 'completed') {
|
||||||
response.output = job.output
|
response.output = run.output // This contains the workflow execution results
|
||||||
response.metadata.completedAt = job.completedAt
|
response.metadata.completedAt = run.finishedAt
|
||||||
if (job.startedAt && job.completedAt) {
|
response.metadata.duration = run.durationMs
|
||||||
response.metadata.duration = job.completedAt.getTime() - job.startedAt.getTime()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (job.status === JOB_STATUS.FAILED) {
|
if (mappedStatus === 'failed') {
|
||||||
response.error = job.error
|
response.error = run.error
|
||||||
response.metadata.completedAt = job.completedAt
|
response.metadata.completedAt = run.finishedAt
|
||||||
if (job.startedAt && job.completedAt) {
|
response.metadata.duration = run.durationMs
|
||||||
response.metadata.duration = job.completedAt.getTime() - job.startedAt.getTime()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (job.status === JOB_STATUS.PROCESSING || job.status === JOB_STATUS.PENDING) {
|
if (mappedStatus === 'processing' || mappedStatus === 'queued') {
|
||||||
response.estimatedDuration = 180000
|
response.estimatedDuration = 180000 // 3 minutes max from our config
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json(response)
|
return NextResponse.json(response)
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import { and, eq } from 'drizzle-orm'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import { generateInternalToken } from '@/lib/auth/internal'
|
import { generateInternalToken } from '@/lib/auth/internal'
|
||||||
import { getMaxExecutionTimeout } from '@/lib/core/execution-limits'
|
|
||||||
import { getBaseUrl } from '@/lib/core/utils/urls'
|
import { getBaseUrl } from '@/lib/core/utils/urls'
|
||||||
|
|
||||||
const logger = createLogger('WorkflowMcpServeAPI')
|
const logger = createLogger('WorkflowMcpServeAPI')
|
||||||
@@ -265,7 +264,7 @@ async function handleToolsCall(
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify({ input: params.arguments || {}, triggerType: 'mcp' }),
|
body: JSON.stringify({ input: params.arguments || {}, triggerType: 'mcp' }),
|
||||||
signal: AbortSignal.timeout(getMaxExecutionTimeout()),
|
signal: AbortSignal.timeout(600000), // 10 minute timeout
|
||||||
})
|
})
|
||||||
|
|
||||||
const executeResult = await response.json()
|
const executeResult = await response.json()
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import type { NextRequest } from 'next/server'
|
import type { NextRequest } from 'next/server'
|
||||||
import { getHighestPrioritySubscription } from '@/lib/billing/core/plan'
|
|
||||||
import { getExecutionTimeout } from '@/lib/core/execution-limits'
|
|
||||||
import type { SubscriptionPlan } from '@/lib/core/rate-limiter/types'
|
|
||||||
import { getParsedBody, withMcpAuth } from '@/lib/mcp/middleware'
|
import { getParsedBody, withMcpAuth } from '@/lib/mcp/middleware'
|
||||||
import { mcpService } from '@/lib/mcp/service'
|
import { mcpService } from '@/lib/mcp/service'
|
||||||
import type { McpTool, McpToolCall, McpToolResult } from '@/lib/mcp/types'
|
import type { McpTool, McpToolCall, McpToolResult } from '@/lib/mcp/types'
|
||||||
@@ -10,6 +7,7 @@ import {
|
|||||||
categorizeError,
|
categorizeError,
|
||||||
createMcpErrorResponse,
|
createMcpErrorResponse,
|
||||||
createMcpSuccessResponse,
|
createMcpSuccessResponse,
|
||||||
|
MCP_CONSTANTS,
|
||||||
validateStringParam,
|
validateStringParam,
|
||||||
} from '@/lib/mcp/utils'
|
} from '@/lib/mcp/utils'
|
||||||
|
|
||||||
@@ -173,16 +171,13 @@ export const POST = withMcpAuth('read')(
|
|||||||
arguments: args,
|
arguments: args,
|
||||||
}
|
}
|
||||||
|
|
||||||
const userSubscription = await getHighestPrioritySubscription(userId)
|
|
||||||
const executionTimeout = getExecutionTimeout(
|
|
||||||
userSubscription?.plan as SubscriptionPlan | undefined,
|
|
||||||
'sync'
|
|
||||||
)
|
|
||||||
|
|
||||||
const result = await Promise.race([
|
const result = await Promise.race([
|
||||||
mcpService.executeTool(userId, serverId, toolCall, workspaceId),
|
mcpService.executeTool(userId, serverId, toolCall, workspaceId),
|
||||||
new Promise<never>((_, reject) =>
|
new Promise<never>((_, reject) =>
|
||||||
setTimeout(() => reject(new Error('Tool execution timeout')), executionTimeout)
|
setTimeout(
|
||||||
|
() => reject(new Error('Tool execution timeout')),
|
||||||
|
MCP_CONSTANTS.EXECUTION_TIMEOUT
|
||||||
|
)
|
||||||
),
|
),
|
||||||
])
|
])
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { db, workflowDeploymentVersion, workflowSchedule } from '@sim/db'
|
import { db, workflowDeploymentVersion, workflowSchedule } from '@sim/db'
|
||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
|
import { tasks } from '@trigger.dev/sdk'
|
||||||
import { and, eq, isNull, lt, lte, not, or, sql } from 'drizzle-orm'
|
import { and, eq, isNull, lt, lte, not, or, sql } from 'drizzle-orm'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { verifyCronAuth } from '@/lib/auth/internal'
|
import { verifyCronAuth } from '@/lib/auth/internal'
|
||||||
import { getJobQueue, shouldExecuteInline } from '@/lib/core/async-jobs'
|
import { isTriggerDevEnabled } from '@/lib/core/config/feature-flags'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { executeScheduleJob } from '@/background/schedule-execution'
|
import { executeScheduleJob } from '@/background/schedule-execution'
|
||||||
|
|
||||||
@@ -54,67 +55,72 @@ export async function GET(request: NextRequest) {
|
|||||||
logger.debug(`[${requestId}] Successfully queried schedules: ${dueSchedules.length} found`)
|
logger.debug(`[${requestId}] Successfully queried schedules: ${dueSchedules.length} found`)
|
||||||
logger.info(`[${requestId}] Processing ${dueSchedules.length} due scheduled workflows`)
|
logger.info(`[${requestId}] Processing ${dueSchedules.length} due scheduled workflows`)
|
||||||
|
|
||||||
const jobQueue = await getJobQueue()
|
if (isTriggerDevEnabled) {
|
||||||
|
const triggerPromises = dueSchedules.map(async (schedule) => {
|
||||||
|
const queueTime = schedule.lastQueuedAt ?? queuedAt
|
||||||
|
|
||||||
const queuePromises = dueSchedules.map(async (schedule) => {
|
try {
|
||||||
const queueTime = schedule.lastQueuedAt ?? queuedAt
|
const payload = {
|
||||||
|
scheduleId: schedule.id,
|
||||||
|
workflowId: schedule.workflowId,
|
||||||
|
blockId: schedule.blockId || undefined,
|
||||||
|
cronExpression: schedule.cronExpression || undefined,
|
||||||
|
lastRanAt: schedule.lastRanAt?.toISOString(),
|
||||||
|
failedCount: schedule.failedCount || 0,
|
||||||
|
now: queueTime.toISOString(),
|
||||||
|
scheduledFor: schedule.nextRunAt?.toISOString(),
|
||||||
|
}
|
||||||
|
|
||||||
const payload = {
|
const handle = await tasks.trigger('schedule-execution', payload)
|
||||||
scheduleId: schedule.id,
|
logger.info(
|
||||||
workflowId: schedule.workflowId,
|
`[${requestId}] Queued schedule execution task ${handle.id} for workflow ${schedule.workflowId}`
|
||||||
blockId: schedule.blockId || undefined,
|
)
|
||||||
cronExpression: schedule.cronExpression || undefined,
|
return handle
|
||||||
lastRanAt: schedule.lastRanAt?.toISOString(),
|
} catch (error) {
|
||||||
failedCount: schedule.failedCount || 0,
|
logger.error(
|
||||||
now: queueTime.toISOString(),
|
`[${requestId}] Failed to trigger schedule execution for workflow ${schedule.workflowId}`,
|
||||||
scheduledFor: schedule.nextRunAt?.toISOString(),
|
error
|
||||||
}
|
)
|
||||||
|
return null
|
||||||
try {
|
|
||||||
const jobId = await jobQueue.enqueue('schedule-execution', payload, {
|
|
||||||
metadata: { workflowId: schedule.workflowId },
|
|
||||||
})
|
|
||||||
logger.info(
|
|
||||||
`[${requestId}] Queued schedule execution task ${jobId} for workflow ${schedule.workflowId}`
|
|
||||||
)
|
|
||||||
|
|
||||||
if (shouldExecuteInline()) {
|
|
||||||
void (async () => {
|
|
||||||
try {
|
|
||||||
await jobQueue.startJob(jobId)
|
|
||||||
const output = await executeScheduleJob(payload)
|
|
||||||
await jobQueue.completeJob(jobId, output)
|
|
||||||
} catch (error) {
|
|
||||||
const errorMessage = error instanceof Error ? error.message : String(error)
|
|
||||||
logger.error(
|
|
||||||
`[${requestId}] Schedule execution failed for workflow ${schedule.workflowId}`,
|
|
||||||
{ jobId, error: errorMessage }
|
|
||||||
)
|
|
||||||
try {
|
|
||||||
await jobQueue.markJobFailed(jobId, errorMessage)
|
|
||||||
} catch (markFailedError) {
|
|
||||||
logger.error(`[${requestId}] Failed to mark job as failed`, {
|
|
||||||
jobId,
|
|
||||||
error:
|
|
||||||
markFailedError instanceof Error
|
|
||||||
? markFailedError.message
|
|
||||||
: String(markFailedError),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})()
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
})
|
||||||
logger.error(
|
|
||||||
`[${requestId}] Failed to queue schedule execution for workflow ${schedule.workflowId}`,
|
await Promise.allSettled(triggerPromises)
|
||||||
error
|
|
||||||
|
logger.info(`[${requestId}] Queued ${dueSchedules.length} schedule executions to Trigger.dev`)
|
||||||
|
} else {
|
||||||
|
const directExecutionPromises = dueSchedules.map(async (schedule) => {
|
||||||
|
const queueTime = schedule.lastQueuedAt ?? queuedAt
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
scheduleId: schedule.id,
|
||||||
|
workflowId: schedule.workflowId,
|
||||||
|
blockId: schedule.blockId || undefined,
|
||||||
|
cronExpression: schedule.cronExpression || undefined,
|
||||||
|
lastRanAt: schedule.lastRanAt?.toISOString(),
|
||||||
|
failedCount: schedule.failedCount || 0,
|
||||||
|
now: queueTime.toISOString(),
|
||||||
|
scheduledFor: schedule.nextRunAt?.toISOString(),
|
||||||
|
}
|
||||||
|
|
||||||
|
void executeScheduleJob(payload).catch((error) => {
|
||||||
|
logger.error(
|
||||||
|
`[${requestId}] Direct schedule execution failed for workflow ${schedule.workflowId}`,
|
||||||
|
error
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`[${requestId}] Queued direct schedule execution for workflow ${schedule.workflowId} (Trigger.dev disabled)`
|
||||||
)
|
)
|
||||||
}
|
})
|
||||||
})
|
|
||||||
|
|
||||||
await Promise.allSettled(queuePromises)
|
await Promise.allSettled(directExecutionPromises)
|
||||||
|
|
||||||
logger.info(`[${requestId}] Queued ${dueSchedules.length} schedule executions`)
|
logger.info(
|
||||||
|
`[${requestId}] Queued ${dueSchedules.length} direct schedule executions (Trigger.dev disabled)`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
message: 'Scheduled workflow executions processed',
|
message: 'Scheduled workflow executions processed',
|
||||||
|
|||||||
101
apps/sim/app/api/templates/[id]/approve/route.ts
Normal file
101
apps/sim/app/api/templates/[id]/approve/route.ts
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
import { db } from '@sim/db'
|
||||||
|
import { templates } from '@sim/db/schema'
|
||||||
|
import { createLogger } from '@sim/logger'
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { getSession } from '@/lib/auth'
|
||||||
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
|
import { verifyEffectiveSuperUser } from '@/lib/templates/permissions'
|
||||||
|
|
||||||
|
const logger = createLogger('TemplateApprovalAPI')
|
||||||
|
|
||||||
|
export const revalidate = 0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/templates/[id]/approve - Approve a template (super users only)
|
||||||
|
*/
|
||||||
|
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const requestId = generateRequestId()
|
||||||
|
const { id } = await params
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
logger.warn(`[${requestId}] Unauthorized template approval attempt for ID: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
|
||||||
|
if (!effectiveSuperUser) {
|
||||||
|
logger.warn(`[${requestId}] Non-super user attempted to approve template: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Only super users can approve templates' }, { status: 403 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingTemplate = await db.select().from(templates).where(eq(templates.id, id)).limit(1)
|
||||||
|
if (existingTemplate.length === 0) {
|
||||||
|
logger.warn(`[${requestId}] Template not found for approval: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Template not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(templates)
|
||||||
|
.set({ status: 'approved', updatedAt: new Date() })
|
||||||
|
.where(eq(templates.id, id))
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Template approved: ${id} by super user: ${session.user.id}`)
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Template approved successfully',
|
||||||
|
templateId: id,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`[${requestId}] Error approving template ${id}`, error)
|
||||||
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DELETE /api/templates/[id]/approve - Unapprove a template (super users only)
|
||||||
|
*/
|
||||||
|
export async function DELETE(
|
||||||
|
_request: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
const requestId = generateRequestId()
|
||||||
|
const { id } = await params
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
logger.warn(`[${requestId}] Unauthorized template rejection attempt for ID: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
|
||||||
|
if (!effectiveSuperUser) {
|
||||||
|
logger.warn(`[${requestId}] Non-super user attempted to reject template: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Only super users can reject templates' }, { status: 403 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingTemplate = await db.select().from(templates).where(eq(templates.id, id)).limit(1)
|
||||||
|
if (existingTemplate.length === 0) {
|
||||||
|
logger.warn(`[${requestId}] Template not found for rejection: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Template not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(templates)
|
||||||
|
.set({ status: 'rejected', updatedAt: new Date() })
|
||||||
|
.where(eq(templates.id, id))
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Template rejected: ${id} by super user: ${session.user.id}`)
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Template rejected successfully',
|
||||||
|
templateId: id,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`[${requestId}] Error rejecting template ${id}`, error)
|
||||||
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
55
apps/sim/app/api/templates/[id]/reject/route.ts
Normal file
55
apps/sim/app/api/templates/[id]/reject/route.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import { db } from '@sim/db'
|
||||||
|
import { templates } from '@sim/db/schema'
|
||||||
|
import { createLogger } from '@sim/logger'
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
|
import { getSession } from '@/lib/auth'
|
||||||
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
|
import { verifyEffectiveSuperUser } from '@/lib/templates/permissions'
|
||||||
|
|
||||||
|
const logger = createLogger('TemplateRejectionAPI')
|
||||||
|
|
||||||
|
export const revalidate = 0
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/templates/[id]/reject - Reject a template (super users only)
|
||||||
|
*/
|
||||||
|
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||||
|
const requestId = generateRequestId()
|
||||||
|
const { id } = await params
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await getSession()
|
||||||
|
if (!session?.user?.id) {
|
||||||
|
logger.warn(`[${requestId}] Unauthorized template rejection attempt for ID: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
|
||||||
|
if (!effectiveSuperUser) {
|
||||||
|
logger.warn(`[${requestId}] Non-super user attempted to reject template: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Only super users can reject templates' }, { status: 403 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingTemplate = await db.select().from(templates).where(eq(templates.id, id)).limit(1)
|
||||||
|
if (existingTemplate.length === 0) {
|
||||||
|
logger.warn(`[${requestId}] Template not found for rejection: ${id}`)
|
||||||
|
return NextResponse.json({ error: 'Template not found' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(templates)
|
||||||
|
.set({ status: 'rejected', updatedAt: new Date() })
|
||||||
|
.where(eq(templates.id, id))
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Template rejected: ${id} by super user: ${session.user.id}`)
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
message: 'Template rejected successfully',
|
||||||
|
templateId: id,
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`[${requestId}] Error rejecting template ${id}`, error)
|
||||||
|
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -106,7 +106,6 @@ const updateTemplateSchema = z.object({
|
|||||||
creatorId: z.string().optional(), // Creator profile ID
|
creatorId: z.string().optional(), // Creator profile ID
|
||||||
tags: z.array(z.string()).max(10, 'Maximum 10 tags allowed').optional(),
|
tags: z.array(z.string()).max(10, 'Maximum 10 tags allowed').optional(),
|
||||||
updateState: z.boolean().optional(), // Explicitly request state update from current workflow
|
updateState: z.boolean().optional(), // Explicitly request state update from current workflow
|
||||||
status: z.enum(['approved', 'rejected', 'pending']).optional(), // Status change (super users only)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
// PUT /api/templates/[id] - Update a template
|
// PUT /api/templates/[id] - Update a template
|
||||||
@@ -132,7 +131,7 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const { name, details, creatorId, tags, updateState, status } = validationResult.data
|
const { name, details, creatorId, tags, updateState } = validationResult.data
|
||||||
|
|
||||||
const existingTemplate = await db.select().from(templates).where(eq(templates.id, id)).limit(1)
|
const existingTemplate = await db.select().from(templates).where(eq(templates.id, id)).limit(1)
|
||||||
|
|
||||||
@@ -143,44 +142,21 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
|
|||||||
|
|
||||||
const template = existingTemplate[0]
|
const template = existingTemplate[0]
|
||||||
|
|
||||||
// Status changes require super user permission
|
if (!template.creatorId) {
|
||||||
if (status !== undefined) {
|
logger.warn(`[${requestId}] Template ${id} has no creator, denying update`)
|
||||||
const { verifyEffectiveSuperUser } = await import('@/lib/templates/permissions')
|
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
||||||
const { effectiveSuperUser } = await verifyEffectiveSuperUser(session.user.id)
|
|
||||||
if (!effectiveSuperUser) {
|
|
||||||
logger.warn(`[${requestId}] Non-super user attempted to change template status: ${id}`)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Only super users can change template status' },
|
|
||||||
{ status: 403 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// For non-status updates, verify creator permission
|
const { verifyCreatorPermission } = await import('@/lib/templates/permissions')
|
||||||
const hasNonStatusUpdates =
|
const { hasPermission, error: permissionError } = await verifyCreatorPermission(
|
||||||
name !== undefined ||
|
session.user.id,
|
||||||
details !== undefined ||
|
template.creatorId,
|
||||||
creatorId !== undefined ||
|
'admin'
|
||||||
tags !== undefined ||
|
)
|
||||||
updateState
|
|
||||||
|
|
||||||
if (hasNonStatusUpdates) {
|
if (!hasPermission) {
|
||||||
if (!template.creatorId) {
|
logger.warn(`[${requestId}] User denied permission to update template ${id}`)
|
||||||
logger.warn(`[${requestId}] Template ${id} has no creator, denying update`)
|
return NextResponse.json({ error: permissionError || 'Access denied' }, { status: 403 })
|
||||||
return NextResponse.json({ error: 'Access denied' }, { status: 403 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { verifyCreatorPermission } = await import('@/lib/templates/permissions')
|
|
||||||
const { hasPermission, error: permissionError } = await verifyCreatorPermission(
|
|
||||||
session.user.id,
|
|
||||||
template.creatorId,
|
|
||||||
'admin'
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!hasPermission) {
|
|
||||||
logger.warn(`[${requestId}] User denied permission to update template ${id}`)
|
|
||||||
return NextResponse.json({ error: permissionError || 'Access denied' }, { status: 403 })
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateData: any = {
|
const updateData: any = {
|
||||||
@@ -191,7 +167,6 @@ export async function PUT(request: NextRequest, { params }: { params: Promise<{
|
|||||||
if (details !== undefined) updateData.details = details
|
if (details !== undefined) updateData.details = details
|
||||||
if (tags !== undefined) updateData.tags = tags
|
if (tags !== undefined) updateData.tags = tags
|
||||||
if (creatorId !== undefined) updateData.creatorId = creatorId
|
if (creatorId !== undefined) updateData.creatorId = creatorId
|
||||||
if (status !== undefined) updateData.status = status
|
|
||||||
|
|
||||||
if (updateState && template.workflowId) {
|
if (updateState && template.workflowId) {
|
||||||
const { verifyWorkflowAccess } = await import('@/socket/middleware/permissions')
|
const { verifyWorkflowAccess } = await import('@/socket/middleware/permissions')
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { type NextRequest, NextResponse } from 'next/server'
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { createA2AClient, extractTextContent, isTerminalState } from '@/lib/a2a/utils'
|
import { createA2AClient, extractTextContent, isTerminalState } from '@/lib/a2a/utils'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
@@ -96,14 +95,6 @@ export async function POST(request: NextRequest) {
|
|||||||
if (validatedData.files && validatedData.files.length > 0) {
|
if (validatedData.files && validatedData.files.length > 0) {
|
||||||
for (const file of validatedData.files) {
|
for (const file of validatedData.files) {
|
||||||
if (file.type === 'url') {
|
if (file.type === 'url') {
|
||||||
const urlValidation = await validateUrlWithDNS(file.data, 'fileUrl')
|
|
||||||
if (!urlValidation.isValid) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: urlValidation.error },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const filePart: FilePart = {
|
const filePart: FilePart = {
|
||||||
kind: 'file',
|
kind: 'file',
|
||||||
file: {
|
file: {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { type NextRequest, NextResponse } from 'next/server'
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { createA2AClient } from '@/lib/a2a/utils'
|
import { createA2AClient } from '@/lib/a2a/utils'
|
||||||
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
import { checkHybridAuth } from '@/lib/auth/hybrid'
|
||||||
import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server'
|
import { validateExternalUrl } from '@/lib/core/security/input-validation'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
@@ -40,7 +40,7 @@ export async function POST(request: NextRequest) {
|
|||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const validatedData = A2ASetPushNotificationSchema.parse(body)
|
const validatedData = A2ASetPushNotificationSchema.parse(body)
|
||||||
|
|
||||||
const urlValidation = await validateUrlWithDNS(validatedData.webhookUrl, 'Webhook URL')
|
const urlValidation = validateExternalUrl(validatedData.webhookUrl, 'Webhook URL')
|
||||||
if (!urlValidation.isValid) {
|
if (!urlValidation.isValid) {
|
||||||
logger.warn(`[${requestId}] Invalid webhook URL`, { error: urlValidation.error })
|
logger.warn(`[${requestId}] Invalid webhook URL`, { error: urlValidation.error })
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -21,8 +21,7 @@ export async function GET(request: NextRequest) {
|
|||||||
const accessToken = searchParams.get('accessToken')
|
const accessToken = searchParams.get('accessToken')
|
||||||
const pageId = searchParams.get('pageId')
|
const pageId = searchParams.get('pageId')
|
||||||
const providedCloudId = searchParams.get('cloudId')
|
const providedCloudId = searchParams.get('cloudId')
|
||||||
const limit = searchParams.get('limit') || '50'
|
const limit = searchParams.get('limit') || '25'
|
||||||
const cursor = searchParams.get('cursor')
|
|
||||||
|
|
||||||
if (!domain) {
|
if (!domain) {
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||||
@@ -48,12 +47,7 @@ export async function GET(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/attachments?limit=${limit}`
|
||||||
queryParams.append('limit', String(Math.min(Number(limit), 250)))
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/attachments?${queryParams.toString()}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -83,20 +77,9 @@ export async function GET(request: NextRequest) {
|
|||||||
fileSize: attachment.fileSize || 0,
|
fileSize: attachment.fileSize || 0,
|
||||||
mediaType: attachment.mediaType || '',
|
mediaType: attachment.mediaType || '',
|
||||||
downloadUrl: attachment.downloadLink || attachment._links?.download || '',
|
downloadUrl: attachment.downloadLink || attachment._links?.download || '',
|
||||||
status: attachment.status ?? null,
|
|
||||||
webuiUrl: attachment._links?.webui ?? null,
|
|
||||||
pageId: attachment.pageId ?? null,
|
|
||||||
blogPostId: attachment.blogPostId ?? null,
|
|
||||||
comment: attachment.comment ?? null,
|
|
||||||
version: attachment.version ?? null,
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({ attachments })
|
||||||
attachments,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Error listing Confluence attachments:', error)
|
logger.error('Error listing Confluence attachments:', error)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -1,285 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluenceBlogPostsAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
const getBlogPostSchema = z
|
|
||||||
.object({
|
|
||||||
domain: z.string().min(1, 'Domain is required'),
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
cloudId: z.string().optional(),
|
|
||||||
blogPostId: z.string().min(1, 'Blog post ID is required'),
|
|
||||||
bodyFormat: z.string().optional(),
|
|
||||||
})
|
|
||||||
.refine(
|
|
||||||
(data) => {
|
|
||||||
const validation = validateAlphanumericId(data.blogPostId, 'blogPostId', 255)
|
|
||||||
return validation.isValid
|
|
||||||
},
|
|
||||||
(data) => {
|
|
||||||
const validation = validateAlphanumericId(data.blogPostId, 'blogPostId', 255)
|
|
||||||
return { message: validation.error || 'Invalid blog post ID', path: ['blogPostId'] }
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
const createBlogPostSchema = z.object({
|
|
||||||
domain: z.string().min(1, 'Domain is required'),
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
cloudId: z.string().optional(),
|
|
||||||
spaceId: z.string().min(1, 'Space ID is required'),
|
|
||||||
title: z.string().min(1, 'Title is required'),
|
|
||||||
content: z.string().min(1, 'Content is required'),
|
|
||||||
status: z.enum(['current', 'draft']).optional(),
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* List all blog posts or get a specific blog post
|
|
||||||
*/
|
|
||||||
export async function GET(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { searchParams } = new URL(request.url)
|
|
||||||
const domain = searchParams.get('domain')
|
|
||||||
const accessToken = searchParams.get('accessToken')
|
|
||||||
const providedCloudId = searchParams.get('cloudId')
|
|
||||||
const limit = searchParams.get('limit') || '25'
|
|
||||||
const status = searchParams.get('status')
|
|
||||||
const sortOrder = searchParams.get('sort')
|
|
||||||
const cursor = searchParams.get('cursor')
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
queryParams.append('limit', String(Math.min(Number(limit), 250)))
|
|
||||||
|
|
||||||
if (status) {
|
|
||||||
queryParams.append('status', status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sortOrder) {
|
|
||||||
queryParams.append('sort', sortOrder)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/blogposts?${queryParams.toString()}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to list blog posts (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const blogPosts = (data.results || []).map((post: any) => ({
|
|
||||||
id: post.id,
|
|
||||||
title: post.title,
|
|
||||||
status: post.status ?? null,
|
|
||||||
spaceId: post.spaceId ?? null,
|
|
||||||
authorId: post.authorId ?? null,
|
|
||||||
createdAt: post.createdAt ?? null,
|
|
||||||
version: post.version ?? null,
|
|
||||||
webUrl: post._links?.webui ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
blogPosts,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error listing blog posts:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a specific blog post by ID
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
|
|
||||||
// Check if this is a create or get request
|
|
||||||
if (body.title && body.content && body.spaceId) {
|
|
||||||
// Create blog post
|
|
||||||
const validation = createBlogPostSchema.safeParse(body)
|
|
||||||
if (!validation.success) {
|
|
||||||
const firstError = validation.error.errors[0]
|
|
||||||
return NextResponse.json({ error: firstError.message }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
domain,
|
|
||||||
accessToken,
|
|
||||||
cloudId: providedCloudId,
|
|
||||||
spaceId,
|
|
||||||
title,
|
|
||||||
content,
|
|
||||||
status,
|
|
||||||
} = validation.data
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/blogposts`
|
|
||||||
|
|
||||||
const createBody = {
|
|
||||||
spaceId,
|
|
||||||
status: status || 'current',
|
|
||||||
title,
|
|
||||||
body: {
|
|
||||||
representation: 'storage',
|
|
||||||
value: content,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify(createBody),
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to create blog post (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
return NextResponse.json({
|
|
||||||
id: data.id,
|
|
||||||
title: data.title,
|
|
||||||
spaceId: data.spaceId,
|
|
||||||
webUrl: data._links?.webui ?? null,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
// Get blog post by ID
|
|
||||||
const validation = getBlogPostSchema.safeParse(body)
|
|
||||||
if (!validation.success) {
|
|
||||||
const firstError = validation.error.errors[0]
|
|
||||||
return NextResponse.json({ error: firstError.message }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
domain,
|
|
||||||
accessToken,
|
|
||||||
cloudId: providedCloudId,
|
|
||||||
blogPostId,
|
|
||||||
bodyFormat,
|
|
||||||
} = validation.data
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
if (bodyFormat) {
|
|
||||||
queryParams.append('body-format', bodyFormat)
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/blogposts/${blogPostId}${queryParams.toString() ? `?${queryParams.toString()}` : ''}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to get blog post (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
return NextResponse.json({
|
|
||||||
id: data.id,
|
|
||||||
title: data.title,
|
|
||||||
status: data.status ?? null,
|
|
||||||
spaceId: data.spaceId ?? null,
|
|
||||||
authorId: data.authorId ?? null,
|
|
||||||
createdAt: data.createdAt ?? null,
|
|
||||||
version: data.version ?? null,
|
|
||||||
body: data.body ?? null,
|
|
||||||
webUrl: data._links?.webui ?? null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error with blog post operation:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -105,8 +105,6 @@ export async function GET(request: NextRequest) {
|
|||||||
const pageId = searchParams.get('pageId')
|
const pageId = searchParams.get('pageId')
|
||||||
const providedCloudId = searchParams.get('cloudId')
|
const providedCloudId = searchParams.get('cloudId')
|
||||||
const limit = searchParams.get('limit') || '25'
|
const limit = searchParams.get('limit') || '25'
|
||||||
const bodyFormat = searchParams.get('bodyFormat') || 'storage'
|
|
||||||
const cursor = searchParams.get('cursor')
|
|
||||||
|
|
||||||
if (!domain) {
|
if (!domain) {
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||||
@@ -132,13 +130,7 @@ export async function GET(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/footer-comments?limit=${limit}`
|
||||||
queryParams.append('limit', String(Math.min(Number(limit), 250)))
|
|
||||||
queryParams.append('body-format', bodyFormat)
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/footer-comments?${queryParams.toString()}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -162,31 +154,14 @@ export async function GET(request: NextRequest) {
|
|||||||
|
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
|
|
||||||
const comments = (data.results || []).map((comment: any) => {
|
const comments = (data.results || []).map((comment: any) => ({
|
||||||
const bodyValue = comment.body?.storage?.value || comment.body?.view?.value || ''
|
id: comment.id,
|
||||||
return {
|
body: comment.body?.storage?.value || comment.body?.view?.value || '',
|
||||||
id: comment.id,
|
createdAt: comment.createdAt || '',
|
||||||
body: {
|
authorId: comment.authorId || '',
|
||||||
value: bodyValue,
|
}))
|
||||||
representation: bodyFormat,
|
|
||||||
},
|
|
||||||
createdAt: comment.createdAt || '',
|
|
||||||
authorId: comment.authorId || '',
|
|
||||||
status: comment.status ?? null,
|
|
||||||
title: comment.title ?? null,
|
|
||||||
pageId: comment.pageId ?? null,
|
|
||||||
blogPostId: comment.blogPostId ?? null,
|
|
||||||
parentCommentId: comment.parentCommentId ?? null,
|
|
||||||
version: comment.version ?? null,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({ comments })
|
||||||
comments,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Error listing Confluence comments:', error)
|
logger.error('Error listing Confluence comments:', error)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ export async function POST(request: NextRequest) {
|
|||||||
cloudId: providedCloudId,
|
cloudId: providedCloudId,
|
||||||
pageId,
|
pageId,
|
||||||
labelName,
|
labelName,
|
||||||
prefix: labelPrefix,
|
|
||||||
} = await request.json()
|
} = await request.json()
|
||||||
|
|
||||||
if (!domain) {
|
if (!domain) {
|
||||||
@@ -53,14 +52,12 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/rest/api/content/${pageId}/label`
|
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/labels`
|
||||||
|
|
||||||
const body = [
|
const body = {
|
||||||
{
|
prefix: 'global',
|
||||||
prefix: labelPrefix || 'global',
|
name: labelName,
|
||||||
name: labelName,
|
}
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -85,14 +82,7 @@ export async function POST(request: NextRequest) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
const addedLabel = data.results?.[0] || data[0] || data
|
return NextResponse.json({ ...data, pageId, labelName })
|
||||||
return NextResponse.json({
|
|
||||||
id: addedLabel.id ?? '',
|
|
||||||
name: addedLabel.name ?? labelName,
|
|
||||||
prefix: addedLabel.prefix ?? labelPrefix ?? 'global',
|
|
||||||
pageId,
|
|
||||||
labelName,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Error adding Confluence label:', error)
|
logger.error('Error adding Confluence label:', error)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
@@ -115,8 +105,6 @@ export async function GET(request: NextRequest) {
|
|||||||
const accessToken = searchParams.get('accessToken')
|
const accessToken = searchParams.get('accessToken')
|
||||||
const pageId = searchParams.get('pageId')
|
const pageId = searchParams.get('pageId')
|
||||||
const providedCloudId = searchParams.get('cloudId')
|
const providedCloudId = searchParams.get('cloudId')
|
||||||
const limit = searchParams.get('limit') || '25'
|
|
||||||
const cursor = searchParams.get('cursor')
|
|
||||||
|
|
||||||
if (!domain) {
|
if (!domain) {
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||||
@@ -142,12 +130,7 @@ export async function GET(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/labels`
|
||||||
queryParams.append('limit', String(Math.min(Number(limit), 250)))
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/labels?${queryParams.toString()}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -177,12 +160,7 @@ export async function GET(request: NextRequest) {
|
|||||||
prefix: label.prefix || 'global',
|
prefix: label.prefix || 'global',
|
||||||
}))
|
}))
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({ labels })
|
||||||
labels,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Error listing Confluence labels:', error)
|
logger.error('Error listing Confluence labels:', error)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -1,96 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluencePageAncestorsAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get ancestors (parent pages) of a specific Confluence page.
|
|
||||||
* Uses GET /wiki/api/v2/pages/{id}/ancestors
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const { domain, accessToken, pageId, cloudId: providedCloudId, limit = 25 } = body
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!pageId) {
|
|
||||||
return NextResponse.json({ error: 'Page ID is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const pageIdValidation = validateAlphanumericId(pageId, 'pageId', 255)
|
|
||||||
if (!pageIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: pageIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
queryParams.append('limit', String(Math.min(limit, 250)))
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/ancestors?${queryParams.toString()}`
|
|
||||||
|
|
||||||
logger.info(`Fetching ancestors for page ${pageId}`)
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to get page ancestors (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const ancestors = (data.results || []).map((page: any) => ({
|
|
||||||
id: page.id,
|
|
||||||
title: page.title,
|
|
||||||
status: page.status ?? null,
|
|
||||||
spaceId: page.spaceId ?? null,
|
|
||||||
webUrl: page._links?.webui ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
ancestors,
|
|
||||||
pageId,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error getting page ancestors:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluencePageChildrenAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get child pages of a specific Confluence page.
|
|
||||||
* Uses GET /wiki/api/v2/pages/{id}/children
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const { domain, accessToken, pageId, cloudId: providedCloudId, limit = 50, cursor } = body
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!pageId) {
|
|
||||||
return NextResponse.json({ error: 'Page ID is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const pageIdValidation = validateAlphanumericId(pageId, 'pageId', 255)
|
|
||||||
if (!pageIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: pageIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
queryParams.append('limit', String(Math.min(limit, 250)))
|
|
||||||
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/children?${queryParams.toString()}`
|
|
||||||
|
|
||||||
logger.info(`Fetching child pages for page ${pageId}`)
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to get child pages (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const children = (data.results || []).map((page: any) => ({
|
|
||||||
id: page.id,
|
|
||||||
title: page.title,
|
|
||||||
status: page.status ?? null,
|
|
||||||
spaceId: page.spaceId ?? null,
|
|
||||||
childPosition: page.childPosition ?? null,
|
|
||||||
webUrl: page._links?.webui ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
children,
|
|
||||||
parentId: pageId,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error getting child pages:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,365 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluencePagePropertiesAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
const createPropertySchema = z.object({
|
|
||||||
domain: z.string().min(1, 'Domain is required'),
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
cloudId: z.string().optional(),
|
|
||||||
pageId: z.string().min(1, 'Page ID is required'),
|
|
||||||
key: z.string().min(1, 'Property key is required'),
|
|
||||||
value: z.any(),
|
|
||||||
})
|
|
||||||
|
|
||||||
const updatePropertySchema = z.object({
|
|
||||||
domain: z.string().min(1, 'Domain is required'),
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
cloudId: z.string().optional(),
|
|
||||||
pageId: z.string().min(1, 'Page ID is required'),
|
|
||||||
propertyId: z.string().min(1, 'Property ID is required'),
|
|
||||||
key: z.string().min(1, 'Property key is required'),
|
|
||||||
value: z.any(),
|
|
||||||
versionNumber: z.number().min(1, 'Version number is required'),
|
|
||||||
})
|
|
||||||
|
|
||||||
const deletePropertySchema = z.object({
|
|
||||||
domain: z.string().min(1, 'Domain is required'),
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
cloudId: z.string().optional(),
|
|
||||||
pageId: z.string().min(1, 'Page ID is required'),
|
|
||||||
propertyId: z.string().min(1, 'Property ID is required'),
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* List all content properties on a page.
|
|
||||||
*/
|
|
||||||
export async function GET(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { searchParams } = new URL(request.url)
|
|
||||||
const domain = searchParams.get('domain')
|
|
||||||
const accessToken = searchParams.get('accessToken')
|
|
||||||
const pageId = searchParams.get('pageId')
|
|
||||||
const providedCloudId = searchParams.get('cloudId')
|
|
||||||
const limit = searchParams.get('limit') || '50'
|
|
||||||
const cursor = searchParams.get('cursor')
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!pageId) {
|
|
||||||
return NextResponse.json({ error: 'Page ID is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const pageIdValidation = validateAlphanumericId(pageId, 'pageId', 255)
|
|
||||||
if (!pageIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: pageIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
queryParams.append('limit', String(Math.min(Number(limit), 250)))
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/properties?${queryParams.toString()}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage =
|
|
||||||
errorData?.message || `Failed to list page properties (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const properties = (data.results || []).map((prop: any) => ({
|
|
||||||
id: prop.id,
|
|
||||||
key: prop.key,
|
|
||||||
value: prop.value ?? null,
|
|
||||||
version: prop.version ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
properties,
|
|
||||||
pageId,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error listing page properties:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a new content property on a page.
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
|
|
||||||
const validation = createPropertySchema.safeParse(body)
|
|
||||||
if (!validation.success) {
|
|
||||||
const firstError = validation.error.errors[0]
|
|
||||||
return NextResponse.json({ error: firstError.message }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { domain, accessToken, cloudId: providedCloudId, pageId, key, value } = validation.data
|
|
||||||
|
|
||||||
const pageIdValidation = validateAlphanumericId(pageId, 'pageId', 255)
|
|
||||||
if (!pageIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: pageIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/properties`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ key, value }),
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage =
|
|
||||||
errorData?.message || `Failed to create page property (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
return NextResponse.json({
|
|
||||||
id: data.id,
|
|
||||||
key: data.key,
|
|
||||||
value: data.value,
|
|
||||||
version: data.version,
|
|
||||||
pageId,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error creating page property:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update a content property on a page.
|
|
||||||
*/
|
|
||||||
export async function PUT(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
|
|
||||||
const validation = updatePropertySchema.safeParse(body)
|
|
||||||
if (!validation.success) {
|
|
||||||
const firstError = validation.error.errors[0]
|
|
||||||
return NextResponse.json({ error: firstError.message }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const {
|
|
||||||
domain,
|
|
||||||
accessToken,
|
|
||||||
cloudId: providedCloudId,
|
|
||||||
pageId,
|
|
||||||
propertyId,
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
versionNumber,
|
|
||||||
} = validation.data
|
|
||||||
|
|
||||||
const pageIdValidation = validateAlphanumericId(pageId, 'pageId', 255)
|
|
||||||
if (!pageIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: pageIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const propertyIdValidation = validateAlphanumericId(propertyId, 'propertyId', 255)
|
|
||||||
if (!propertyIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: propertyIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/properties/${propertyId}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'PUT',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
key,
|
|
||||||
value,
|
|
||||||
version: { number: versionNumber },
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage =
|
|
||||||
errorData?.message || `Failed to update page property (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
return NextResponse.json({
|
|
||||||
id: data.id,
|
|
||||||
key: data.key,
|
|
||||||
value: data.value,
|
|
||||||
version: data.version,
|
|
||||||
pageId,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error updating page property:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete a content property from a page.
|
|
||||||
*/
|
|
||||||
export async function DELETE(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
|
|
||||||
const validation = deletePropertySchema.safeParse(body)
|
|
||||||
if (!validation.success) {
|
|
||||||
const firstError = validation.error.errors[0]
|
|
||||||
return NextResponse.json({ error: firstError.message }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const { domain, accessToken, cloudId: providedCloudId, pageId, propertyId } = validation.data
|
|
||||||
|
|
||||||
const pageIdValidation = validateAlphanumericId(pageId, 'pageId', 255)
|
|
||||||
if (!pageIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: pageIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const propertyIdValidation = validateAlphanumericId(propertyId, 'propertyId', 255)
|
|
||||||
if (!propertyIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: propertyIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/properties/${propertyId}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'DELETE',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage =
|
|
||||||
errorData?.message || `Failed to delete page property (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
return NextResponse.json({ propertyId, pageId, deleted: true })
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error deleting page property:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluencePageVersionsAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* List all versions of a page or get a specific version.
|
|
||||||
* Uses GET /wiki/api/v2/pages/{id}/versions
|
|
||||||
* and GET /wiki/api/v2/pages/{page-id}/versions/{version-number}
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const {
|
|
||||||
domain,
|
|
||||||
accessToken,
|
|
||||||
pageId,
|
|
||||||
versionNumber,
|
|
||||||
cloudId: providedCloudId,
|
|
||||||
limit = 50,
|
|
||||||
cursor,
|
|
||||||
} = body
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!pageId) {
|
|
||||||
return NextResponse.json({ error: 'Page ID is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const pageIdValidation = validateAlphanumericId(pageId, 'pageId', 255)
|
|
||||||
if (!pageIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: pageIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
// If versionNumber is provided, get specific version
|
|
||||||
if (versionNumber !== undefined && versionNumber !== null) {
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/versions/${versionNumber}`
|
|
||||||
|
|
||||||
logger.info(`Fetching version ${versionNumber} for page ${pageId}`)
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to get page version (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
version: {
|
|
||||||
number: data.number,
|
|
||||||
message: data.message ?? null,
|
|
||||||
minorEdit: data.minorEdit ?? false,
|
|
||||||
authorId: data.authorId ?? null,
|
|
||||||
createdAt: data.createdAt ?? null,
|
|
||||||
},
|
|
||||||
pageId,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
// List all versions
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
queryParams.append('limit', String(Math.min(limit, 250)))
|
|
||||||
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}/versions?${queryParams.toString()}`
|
|
||||||
|
|
||||||
logger.info(`Fetching versions for page ${pageId}`)
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to list page versions (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const versions = (data.results || []).map((version: any) => ({
|
|
||||||
number: version.number,
|
|
||||||
message: version.message ?? null,
|
|
||||||
minorEdit: version.minorEdit ?? false,
|
|
||||||
authorId: version.authorId ?? null,
|
|
||||||
createdAt: version.createdAt ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
versions,
|
|
||||||
pageId,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error with page versions:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -62,7 +62,6 @@ const deletePageSchema = z
|
|||||||
accessToken: z.string().min(1, 'Access token is required'),
|
accessToken: z.string().min(1, 'Access token is required'),
|
||||||
cloudId: z.string().optional(),
|
cloudId: z.string().optional(),
|
||||||
pageId: z.string().min(1, 'Page ID is required'),
|
pageId: z.string().min(1, 'Page ID is required'),
|
||||||
purge: z.boolean().optional(),
|
|
||||||
})
|
})
|
||||||
.refine(
|
.refine(
|
||||||
(data) => {
|
(data) => {
|
||||||
@@ -99,7 +98,7 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}?body-format=storage`
|
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}?expand=body.storage,body.view,body.atlas_doc_format`
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -131,18 +130,16 @@ export async function POST(request: NextRequest) {
|
|||||||
id: data.id,
|
id: data.id,
|
||||||
title: data.title,
|
title: data.title,
|
||||||
body: {
|
body: {
|
||||||
storage: {
|
view: {
|
||||||
value: data.body?.storage?.value ?? null,
|
value:
|
||||||
representation: 'storage',
|
data.body?.storage?.value ||
|
||||||
|
data.body?.view?.value ||
|
||||||
|
data.body?.atlas_doc_format?.value ||
|
||||||
|
data.content || // try alternative fields
|
||||||
|
data.description ||
|
||||||
|
`Content for page ${data.title}`, // fallback content
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
status: data.status ?? null,
|
|
||||||
spaceId: data.spaceId ?? null,
|
|
||||||
parentId: data.parentId ?? null,
|
|
||||||
authorId: data.authorId ?? null,
|
|
||||||
createdAt: data.createdAt ?? null,
|
|
||||||
version: data.version ?? null,
|
|
||||||
_links: data._links ?? null,
|
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Error fetching Confluence page:', error)
|
logger.error('Error fetching Confluence page:', error)
|
||||||
@@ -277,7 +274,7 @@ export async function DELETE(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: firstError.message }, { status: 400 })
|
return NextResponse.json({ error: firstError.message }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const { domain, accessToken, cloudId: providedCloudId, pageId, purge } = validation.data
|
const { domain, accessToken, cloudId: providedCloudId, pageId } = validation.data
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
||||||
|
|
||||||
@@ -286,12 +283,7 @@ export async function DELETE(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}`
|
||||||
if (purge) {
|
|
||||||
queryParams.append('purge', 'true')
|
|
||||||
}
|
|
||||||
const queryString = queryParams.toString()
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages/${pageId}${queryString ? `?${queryString}` : ''}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Use provided cloudId or fetch it if not provided
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||||
@@ -39,6 +40,7 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Build the URL with query parameters
|
||||||
const baseUrl = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages`
|
const baseUrl = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/pages`
|
||||||
const queryParams = new URLSearchParams()
|
const queryParams = new URLSearchParams()
|
||||||
|
|
||||||
@@ -55,6 +57,7 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
logger.info(`Fetching Confluence pages from: ${url}`)
|
logger.info(`Fetching Confluence pages from: ${url}`)
|
||||||
|
|
||||||
|
// Make the request to Confluence API with OAuth Bearer token
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -76,6 +79,7 @@ export async function POST(request: NextRequest) {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error('Could not parse error response as JSON:', e)
|
logger.error('Could not parse error response as JSON:', e)
|
||||||
|
|
||||||
|
// Try to get the response text for more context
|
||||||
try {
|
try {
|
||||||
const text = await response.text()
|
const text = await response.text()
|
||||||
logger.error('Response text:', text)
|
logger.error('Response text:', text)
|
||||||
|
|||||||
@@ -1,120 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluenceSearchInSpaceAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Search for content within a specific Confluence space using CQL.
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const {
|
|
||||||
domain,
|
|
||||||
accessToken,
|
|
||||||
spaceKey,
|
|
||||||
query,
|
|
||||||
cloudId: providedCloudId,
|
|
||||||
limit = 25,
|
|
||||||
contentType,
|
|
||||||
} = body
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!spaceKey) {
|
|
||||||
return NextResponse.json({ error: 'Space key is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const spaceKeyValidation = validateAlphanumericId(spaceKey, 'spaceKey', 255)
|
|
||||||
if (!spaceKeyValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: spaceKeyValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const escapeCqlValue = (value: string) => value.replace(/"/g, '\\"')
|
|
||||||
|
|
||||||
let cql = `space = "${escapeCqlValue(spaceKey)}"`
|
|
||||||
|
|
||||||
if (query) {
|
|
||||||
cql += ` AND text ~ "${escapeCqlValue(query)}"`
|
|
||||||
}
|
|
||||||
|
|
||||||
if (contentType) {
|
|
||||||
cql += ` AND type = "${escapeCqlValue(contentType)}"`
|
|
||||||
}
|
|
||||||
|
|
||||||
const searchParams = new URLSearchParams({
|
|
||||||
cql,
|
|
||||||
limit: String(Math.min(limit, 250)),
|
|
||||||
})
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/rest/api/search?${searchParams.toString()}`
|
|
||||||
|
|
||||||
logger.info(`Searching in space ${spaceKey} with CQL: ${cql}`)
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage = errorData?.message || `Failed to search in space (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const results = (data.results || []).map((result: any) => ({
|
|
||||||
id: result.content?.id ?? result.id,
|
|
||||||
title: result.content?.title ?? result.title,
|
|
||||||
type: result.content?.type ?? result.type,
|
|
||||||
status: result.content?.status ?? null,
|
|
||||||
url: result.url ?? result._links?.webui ?? '',
|
|
||||||
excerpt: result.excerpt ?? '',
|
|
||||||
lastModified: result.lastModified ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
results,
|
|
||||||
spaceKey,
|
|
||||||
totalSize: data.totalSize ?? results.length,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error searching in space:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -42,10 +42,8 @@ export async function POST(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const escapeCqlValue = (value: string) => value.replace(/"/g, '\\"')
|
|
||||||
|
|
||||||
const searchParams = new URLSearchParams({
|
const searchParams = new URLSearchParams({
|
||||||
cql: `text ~ "${escapeCqlValue(query)}"`,
|
cql: `text ~ "${query}"`,
|
||||||
limit: limit.toString(),
|
limit: limit.toString(),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -72,27 +70,13 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
const data = await response.json()
|
const data = await response.json()
|
||||||
|
|
||||||
const results = (data.results || []).map((result: any) => {
|
const results = (data.results || []).map((result: any) => ({
|
||||||
const spaceData = result.resultGlobalContainer || result.content?.space
|
id: result.content?.id || result.id,
|
||||||
return {
|
title: result.content?.title || result.title,
|
||||||
id: result.content?.id || result.id,
|
type: result.content?.type || result.type,
|
||||||
title: result.content?.title || result.title,
|
url: result.url || result._links?.webui || '',
|
||||||
type: result.content?.type || result.type,
|
excerpt: result.excerpt || '',
|
||||||
url: result.url || result._links?.webui || '',
|
}))
|
||||||
excerpt: result.excerpt || '',
|
|
||||||
status: result.content?.status ?? null,
|
|
||||||
spaceKey: result.resultGlobalContainer?.key ?? result.content?.space?.key ?? null,
|
|
||||||
space: spaceData
|
|
||||||
? {
|
|
||||||
id: spaceData.id ?? null,
|
|
||||||
key: spaceData.key ?? null,
|
|
||||||
name: spaceData.name ?? spaceData.title ?? null,
|
|
||||||
}
|
|
||||||
: null,
|
|
||||||
lastModified: result.lastModified ?? result.content?.history?.lastUpdated?.when ?? null,
|
|
||||||
entityType: result.entityType ?? null,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return NextResponse.json({ results })
|
return NextResponse.json({ results })
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,124 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluenceSpaceBlogPostsAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* List all blog posts in a specific Confluence space.
|
|
||||||
* Uses GET /wiki/api/v2/spaces/{id}/blogposts
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const {
|
|
||||||
domain,
|
|
||||||
accessToken,
|
|
||||||
spaceId,
|
|
||||||
cloudId: providedCloudId,
|
|
||||||
limit = 25,
|
|
||||||
status,
|
|
||||||
bodyFormat,
|
|
||||||
cursor,
|
|
||||||
} = body
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!spaceId) {
|
|
||||||
return NextResponse.json({ error: 'Space ID is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const spaceIdValidation = validateAlphanumericId(spaceId, 'spaceId', 255)
|
|
||||||
if (!spaceIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: spaceIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
queryParams.append('limit', String(Math.min(limit, 250)))
|
|
||||||
|
|
||||||
if (status) {
|
|
||||||
queryParams.append('status', status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (bodyFormat) {
|
|
||||||
queryParams.append('body-format', bodyFormat)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/spaces/${spaceId}/blogposts?${queryParams.toString()}`
|
|
||||||
|
|
||||||
logger.info(`Fetching blog posts in space ${spaceId}`)
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage =
|
|
||||||
errorData?.message || `Failed to list blog posts in space (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const blogPosts = (data.results || []).map((post: any) => ({
|
|
||||||
id: post.id,
|
|
||||||
title: post.title,
|
|
||||||
status: post.status ?? null,
|
|
||||||
spaceId: post.spaceId ?? null,
|
|
||||||
authorId: post.authorId ?? null,
|
|
||||||
createdAt: post.createdAt ?? null,
|
|
||||||
version: post.version ?? null,
|
|
||||||
body: post.body ?? null,
|
|
||||||
webUrl: post._links?.webui ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
blogPosts,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error listing blog posts in space:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { validateAlphanumericId, validateJiraCloudId } from '@/lib/core/security/input-validation'
|
|
||||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('ConfluenceSpacePagesAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
/**
|
|
||||||
* List all pages in a specific Confluence space.
|
|
||||||
* Uses GET /wiki/api/v2/spaces/{id}/pages
|
|
||||||
*/
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
try {
|
|
||||||
const auth = await checkSessionOrInternalAuth(request)
|
|
||||||
if (!auth.success || !auth.userId) {
|
|
||||||
return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const {
|
|
||||||
domain,
|
|
||||||
accessToken,
|
|
||||||
spaceId,
|
|
||||||
cloudId: providedCloudId,
|
|
||||||
limit = 50,
|
|
||||||
status,
|
|
||||||
bodyFormat,
|
|
||||||
cursor,
|
|
||||||
} = body
|
|
||||||
|
|
||||||
if (!domain) {
|
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!accessToken) {
|
|
||||||
return NextResponse.json({ error: 'Access token is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!spaceId) {
|
|
||||||
return NextResponse.json({ error: 'Space ID is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const spaceIdValidation = validateAlphanumericId(spaceId, 'spaceId', 255)
|
|
||||||
if (!spaceIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: spaceIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId = providedCloudId || (await getConfluenceCloudId(domain, accessToken))
|
|
||||||
|
|
||||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
|
||||||
if (!cloudIdValidation.isValid) {
|
|
||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
|
||||||
queryParams.append('limit', String(Math.min(limit, 250)))
|
|
||||||
|
|
||||||
if (status) {
|
|
||||||
queryParams.append('status', status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (bodyFormat) {
|
|
||||||
queryParams.append('body-format', bodyFormat)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/spaces/${spaceId}/pages?${queryParams.toString()}`
|
|
||||||
|
|
||||||
logger.info(`Fetching pages in space ${spaceId}`)
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/json',
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = await response.json().catch(() => null)
|
|
||||||
logger.error('Confluence API error response:', {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: JSON.stringify(errorData, null, 2),
|
|
||||||
})
|
|
||||||
const errorMessage =
|
|
||||||
errorData?.message || `Failed to list pages in space (${response.status})`
|
|
||||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
const pages = (data.results || []).map((page: any) => ({
|
|
||||||
id: page.id,
|
|
||||||
title: page.title,
|
|
||||||
status: page.status ?? null,
|
|
||||||
spaceId: page.spaceId ?? null,
|
|
||||||
parentId: page.parentId ?? null,
|
|
||||||
authorId: page.authorId ?? null,
|
|
||||||
createdAt: page.createdAt ?? null,
|
|
||||||
version: page.version ?? null,
|
|
||||||
body: page.body ?? null,
|
|
||||||
webUrl: page._links?.webui ?? null,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
pages,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Error listing pages in space:', error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: (error as Error).message || 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,6 @@ export async function GET(request: NextRequest) {
|
|||||||
const accessToken = searchParams.get('accessToken')
|
const accessToken = searchParams.get('accessToken')
|
||||||
const providedCloudId = searchParams.get('cloudId')
|
const providedCloudId = searchParams.get('cloudId')
|
||||||
const limit = searchParams.get('limit') || '25'
|
const limit = searchParams.get('limit') || '25'
|
||||||
const cursor = searchParams.get('cursor')
|
|
||||||
|
|
||||||
if (!domain) {
|
if (!domain) {
|
||||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||||
@@ -38,12 +37,7 @@ export async function GET(request: NextRequest) {
|
|||||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const queryParams = new URLSearchParams()
|
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/spaces?limit=${limit}`
|
||||||
queryParams.append('limit', String(Math.min(Number(limit), 250)))
|
|
||||||
if (cursor) {
|
|
||||||
queryParams.append('cursor', cursor)
|
|
||||||
}
|
|
||||||
const url = `https://api.atlassian.com/ex/confluence/${cloudId}/wiki/api/v2/spaces?${queryParams.toString()}`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -73,18 +67,9 @@ export async function GET(request: NextRequest) {
|
|||||||
key: space.key,
|
key: space.key,
|
||||||
type: space.type,
|
type: space.type,
|
||||||
status: space.status,
|
status: space.status,
|
||||||
authorId: space.authorId ?? null,
|
|
||||||
createdAt: space.createdAt ?? null,
|
|
||||||
homepageId: space.homepageId ?? null,
|
|
||||||
description: space.description ?? null,
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({ spaces })
|
||||||
spaces,
|
|
||||||
nextCursor: data._links?.next
|
|
||||||
? new URL(data._links.next, 'https://placeholder').searchParams.get('cursor')
|
|
||||||
: null,
|
|
||||||
})
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Error listing Confluence spaces:', error)
|
logger.error('Error listing Confluence spaces:', error)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -92,9 +92,6 @@ export async function POST(request: NextRequest) {
|
|||||||
formData.append('comment', comment)
|
formData.append('comment', comment)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add minorEdit field as required by Confluence API
|
|
||||||
formData.append('minorEdit', 'false')
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { z } from 'zod'
|
|||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||||
import { validateNumericId } from '@/lib/core/security/input-validation'
|
import { validateNumericId } from '@/lib/core/security/input-validation'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas'
|
|
||||||
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
||||||
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
||||||
|
|
||||||
@@ -16,7 +15,7 @@ const DiscordSendMessageSchema = z.object({
|
|||||||
botToken: z.string().min(1, 'Bot token is required'),
|
botToken: z.string().min(1, 'Bot token is required'),
|
||||||
channelId: z.string().min(1, 'Channel ID is required'),
|
channelId: z.string().min(1, 'Channel ID is required'),
|
||||||
content: z.string().optional().nullable(),
|
content: z.string().optional().nullable(),
|
||||||
files: RawFileInputArraySchema.optional().nullable(),
|
files: z.array(z.any()).optional().nullable(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
@@ -102,12 +101,6 @@ export async function POST(request: NextRequest) {
|
|||||||
logger.info(`[${requestId}] Processing ${validatedData.files.length} file(s)`)
|
logger.info(`[${requestId}] Processing ${validatedData.files.length} file(s)`)
|
||||||
|
|
||||||
const userFiles = processFilesToUserFiles(validatedData.files, requestId, logger)
|
const userFiles = processFilesToUserFiles(validatedData.files, requestId, logger)
|
||||||
const filesOutput: Array<{
|
|
||||||
name: string
|
|
||||||
mimeType: string
|
|
||||||
data: string
|
|
||||||
size: number
|
|
||||||
}> = []
|
|
||||||
|
|
||||||
if (userFiles.length === 0) {
|
if (userFiles.length === 0) {
|
||||||
logger.warn(`[${requestId}] No valid files to upload, falling back to text-only`)
|
logger.warn(`[${requestId}] No valid files to upload, falling back to text-only`)
|
||||||
@@ -144,12 +137,6 @@ export async function POST(request: NextRequest) {
|
|||||||
logger.info(`[${requestId}] Downloading file ${i}: ${userFile.name}`)
|
logger.info(`[${requestId}] Downloading file ${i}: ${userFile.name}`)
|
||||||
|
|
||||||
const buffer = await downloadFileFromStorage(userFile, requestId, logger)
|
const buffer = await downloadFileFromStorage(userFile, requestId, logger)
|
||||||
filesOutput.push({
|
|
||||||
name: userFile.name,
|
|
||||||
mimeType: userFile.type || 'application/octet-stream',
|
|
||||||
data: buffer.toString('base64'),
|
|
||||||
size: buffer.length,
|
|
||||||
})
|
|
||||||
|
|
||||||
const blob = new Blob([new Uint8Array(buffer)], { type: userFile.type })
|
const blob = new Blob([new Uint8Array(buffer)], { type: userFile.type })
|
||||||
formData.append(`files[${i}]`, blob, userFile.name)
|
formData.append(`files[${i}]`, blob, userFile.name)
|
||||||
@@ -186,7 +173,6 @@ export async function POST(request: NextRequest) {
|
|||||||
message: data.content,
|
message: data.content,
|
||||||
data: data,
|
data: data,
|
||||||
fileCount: userFiles.length,
|
fileCount: userFiles.length,
|
||||||
files: filesOutput,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,132 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
|
||||||
import { httpHeaderSafeJson } from '@/lib/core/utils/validation'
|
|
||||||
import { FileInputSchema } from '@/lib/uploads/utils/file-schemas'
|
|
||||||
import { processFilesToUserFiles, type RawFileInput } from '@/lib/uploads/utils/file-utils'
|
|
||||||
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
const logger = createLogger('DropboxUploadAPI')
|
|
||||||
|
|
||||||
const DropboxUploadSchema = z.object({
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
path: z.string().min(1, 'Destination path is required'),
|
|
||||||
file: FileInputSchema.optional().nullable(),
|
|
||||||
// Legacy field for backwards compatibility
|
|
||||||
fileContent: z.string().optional().nullable(),
|
|
||||||
fileName: z.string().optional().nullable(),
|
|
||||||
mode: z.enum(['add', 'overwrite']).optional().nullable(),
|
|
||||||
autorename: z.boolean().optional().nullable(),
|
|
||||||
mute: z.boolean().optional().nullable(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
const requestId = generateRequestId()
|
|
||||||
|
|
||||||
try {
|
|
||||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
|
||||||
|
|
||||||
if (!authResult.success) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized Dropbox upload attempt: ${authResult.error}`)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: authResult.error || 'Authentication required' },
|
|
||||||
{ status: 401 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Authenticated Dropbox upload request via ${authResult.authType}`)
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const validatedData = DropboxUploadSchema.parse(body)
|
|
||||||
|
|
||||||
let fileBuffer: Buffer
|
|
||||||
let fileName: string
|
|
||||||
|
|
||||||
// Prefer UserFile input, fall back to legacy base64 string
|
|
||||||
if (validatedData.file) {
|
|
||||||
// Process UserFile input
|
|
||||||
const userFiles = processFilesToUserFiles(
|
|
||||||
[validatedData.file as RawFileInput],
|
|
||||||
requestId,
|
|
||||||
logger
|
|
||||||
)
|
|
||||||
|
|
||||||
if (userFiles.length === 0) {
|
|
||||||
return NextResponse.json({ success: false, error: 'Invalid file input' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const userFile = userFiles[0]
|
|
||||||
logger.info(`[${requestId}] Downloading file: ${userFile.name} (${userFile.size} bytes)`)
|
|
||||||
|
|
||||||
fileBuffer = await downloadFileFromStorage(userFile, requestId, logger)
|
|
||||||
fileName = userFile.name
|
|
||||||
} else if (validatedData.fileContent) {
|
|
||||||
// Legacy: base64 string input (backwards compatibility)
|
|
||||||
logger.info(`[${requestId}] Using legacy base64 content input`)
|
|
||||||
fileBuffer = Buffer.from(validatedData.fileContent, 'base64')
|
|
||||||
fileName = validatedData.fileName || 'file'
|
|
||||||
} else {
|
|
||||||
return NextResponse.json({ success: false, error: 'File is required' }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine final path
|
|
||||||
let finalPath = validatedData.path
|
|
||||||
if (finalPath.endsWith('/')) {
|
|
||||||
finalPath = `${finalPath}${fileName}`
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Uploading to Dropbox: ${finalPath} (${fileBuffer.length} bytes)`)
|
|
||||||
|
|
||||||
const dropboxApiArg = {
|
|
||||||
path: finalPath,
|
|
||||||
mode: validatedData.mode || 'add',
|
|
||||||
autorename: validatedData.autorename ?? true,
|
|
||||||
mute: validatedData.mute ?? false,
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch('https://content.dropboxapi.com/2/files/upload', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${validatedData.accessToken}`,
|
|
||||||
'Content-Type': 'application/octet-stream',
|
|
||||||
'Dropbox-API-Arg': httpHeaderSafeJson(dropboxApiArg),
|
|
||||||
},
|
|
||||||
body: new Uint8Array(fileBuffer),
|
|
||||||
})
|
|
||||||
|
|
||||||
const data = await response.json()
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorMessage = data.error_summary || data.error?.message || 'Failed to upload file'
|
|
||||||
logger.error(`[${requestId}] Dropbox API error:`, { status: response.status, data })
|
|
||||||
return NextResponse.json({ success: false, error: errorMessage }, { status: response.status })
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] File uploaded successfully to ${data.path_display}`)
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
output: {
|
|
||||||
file: data,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof z.ZodError) {
|
|
||||||
logger.warn(`[${requestId}] Validation error:`, error.errors)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: error.errors[0]?.message || 'Validation failed' },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.error(`[${requestId}] Unexpected error:`, error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: error instanceof Error ? error.message : 'Unknown error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,195 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
|
||||||
secureFetchWithPinnedIP,
|
|
||||||
validateUrlWithDNS,
|
|
||||||
} from '@/lib/core/security/input-validation.server'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
const logger = createLogger('GitHubLatestCommitAPI')
|
|
||||||
|
|
||||||
interface GitHubErrorResponse {
|
|
||||||
message?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GitHubCommitResponse {
|
|
||||||
sha: string
|
|
||||||
html_url: string
|
|
||||||
commit: {
|
|
||||||
message: string
|
|
||||||
author: { name: string; email: string; date: string }
|
|
||||||
committer: { name: string; email: string; date: string }
|
|
||||||
}
|
|
||||||
author?: { login: string; avatar_url: string; html_url: string }
|
|
||||||
committer?: { login: string; avatar_url: string; html_url: string }
|
|
||||||
stats?: { additions: number; deletions: number; total: number }
|
|
||||||
files?: Array<{
|
|
||||||
filename: string
|
|
||||||
status: string
|
|
||||||
additions: number
|
|
||||||
deletions: number
|
|
||||||
changes: number
|
|
||||||
patch?: string
|
|
||||||
raw_url?: string
|
|
||||||
blob_url?: string
|
|
||||||
}>
|
|
||||||
}
|
|
||||||
|
|
||||||
const GitHubLatestCommitSchema = z.object({
|
|
||||||
owner: z.string().min(1, 'Owner is required'),
|
|
||||||
repo: z.string().min(1, 'Repo is required'),
|
|
||||||
branch: z.string().optional().nullable(),
|
|
||||||
apiKey: z.string().min(1, 'API key is required'),
|
|
||||||
})
|
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
const requestId = generateRequestId()
|
|
||||||
|
|
||||||
try {
|
|
||||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
|
||||||
|
|
||||||
if (!authResult.success) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized GitHub latest commit attempt: ${authResult.error}`)
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: authResult.error || 'Authentication required',
|
|
||||||
},
|
|
||||||
{ status: 401 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const validatedData = GitHubLatestCommitSchema.parse(body)
|
|
||||||
|
|
||||||
const { owner, repo, branch, apiKey } = validatedData
|
|
||||||
|
|
||||||
const baseUrl = `https://api.github.com/repos/${owner}/${repo}`
|
|
||||||
const commitUrl = branch ? `${baseUrl}/commits/${branch}` : `${baseUrl}/commits/HEAD`
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Fetching latest commit from GitHub`, { owner, repo, branch })
|
|
||||||
|
|
||||||
const urlValidation = await validateUrlWithDNS(commitUrl, 'commitUrl')
|
|
||||||
if (!urlValidation.isValid) {
|
|
||||||
return NextResponse.json({ success: false, error: urlValidation.error }, { status: 400 })
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await secureFetchWithPinnedIP(commitUrl, urlValidation.resolvedIP!, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Accept: 'application/vnd.github.v3+json',
|
|
||||||
Authorization: `Bearer ${apiKey}`,
|
|
||||||
'X-GitHub-Api-Version': '2022-11-28',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorData = (await response.json().catch(() => ({}))) as GitHubErrorResponse
|
|
||||||
logger.error(`[${requestId}] GitHub API error`, {
|
|
||||||
status: response.status,
|
|
||||||
error: errorData,
|
|
||||||
})
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: errorData.message || `GitHub API error: ${response.status}` },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = (await response.json()) as GitHubCommitResponse
|
|
||||||
|
|
||||||
const content = `Latest commit: "${data.commit.message}" by ${data.commit.author.name} on ${data.commit.author.date}. SHA: ${data.sha}`
|
|
||||||
|
|
||||||
const files = data.files || []
|
|
||||||
const fileDetailsWithContent = []
|
|
||||||
|
|
||||||
for (const file of files) {
|
|
||||||
const fileDetail: Record<string, any> = {
|
|
||||||
filename: file.filename,
|
|
||||||
additions: file.additions,
|
|
||||||
deletions: file.deletions,
|
|
||||||
changes: file.changes,
|
|
||||||
status: file.status,
|
|
||||||
raw_url: file.raw_url,
|
|
||||||
blob_url: file.blob_url,
|
|
||||||
patch: file.patch,
|
|
||||||
content: undefined,
|
|
||||||
}
|
|
||||||
|
|
||||||
if (file.status !== 'removed' && file.raw_url) {
|
|
||||||
try {
|
|
||||||
const rawUrlValidation = await validateUrlWithDNS(file.raw_url, 'rawUrl')
|
|
||||||
if (rawUrlValidation.isValid) {
|
|
||||||
const contentResponse = await secureFetchWithPinnedIP(
|
|
||||||
file.raw_url,
|
|
||||||
rawUrlValidation.resolvedIP!,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${apiKey}`,
|
|
||||||
'X-GitHub-Api-Version': '2022-11-28',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
if (contentResponse.ok) {
|
|
||||||
fileDetail.content = await contentResponse.text()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.warn(`[${requestId}] Failed to fetch content for ${file.filename}:`, error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fileDetailsWithContent.push(fileDetail)
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Latest commit fetched successfully`, {
|
|
||||||
sha: data.sha,
|
|
||||||
fileCount: files.length,
|
|
||||||
})
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
output: {
|
|
||||||
content,
|
|
||||||
metadata: {
|
|
||||||
sha: data.sha,
|
|
||||||
html_url: data.html_url,
|
|
||||||
commit_message: data.commit.message,
|
|
||||||
author: {
|
|
||||||
name: data.commit.author.name,
|
|
||||||
login: data.author?.login || 'Unknown',
|
|
||||||
avatar_url: data.author?.avatar_url || '',
|
|
||||||
html_url: data.author?.html_url || '',
|
|
||||||
},
|
|
||||||
committer: {
|
|
||||||
name: data.commit.committer.name,
|
|
||||||
login: data.committer?.login || 'Unknown',
|
|
||||||
avatar_url: data.committer?.avatar_url || '',
|
|
||||||
html_url: data.committer?.html_url || '',
|
|
||||||
},
|
|
||||||
stats: data.stats
|
|
||||||
? {
|
|
||||||
additions: data.stats.additions,
|
|
||||||
deletions: data.stats.deletions,
|
|
||||||
total: data.stats.total,
|
|
||||||
}
|
|
||||||
: undefined,
|
|
||||||
files: fileDetailsWithContent.length > 0 ? fileDetailsWithContent : undefined,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error(`[${requestId}] Error fetching GitHub latest commit:`, error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: error instanceof Error ? error.message : 'Unknown error occurred',
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ import { type NextRequest, NextResponse } from 'next/server'
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas'
|
|
||||||
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
||||||
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
||||||
import {
|
import {
|
||||||
@@ -29,7 +28,7 @@ const GmailDraftSchema = z.object({
|
|||||||
replyToMessageId: z.string().optional().nullable(),
|
replyToMessageId: z.string().optional().nullable(),
|
||||||
cc: z.string().optional().nullable(),
|
cc: z.string().optional().nullable(),
|
||||||
bcc: z.string().optional().nullable(),
|
bcc: z.string().optional().nullable(),
|
||||||
attachments: RawFileInputArraySchema.optional().nullable(),
|
attachments: z.array(z.any()).optional().nullable(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { type NextRequest, NextResponse } from 'next/server'
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas'
|
|
||||||
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
||||||
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
||||||
import {
|
import {
|
||||||
@@ -29,7 +28,7 @@ const GmailSendSchema = z.object({
|
|||||||
replyToMessageId: z.string().optional().nullable(),
|
replyToMessageId: z.string().optional().nullable(),
|
||||||
cc: z.string().optional().nullable(),
|
cc: z.string().optional().nullable(),
|
||||||
bcc: z.string().optional().nullable(),
|
bcc: z.string().optional().nullable(),
|
||||||
attachments: RawFileInputArraySchema.optional().nullable(),
|
attachments: z.array(z.any()).optional().nullable(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
|
|||||||
@@ -1,252 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
|
||||||
secureFetchWithPinnedIP,
|
|
||||||
validateUrlWithDNS,
|
|
||||||
} from '@/lib/core/security/input-validation.server'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
|
||||||
import type { GoogleDriveFile, GoogleDriveRevision } from '@/tools/google_drive/types'
|
|
||||||
import {
|
|
||||||
ALL_FILE_FIELDS,
|
|
||||||
ALL_REVISION_FIELDS,
|
|
||||||
DEFAULT_EXPORT_FORMATS,
|
|
||||||
GOOGLE_WORKSPACE_MIME_TYPES,
|
|
||||||
} from '@/tools/google_drive/utils'
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
const logger = createLogger('GoogleDriveDownloadAPI')
|
|
||||||
|
|
||||||
/** Google API error response structure */
|
|
||||||
interface GoogleApiErrorResponse {
|
|
||||||
error?: {
|
|
||||||
message?: string
|
|
||||||
code?: number
|
|
||||||
status?: string
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Google Drive revisions list response */
|
|
||||||
interface GoogleDriveRevisionsResponse {
|
|
||||||
revisions?: GoogleDriveRevision[]
|
|
||||||
nextPageToken?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
const GoogleDriveDownloadSchema = z.object({
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
fileId: z.string().min(1, 'File ID is required'),
|
|
||||||
mimeType: z.string().optional().nullable(),
|
|
||||||
fileName: z.string().optional().nullable(),
|
|
||||||
includeRevisions: z.boolean().optional().default(true),
|
|
||||||
})
|
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
const requestId = generateRequestId()
|
|
||||||
|
|
||||||
try {
|
|
||||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
|
||||||
|
|
||||||
if (!authResult.success) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized Google Drive download attempt: ${authResult.error}`)
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: authResult.error || 'Authentication required',
|
|
||||||
},
|
|
||||||
{ status: 401 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const validatedData = GoogleDriveDownloadSchema.parse(body)
|
|
||||||
|
|
||||||
const {
|
|
||||||
accessToken,
|
|
||||||
fileId,
|
|
||||||
mimeType: exportMimeType,
|
|
||||||
fileName,
|
|
||||||
includeRevisions,
|
|
||||||
} = validatedData
|
|
||||||
const authHeader = `Bearer ${accessToken}`
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Getting file metadata from Google Drive`, { fileId })
|
|
||||||
|
|
||||||
const metadataUrl = `https://www.googleapis.com/drive/v3/files/${fileId}?fields=${ALL_FILE_FIELDS}&supportsAllDrives=true`
|
|
||||||
const metadataUrlValidation = await validateUrlWithDNS(metadataUrl, 'metadataUrl')
|
|
||||||
if (!metadataUrlValidation.isValid) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: metadataUrlValidation.error },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const metadataResponse = await secureFetchWithPinnedIP(
|
|
||||||
metadataUrl,
|
|
||||||
metadataUrlValidation.resolvedIP!,
|
|
||||||
{
|
|
||||||
headers: { Authorization: authHeader },
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!metadataResponse.ok) {
|
|
||||||
const errorDetails = (await metadataResponse
|
|
||||||
.json()
|
|
||||||
.catch(() => ({}))) as GoogleApiErrorResponse
|
|
||||||
logger.error(`[${requestId}] Failed to get file metadata`, {
|
|
||||||
status: metadataResponse.status,
|
|
||||||
error: errorDetails,
|
|
||||||
})
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: errorDetails.error?.message || 'Failed to get file metadata' },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const metadata = (await metadataResponse.json()) as GoogleDriveFile
|
|
||||||
const fileMimeType = metadata.mimeType
|
|
||||||
|
|
||||||
let fileBuffer: Buffer
|
|
||||||
let finalMimeType = fileMimeType
|
|
||||||
|
|
||||||
if (GOOGLE_WORKSPACE_MIME_TYPES.includes(fileMimeType)) {
|
|
||||||
const exportFormat = exportMimeType || DEFAULT_EXPORT_FORMATS[fileMimeType] || 'text/plain'
|
|
||||||
finalMimeType = exportFormat
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Exporting Google Workspace file`, {
|
|
||||||
fileId,
|
|
||||||
mimeType: fileMimeType,
|
|
||||||
exportFormat,
|
|
||||||
})
|
|
||||||
|
|
||||||
const exportUrl = `https://www.googleapis.com/drive/v3/files/${fileId}/export?mimeType=${encodeURIComponent(exportFormat)}&supportsAllDrives=true`
|
|
||||||
const exportUrlValidation = await validateUrlWithDNS(exportUrl, 'exportUrl')
|
|
||||||
if (!exportUrlValidation.isValid) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: exportUrlValidation.error },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const exportResponse = await secureFetchWithPinnedIP(
|
|
||||||
exportUrl,
|
|
||||||
exportUrlValidation.resolvedIP!,
|
|
||||||
{ headers: { Authorization: authHeader } }
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!exportResponse.ok) {
|
|
||||||
const exportError = (await exportResponse
|
|
||||||
.json()
|
|
||||||
.catch(() => ({}))) as GoogleApiErrorResponse
|
|
||||||
logger.error(`[${requestId}] Failed to export file`, {
|
|
||||||
status: exportResponse.status,
|
|
||||||
error: exportError,
|
|
||||||
})
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: exportError.error?.message || 'Failed to export Google Workspace file',
|
|
||||||
},
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const arrayBuffer = await exportResponse.arrayBuffer()
|
|
||||||
fileBuffer = Buffer.from(arrayBuffer)
|
|
||||||
} else {
|
|
||||||
logger.info(`[${requestId}] Downloading regular file`, { fileId, mimeType: fileMimeType })
|
|
||||||
|
|
||||||
const downloadUrl = `https://www.googleapis.com/drive/v3/files/${fileId}?alt=media&supportsAllDrives=true`
|
|
||||||
const downloadUrlValidation = await validateUrlWithDNS(downloadUrl, 'downloadUrl')
|
|
||||||
if (!downloadUrlValidation.isValid) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: downloadUrlValidation.error },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const downloadResponse = await secureFetchWithPinnedIP(
|
|
||||||
downloadUrl,
|
|
||||||
downloadUrlValidation.resolvedIP!,
|
|
||||||
{ headers: { Authorization: authHeader } }
|
|
||||||
)
|
|
||||||
|
|
||||||
if (!downloadResponse.ok) {
|
|
||||||
const downloadError = (await downloadResponse
|
|
||||||
.json()
|
|
||||||
.catch(() => ({}))) as GoogleApiErrorResponse
|
|
||||||
logger.error(`[${requestId}] Failed to download file`, {
|
|
||||||
status: downloadResponse.status,
|
|
||||||
error: downloadError,
|
|
||||||
})
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: downloadError.error?.message || 'Failed to download file' },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const arrayBuffer = await downloadResponse.arrayBuffer()
|
|
||||||
fileBuffer = Buffer.from(arrayBuffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
const canReadRevisions = metadata.capabilities?.canReadRevisions === true
|
|
||||||
if (includeRevisions && canReadRevisions) {
|
|
||||||
try {
|
|
||||||
const revisionsUrl = `https://www.googleapis.com/drive/v3/files/${fileId}/revisions?fields=revisions(${ALL_REVISION_FIELDS})&pageSize=100`
|
|
||||||
const revisionsUrlValidation = await validateUrlWithDNS(revisionsUrl, 'revisionsUrl')
|
|
||||||
if (revisionsUrlValidation.isValid) {
|
|
||||||
const revisionsResponse = await secureFetchWithPinnedIP(
|
|
||||||
revisionsUrl,
|
|
||||||
revisionsUrlValidation.resolvedIP!,
|
|
||||||
{ headers: { Authorization: authHeader } }
|
|
||||||
)
|
|
||||||
|
|
||||||
if (revisionsResponse.ok) {
|
|
||||||
const revisionsData = (await revisionsResponse.json()) as GoogleDriveRevisionsResponse
|
|
||||||
metadata.revisions = revisionsData.revisions
|
|
||||||
logger.info(`[${requestId}] Fetched file revisions`, {
|
|
||||||
fileId,
|
|
||||||
revisionCount: metadata.revisions?.length || 0,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
logger.warn(`[${requestId}] Error fetching revisions, continuing without them`, { error })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const resolvedName = fileName || metadata.name || 'download'
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] File downloaded successfully`, {
|
|
||||||
fileId,
|
|
||||||
name: resolvedName,
|
|
||||||
size: fileBuffer.length,
|
|
||||||
mimeType: finalMimeType,
|
|
||||||
})
|
|
||||||
|
|
||||||
const base64Data = fileBuffer.toString('base64')
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
output: {
|
|
||||||
file: {
|
|
||||||
name: resolvedName,
|
|
||||||
mimeType: finalMimeType,
|
|
||||||
data: base64Data,
|
|
||||||
size: fileBuffer.length,
|
|
||||||
},
|
|
||||||
metadata,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error(`[${requestId}] Error downloading Google Drive file:`, error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: error instanceof Error ? error.message : 'Unknown error occurred',
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ import { type NextRequest, NextResponse } from 'next/server'
|
|||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { RawFileInputSchema } from '@/lib/uploads/utils/file-schemas'
|
|
||||||
import { processSingleFileToUserFile } from '@/lib/uploads/utils/file-utils'
|
import { processSingleFileToUserFile } from '@/lib/uploads/utils/file-utils'
|
||||||
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
||||||
import {
|
import {
|
||||||
@@ -21,7 +20,7 @@ const GOOGLE_DRIVE_API_BASE = 'https://www.googleapis.com/upload/drive/v3/files'
|
|||||||
const GoogleDriveUploadSchema = z.object({
|
const GoogleDriveUploadSchema = z.object({
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
accessToken: z.string().min(1, 'Access token is required'),
|
||||||
fileName: z.string().min(1, 'File name is required'),
|
fileName: z.string().min(1, 'File name is required'),
|
||||||
file: RawFileInputSchema.optional().nullable(),
|
file: z.any().optional().nullable(),
|
||||||
mimeType: z.string().optional().nullable(),
|
mimeType: z.string().optional().nullable(),
|
||||||
folderId: z.string().optional().nullable(),
|
folderId: z.string().optional().nullable(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,131 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import {
|
|
||||||
secureFetchWithPinnedIP,
|
|
||||||
validateUrlWithDNS,
|
|
||||||
} from '@/lib/core/security/input-validation.server'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
|
||||||
import { enhanceGoogleVaultError } from '@/tools/google_vault/utils'
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
const logger = createLogger('GoogleVaultDownloadExportFileAPI')
|
|
||||||
|
|
||||||
const GoogleVaultDownloadExportFileSchema = z.object({
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
bucketName: z.string().min(1, 'Bucket name is required'),
|
|
||||||
objectName: z.string().min(1, 'Object name is required'),
|
|
||||||
fileName: z.string().optional().nullable(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
const requestId = generateRequestId()
|
|
||||||
|
|
||||||
try {
|
|
||||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
|
||||||
|
|
||||||
if (!authResult.success) {
|
|
||||||
logger.warn(`[${requestId}] Unauthorized Google Vault download attempt: ${authResult.error}`)
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: authResult.error || 'Authentication required',
|
|
||||||
},
|
|
||||||
{ status: 401 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const validatedData = GoogleVaultDownloadExportFileSchema.parse(body)
|
|
||||||
|
|
||||||
const { accessToken, bucketName, objectName, fileName } = validatedData
|
|
||||||
|
|
||||||
const bucket = encodeURIComponent(bucketName)
|
|
||||||
const object = encodeURIComponent(objectName)
|
|
||||||
const downloadUrl = `https://storage.googleapis.com/storage/v1/b/${bucket}/o/${object}?alt=media`
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Downloading file from Google Vault`, { bucketName, objectName })
|
|
||||||
|
|
||||||
const urlValidation = await validateUrlWithDNS(downloadUrl, 'downloadUrl')
|
|
||||||
if (!urlValidation.isValid) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: enhanceGoogleVaultError(urlValidation.error || 'Invalid URL') },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const downloadResponse = await secureFetchWithPinnedIP(downloadUrl, urlValidation.resolvedIP!, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${accessToken}`,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!downloadResponse.ok) {
|
|
||||||
const errorText = await downloadResponse.text().catch(() => '')
|
|
||||||
const errorMessage = `Failed to download file: ${errorText || downloadResponse.statusText}`
|
|
||||||
logger.error(`[${requestId}] Failed to download Vault export file`, {
|
|
||||||
status: downloadResponse.status,
|
|
||||||
error: errorText,
|
|
||||||
})
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: enhanceGoogleVaultError(errorMessage) },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const contentType = downloadResponse.headers.get('content-type') || 'application/octet-stream'
|
|
||||||
const disposition = downloadResponse.headers.get('content-disposition') || ''
|
|
||||||
const match = disposition.match(/filename\*=UTF-8''([^;]+)|filename="([^"]+)"/)
|
|
||||||
|
|
||||||
let resolvedName = fileName
|
|
||||||
if (!resolvedName) {
|
|
||||||
if (match?.[1]) {
|
|
||||||
try {
|
|
||||||
resolvedName = decodeURIComponent(match[1])
|
|
||||||
} catch {
|
|
||||||
resolvedName = match[1]
|
|
||||||
}
|
|
||||||
} else if (match?.[2]) {
|
|
||||||
resolvedName = match[2]
|
|
||||||
} else if (objectName) {
|
|
||||||
const parts = objectName.split('/')
|
|
||||||
resolvedName = parts[parts.length - 1] || 'vault-export.bin'
|
|
||||||
} else {
|
|
||||||
resolvedName = 'vault-export.bin'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const arrayBuffer = await downloadResponse.arrayBuffer()
|
|
||||||
const buffer = Buffer.from(arrayBuffer)
|
|
||||||
|
|
||||||
logger.info(`[${requestId}] Vault export file downloaded successfully`, {
|
|
||||||
name: resolvedName,
|
|
||||||
size: buffer.length,
|
|
||||||
mimeType: contentType,
|
|
||||||
})
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
output: {
|
|
||||||
file: {
|
|
||||||
name: resolvedName,
|
|
||||||
mimeType: contentType,
|
|
||||||
data: buffer.toString('base64'),
|
|
||||||
size: buffer.length,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
logger.error(`[${requestId}] Error downloading Google Vault export file:`, error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: error instanceof Error ? error.message : 'Unknown error occurred',
|
|
||||||
},
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,7 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
import { createLogger } from '@sim/logger'
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||||
import {
|
import { validateImageUrl } from '@/lib/core/security/input-validation'
|
||||||
secureFetchWithPinnedIP,
|
|
||||||
validateUrlWithDNS,
|
|
||||||
} from '@/lib/core/security/input-validation.server'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
|
|
||||||
const logger = createLogger('ImageProxyAPI')
|
const logger = createLogger('ImageProxyAPI')
|
||||||
@@ -29,7 +26,7 @@ export async function GET(request: NextRequest) {
|
|||||||
return new NextResponse('Missing URL parameter', { status: 400 })
|
return new NextResponse('Missing URL parameter', { status: 400 })
|
||||||
}
|
}
|
||||||
|
|
||||||
const urlValidation = await validateUrlWithDNS(imageUrl, 'imageUrl')
|
const urlValidation = validateImageUrl(imageUrl)
|
||||||
if (!urlValidation.isValid) {
|
if (!urlValidation.isValid) {
|
||||||
logger.warn(`[${requestId}] Blocked image proxy request`, {
|
logger.warn(`[${requestId}] Blocked image proxy request`, {
|
||||||
url: imageUrl.substring(0, 100),
|
url: imageUrl.substring(0, 100),
|
||||||
@@ -41,8 +38,7 @@ export async function GET(request: NextRequest) {
|
|||||||
logger.info(`[${requestId}] Proxying image request for: ${imageUrl}`)
|
logger.info(`[${requestId}] Proxying image request for: ${imageUrl}`)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const imageResponse = await secureFetchWithPinnedIP(imageUrl, urlValidation.resolvedIP!, {
|
const imageResponse = await fetch(imageUrl, {
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
headers: {
|
||||||
'User-Agent':
|
'User-Agent':
|
||||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
|
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
|
||||||
@@ -68,14 +64,14 @@ export async function GET(request: NextRequest) {
|
|||||||
|
|
||||||
const contentType = imageResponse.headers.get('content-type') || 'image/jpeg'
|
const contentType = imageResponse.headers.get('content-type') || 'image/jpeg'
|
||||||
|
|
||||||
const imageArrayBuffer = await imageResponse.arrayBuffer()
|
const imageBlob = await imageResponse.blob()
|
||||||
|
|
||||||
if (imageArrayBuffer.byteLength === 0) {
|
if (imageBlob.size === 0) {
|
||||||
logger.error(`[${requestId}] Empty image received`)
|
logger.error(`[${requestId}] Empty image blob received`)
|
||||||
return new NextResponse('Empty image received', { status: 404 })
|
return new NextResponse('Empty image received', { status: 404 })
|
||||||
}
|
}
|
||||||
|
|
||||||
return new NextResponse(imageArrayBuffer, {
|
return new NextResponse(imageBlob, {
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': contentType,
|
'Content-Type': contentType,
|
||||||
'Access-Control-Allow-Origin': '*',
|
'Access-Control-Allow-Origin': '*',
|
||||||
|
|||||||
@@ -1,121 +0,0 @@
|
|||||||
import { createLogger } from '@sim/logger'
|
|
||||||
import { type NextRequest, NextResponse } from 'next/server'
|
|
||||||
import { z } from 'zod'
|
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
|
||||||
import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas'
|
|
||||||
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
|
||||||
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
|
||||||
import { getJiraCloudId } from '@/tools/jira/utils'
|
|
||||||
|
|
||||||
const logger = createLogger('JiraAddAttachmentAPI')
|
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
|
||||||
|
|
||||||
const JiraAddAttachmentSchema = z.object({
|
|
||||||
accessToken: z.string().min(1, 'Access token is required'),
|
|
||||||
domain: z.string().min(1, 'Domain is required'),
|
|
||||||
issueKey: z.string().min(1, 'Issue key is required'),
|
|
||||||
files: RawFileInputArraySchema,
|
|
||||||
cloudId: z.string().optional().nullable(),
|
|
||||||
})
|
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
|
||||||
const requestId = `jira-attach-${Date.now()}`
|
|
||||||
|
|
||||||
try {
|
|
||||||
const authResult = await checkInternalAuth(request, { requireWorkflowId: false })
|
|
||||||
if (!authResult.success) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: authResult.error || 'Unauthorized' },
|
|
||||||
{ status: 401 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const body = await request.json()
|
|
||||||
const validatedData = JiraAddAttachmentSchema.parse(body)
|
|
||||||
|
|
||||||
const userFiles = processFilesToUserFiles(validatedData.files, requestId, logger)
|
|
||||||
if (userFiles.length === 0) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: 'No valid files provided for upload' },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const cloudId =
|
|
||||||
validatedData.cloudId ||
|
|
||||||
(await getJiraCloudId(validatedData.domain, validatedData.accessToken))
|
|
||||||
|
|
||||||
const formData = new FormData()
|
|
||||||
const filesOutput: Array<{ name: string; mimeType: string; data: string; size: number }> = []
|
|
||||||
|
|
||||||
for (const file of userFiles) {
|
|
||||||
const buffer = await downloadFileFromStorage(file, requestId, logger)
|
|
||||||
filesOutput.push({
|
|
||||||
name: file.name,
|
|
||||||
mimeType: file.type || 'application/octet-stream',
|
|
||||||
data: buffer.toString('base64'),
|
|
||||||
size: buffer.length,
|
|
||||||
})
|
|
||||||
const blob = new Blob([new Uint8Array(buffer)], {
|
|
||||||
type: file.type || 'application/octet-stream',
|
|
||||||
})
|
|
||||||
formData.append('file', blob, file.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/issue/${validatedData.issueKey}/attachments`
|
|
||||||
|
|
||||||
const response = await fetch(url, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
Authorization: `Bearer ${validatedData.accessToken}`,
|
|
||||||
'X-Atlassian-Token': 'no-check',
|
|
||||||
},
|
|
||||||
body: formData,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const errorText = await response.text()
|
|
||||||
logger.error(`[${requestId}] Jira attachment upload failed`, {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
error: errorText,
|
|
||||||
})
|
|
||||||
return NextResponse.json(
|
|
||||||
{
|
|
||||||
success: false,
|
|
||||||
error: `Failed to upload attachments: ${response.statusText}`,
|
|
||||||
},
|
|
||||||
{ status: response.status }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const attachments = await response.json()
|
|
||||||
const attachmentIds = Array.isArray(attachments)
|
|
||||||
? attachments.map((attachment) => attachment.id).filter(Boolean)
|
|
||||||
: []
|
|
||||||
|
|
||||||
return NextResponse.json({
|
|
||||||
success: true,
|
|
||||||
output: {
|
|
||||||
ts: new Date().toISOString(),
|
|
||||||
issueKey: validatedData.issueKey,
|
|
||||||
attachmentIds,
|
|
||||||
files: filesOutput,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof z.ZodError) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: 'Invalid request data', details: error.errors },
|
|
||||||
{ status: 400 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.error(`[${requestId}] Jira attachment upload error`, error)
|
|
||||||
return NextResponse.json(
|
|
||||||
{ success: false, error: error instanceof Error ? error.message : 'Internal server error' },
|
|
||||||
{ status: 500 }
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,11 +2,9 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||||
import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas'
|
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
||||||
import { uploadFilesForTeamsMessage } from '@/tools/microsoft_teams/server-utils'
|
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
||||||
import type { GraphApiErrorResponse, GraphChatMessage } from '@/tools/microsoft_teams/types'
|
|
||||||
import { resolveMentionsForChannel, type TeamsMention } from '@/tools/microsoft_teams/utils'
|
import { resolveMentionsForChannel, type TeamsMention } from '@/tools/microsoft_teams/utils'
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
@@ -18,7 +16,7 @@ const TeamsWriteChannelSchema = z.object({
|
|||||||
teamId: z.string().min(1, 'Team ID is required'),
|
teamId: z.string().min(1, 'Team ID is required'),
|
||||||
channelId: z.string().min(1, 'Channel ID is required'),
|
channelId: z.string().min(1, 'Channel ID is required'),
|
||||||
content: z.string().min(1, 'Message content is required'),
|
content: z.string().min(1, 'Message content is required'),
|
||||||
files: RawFileInputArraySchema.optional().nullable(),
|
files: z.array(z.any()).optional().nullable(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
@@ -55,12 +53,93 @@ export async function POST(request: NextRequest) {
|
|||||||
fileCount: validatedData.files?.length || 0,
|
fileCount: validatedData.files?.length || 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
const { attachments, filesOutput } = await uploadFilesForTeamsMessage({
|
const attachments: any[] = []
|
||||||
rawFiles: validatedData.files || [],
|
if (validatedData.files && validatedData.files.length > 0) {
|
||||||
accessToken: validatedData.accessToken,
|
const rawFiles = validatedData.files
|
||||||
requestId,
|
logger.info(`[${requestId}] Processing ${rawFiles.length} file(s) for upload to OneDrive`)
|
||||||
logger,
|
|
||||||
})
|
const userFiles = processFilesToUserFiles(rawFiles, requestId, logger)
|
||||||
|
|
||||||
|
for (const file of userFiles) {
|
||||||
|
try {
|
||||||
|
logger.info(`[${requestId}] Uploading file to Teams: ${file.name} (${file.size} bytes)`)
|
||||||
|
|
||||||
|
const buffer = await downloadFileFromStorage(file, requestId, logger)
|
||||||
|
|
||||||
|
const uploadUrl =
|
||||||
|
'https://graph.microsoft.com/v1.0/me/drive/root:/TeamsAttachments/' +
|
||||||
|
encodeURIComponent(file.name) +
|
||||||
|
':/content'
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Uploading to Teams: ${uploadUrl}`)
|
||||||
|
|
||||||
|
const uploadResponse = await fetch(uploadUrl, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
||||||
|
'Content-Type': file.type || 'application/octet-stream',
|
||||||
|
},
|
||||||
|
body: new Uint8Array(buffer),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!uploadResponse.ok) {
|
||||||
|
const errorData = await uploadResponse.json().catch(() => ({}))
|
||||||
|
logger.error(`[${requestId}] Teams upload failed:`, errorData)
|
||||||
|
throw new Error(
|
||||||
|
`Failed to upload file to Teams: ${errorData.error?.message || 'Unknown error'}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const uploadedFile = await uploadResponse.json()
|
||||||
|
logger.info(`[${requestId}] File uploaded to Teams successfully`, {
|
||||||
|
id: uploadedFile.id,
|
||||||
|
webUrl: uploadedFile.webUrl,
|
||||||
|
})
|
||||||
|
|
||||||
|
const fileDetailsUrl = `https://graph.microsoft.com/v1.0/me/drive/items/${uploadedFile.id}?$select=id,name,webDavUrl,eTag,size`
|
||||||
|
|
||||||
|
const fileDetailsResponse = await fetch(fileDetailsUrl, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!fileDetailsResponse.ok) {
|
||||||
|
const errorData = await fileDetailsResponse.json().catch(() => ({}))
|
||||||
|
logger.error(`[${requestId}] Failed to get file details:`, errorData)
|
||||||
|
throw new Error(
|
||||||
|
`Failed to get file details: ${errorData.error?.message || 'Unknown error'}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileDetails = await fileDetailsResponse.json()
|
||||||
|
logger.info(`[${requestId}] Got file details`, {
|
||||||
|
webDavUrl: fileDetails.webDavUrl,
|
||||||
|
eTag: fileDetails.eTag,
|
||||||
|
})
|
||||||
|
|
||||||
|
const attachmentId = fileDetails.eTag?.match(/\{([a-f0-9-]+)\}/i)?.[1] || fileDetails.id
|
||||||
|
|
||||||
|
attachments.push({
|
||||||
|
id: attachmentId,
|
||||||
|
contentType: 'reference',
|
||||||
|
contentUrl: fileDetails.webDavUrl,
|
||||||
|
name: file.name,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Created attachment reference for ${file.name}`)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`[${requestId}] Failed to process file ${file.name}:`, error)
|
||||||
|
throw new Error(
|
||||||
|
`Failed to process file "${file.name}": ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`[${requestId}] All ${attachments.length} file(s) uploaded and attachment references created`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
let messageContent = validatedData.content
|
let messageContent = validatedData.content
|
||||||
let contentType: 'text' | 'html' = 'text'
|
let contentType: 'text' | 'html' = 'text'
|
||||||
@@ -118,21 +197,17 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
const teamsUrl = `https://graph.microsoft.com/v1.0/teams/${encodeURIComponent(validatedData.teamId)}/channels/${encodeURIComponent(validatedData.channelId)}/messages`
|
const teamsUrl = `https://graph.microsoft.com/v1.0/teams/${encodeURIComponent(validatedData.teamId)}/channels/${encodeURIComponent(validatedData.channelId)}/messages`
|
||||||
|
|
||||||
const teamsResponse = await secureFetchWithValidation(
|
const teamsResponse = await fetch(teamsUrl, {
|
||||||
teamsUrl,
|
method: 'POST',
|
||||||
{
|
headers: {
|
||||||
method: 'POST',
|
'Content-Type': 'application/json',
|
||||||
headers: {
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${validatedData.accessToken}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify(messageBody),
|
|
||||||
},
|
},
|
||||||
'teamsUrl'
|
body: JSON.stringify(messageBody),
|
||||||
)
|
})
|
||||||
|
|
||||||
if (!teamsResponse.ok) {
|
if (!teamsResponse.ok) {
|
||||||
const errorData = (await teamsResponse.json().catch(() => ({}))) as GraphApiErrorResponse
|
const errorData = await teamsResponse.json().catch(() => ({}))
|
||||||
logger.error(`[${requestId}] Microsoft Teams API error:`, errorData)
|
logger.error(`[${requestId}] Microsoft Teams API error:`, errorData)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
@@ -143,7 +218,7 @@ export async function POST(request: NextRequest) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const responseData = (await teamsResponse.json()) as GraphChatMessage
|
const responseData = await teamsResponse.json()
|
||||||
logger.info(`[${requestId}] Teams channel message sent successfully`, {
|
logger.info(`[${requestId}] Teams channel message sent successfully`, {
|
||||||
messageId: responseData.id,
|
messageId: responseData.id,
|
||||||
attachmentCount: attachments.length,
|
attachmentCount: attachments.length,
|
||||||
@@ -162,7 +237,6 @@ export async function POST(request: NextRequest) {
|
|||||||
url: responseData.webUrl || '',
|
url: responseData.webUrl || '',
|
||||||
attachmentCount: attachments.length,
|
attachmentCount: attachments.length,
|
||||||
},
|
},
|
||||||
files: filesOutput,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -2,11 +2,9 @@ import { createLogger } from '@sim/logger'
|
|||||||
import { type NextRequest, NextResponse } from 'next/server'
|
import { type NextRequest, NextResponse } from 'next/server'
|
||||||
import { z } from 'zod'
|
import { z } from 'zod'
|
||||||
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
import { checkInternalAuth } from '@/lib/auth/hybrid'
|
||||||
import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server'
|
|
||||||
import { generateRequestId } from '@/lib/core/utils/request'
|
import { generateRequestId } from '@/lib/core/utils/request'
|
||||||
import { RawFileInputArraySchema } from '@/lib/uploads/utils/file-schemas'
|
import { processFilesToUserFiles } from '@/lib/uploads/utils/file-utils'
|
||||||
import { uploadFilesForTeamsMessage } from '@/tools/microsoft_teams/server-utils'
|
import { downloadFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
|
||||||
import type { GraphApiErrorResponse, GraphChatMessage } from '@/tools/microsoft_teams/types'
|
|
||||||
import { resolveMentionsForChat, type TeamsMention } from '@/tools/microsoft_teams/utils'
|
import { resolveMentionsForChat, type TeamsMention } from '@/tools/microsoft_teams/utils'
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
@@ -17,7 +15,7 @@ const TeamsWriteChatSchema = z.object({
|
|||||||
accessToken: z.string().min(1, 'Access token is required'),
|
accessToken: z.string().min(1, 'Access token is required'),
|
||||||
chatId: z.string().min(1, 'Chat ID is required'),
|
chatId: z.string().min(1, 'Chat ID is required'),
|
||||||
content: z.string().min(1, 'Message content is required'),
|
content: z.string().min(1, 'Message content is required'),
|
||||||
files: RawFileInputArraySchema.optional().nullable(),
|
files: z.array(z.any()).optional().nullable(),
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function POST(request: NextRequest) {
|
export async function POST(request: NextRequest) {
|
||||||
@@ -53,12 +51,93 @@ export async function POST(request: NextRequest) {
|
|||||||
fileCount: validatedData.files?.length || 0,
|
fileCount: validatedData.files?.length || 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
const { attachments, filesOutput } = await uploadFilesForTeamsMessage({
|
const attachments: any[] = []
|
||||||
rawFiles: validatedData.files || [],
|
if (validatedData.files && validatedData.files.length > 0) {
|
||||||
accessToken: validatedData.accessToken,
|
const rawFiles = validatedData.files
|
||||||
requestId,
|
logger.info(`[${requestId}] Processing ${rawFiles.length} file(s) for upload to Teams`)
|
||||||
logger,
|
|
||||||
})
|
const userFiles = processFilesToUserFiles(rawFiles, requestId, logger)
|
||||||
|
|
||||||
|
for (const file of userFiles) {
|
||||||
|
try {
|
||||||
|
logger.info(`[${requestId}] Uploading file to Teams: ${file.name} (${file.size} bytes)`)
|
||||||
|
|
||||||
|
const buffer = await downloadFileFromStorage(file, requestId, logger)
|
||||||
|
|
||||||
|
const uploadUrl =
|
||||||
|
'https://graph.microsoft.com/v1.0/me/drive/root:/TeamsAttachments/' +
|
||||||
|
encodeURIComponent(file.name) +
|
||||||
|
':/content'
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Uploading to Teams: ${uploadUrl}`)
|
||||||
|
|
||||||
|
const uploadResponse = await fetch(uploadUrl, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
||||||
|
'Content-Type': file.type || 'application/octet-stream',
|
||||||
|
},
|
||||||
|
body: new Uint8Array(buffer),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!uploadResponse.ok) {
|
||||||
|
const errorData = await uploadResponse.json().catch(() => ({}))
|
||||||
|
logger.error(`[${requestId}] Teams upload failed:`, errorData)
|
||||||
|
throw new Error(
|
||||||
|
`Failed to upload file to Teams: ${errorData.error?.message || 'Unknown error'}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const uploadedFile = await uploadResponse.json()
|
||||||
|
logger.info(`[${requestId}] File uploaded to Teams successfully`, {
|
||||||
|
id: uploadedFile.id,
|
||||||
|
webUrl: uploadedFile.webUrl,
|
||||||
|
})
|
||||||
|
|
||||||
|
const fileDetailsUrl = `https://graph.microsoft.com/v1.0/me/drive/items/${uploadedFile.id}?$select=id,name,webDavUrl,eTag,size`
|
||||||
|
|
||||||
|
const fileDetailsResponse = await fetch(fileDetailsUrl, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!fileDetailsResponse.ok) {
|
||||||
|
const errorData = await fileDetailsResponse.json().catch(() => ({}))
|
||||||
|
logger.error(`[${requestId}] Failed to get file details:`, errorData)
|
||||||
|
throw new Error(
|
||||||
|
`Failed to get file details: ${errorData.error?.message || 'Unknown error'}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fileDetails = await fileDetailsResponse.json()
|
||||||
|
logger.info(`[${requestId}] Got file details`, {
|
||||||
|
webDavUrl: fileDetails.webDavUrl,
|
||||||
|
eTag: fileDetails.eTag,
|
||||||
|
})
|
||||||
|
|
||||||
|
const attachmentId = fileDetails.eTag?.match(/\{([a-f0-9-]+)\}/i)?.[1] || fileDetails.id
|
||||||
|
|
||||||
|
attachments.push({
|
||||||
|
id: attachmentId,
|
||||||
|
contentType: 'reference',
|
||||||
|
contentUrl: fileDetails.webDavUrl,
|
||||||
|
name: file.name,
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.info(`[${requestId}] Created attachment reference for ${file.name}`)
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`[${requestId}] Failed to process file ${file.name}:`, error)
|
||||||
|
throw new Error(
|
||||||
|
`Failed to process file "${file.name}": ${error instanceof Error ? error.message : 'Unknown error'}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`[${requestId}] All ${attachments.length} file(s) uploaded and attachment references created`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
let messageContent = validatedData.content
|
let messageContent = validatedData.content
|
||||||
let contentType: 'text' | 'html' = 'text'
|
let contentType: 'text' | 'html' = 'text'
|
||||||
@@ -115,21 +194,17 @@ export async function POST(request: NextRequest) {
|
|||||||
|
|
||||||
const teamsUrl = `https://graph.microsoft.com/v1.0/chats/${encodeURIComponent(validatedData.chatId)}/messages`
|
const teamsUrl = `https://graph.microsoft.com/v1.0/chats/${encodeURIComponent(validatedData.chatId)}/messages`
|
||||||
|
|
||||||
const teamsResponse = await secureFetchWithValidation(
|
const teamsResponse = await fetch(teamsUrl, {
|
||||||
teamsUrl,
|
method: 'POST',
|
||||||
{
|
headers: {
|
||||||
method: 'POST',
|
'Content-Type': 'application/json',
|
||||||
headers: {
|
Authorization: `Bearer ${validatedData.accessToken}`,
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: `Bearer ${validatedData.accessToken}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify(messageBody),
|
|
||||||
},
|
},
|
||||||
'teamsUrl'
|
body: JSON.stringify(messageBody),
|
||||||
)
|
})
|
||||||
|
|
||||||
if (!teamsResponse.ok) {
|
if (!teamsResponse.ok) {
|
||||||
const errorData = (await teamsResponse.json().catch(() => ({}))) as GraphApiErrorResponse
|
const errorData = await teamsResponse.json().catch(() => ({}))
|
||||||
logger.error(`[${requestId}] Microsoft Teams API error:`, errorData)
|
logger.error(`[${requestId}] Microsoft Teams API error:`, errorData)
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{
|
{
|
||||||
@@ -140,7 +215,7 @@ export async function POST(request: NextRequest) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const responseData = (await teamsResponse.json()) as GraphChatMessage
|
const responseData = await teamsResponse.json()
|
||||||
logger.info(`[${requestId}] Teams message sent successfully`, {
|
logger.info(`[${requestId}] Teams message sent successfully`, {
|
||||||
messageId: responseData.id,
|
messageId: responseData.id,
|
||||||
attachmentCount: attachments.length,
|
attachmentCount: attachments.length,
|
||||||
@@ -158,7 +233,6 @@ export async function POST(request: NextRequest) {
|
|||||||
url: responseData.webUrl || '',
|
url: responseData.webUrl || '',
|
||||||
attachmentCount: attachments.length,
|
attachmentCount: attachments.length,
|
||||||
},
|
},
|
||||||
files: filesOutput,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user