"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTenantSchema = getTenantSchema;
const api_client_1 = require("../lib/api-client");
const device_flow_1 = require("../lib/device-flow");
/**
* Resolve a project identifier to a tenant ID
* Accepts either a UUID or a project name
*/
async function resolveProjectId(projectIdentifier) {
// Check if it looks like a UUID
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (uuidPattern.test(projectIdentifier)) {
// It's already a UUID, use it directly
return { tenantId: projectIdentifier };
}
// Otherwise, look up by name using /api/tenants
const response = await (0, api_client_1.apiRequest)('/api/tenants');
if ((0, api_client_1.isApiError)(response)) {
return { error: `Failed to look up project: ${response.error}` };
}
const projects = response.data;
// Find by exact name match (case-insensitive)
const match = projects.find(p => p.name.toLowerCase() === projectIdentifier.toLowerCase());
if (match) {
return { tenantId: match.id };
}
// Try partial match
const partialMatch = projects.find(p => p.name.toLowerCase().includes(projectIdentifier.toLowerCase()));
if (partialMatch) {
return { tenantId: partialMatch.id };
}
// List available projects for the user
const availableProjects = projects.map(p => `- ${p.name} (${p.id})`).join('\n');
return {
error: `Project "${projectIdentifier}" not found.\n\nAvailable projects:\n${availableProjects || 'None'}\n\nUse list_projects to see all your projects.`
};
}
/**
* Fetches the complete schema for a specific project including:
* - All custom collections with their fields
* - Field tokens, types, and descriptions for AI context
* - Template patterns and example usage
*
* Each field includes:
* - Field Name (display name)
* - Token (the exact syntax to use in templates)
* - Type (text, richText, image, etc.)
* - Description (help text for context)
*
* Uses stored credentials or triggers device flow for authentication.
*
* @param projectId - Project ID (UUID) or project name
*/
async function getTenantSchema(projectId) {
// Check if we need to authenticate
if (await (0, api_client_1.needsAuthentication)()) {
const authResult = await (0, device_flow_1.ensureAuthenticated)();
if (!authResult.authenticated) {
return authResult.message;
}
}
// Resolve project identifier to tenant ID
const resolved = await resolveProjectId(projectId);
if ('error' in resolved) {
return `# Project Not Found
${resolved.error}
`;
}
const { tenantId } = resolved;
const apiUrl = (0, api_client_1.getApiUrl)();
// Fetch the AI prompt for this tenant
const response = await (0, api_client_1.apiRequest)('/api/collections/ai-prompt', {
tenantId,
});
if ((0, api_client_1.isApiError)(response)) {
// If auth error, try to re-authenticate
if ((0, api_client_1.needsAuthError)(response)) {
const authResult = await (0, device_flow_1.ensureAuthenticated)();
if (!authResult.authenticated) {
return authResult.message;
}
// Retry the request
const retryResponse = await (0, api_client_1.apiRequest)('/api/collections/ai-prompt', {
tenantId,
});
if ((0, api_client_1.isApiError)(retryResponse)) {
return `# API Error
Failed to fetch project schema: ${retryResponse.error}
**Project ID:** ${tenantId}
**Status:** ${retryResponse.statusCode}
Please try authenticating again.
`;
}
return formatSchemaResponse(retryResponse.data, tenantId);
}
if (response.statusCode === 403) {
return `# Authorization Error
You don't have permission to access this project's schema.
**Project ID:** ${tenantId}
Make sure:
1. You have membership in this project
2. Try running \`list_projects\` to see your accessible projects
`;
}
return `# API Error
Failed to fetch project schema: ${response.error}
**Project ID:** ${tenantId}
**API URL:** ${apiUrl}
**Status:** ${response.statusCode}
Please verify:
1. The project ID is correct
2. You have network connectivity
`;
}
return formatSchemaResponse(response.data, tenantId);
}
/**
* Format the schema response for display
*/
function formatSchemaResponse(data, tenantId) {
if (!data?.prompt) {
return `# Unexpected Response
The API returned a successful response but the prompt data was missing.
**Project ID:** ${tenantId}
**Response:** ${JSON.stringify(data, null, 2).slice(0, 500)}
`;
}
// Return the full AI prompt which includes all schema information
return `# Project Schema
**Project ID:** \`${tenantId}\`
This schema is specific to this project and includes all collections with their fields.
**Field Table Format:**
- **Field Name** - Display name for the field
- **Token** - The exact token to use in templates (use triple braces for richText)
- **Type** - Field type (text, richText, image, url, videoEmbed, boolean, number, date, select, relation)
- **Description** - Help text explaining what the field is for
---
${data.prompt}
`;
}