Skip to content

Commit 6c505b7

Browse files
responding to feedback, removing dead code, refactoring
1 parent 004aa11 commit 6c505b7

File tree

10 files changed

+222
-576
lines changed

10 files changed

+222
-576
lines changed

apps/google-docs/functions/agents/documentParserAgent/documentParser.agent.ts

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,8 @@ export async function createPreviewWithAgent(
4444
apiKey: openAiApiKey,
4545
});
4646

47-
console.log('Document Parser Agent document JSON received (fetched from frontend)');
48-
49-
// Step 1: Build extraction prompt
50-
const promptStartTime = Date.now();
5147
const prompt = buildExtractionPrompt({ contentTypes, documentJson, locale });
52-
const promptDuration = Date.now() - promptStartTime;
53-
console.log(`[Timing] Build extraction prompt: ${promptDuration}ms`);
5448

55-
// Step 3: Generate object with AI
5649
const aiStartTime = Date.now();
5750
const result = await generateObject({
5851
model: openaiClient(modelVersion),
@@ -64,14 +57,7 @@ export async function createPreviewWithAgent(
6457
const aiDuration = Date.now() - aiStartTime;
6558
console.log(`[Timing] AI generateObject: ${aiDuration}ms`);
6659

67-
// Step 4: Process result
68-
const processStartTime = Date.now();
6960
const finalResult = result.object as FinalEntriesResult;
70-
const processDuration = Date.now() - processStartTime;
71-
console.log(`[Timing] Process result: ${processDuration}ms`);
72-
73-
const totalDuration = Date.now() - promptStartTime;
74-
console.log(`[Timing] Total Document Parser Agent execution: ${totalDuration}ms`);
7561

7662
return finalResult;
7763
}

apps/google-docs/functions/handlers/createEntries/createEntriesHandler.ts

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ export const handler: FunctionEventHandler<
3131
event: AppActionRequest<'Custom', CreateEntriesParameters>,
3232
context: FunctionEventContext
3333
) => {
34-
const { contentTypeIds, documentJson, entries: providedEntries } = event.body;
35-
const { openAiApiKey } = context.appInstallationParameters as AppInstallationParameters;
34+
const { contentTypeIds, entries: providedEntries } = event.body;
3635

3736
if (!contentTypeIds || contentTypeIds.length === 0) {
3837
throw new Error('At least one content type ID is required');
@@ -51,16 +50,6 @@ export const handler: FunctionEventHandler<
5150
entriesToCreate = providedEntries;
5251
summary = `Creating ${entriesToCreate.length} entries from plan`;
5352
totalEntries = entriesToCreate.length;
54-
} else if (documentJson) {
55-
// Fallback: analyze document if entries not provided but documentJson is available
56-
const aiDocumentResponse = await createPreviewWithAgent({
57-
documentJson,
58-
openAiApiKey,
59-
contentTypes,
60-
});
61-
entriesToCreate = aiDocumentResponse.entries;
62-
summary = aiDocumentResponse.summary;
63-
totalEntries = aiDocumentResponse.totalEntries;
6453
} else {
6554
throw new Error('Either entries or documentJson must be provided');
6655
}

apps/google-docs/functions/handlers/createPreview/createPreviewHandler.ts

Lines changed: 3 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,9 @@ import type {
44
FunctionTypeEnum,
55
AppActionRequest,
66
} from '@contentful/node-apps-toolkit';
7-
import { ContentTypeProps } from 'contentful-management';
87
import { createPreviewWithAgent } from '../../agents/documentParserAgent/documentParser.agent';
98
import { fetchContentTypes } from '../../service/contentTypeService';
109
import { initContentfulManagementClient } from '../../service/initCMAClient';
11-
import { EntryToCreate } from '../../agents/documentParserAgent/schema';
1210

1311
export type AppActionParameters = {
1412
contentTypeIds: string[];
@@ -19,74 +17,6 @@ interface AppInstallationParameters {
1917
openAiApiKey: string;
2018
}
2119

22-
interface AssetInfo {
23-
url: string;
24-
altText: string;
25-
fileName: string;
26-
}
27-
28-
/**
29-
* Extracts asset information from entries by scanning RichText fields for image tokens
30-
*/
31-
function extractAssetsFromEntries(
32-
entries: EntryToCreate[],
33-
contentTypes: ContentTypeProps[]
34-
): AssetInfo[] {
35-
const IMAGE_TOKEN_REGEX = /!\[([^\]]*?)\]\(([\s\S]*?)\)/g;
36-
const assetsMap = new Map<string, AssetInfo>();
37-
38-
for (const entry of entries) {
39-
const contentType = contentTypes.find((ct) => ct.sys.id === entry.contentTypeId);
40-
if (!contentType) continue;
41-
42-
// Check all RichText fields
43-
for (const field of contentType.fields) {
44-
if (field.type !== 'RichText') continue;
45-
46-
const localizedValue = entry.fields[field.id];
47-
if (!localizedValue || typeof localizedValue !== 'object') continue;
48-
49-
// Check all locales
50-
for (const value of Object.values(localizedValue)) {
51-
if (typeof value !== 'string') continue;
52-
53-
// Reset regex state
54-
IMAGE_TOKEN_REGEX.lastIndex = 0;
55-
for (const match of value.matchAll(IMAGE_TOKEN_REGEX)) {
56-
const altText = (match[1] || '').trim();
57-
const url = String(match[2]).replace(/\s+/g, '').trim();
58-
59-
if (!url) continue;
60-
61-
// Extract filename from URL
62-
let fileName = 'image';
63-
try {
64-
const urlObj = new URL(url);
65-
const pathname = urlObj.pathname.toLowerCase();
66-
const pathParts = pathname.split('/').filter(Boolean);
67-
fileName = pathParts[pathParts.length - 1] || 'image';
68-
// Remove query params if present
69-
fileName = fileName.split('?')[0];
70-
} catch {
71-
// If URL parsing fails, use default
72-
}
73-
74-
// Use URL as key to avoid duplicates
75-
if (!assetsMap.has(url)) {
76-
assetsMap.set(url, {
77-
url,
78-
altText: altText || fileName,
79-
fileName: fileName || 'image',
80-
});
81-
}
82-
}
83-
}
84-
}
85-
}
86-
87-
return Array.from(assetsMap.values());
88-
}
89-
9020
/**
9121
* Create Preview
9222
*
@@ -102,9 +32,7 @@ export const handler: FunctionEventHandler<
10232
context: FunctionEventContext
10333
) => {
10434
const { contentTypeIds, documentJson } = event.body;
105-
console.log('Content types:', contentTypeIds);
10635
const { openAiApiKey } = context.appInstallationParameters as AppInstallationParameters;
107-
console.log('Open AI API Key:', openAiApiKey);
10836
if (!documentJson) {
10937
throw new Error('Document JSON is required');
11038
}
@@ -115,26 +43,20 @@ export const handler: FunctionEventHandler<
11543

11644
const cma = initContentfulManagementClient(context);
11745
const contentTypes = await fetchContentTypes(cma, new Set<string>(contentTypeIds));
118-
console.log('Content types:', contentTypes);
11946

12047
// Use the same AI agent to analyze the document and generate proposed entries
12148
const aiDocumentResponse = await createPreviewWithAgent({
12249
documentJson,
12350
openAiApiKey,
12451
contentTypes,
12552
});
126-
console.log('AI document response:', aiDocumentResponse);
127-
// Extract asset information from entries
128-
const assets = extractAssetsFromEntries(aiDocumentResponse.entries, contentTypes);
12953

130-
console.log('Assets:', assets);
131-
// Return plan data without creating entries
13254
return {
13355
success: true,
13456
response: {
135-
...aiDocumentResponse,
136-
assets,
137-
totalAssets: assets.length,
57+
entries: aiDocumentResponse.entries,
58+
summary: aiDocumentResponse.summary,
59+
totalEntries: aiDocumentResponse.totalEntries,
13860
},
13961
};
14062
};

apps/google-docs/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
"upload:app-dev": "contentful-app-scripts upload --bundle-dir ./build --organization-id 6xdLsz6lCsk0yPOccSsDK7 --definition-id 653vTnuQw3j5onU1tUoH6t --token $CONTENTFUL_ACCESS_TOKEN",
3131
"deploy:sync-dev": "aws s3 sync ./build ${STATIC_S3_BASE}/google-docs-dev && aws cloudfront create-invalidation --distribution-id $GOOGLE_DOCS_TEST_CLOUDFRONT_DIST_ID --paths \"/*\" > /dev/null 2>&1",
3232
"deploy:dev": "npm run build && npm run upload:app-dev && npm run deploy:sync-dev",
33+
"upload:app-staging": "contentful-app-scripts upload --bundle-dir ./build --organization-id 6xdLsz6lCsk0yPOccSsDK7 --definition-id 4i0mp5lQtgNsHYVrD5jIkj --token $CONTENTFUL_ACCESS_TOKEN",
3334
"deploy:staging": "npm run build && npm run upload:app-staging && npm run deploy:sync-dev",
3435
"deploy:sync-prod": "aws s3 sync ./build ${STATIC_S3_BASE}/google-docs && aws cloudfront create-invalidation --distribution-id $GOOGLE_DOCS_PROD_CLOUDFRONT_DIST_ID --paths \"/*\" > /dev/null 2>&1",
3536
"upload": "contentful-app-scripts upload --bundle-dir ./build --organization-id 5EJGHo8tYJcjnEhYWDxivp --definition-id 3EaGZUMKRKVZUyrcoNJ4o4 --token $CONTENTFUL_ACCESS_TOKEN",

0 commit comments

Comments
 (0)