AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(google-slides): build and edit slides, text, shapes, tables and images, and export decks (#16007)
Odai Ahmad49f3623a3255
diff --git a/bun.lock b/bun.lockindex 5a5007a86a5..fff538f8594 100644--- a/bun.lock+++ b/bun.lock@@ -3987,7 +3987,7 @@},"packages/pieces/community/google-slides": {"name": "@activepieces/piece-google-slides",- "version": "0.3.0",+ "version": "0.4.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",@@ -3998,6 +3998,7 @@},"devDependencies": {"tslib": "2.6.2",+ "vitest": "3.2.6",},},"packages/pieces/community/google-tasks": {diff --git a/packages/pieces/community/google-slides/package.json b/packages/pieces/community/google-slides/package.jsonindex 1e5609b7251..6e2fd8cf7ac 100644--- a/packages/pieces/community/google-slides/package.json+++ b/packages/pieces/community/google-slides/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-google-slides",- "version": "0.3.0",+ "version": "0.4.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {@@ -12,11 +12,13 @@"@activepieces/core-utils": "workspace:*"},"devDependencies": {- "tslib": "2.6.2"+ "tslib": "2.6.2",+ "vitest": "3.2.6"},"scripts": {"build": "tsc -p tsconfig.lib.json && cp package.json dist/","bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",- "lint": "eslint 'src/**/*.ts'"+ "lint": "eslint 'src/**/*.ts'",+ "test": "vitest run"}}diff --git a/packages/pieces/community/google-slides/src/i18n/translation.json b/packages/pieces/community/google-slides/src/i18n/translation.jsonindex 9bdd894f726..c1f71883b5d 100644--- a/packages/pieces/community/google-slides/src/i18n/translation.json+++ b/packages/pieces/community/google-slides/src/i18n/translation.json@@ -2,40 +2,363 @@"Get Presentation": "Get Presentation","Refresh Sheets Charts": "Refresh Sheets Charts","Generate from template": "Generate from template",+ "Create Presentation": "Create Presentation",+ "Copy Presentation": "Copy Presentation",+ "Find Presentations": "Find Presentations",+ "Get Presentation Outline": "Get Presentation Outline",+ "Get Slide": "Get Slide",+ "Get Slide Thumbnail": "Get Slide Thumbnail",+ "Add Slide": "Add Slide",+ "Duplicate Slide": "Duplicate Slide",+ "Move Slide": "Move Slide",+ "Delete Slide": "Delete Slide",+ "Replace Text": "Replace Text",+ "Replace Shapes with Image": "Replace Shapes with Image",+ "Insert Image": "Insert Image",+ "Set Speaker Notes": "Set Speaker Notes",+ "Export Presentation": "Export Presentation",+ "Batch Update (Advanced)": "Batch Update (Advanced)",+ "List Slide Elements": "List Slide Elements",+ "Create Shape or Text Box": "Create Shape or Text Box",+ "Insert Text": "Insert Text",+ "Set Element Text": "Set Element Text",+ "Update Text Style": "Update Text Style",+ "Update Paragraph Style": "Update Paragraph Style",+ "Update Shape Properties": "Update Shape Properties",+ "Move or Resize Element": "Move or Resize Element",+ "Delete Elements": "Delete Elements",+ "Create Table": "Create Table",+ "Insert Table Rows or Columns": "Insert Table Rows or Columns",+ "Delete Table Rows or Columns": "Delete Table Rows or Columns",+ "Set Slide Background": "Set Slide Background",+ "Insert Video": "Insert Video",+ "Replace Image": "Replace Image","Custom API Call": "Custom API Call","Get all slides from a presentation": "Get all slides from a presentation","Refresh all Google Sheets charts in the presentation": "Refresh all Google Sheets charts in the presentation","Generate a new slide from a template": "Generate a new slide from a template",+ "Create a new, empty Google Slides presentation, optionally in a Drive folder.": "Create a new, empty Google Slides presentation, optionally in a Drive folder.",+ "Make a copy of a presentation, optionally with a new name and folder.": "Make a copy of a presentation, optionally with a new name and folder.",+ "Search Google Drive for presentations by name and/or folder.": "Search Google Drive for presentations by name and/or folder.",+ "Get each slide's number, object ID, title, text and speaker notes.": "Get each slide's number, object ID, title, text and speaker notes.",+ "Get one slide with all of its elements.": "Get one slide with all of its elements.",+ "Get a PNG image of a slide, as a link and optionally as a file.": "Get a PNG image of a slide, as a link and optionally as a file.",+ "Add a new slide with a layout, and optionally fill its title and body.": "Add a new slide with a layout, and optionally fill its title and body.",+ "Copy a slide within the same presentation.": "Copy a slide within the same presentation.",+ "Move a slide to a new position in the presentation.": "Move a slide to a new position in the presentation.",+ "Delete a slide from the presentation.": "Delete a slide from the presentation.",+ "Replace every occurrence of a text in the presentation.": "Replace every occurrence of a text in the presentation.",+ "Replace every shape that contains a text (e.g. {{logo}}) with an image from a URL.": "Replace every shape that contains a text (e.g. {{logo}}) with an image from a URL.",+ "Add an image from a URL to a slide.": "Add an image from a URL to a slide.",+ "Replace the speaker notes of a slide.": "Replace the speaker notes of a slide.",+ "Download a presentation as a PDF, PowerPoint, OpenDocument or plain-text file.": "Download a presentation as a PDF, PowerPoint, OpenDocument or plain-text file.",+ "Send raw Google Slides batchUpdate requests to a presentation.": "Send raw Google Slides batchUpdate requests to a presentation.",+ "List the elements on one slide with their position, size and text, in points.": "List the elements on one slide with their position, size and text, in points.",+ "Add a text box or shape to a slide, optionally with text and a fill colour.": "Add a text box or shape to a slide, optionally with text and a fill colour.",+ "Insert text into a shape, text box or table cell (appends by default).": "Insert text into a shape, text box or table cell (appends by default).",+ "Replace all text in a shape, text box, placeholder or table cell.": "Replace all text in a shape, text box, placeholder or table cell.",+ "Change bold, italic, font, size, colour or link of text in a shape or table cell.": "Change bold, italic, font, size, colour or link of text in a shape or table cell.",+ "Set alignment, line spacing, paragraph spacing and bullets in a shape or table cell.": "Set alignment, line spacing, paragraph spacing and bullets in a shape or table cell.",+ "Change the fill, outline and vertical text alignment of a shape or text box.": "Change the fill, outline and vertical text alignment of a shape or text box.",+ "Set the position and/or size of an element on a slide, in points.": "Set the position and/or size of an element on a slide, in points.",+ "Delete one or more elements (shapes, images, tables, groups…) from slides.": "Delete one or more elements (shapes, images, tables, groups…) from slides.",+ "Add a table to a slide, optionally filled from a 2D array with a styled header row.": "Add a table to a slide, optionally filled from a 2D array with a styled header row.",+ "Add rows or columns to a table, optionally filling one new row or column.": "Add rows or columns to a table, optionally filling one new row or column.",+ "Delete one or more neighbouring rows or columns from a table.": "Delete one or more neighbouring rows or columns from a table.",+ "Set a solid colour or an image as the background of one slide or all slides.": "Set a solid colour or an image as the background of one slide or all slides.",+ "Embed a YouTube or Google Drive video on a slide.": "Embed a YouTube or Google Drive video on a slide.",+ "Swap an existing image for a new one from a URL, keeping its position and size.": "Swap an existing image for a new one from a URL, keeping its position and size.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","Presentation ID": "Presentation ID",+ "Fields": "Fields","Template presentation ID": "Template presentation ID","Placeholder Format": "Placeholder Format","Table Data": "Table Data",+ "Folder": "Folder",+ "Title": "Title",+ "Presentation to Copy": "Presentation to Copy",+ "New Name": "New Name",+ "Name Contains": "Name Contains",+ "Limit": "Limit",+ "Page Token": "Page Token",+ "Presentation": "Presentation",+ "Slide Number": "Slide Number",+ "Slide Object ID": "Slide Object ID",+ "Size": "Size",+ "Save as File": "Save as File",+ "Layout": "Layout",+ "Position": "Position",+ "Body": "Body",+ "Position of the Copy": "Position of the Copy",+ "New Position": "New Position",+ "Find": "Find",+ "Replace With": "Replace With",+ "Match Case": "Match Case",+ "Only on These Slides": "Only on These Slides",+ "Shape Text": "Shape Text",+ "Image URL": "Image URL",+ "Fit": "Fit",+ "X (pt)": "X (pt)",+ "Y (pt)": "Y (pt)",+ "Width (pt)": "Width (pt)",+ "Height (pt)": "Height (pt)",+ "Notes": "Notes",+ "Clear Notes": "Clear Notes",+ "Format": "Format",+ "File Name": "File Name",+ "Requests": "Requests",+ "Required Revision ID": "Required Revision ID",+ "Shape Type": "Shape Type",+ "Text": "Text",+ "Fill Color": "Fill Color",+ "Element Object ID": "Element Object ID",+ "Row": "Row",+ "Column": "Column",+ "Insertion Index": "Insertion Index",+ "Clear Text": "Clear Text",+ "Match Text": "Match Text",+ "Start Index": "Start Index",+ "End Index": "End Index",+ "Bold": "Bold",+ "Italic": "Italic",+ "Underline": "Underline",+ "Strikethrough": "Strikethrough",+ "Font Family": "Font Family",+ "Font Size (pt)": "Font Size (pt)",+ "Text Color": "Text Color",+ "Highlight Color": "Highlight Color",+ "Link URL": "Link URL",+ "Alignment": "Alignment",+ "Line Spacing (%)": "Line Spacing (%)",+ "Space Above (pt)": "Space Above (pt)",+ "Space Below (pt)": "Space Below (pt)",+ "Bullets": "Bullets",+ "Shape Object ID": "Shape Object ID",+ "Outline Color": "Outline Color",+ "Outline Weight (pt)": "Outline Weight (pt)",+ "Outline Dash": "Outline Dash",+ "Vertical Alignment": "Vertical Alignment",+ "Element Object IDs": "Element Object IDs",+ "Data": "Data",+ "Rows": "Rows",+ "Columns": "Columns",+ "Bold Header Row": "Bold Header Row",+ "Header Fill Color": "Header Fill Color",+ "Table Object ID": "Table Object ID",+ "Dimension": "Dimension",+ "Count": "Count",+ "Values": "Values",+ "All Slides": "All Slides",+ "Color": "Color",+ "Video": "Video",+ "Source": "Source",+ "Image Object ID": "Image Object ID","Method": "Method","Headers": "Headers","Query Parameters": "Query Parameters","Body Type": "Body Type",- "Body": "Body",- "Response is Binary ?": "Response is Binary ?",- "No Error on Failure": "No Error on Failure",- "Timeout (in seconds)": "Timeout (in seconds)",+ "Response is Binary": "Response is Binary",+ "Return Error as Output": "Return Error as Output",+ "Timeout": "Timeout","Follow redirects": "Follow redirects",- "The ID of the presentation": "The ID of the presentation",- "The ID of the presentation, between /d and /edit": "The ID of the presentation, between /d and /edit",- "The ID of the templated presentation": "The ID of the templated presentation",+ "The presentation ID (between /d/ and /edit in its URL), or the full URL.": "The presentation ID (between /d/ and /edit in its URL), or the full URL.",+ "Optional Google field mask to return only part of the presentation, e.g. presentationId,title,slides(objectId). Leave empty for the full presentation.": "Optional Google field mask to return only part of the presentation, e.g. presentationId,title,slides(objectId). Leave empty for the full presentation.",+ "The template presentation ID (between /d/ and /edit in its URL), or the full URL.": "The template presentation ID (between /d/ and /edit in its URL), or the full URL.","Choose the format of placeholders in your template": "Choose the format of placeholders in your template",+ "Optional Drive folder for the new presentation: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to use the default location. A service account needs a folder in a Shared Drive here.": "Optional Drive folder for the new presentation: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to use the default location. A service account needs a folder in a Shared Drive here.",+ "Name of the new presentation, e.g. \"Q3 Business Review\".": "Name of the new presentation, e.g. \"Q3 Business Review\".",+ "Optional Drive folder: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty for My Drive. A service account needs a folder in a Shared Drive here.": "Optional Drive folder: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty for My Drive. A service account needs a folder in a Shared Drive here.",+ "The presentation ID or its full URL, e.g. https://docs.google.com/presentation/d/1AbC...xyz/edit or just 1AbC...xyz.": "The presentation ID or its full URL, e.g. https://docs.google.com/presentation/d/1AbC...xyz/edit or just 1AbC...xyz.",+ "Name of the copy. Leave empty for Google's default (\"Copy of <name>\").": "Name of the copy. Leave empty for Google's default (\"Copy of <name>\").",+ "Optional Drive folder for the copy: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to use the default location. A service account needs a folder in a Shared Drive here.": "Optional Drive folder for the copy: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to use the default location. A service account needs a folder in a Shared Drive here.",+ "Return presentations whose name contains this text (case-insensitive). Leave empty to list all.": "Return presentations whose name contains this text (case-insensitive). Leave empty to list all.",+ "Only presentations directly in this Drive folder: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to search all of Drive.": "Only presentations directly in this Drive folder: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to search all of Drive.",+ "Maximum number of presentations to return (1-1000). Default 50.": "Maximum number of presentations to return (1-1000). Default 50.",+ "The nextPageToken of a previous call, to get the next results. Leave empty for the first page.": "The nextPageToken of a previous call, to get the next results. Leave empty for the first page.",+ "Position of the slide in the deck, starting at 1 for the first slide. Set this or Slide Object ID, not both.": "Position of the slide in the deck, starting at 1 for the first slide. Set this or Slide Object ID, not both.",+ "The slide object ID (e.g. \"g2c8d1e5a7f_0_12\", from Get Presentation Outline), or the slide URL copied from the browser while the slide is selected (it ends in #slide=id.<objectId>). Set this or Slide Number, not both.": "The slide object ID (e.g. \"g2c8d1e5a7f_0_12\", from Get Presentation Outline), or the slide URL copied from the browser while the slide is selected (it ends in #slide=id.<objectId>). Set this or Slide Number, not both.",+ "Width of the image.": "Width of the image.",+ "Also download the image and return it as a file (the image link expires after about 30 minutes).": "Also download the image and return it as a file (the image link expires after about 30 minutes).",+ "Layout of the new slide, from the presentation's theme.": "Layout of the new slide, from the presentation's theme.",+ "Where to put the slide, starting at 1 for the first slide. Leave empty to add it at the end.": "Where to put the slide, starting at 1 for the first slide. Leave empty to add it at the end.",+ "Text for the slide title. Leave empty to keep the placeholder empty.": "Text for the slide title. Leave empty to keep the placeholder empty.",+ "Text for the body (or the subtitle, on the Title slide layout). New lines start new paragraphs.": "Text for the body (or the subtitle, on the Title slide layout). New lines start new paragraphs.",+ "Where to put the copy, starting at 1. Leave empty to place it right after the original.": "Where to put the copy, starting at 1. Leave empty to place it right after the original.",+ "Position the slide should end up at, starting at 1 for the first slide.": "Position the slide should end up at, starting at 1 for the first slide.",+ "Text to search for, e.g. [[customer_name]]. Activepieces reads {{...}} typed into a field as a reference to earlier step data, so search for [[name]]-style tokens or map the text from a previous step.": "Text to search for, e.g. [[customer_name]]. Activepieces reads {{...}} typed into a field as a reference to earlier step data, so search for [[name]]-style tokens or map the text from a previous step.",+ "Replacement text. Leave empty to delete every match.": "Replacement text. Leave empty to delete every match.",+ "When on, \"Name\" does not match \"name\".": "When on, \"Name\" does not match \"name\".",+ "Optional list of slide object IDs (or slide URLs) to limit the change to. Leave empty for every slide. Speaker notes pages cannot be listed here.": "Optional list of slide object IDs (or slide URLs) to limit the change to. Leave empty for every slide. Speaker notes pages cannot be listed here.",+ "Shapes containing this text are replaced, e.g. [[logo]]. Activepieces reads {{...}} typed into a field as a reference to earlier step data, so search for [[name]]-style tokens or map the text from a previous step.": "Shapes containing this text are replaced, e.g. [[logo]]. Activepieces reads {{...}} typed into a field as a reference to earlier step data, so search for [[name]]-style tokens or map the text from a previous step.",+ "Public link to a PNG, JPEG or GIF image (under 50 MB), e.g. https://example.com/logo.png.": "Public link to a PNG, JPEG or GIF image (under 50 MB), e.g. https://example.com/logo.png.",+ "How the image fills the shape.": "How the image fills the shape.",+ "Public link to a PNG, JPEG or GIF image (under 50 MB), e.g. https://example.com/chart.png.": "Public link to a PNG, JPEG or GIF image (under 50 MB), e.g. https://example.com/chart.png.",+ "Distance from the left edge of the slide, in points. Set together with Y.": "Distance from the left edge of the slide, in points. Set together with Y.",+ "Distance from the top edge of the slide, in points. Set together with X.": "Distance from the top edge of the slide, in points. Set together with X.",+ "Width of the image box, in points. Set together with Height. Leave both empty for the image's own size.": "Width of the image box, in points. Set together with Height. Leave both empty for the image's own size.",+ "Height of the image box, in points. Set together with Width.": "Height of the image box, in points. Set together with Width.",+ "The new speaker notes. They replace the current notes.": "The new speaker notes. They replace the current notes.",+ "Turn on to remove the slide's speaker notes. Leave Notes empty when using this.": "Turn on to remove the slide's speaker notes. Leave Notes empty when using this.",+ "File format of the export.": "File format of the export.",+ "Name of the exported file without extension. Leave empty to use the presentation name.": "Name of the exported file without extension. Leave empty to use the presentation name.",+ "JSON array of Slides API Request objects, e.g. [{\"createShape\":{\"objectId\":\"box_001\",\"shapeType\":\"TEXT_BOX\",\"elementProperties\":{\"pageObjectId\":\"p\"}}}].": "JSON array of Slides API Request objects, e.g. [{\"createShape\":{\"objectId\":\"box_001\",\"shapeType\":\"TEXT_BOX\",\"elementProperties\":{\"pageObjectId\":\"p\"}}}].",+ "Optional revisionId (from Get Presentation Outline); the update fails if the presentation changed since.": "Optional revisionId (from Get Presentation Outline); the update fails if the presentation changed since.",+ "TEXT_BOX (default) has no fill or outline; the others are filled shapes.": "TEXT_BOX (default) has no fill or outline; the others are filled shapes.",+ "Distance from the left edge of the slide, in points.": "Distance from the left edge of the slide, in points.",+ "Distance from the top edge of the slide, in points.": "Distance from the top edge of the slide, in points.",+ "Width in points, greater than 0.": "Width in points, greater than 0.",+ "Height in points, greater than 0.": "Height in points, greater than 0.",+ "Optional text to put in the shape. Use \\n for a new paragraph.": "Optional text to put in the shape. Use \\n for a new paragraph.",+ "Optional hex colour for the background, e.g. #1A73E8, or \"transparent\".": "Optional hex colour for the background, e.g. #1A73E8, or \"transparent\".",+ "Object ID of the shape, text box, placeholder or table, e.g. \"g2c8d1e5a7f_0_3\". Get it from List Slide Elements, Get Presentation Outline (elements[].objectId), or the output of Create Shape / Create Table. For a table also set Row and Column.": "Object ID of the shape, text box, placeholder or table, e.g. \"g2c8d1e5a7f_0_3\". Get it from List Slide Elements, Get Presentation Outline (elements[].objectId), or the output of Create Shape / Create Table. For a table also set Row and Column.",+ "Table cells only: row number, starting at 1. Leave empty for shapes and text boxes.": "Table cells only: row number, starting at 1. Leave empty for shapes and text boxes.",+ "Table cells only: column number, starting at 1. Leave empty for shapes and text boxes.": "Table cells only: column number, starting at 1. Leave empty for shapes and text boxes.",+ "The text to insert. Start it with \\n to begin a new paragraph after the existing text.": "The text to insert. Start it with \\n to begin a new paragraph after the existing text.",+ "Optional 0-based character position (0 = start). Leave empty to append at the end.": "Optional 0-based character position (0 = start). Leave empty to append at the end.",+ "The new text. Use \\n for a new paragraph. Leave empty only together with Clear Text.": "The new text. Use \\n for a new paragraph. Leave empty only together with Clear Text.",+ "Turn on to remove all text from the element. Leave Text empty when using this.": "Turn on to remove all text from the element. Leave Text empty when using this.",+ "Optional: only change every occurrence of this exact text (case-sensitive) inside the element. Leave empty (and Start/End Index empty) for all of its text.": "Optional: only change every occurrence of this exact text (case-sensitive) inside the element. Leave empty (and Start/End Index empty) for all of its text.",+ "Optional 0-based start of a character range (instead of Match Text).": "Optional 0-based start of a character range (instead of Match Text).",+ "Optional 0-based end of the range, exclusive (instead of Match Text).": "Optional 0-based end of the range, exclusive (instead of Match Text).",+ "true or false; leave unset to keep.": "true or false; leave unset to keep.",+ "Google Fonts family name, e.g. \"Roboto\" or \"Montserrat\".": "Google Fonts family name, e.g. \"Roboto\" or \"Montserrat\".",+ "Font size in points, e.g. 24.": "Font size in points, e.g. 24.",+ "Hex colour, e.g. #202124.": "Hex colour, e.g. #202124.",+ "Hex background colour behind the text, or \"none\" to remove the highlight.": "Hex background colour behind the text, or \"none\" to remove the highlight.",+ "Make the text a link to this http(s) URL, or \"none\" to remove an existing link.": "Make the text a link to this http(s) URL, or \"none\" to remove an existing link.",+ "START (left in left-to-right text), CENTER, END or JUSTIFIED.": "START (left in left-to-right text), CENTER, END or JUSTIFIED.",+ "Line spacing as a percentage of normal: 100 = single, 150 = one and a half.": "Line spacing as a percentage of normal: 100 = single, 150 = one and a half.",+ "Space before each paragraph, in points.": "Space before each paragraph, in points.",+ "Space after each paragraph, in points.": "Space after each paragraph, in points.",+ "Bullet or numbering preset for the paragraphs, or NONE to remove bullets.": "Bullet or numbering preset for the paragraphs, or NONE to remove bullets.",+ "Object ID of the shape or text box (from List Slide Elements, Get Presentation Outline or Create Shape).": "Object ID of the shape or text box (from List Slide Elements, Get Presentation Outline or Create Shape).",+ "Hex colour, e.g. #E8F0FE, or \"transparent\".": "Hex colour, e.g. #E8F0FE, or \"transparent\".",+ "Hex colour, e.g. #1A73E8, or \"none\" to hide the outline.": "Hex colour, e.g. #1A73E8, or \"none\" to hide the outline.",+ "Outline thickness in points.": "Outline thickness in points.",+ "Outline dash style.": "Outline dash style.",+ "Where the text sits inside the shape.": "Where the text sits inside the shape.",+ "Object ID of the element to move or resize (from List Slide Elements or Get Presentation Outline).": "Object ID of the element to move or resize (from List Slide Elements or Get Presentation Outline).",+ "New distance from the left edge of the slide, in points.": "New distance from the left edge of the slide, in points.",+ "New distance from the top edge of the slide, in points.": "New distance from the top edge of the slide, in points.",+ "New width in points.": "New width in points.",+ "New height in points.": "New height in points.",+ "Object IDs of the elements to delete, e.g. [\"g2c8d1e5a7f_0_3\"].": "Object IDs of the elements to delete, e.g. [\"g2c8d1e5a7f_0_3\"].",+ "Optional JSON array of rows, each an array of cell values, e.g. [[\"Name\",\"Score\"],[\"Ann\",9]].": "Optional JSON array of rows, each an array of cell values, e.g. [[\"Name\",\"Score\"],[\"Ann\",9]].",+ "Number of rows. Leave empty to use the number of rows in Data.": "Number of rows. Leave empty to use the number of rows in Data.",+ "Number of columns. Leave empty to use the longest row in Data.": "Number of columns. Leave empty to use the longest row in Data.",+ "Make the text of the first row bold.": "Make the text of the first row bold.",+ "Optional hex background colour for the first row, e.g. #E8F0FE.": "Optional hex background colour for the first row, e.g. #E8F0FE.",+ "Distance from the left edge, in points. Set together with Y.": "Distance from the left edge, in points. Set together with Y.",+ "Distance from the top edge, in points. Set together with X.": "Distance from the top edge, in points. Set together with X.",+ "Table width in points. Set together with Height.": "Table width in points. Set together with Height.",+ "Table height in points. Set together with Width.": "Table height in points. Set together with Width.",+ "Object ID of the table (from Create Table, List Slide Elements or Get Presentation Outline).": "Object ID of the table (from Create Table, List Slide Elements or Get Presentation Outline).",+ "ROW or COLUMN.": "ROW or COLUMN.",+ "Where the first new row/column goes, starting at 1 (1 = before the first). Leave empty to add at the end.": "Where the first new row/column goes, starting at 1 (1 = before the first). Leave empty to add at the end.",+ "How many to add, 1-20. Default 1.": "How many to add, 1-20. Default 1.",+ "Optional cell texts for the new row (left to right) or column (top to bottom). Only with Count 1.": "Optional cell texts for the new row (left to right) or column (top to bottom). Only with Count 1.",+ "First row/column to delete, starting at 1.": "First row/column to delete, starting at 1.",+ "How many neighbouring rows/columns to delete. Default 1.": "How many neighbouring rows/columns to delete. Default 1.",+ "Turn on to change every slide. Leave Slide Number and Slide Object ID empty when using this.": "Turn on to change every slide. Leave Slide Number and Slide Object ID empty when using this.",+ "Hex colour, e.g. #0B1F3A.": "Hex colour, e.g. #0B1F3A.",+ "Public PNG, JPEG or GIF URL to stretch over the slide, e.g. https://example.com/bg.png.": "Public PNG, JPEG or GIF URL to stretch over the slide, e.g. https://example.com/bg.png.",+ "YouTube or Google Drive video URL, or the video ID.": "YouTube or Google Drive video URL, or the video ID.",+ "Only needed for a bare Drive file ID: DRIVE. YouTube IDs and URLs are detected.": "Only needed for a bare Drive file ID: DRIVE. YouTube IDs and URLs are detected.",+ "Width in points. Set together with Height.": "Width in points. Set together with Height.",+ "Height in points. Set together with Width.": "Height in points. Set together with Width.",+ "Object ID of the image to replace (type IMAGE in List Slide Elements, or from Insert Image).": "Object ID of the image to replace (type IMAGE in List Slide Elements, or from Insert Image).",+ "Public link to a PNG, JPEG or GIF image (under 50 MB).": "Public link to a PNG, JPEG or GIF image (under 50 MB).",+ "CENTER_INSIDE (default) fits the whole image in the frame; CENTER_CROP fills the frame and crops.": "CENTER_INSIDE (default) fits the whole image in the frame; CENTER_CROP fills the frame and crops.","Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.","Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.","Curly Braces {{}}": "Curly Braces {{}}","Square Brackets [[]]": "Square Brackets [[]]",+ "Large (1600 px wide)": "Large (1600 px wide)",+ "Medium (800 px wide)": "Medium (800 px wide)",+ "Small (200 px wide)": "Small (200 px wide)",+ "Title and body": "Title and body",+ "Title slide (title and subtitle)": "Title slide (title and subtitle)",+ "Title only": "Title only",+ "Title and two columns": "Title and two columns",+ "Section header": "Section header",+ "Section title and description": "Section title and description",+ "One column text": "One column text",+ "Main point": "Main point",+ "Big number": "Big number",+ "Caption only": "Caption only",+ "Blank": "Blank",+ "Fit inside the shape (keep the whole image)": "Fit inside the shape (keep the whole image)",+ "Fill the shape (crop the image)": "Fill the shape (crop the image)",+ "PDF (.pdf)": "PDF (.pdf)",+ "PowerPoint (.pptx)": "PowerPoint (.pptx)",+ "OpenDocument (.odp)": "OpenDocument (.odp)",+ "Plain text (.txt)": "Plain text (.txt)",+ "TEXT_BOX": "TEXT_BOX",+ "RECTANGLE": "RECTANGLE",+ "ROUND_RECTANGLE": "ROUND_RECTANGLE",+ "ELLIPSE": "ELLIPSE",+ "TRIANGLE": "TRIANGLE",+ "RIGHT_TRIANGLE": "RIGHT_TRIANGLE",+ "DIAMOND": "DIAMOND",+ "PENTAGON": "PENTAGON",+ "HEXAGON": "HEXAGON",+ "OCTAGON": "OCTAGON",+ "PARALLELOGRAM": "PARALLELOGRAM",+ "TRAPEZOID": "TRAPEZOID",+ "CHEVRON": "CHEVRON",+ "HOME_PLATE": "HOME_PLATE",+ "RIGHT_ARROW": "RIGHT_ARROW",+ "LEFT_ARROW": "LEFT_ARROW",+ "UP_ARROW": "UP_ARROW",+ "DOWN_ARROW": "DOWN_ARROW",+ "LEFT_RIGHT_ARROW": "LEFT_RIGHT_ARROW",+ "STAR_5": "STAR_5",+ "HEART": "HEART",+ "CLOUD": "CLOUD",+ "PLUS": "PLUS",+ "DONUT": "DONUT",+ "WEDGE_RECTANGLE_CALLOUT": "WEDGE_RECTANGLE_CALLOUT",+ "WEDGE_ROUND_RECTANGLE_CALLOUT": "WEDGE_ROUND_RECTANGLE_CALLOUT",+ "FLOW_CHART_PROCESS": "FLOW_CHART_PROCESS",+ "FLOW_CHART_DECISION": "FLOW_CHART_DECISION",+ "FLOW_CHART_TERMINATOR": "FLOW_CHART_TERMINATOR",+ "START": "START",+ "CENTER": "CENTER",+ "END": "END",+ "JUSTIFIED": "JUSTIFIED",+ "BULLET_DISC_CIRCLE_SQUARE": "BULLET_DISC_CIRCLE_SQUARE",+ "BULLET_ARROW_DIAMOND_DISC": "BULLET_ARROW_DIAMOND_DISC",+ "BULLET_CHECKBOX": "BULLET_CHECKBOX",+ "BULLET_STAR_CIRCLE_SQUARE": "BULLET_STAR_CIRCLE_SQUARE",+ "NUMBERED_DIGIT_ALPHA_ROMAN": "NUMBERED_DIGIT_ALPHA_ROMAN",+ "NUMBERED_DIGIT_ALPHA_ROMAN_PARENS": "NUMBERED_DIGIT_ALPHA_ROMAN_PARENS",+ "NUMBERED_DIGIT_NESTED": "NUMBERED_DIGIT_NESTED",+ "NUMBERED_UPPERALPHA_ALPHA_ROMAN": "NUMBERED_UPPERALPHA_ALPHA_ROMAN",+ "NUMBERED_UPPERROMAN_UPPERALPHA_DIGIT": "NUMBERED_UPPERROMAN_UPPERALPHA_DIGIT",+ "NONE": "NONE",+ "SOLID": "SOLID",+ "DOT": "DOT",+ "DASH": "DASH",+ "DASH_DOT": "DASH_DOT",+ "LONG_DASH": "LONG_DASH",+ "LONG_DASH_DOT": "LONG_DASH_DOT",+ "TOP": "TOP",+ "MIDDLE": "MIDDLE",+ "BOTTOM": "BOTTOM",+ "ROW": "ROW",+ "COLUMN": "COLUMN",+ "YOUTUBE": "YOUTUBE",+ "DRIVE": "DRIVE",+ "CENTER_INSIDE": "CENTER_INSIDE",+ "CENTER_CROP": "CENTER_CROP","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE",- "HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw"+ "HEAD": "HEAD"}\ No newline at end of filediff --git a/packages/pieces/community/google-slides/src/index.ts b/packages/pieces/community/google-slides/src/index.tsindex 8d26a2a1f90..fa4cbe66d6b 100644--- a/packages/pieces/community/google-slides/src/index.ts+++ b/packages/pieces/community/google-slides/src/index.ts@@ -1,22 +1,84 @@-import { createPiece } from "@activepieces/pieces-framework";+import { createPiece } from '@activepieces/pieces-framework';import { createCustomApiCallAction } from '@activepieces/pieces-common';-import { refreshSheetsCharts } from "./lib/actions/refresh-charts";-import { generateFromTemplate } from "./lib/actions/generate-from-template";-import { getPresentation } from "./lib/actions/get-presentation";+import { refreshSheetsCharts } from './lib/actions/refresh-charts';+import { generateFromTemplate } from './lib/actions/generate-from-template';+import { getPresentation } from './lib/actions/get-presentation';+import { createPresentation } from './lib/actions/create-presentation';+import { copyPresentation } from './lib/actions/copy-presentation';+import { findPresentations } from './lib/actions/find-presentations';+import { getPresentationOutline } from './lib/actions/get-presentation-outline';+import { getSlide } from './lib/actions/get-slide';+import { getSlideThumbnail } from './lib/actions/get-slide-thumbnail';+import { addSlide } from './lib/actions/add-slide';+import { duplicateSlide } from './lib/actions/duplicate-slide';+import { moveSlide } from './lib/actions/move-slide';+import { deleteSlide } from './lib/actions/delete-slide';+import { replaceText } from './lib/actions/replace-text';+import { replaceShapesWithImage } from './lib/actions/replace-shapes-with-image';+import { insertImage } from './lib/actions/insert-image';+import { setSpeakerNotes } from './lib/actions/set-speaker-notes';+import { exportPresentation } from './lib/actions/export-presentation';+import { batchUpdate } from './lib/actions/batch-update';+import { listSlideElements } from './lib/actions/list-slide-elements';+import { createShape } from './lib/actions/create-shape';+import { insertText } from './lib/actions/insert-text';+import { setElementText } from './lib/actions/set-element-text';+import { updateTextStyle } from './lib/actions/update-text-style';+import { updateParagraphStyle } from './lib/actions/update-paragraph-style';+import { updateShapeProperties } from './lib/actions/update-shape-properties';+import { moveResizeElement } from './lib/actions/move-resize-element';+import { deleteElements } from './lib/actions/delete-elements';+import { createTable } from './lib/actions/create-table';+import { insertTableRowsOrColumns } from './lib/actions/insert-table-rows-or-columns';+import { deleteTableRowsOrColumns } from './lib/actions/delete-table-rows-or-columns';+import { setSlideBackground } from './lib/actions/set-slide-background';+import { insertVideo } from './lib/actions/insert-video';+import { replaceImage } from './lib/actions/replace-image';import { getAccessToken, googleSlidesAuth, GoogleSlidesAuthValue } from './lib/auth';export { googleSlidesAuth, getAccessToken, GoogleSlidesAuthValue } from './lib/auth';export const googleSlide = createPiece({- displayName: "Google Slides",+ displayName: 'Google Slides',auth: googleSlidesAuth,- minimumSupportedRelease: '0.86.4',- logoUrl: "https://cdn.activepieces.com/pieces/google-slides.png",- authors: ["Kevinyu-alan"],+ minimumSupportedRelease: '0.88.2',+ logoUrl: 'https://cdn.activepieces.com/pieces/google-slides.png',+ authors: ['Kevinyu-alan'],actions: [getPresentation,refreshSheetsCharts,generateFromTemplate,+ createPresentation,+ copyPresentation,+ findPresentations,+ getPresentationOutline,+ getSlide,+ getSlideThumbnail,+ addSlide,+ duplicateSlide,+ moveSlide,+ deleteSlide,+ replaceText,+ replaceShapesWithImage,+ insertImage,+ setSpeakerNotes,+ exportPresentation,+ batchUpdate,+ listSlideElements,+ createShape,+ insertText,+ setElementText,+ updateTextStyle,+ updateParagraphStyle,+ updateShapeProperties,+ moveResizeElement,+ deleteElements,+ createTable,+ insertTableRowsOrColumns,+ deleteTableRowsOrColumns,+ setSlideBackground,+ insertVideo,+ replaceImage,createCustomApiCallAction({baseUrl: () => 'https://slides.googleapis.com/v1/presentations/',auth: googleSlidesAuth,diff --git a/packages/pieces/community/google-slides/src/lib/actions/add-slide.ts b/packages/pieces/community/google-slides/src/lib/actions/add-slide.tsnew file mode 100644index 00000000000..a143ba04292--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/add-slide.ts@@ -0,0 +1,92 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { FIELD_MASKS, PREDEFINED_LAYOUTS, slidesRequests } from '../commons/requests';+import { addSlideOutputSchema } from '../output-schemas';++export const addSlide = createAction({+ auth: googleSlidesAuth,+ name: 'add_slide',+ classification: 'WRITE',+ displayName: 'Add Slide',+ description: 'Add a new slide with a layout, and optionally fill its title and body.',+ audience: 'both',+ aiMetadata: {+ description:+ "Insert a new slide using one of the theme's standard layouts (e.g. TITLE_AND_BODY, TITLE, SECTION_HEADER, BLANK) at a 1-based position or at the end, optionally writing a title and body into the layout's placeholders (the TITLE layout uses its subtitle as the body). Use it to build or extend a deck; to reuse an existing slide's design use Duplicate Slide. Fails without changes if the theme lacks the layout or a needed placeholder. Not idempotent: each call adds another slide.",+ idempotent: false,+ },+ outputSchema: addSlideOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ layout: Property.StaticDropdown({+ displayName: 'Layout',+ description: "Layout of the new slide, from the presentation's theme.",+ required: true,+ defaultValue: 'TITLE_AND_BODY',+ options: { options: PREDEFINED_LAYOUTS },+ }),+ position: Property.Number({+ displayName: 'Position',+ description: 'Where to put the slide, starting at 1 for the first slide. Leave empty to add it at the end.',+ required: false,+ }),+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Text for the slide title. Leave empty to keep the placeholder empty.',+ required: false,+ }),+ body: Property.LongText({+ displayName: 'Body',+ description: 'Text for the body (or the subtitle, on the Title slide layout). New lines start new paragraphs.',+ required: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const layout = context.propsValue.layout;+ if (!PREDEFINED_LAYOUTS.some((option) => option.value === layout)) {+ throw new Error(`Layout must be one of: ${PREDEFINED_LAYOUTS.map((option) => option.value).join(', ')}.`);+ }+ const accessToken = await getAccessToken(context.auth);+ const action = 'add the slide';+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.addSlide })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const slideCount = presentation.slides?.length ?? 0;+ const insertionIndex = slidesRequests.readPosition({+ position: context.propsValue.position,+ maxPosition: slideCount + 1,+ });+ const built = slidesRequests.buildAddSlideRequests({+ layouts: presentation.layouts ?? [],+ predefinedLayout: layout,+ insertionIndex,+ title: context.propsValue.title ?? undefined,+ body: context.propsValue.body ?? undefined,+ newId: slidesIds.generateObjectId,+ });+ await slidesApi+ .batchUpdate({+ accessToken,+ presentationId,+ requests: built.requests,+ requiredRevisionId: presentation.revisionId,+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ return {+ presentationId,+ slideObjectId: built.slideObjectId,+ slideNumber: (insertionIndex ?? slideCount) + 1,+ slideUrl: slidesApi.slideUrl({ presentationId, slideObjectId: built.slideObjectId }),+ titleObjectId: built.titleObjectId,+ bodyObjectId: built.bodyObjectId,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/batch-update.ts b/packages/pieces/community/google-slides/src/lib/actions/batch-update.tsnew file mode 100644index 00000000000..af85ca50f38--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/batch-update.ts@@ -0,0 +1,57 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { batchUpdateOutputSchema } from '../output-schemas';++export const batchUpdate = createAction({+ auth: googleSlidesAuth,+ name: 'batch_update',+ classification: 'WRITE',+ displayName: 'Batch Update (Advanced)',+ description: 'Send raw Google Slides batchUpdate requests to a presentation.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Advanced escape hatch that sends a raw array of Google Slides API batchUpdate Request objects (createShape, insertText, updateTextStyle, createTable, groupObjects, etc.) to one presentation; all requests apply atomically or none do. Only use it for edits no dedicated Slides action covers (grouping, merged cells, lines, table borders, column widths): prefer Create Shape or Text Box, Insert Text, Set Element Text, Update Text Style, Update Paragraph Style, Create Table, Move or Resize Element, Add Slide, Replace Text and the others, which validate input and return the IDs you need. Get object IDs from Get Presentation Outline; new object IDs must be 5-50 characters of [a-zA-Z0-9_-:]. Optionally pass Required Revision ID to fail if the deck changed. Not idempotent in general.',+ idempotent: false,+ },+ outputSchema: batchUpdateOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ requests: Property.Json({+ displayName: 'Requests',+ description:+ 'JSON array of Slides API Request objects, e.g. [{"createShape":{"objectId":"box_001","shapeType":"TEXT_BOX","elementProperties":{"pageObjectId":"p"}}}].',+ required: true,+ }),+ required_revision_id: Property.ShortText({+ displayName: 'Required Revision ID',+ description: 'Optional revisionId (from Get Presentation Outline); the update fails if the presentation changed since.',+ required: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const requests = slidesRequests.readBatchRequests(context.propsValue.requests);+ const accessToken = await getAccessToken(context.auth);+ const response = await slidesApi+ .batchUpdate({+ accessToken,+ presentationId,+ requests,+ requiredRevisionId: context.propsValue.required_revision_id?.trim() || undefined,+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'apply the batch update' });+ });+ return {+ presentationId: response.presentationId ?? presentationId,+ appliedRequests: requests.length,+ replies: response.replies ?? [],+ writeControl: response.writeControl ?? null,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/copy-presentation.ts b/packages/pieces/community/google-slides/src/lib/actions/copy-presentation.tsnew file mode 100644index 00000000000..de07c7b9000--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/copy-presentation.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { drive as googleDrive } from '@googleapis/drive';+import { createGoogleClient, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { copyPresentationOutputSchema } from '../output-schemas';++export const copyPresentation = createAction({+ auth: googleSlidesAuth,+ name: 'copy_presentation',+ classification: 'WRITE',+ displayName: 'Copy Presentation',+ description: 'Make a copy of a presentation, optionally with a new name and folder.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Duplicate an existing Google Slides presentation as a new file, with an optional new name and Drive folder; the content is copied unchanged. Use it to work on a copy of a deck (then Replace Text, Add Slide, etc. on the copy); for one-step copy-and-fill of {{placeholders}} use Generate from Template. A service account needs a Shared Drive folder. Not idempotent: each call creates another file.',+ idempotent: false,+ },+ outputSchema: copyPresentationOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp('Presentation to Copy'),+ name: Property.ShortText({+ displayName: 'New Name',+ description: 'Name of the copy. Leave empty for Google\'s default ("Copy of <name>").',+ required: false,+ }),+ folder_id: slidesProps.folderIdProp(+ 'Optional Drive folder for the copy: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to use the default location. A service account needs a folder in a Shared Drive here.'+ ),+ },+ async run(context) {+ const sourceId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const folderId = slidesIds.parseFolderId(context.propsValue.folder_id);+ const name = context.propsValue.name?.trim();+ const drive = googleDrive({ version: 'v3', auth: await createGoogleClient(context.auth) });+ const response = await drive.files+ .copy({+ fileId: sourceId,+ requestBody: {+ ...(name ? { name } : {}),+ ...(folderId ? { parents: [folderId] } : {}),+ },+ supportsAllDrives: true,+ fields: 'id,name,createdTime',+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'copy the presentation' });+ });+ const id = response.data.id;+ if (!id) {+ throw new Error('Google Drive copied the presentation but returned no file ID.');+ }+ return {+ presentationId: id,+ title: response.data.name ?? null,+ presentationUrl: slidesApi.presentationUrl(id),+ sourcePresentationId: sourceId,+ folderId: folderId ?? null,+ createdTime: response.data.createdTime ?? null,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/create-presentation.ts b/packages/pieces/community/google-slides/src/lib/actions/create-presentation.tsnew file mode 100644index 00000000000..d955bcc4ee4--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/create-presentation.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { drive as googleDrive } from '@googleapis/drive';+import { createGoogleClient, googleSlidesAuth } from '../auth';+import { PRESENTATION_MIME_TYPE, slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { createPresentationOutputSchema } from '../output-schemas';++export const createPresentation = createAction({+ auth: googleSlidesAuth,+ name: 'create_presentation',+ classification: 'WRITE',+ displayName: 'Create Presentation',+ description: 'Create a new, empty Google Slides presentation, optionally in a Drive folder.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Create a new, empty Google Slides presentation with the given title, in My Drive or in a chosen Drive folder. Use it to start a deck from scratch, then add content with Add Slide, Insert Image and Replace Text; to start from an existing deck use Copy Presentation or Generate from Template instead. A service account has no Drive storage of its own, so it needs a folder in a Shared Drive. Not idempotent: each call creates another presentation.',+ idempotent: false,+ },+ outputSchema: createPresentationOutputSchema,+ props: {+ title: Property.ShortText({+ displayName: 'Title',+ description: 'Name of the new presentation, e.g. "Q3 Business Review".',+ required: true,+ }),+ folder_id: slidesProps.folderIdProp(+ 'Optional Drive folder: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty for My Drive. A service account needs a folder in a Shared Drive here.'+ ),+ },+ async run(context) {+ const title = context.propsValue.title?.trim();+ if (!title) {+ throw new Error('Title is required.');+ }+ const folderId = slidesIds.parseFolderId(context.propsValue.folder_id);+ const drive = googleDrive({ version: 'v3', auth: await createGoogleClient(context.auth) });+ const response = await drive.files+ .create({+ requestBody: {+ name: title,+ mimeType: PRESENTATION_MIME_TYPE,+ ...(folderId ? { parents: [folderId] } : {}),+ },+ supportsAllDrives: true,+ fields: 'id,name,createdTime',+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'create the presentation' });+ });+ const id = response.data.id;+ if (!id) {+ throw new Error('Google Drive created the presentation but returned no file ID.');+ }+ return {+ presentationId: id,+ title: response.data.name ?? title,+ presentationUrl: slidesApi.presentationUrl(id),+ folderId: folderId ?? null,+ createdTime: response.data.createdTime ?? null,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/create-shape.ts b/packages/pieces/community/google-slides/src/lib/actions/create-shape.tsnew file mode 100644index 00000000000..2a48555e6bf--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/create-shape.ts@@ -0,0 +1,86 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { SHAPE_TYPES, slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { createShapeOutputSchema } from '../output-schemas';++export const createShape = createAction({+ auth: googleSlidesAuth,+ name: 'create_shape',+ classification: 'WRITE',+ displayName: 'Create Shape or Text Box',+ description: 'Add a text box or shape to a slide, optionally with text and a fill colour.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Add a text box (default) or another shape (rectangle, ellipse, arrow, callout…) to one slide at X/Y with Width/Height in points (a standard 16:9 slide is 720 x 405 pt; List Slide Elements gives the exact size and what is already there), optionally with its text and fill colour in the same call. Use it to put new text or boxes on a slide; to fill an existing placeholder use Set Element Text, and for pictures use Insert Image. Returns the new objectId for styling calls (Update Text Style, Update Shape Properties). Not idempotent: each call adds another shape.',+ idempotent: false,+ },+ outputSchema: createShapeOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ shape_type: slidesProps.enumProp({+ displayName: 'Shape Type',+ description: 'TEXT_BOX (default) has no fill or outline; the others are filled shapes.',+ values: SHAPE_TYPES,+ }),+ x: slidesProps.pointProp({ displayName: 'X (pt)', description: 'Distance from the left edge of the slide, in points.', required: true }),+ y: slidesProps.pointProp({ displayName: 'Y (pt)', description: 'Distance from the top edge of the slide, in points.', required: true }),+ width: slidesProps.pointProp({ displayName: 'Width (pt)', description: 'Width in points, greater than 0.', required: true }),+ height: slidesProps.pointProp({ displayName: 'Height (pt)', description: 'Height in points, greater than 0.', required: true }),+ text: Property.LongText({+ displayName: 'Text',+ description: 'Optional text to put in the shape. Use \\n for a new paragraph.',+ required: false,+ }),+ fill_color: slidesProps.colorProp({+ displayName: 'Fill Color',+ description: 'Optional hex colour for the background, e.g. #1A73E8, or "transparent".',+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: propsValue.slide_number,+ slideObjectId: propsValue.slide_object_id,+ });+ const shapeType =+ slidesElements.readEnum({ value: propsValue.shape_type, label: 'Shape Type', allowed: SHAPE_TYPES }) ?? 'TEXT_BOX';+ const box = slidesElements.readBox({ x: propsValue.x, y: propsValue.y, width: propsValue.width, height: propsValue.height, required: true });+ const text = slidesElements.readText(propsValue.text);+ const fillColor = slidesElements.readColor({ value: propsValue.fill_color, label: 'Fill Color' });+ const objectId = slidesIds.generateObjectId('shape');+ const accessToken = await getAccessToken(context.auth);+ const action = 'create the shape';+ const { objectId: slideObjectId, revisionId } = await slidesRequests+ .lookupSlide({ accessToken, presentationId, selector })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: slidesElementRequests.buildCreateShapeRequests({ objectId, slideObjectId, shapeType, box, text, fillColor }),+ revisionId,+ action,+ });+ return {+ presentationId,+ slideObjectId,+ objectId,+ shapeType,+ x: box.position?.x ?? null,+ y: box.position?.y ?? null,+ width: box.size?.width ?? null,+ height: box.size?.height ?? null,+ text: text ?? '',+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/create-table.ts b/packages/pieces/community/google-slides/src/lib/actions/create-table.tsnew file mode 100644index 00000000000..3bbfae812e3--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/create-table.ts@@ -0,0 +1,96 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { createTableOutputSchema } from '../output-schemas';++export const createTable = createAction({+ auth: googleSlidesAuth,+ name: 'create_table',+ classification: 'WRITE',+ displayName: 'Create Table',+ description: 'Add a table to a slide, optionally filled from a 2D array with a styled header row.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Add a table to one slide and fill it in the same call from Data, a JSON array of rows (e.g. [["Region","Q1"],["EMEA","12"]]); Rows/Columns default to the size of Data. Optionally bold and colour the first (header) row, and place it with X/Y and Width/Height in points (both pairs optional). Use Set Element Text with Row/Column to change one cell later, and Insert/Delete Table Rows or Columns to change its size. Returns the tableObjectId. Not idempotent: each call adds another table.',+ idempotent: false,+ },+ outputSchema: createTableOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ data: Property.Json({+ displayName: 'Data',+ description: 'Optional JSON array of rows, each an array of cell values, e.g. [["Name","Score"],["Ann",9]].',+ required: false,+ }),+ rows: Property.Number({ displayName: 'Rows', description: 'Number of rows. Leave empty to use the number of rows in Data.', required: false }),+ columns: Property.Number({+ displayName: 'Columns',+ description: 'Number of columns. Leave empty to use the longest row in Data.',+ required: false,+ }),+ header_bold: Property.Checkbox({ displayName: 'Bold Header Row', description: 'Make the text of the first row bold.', required: false }),+ header_fill_color: slidesProps.colorProp({+ displayName: 'Header Fill Color',+ description: 'Optional hex background colour for the first row, e.g. #E8F0FE.',+ }),+ x: slidesProps.pointProp({ displayName: 'X (pt)', description: 'Distance from the left edge, in points. Set together with Y.', required: false }),+ y: slidesProps.pointProp({ displayName: 'Y (pt)', description: 'Distance from the top edge, in points. Set together with X.', required: false }),+ width: slidesProps.pointProp({ displayName: 'Width (pt)', description: 'Table width in points. Set together with Height.', required: false }),+ height: slidesProps.pointProp({ displayName: 'Height (pt)', description: 'Table height in points. Set together with Width.', required: false }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: propsValue.slide_number,+ slideObjectId: propsValue.slide_object_id,+ });+ const data = slidesElementRequests.readTableData(propsValue.data);+ const size = slidesElementRequests.resolveTableSize({+ rows: slidesRequests.toInteger({ value: propsValue.rows, label: 'Rows' }),+ columns: slidesRequests.toInteger({ value: propsValue.columns, label: 'Columns' }),+ data,+ });+ const box = slidesElements.readBox({ x: propsValue.x, y: propsValue.y, width: propsValue.width, height: propsValue.height, required: false });+ const headerFill = slidesElements.readColor({ value: propsValue.header_fill_color, label: 'Header Fill Color' });+ if (headerFill?.kind === 'none') {+ throw new Error('Header Fill Color must be a hex colour like #E8F0FE; leave it empty for no fill.');+ }+ const headerBold = slidesElements.readBoolean({ value: propsValue.header_bold, label: 'Bold Header Row' }) ?? false;+ const objectId = slidesIds.generateObjectId('table');+ const accessToken = await getAccessToken(context.auth);+ const action = 'create the table';+ const { objectId: slideObjectId, revisionId } = await slidesRequests+ .lookupSlide({ accessToken, presentationId, selector })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const { requests, filledCells } = slidesElementRequests.buildCreateTableRequests({+ objectId,+ slideObjectId,+ rows: size.rows,+ columns: size.columns,+ data: data ?? [],+ box,+ headerBold,+ headerFill: headerFill?.kind === 'rgb' ? headerFill.rgbColor : undefined,+ });+ await slidesElements.applyRequests({ accessToken, presentationId, requests, revisionId, action });+ return {+ presentationId,+ slideObjectId,+ tableObjectId: objectId,+ rows: size.rows,+ columns: size.columns,+ filledCells,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/delete-elements.ts b/packages/pieces/community/google-slides/src/lib/actions/delete-elements.tsnew file mode 100644index 00000000000..9075f9d0f19--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/delete-elements.ts@@ -0,0 +1,55 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { deleteElementsOutputSchema } from '../output-schemas';++export const deleteElements = createAction({+ auth: googleSlidesAuth,+ name: 'delete_elements',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Elements',+ description: 'Delete one or more elements (shapes, images, tables, groups…) from slides.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Permanently delete one or more page elements (shapes, text boxes, images, tables, videos, lines, groups) by object ID, all in one atomic change: if any ID is wrong nothing is deleted. Deleting a group deletes its children. Use Delete Slide to remove a whole slide and Set Element Text with Clear Text to only empty a box. Get IDs from List Slide Elements or Get Presentation Outline. Not idempotent: a repeat fails because the elements are gone.',+ idempotent: false,+ },+ outputSchema: deleteElementsOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ object_ids: Property.Array({+ displayName: 'Element Object IDs',+ description: 'Object IDs of the elements to delete, e.g. ["g2c8d1e5a7f_0_3"].',+ required: true,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const objectIds = slidesElements.readElementIds({ value: context.propsValue.object_ids, label: 'Element Object IDs' });+ const accessToken = await getAccessToken(context.auth);+ const action = 'delete the elements';+ const presentation = await slidesElements.fetchDeck({ accessToken, presentationId }).catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const located = objectIds.map((objectId) => slidesElements.locateElement({ presentation, objectId }));+ const listed = new Set(objectIds);+ const topLevel = located.filter((entry) => !entry.ancestorGroupIds.some((groupId) => listed.has(groupId)));+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: topLevel.map((entry) => ({ deleteObject: { objectId: entry.element.objectId } })),+ revisionId: presentation.revisionId,+ action,+ });+ return {+ presentationId,+ deletedObjectIds: objectIds,+ deletedCount: objectIds.length,+ slideObjectIds: Array.from(new Set(located.map((entry) => entry.slideObjectId))),+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/delete-slide.ts b/packages/pieces/community/google-slides/src/lib/actions/delete-slide.tsnew file mode 100644index 00000000000..69880248e7f--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/delete-slide.ts@@ -0,0 +1,59 @@+import { createAction } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { FIELD_MASKS, slidesRequests } from '../commons/requests';+import { deleteSlideOutputSchema } from '../output-schemas';++export const deleteSlide = createAction({+ auth: googleSlidesAuth,+ name: 'delete_slide',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Slide',+ description: 'Delete a slide from the presentation.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Delete one slide, chosen by slide number or slide object ID (only slides, never other elements). Use it to remove a slide from a deck; it can only be undone from the version history in Google Slides. Not idempotent: a repeat by object ID fails because the slide is gone, and a repeat by slide number deletes the next slide, so prefer the object ID.',+ idempotent: false,+ },+ outputSchema: deleteSlideOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const accessToken = await getAccessToken(context.auth);+ const action = 'delete the slide';+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.slideIds })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const slides = presentation.slides ?? [];+ const slide = slidesRequests.resolveSlide({ slides, selector });+ await slidesApi+ .batchUpdate({+ accessToken,+ presentationId,+ requests: [{ deleteObject: { objectId: slide.objectId } }],+ requiredRevisionId: presentation.revisionId,+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ return {+ presentationId,+ deletedSlideObjectId: slide.objectId,+ deletedSlideNumber: slide.index + 1,+ remainingSlideCount: slides.length - 1,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/delete-table-rows-or-columns.ts b/packages/pieces/community/google-slides/src/lib/actions/delete-table-rows-or-columns.tsnew file mode 100644index 00000000000..30032b12dc4--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/delete-table-rows-or-columns.ts@@ -0,0 +1,74 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesElementRequests, TABLE_DIMENSIONS } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { tableLinesOutputSchema } from '../output-schemas';++export const deleteTableRowsOrColumns = createAction({+ auth: googleSlidesAuth,+ name: 'delete_table_rows_or_columns',+ classification: 'DESTRUCTIVE',+ displayName: 'Delete Table Rows or Columns',+ description: 'Delete one or more neighbouring rows or columns from a table.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Delete Count neighbouring rows (Dimension ROW) or columns (COLUMN) of a table starting at Position (1-based), with their content. It refuses to delete every row or column; use Delete Elements to remove the whole table. Check the row/column numbers with List Slide Elements (tableCells) first. Not idempotent: a repeat deletes the next rows or columns.',+ idempotent: false,+ },+ outputSchema: tableLinesOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ table_object_id: slidesProps.elementIdProp({+ displayName: 'Table Object ID',+ description: 'Object ID of the table (from Create Table, List Slide Elements or Get Presentation Outline).',+ }),+ dimension: slidesProps.enumProp({ displayName: 'Dimension', description: 'ROW or COLUMN.', values: TABLE_DIMENSIONS, required: true }),+ position: Property.Number({ displayName: 'Position', description: 'First row/column to delete, starting at 1.', required: true }),+ count: Property.Number({ displayName: 'Count', description: 'How many neighbouring rows/columns to delete. Default 1.', required: false }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const tableObjectId = slidesElements.readElementId({ value: propsValue.table_object_id, label: 'Table Object ID' });+ const dimension = slidesElements.readEnum({ value: propsValue.dimension, label: 'Dimension', allowed: TABLE_DIMENSIONS });+ if (!slidesElementRequests.isTableDimension(dimension)) {+ throw new Error('Dimension is required: ROW or COLUMN.');+ }+ const position = slidesRequests.toInteger({ value: propsValue.position, label: 'Position' });+ if (position === undefined) {+ throw new Error('Position is required: the first row/column to delete, starting at 1.');+ }+ const count = slidesRequests.toInteger({ value: propsValue.count, label: 'Count' }) ?? 1;+ if (position < 1 || count < 1) {+ throw new Error(`Position and Count start at 1, got position ${position} and count ${count}.`);+ }+ const accessToken = await getAccessToken(context.auth);+ const action = `delete table ${dimension === 'ROW' ? 'rows' : 'columns'}`;+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId: tableObjectId, action });+ slidesElements.requireType({ located, types: ['TABLE'], purpose: 'this action needs a table' });+ const size = slidesElements.tableSize(located.element);+ const requests = slidesElementRequests.buildDeleteTableLinesRequests({+ tableObjectId,+ dimension,+ rows: size.rows,+ columns: size.columns,+ position,+ count,+ });+ await slidesElements.applyRequests({ accessToken, presentationId, requests, revisionId: located.revisionId, action });+ return {+ presentationId,+ slideObjectId: located.slideObjectId,+ tableObjectId,+ dimension,+ position,+ count,+ rows: dimension === 'ROW' ? size.rows - count : size.rows,+ columns: dimension === 'COLUMN' ? size.columns - count : size.columns,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/duplicate-slide.ts b/packages/pieces/community/google-slides/src/lib/actions/duplicate-slide.tsnew file mode 100644index 00000000000..aa4cb055f73--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/duplicate-slide.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { FIELD_MASKS, slidesRequests } from '../commons/requests';+import { duplicateSlideOutputSchema } from '../output-schemas';++export const duplicateSlide = createAction({+ auth: googleSlidesAuth,+ name: 'duplicate_slide',+ classification: 'WRITE',+ displayName: 'Duplicate Slide',+ description: 'Copy a slide within the same presentation.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Duplicate one slide (by number or object ID) inside the same presentation, with all its elements; the copy goes right after the original or at a chosen 1-based position. Use it to reuse a designed slide, then change the copy\'s text with Replace Text limited to the new slide ID. Not idempotent: each call adds another copy.',+ idempotent: false,+ },+ outputSchema: duplicateSlideOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ position: Property.Number({+ displayName: 'Position of the Copy',+ description: 'Where to put the copy, starting at 1. Leave empty to place it right after the original.',+ required: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const accessToken = await getAccessToken(context.auth);+ const action = 'duplicate the slide';+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.slideIds })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const slides = presentation.slides ?? [];+ const source = slidesRequests.resolveSlide({ slides, selector });+ const targetIndex = slidesRequests.readPosition({+ position: context.propsValue.position,+ maxPosition: slides.length + 1,+ });+ const newObjectId = slidesIds.generateObjectId('slide');+ const { requests, finalIndex } = slidesRequests.buildDuplicateRequests({+ sourceObjectId: source.objectId,+ sourceIndex: source.index,+ newObjectId,+ targetIndex,+ });+ await slidesApi+ .batchUpdate({ accessToken, presentationId, requests, requiredRevisionId: presentation.revisionId })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ return {+ presentationId,+ sourceSlideObjectId: source.objectId,+ slideObjectId: newObjectId,+ slideNumber: finalIndex + 1,+ slideUrl: slidesApi.slideUrl({ presentationId, slideObjectId: newObjectId }),+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/export-presentation.ts b/packages/pieces/community/google-slides/src/lib/actions/export-presentation.tsnew file mode 100644index 00000000000..c99d4b7d537--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/export-presentation.ts@@ -0,0 +1,94 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { drive as googleDrive } from '@googleapis/drive';+import { createGoogleClient, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { EXPORT_FORMATS, slidesRequests } from '../commons/requests';+import { exportPresentationOutputSchema } from '../output-schemas';++export const exportPresentation = createAction({+ auth: googleSlidesAuth,+ name: 'export_presentation',+ classification: 'READ',+ displayName: 'Export Presentation',+ description: 'Download a presentation as a PDF, PowerPoint, OpenDocument or plain-text file.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Export a Google Slides presentation through Google Drive as a PDF, PowerPoint (.pptx), OpenDocument (.odp) or plain-text file and return it as a file for later steps (email attachment, upload). Use it to share or archive a deck outside Google; to read slide text for reasoning prefer Get Presentation Outline. Drive refuses exports above 10 MB. Read-only and idempotent: repeating the call exports the same content.',+ idempotent: true,+ },+ outputSchema: exportPresentationOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ format: Property.StaticDropdown({+ displayName: 'Format',+ description: 'File format of the export.',+ required: true,+ defaultValue: 'pdf',+ options: {+ options: [+ { label: 'PDF (.pdf)', value: 'pdf' },+ { label: 'PowerPoint (.pptx)', value: 'pptx' },+ { label: 'OpenDocument (.odp)', value: 'odp' },+ { label: 'Plain text (.txt)', value: 'txt' },+ ],+ },+ }),+ file_name: Property.ShortText({+ displayName: 'File Name',+ description: 'Name of the exported file without extension. Leave empty to use the presentation name.',+ required: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const format = EXPORT_FORMATS[context.propsValue.format ?? 'pdf'];+ if (!format) {+ throw new Error(`Format must be one of: ${Object.keys(EXPORT_FORMATS).join(', ')}.`);+ }+ const drive = googleDrive({ version: 'v3', auth: await createGoogleClient(context.auth) });+ const action = 'export the presentation';+ const requestedName = context.propsValue.file_name?.trim();+ const baseName =+ requestedName ||+ (await drive.files+ .get({ fileId: presentationId, fields: 'name', supportsAllDrives: true })+ .then((meta) => meta.data.name ?? presentationId)+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ }));+ const response = await drive.files+ .export({ fileId: presentationId, mimeType: format.mimeType }, { responseType: 'arraybuffer' })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const data = toBuffer(response.data);+ const fileName = slidesRequests.exportFileName({ baseName, extension: format.extension });+ const file = await context.files.write({ fileName, data });+ return {+ presentationId,+ fileName,+ mimeType: format.mimeType,+ sizeBytes: data.length,+ file,+ };+ },+});++function toBuffer(data: unknown): Buffer {+ if (Buffer.isBuffer(data)) {+ return data;+ }+ if (data instanceof ArrayBuffer) {+ return Buffer.from(data);+ }+ if (ArrayBuffer.isView(data)) {+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength);+ }+ if (typeof data === 'string') {+ return Buffer.from(data, 'utf8');+ }+ throw new Error('Google Drive returned the export in an unexpected format, so no file was saved.');+}diff --git a/packages/pieces/community/google-slides/src/lib/actions/find-presentations.ts b/packages/pieces/community/google-slides/src/lib/actions/find-presentations.tsnew file mode 100644index 00000000000..5f6e61e0409--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/find-presentations.ts@@ -0,0 +1,109 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { drive as googleDrive } from '@googleapis/drive';+import { createGoogleClient, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { findPresentationsOutputSchema } from '../output-schemas';++const MAX_LIMIT = 1000;++export const findPresentations = createAction({+ auth: googleSlidesAuth,+ name: 'find_presentations',+ classification: 'SEARCH',+ displayName: 'Find Presentations',+ description: 'Search Google Drive for presentations by name and/or folder.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Search Google Drive for Google Slides presentations whose name contains some text and/or that sit in a given folder, most recently modified first. Use it to turn a deck name into a presentation ID before calling the other Slides actions. Returns at most Limit results; when hasMore is true pass nextPageToken as Page Token to continue. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: findPresentationsOutputSchema,+ props: {+ name_contains: Property.ShortText({+ displayName: 'Name Contains',+ description: 'Return presentations whose name contains this text (case-insensitive). Leave empty to list all.',+ required: false,+ }),+ folder_id: slidesProps.folderIdProp(+ 'Only presentations directly in this Drive folder: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to search all of Drive.'+ ),+ limit: Property.Number({+ displayName: 'Limit',+ description: `Maximum number of presentations to return (1-${MAX_LIMIT}). Default 50.`,+ required: false,+ defaultValue: 50,+ }),+ page_token: Property.ShortText({+ displayName: 'Page Token',+ description: 'The nextPageToken of a previous call, to get the next results. Leave empty for the first page.',+ required: false,+ }),+ },+ async run(context) {+ const nameContains = context.propsValue.name_contains?.trim() || undefined;+ const folderId = slidesIds.parseFolderId(context.propsValue.folder_id);+ const rawLimit = context.propsValue.limit ?? 50;+ const limit = Number(rawLimit);+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {+ throw new Error(`Limit must be a whole number between 1 and ${MAX_LIMIT}, got "${String(rawLimit)}".`);+ }+ const drive = googleDrive({ version: 'v3', auth: await createGoogleClient(context.auth) });+ const q = slidesRequests.buildFindQuery({ nameContains, folderId });++ const presentations: PresentationListItem[] = [];+ let pageToken: string | undefined = context.propsValue.page_token?.trim() || undefined;+ do {+ const response = await drive.files+ .list({+ q,+ pageSize: limit - presentations.length,+ pageToken,+ orderBy: 'modifiedTime desc',+ supportsAllDrives: true,+ includeItemsFromAllDrives: true,+ corpora: 'allDrives',+ fields:+ 'nextPageToken, files(id, name, webViewLink, createdTime, modifiedTime, owners(displayName, emailAddress), parents)',+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'search for presentations' });+ });+ presentations.push(+ ...(response.data.files ?? []).map((file) => ({+ id: file.id ?? null,+ name: file.name ?? null,+ webViewLink: file.webViewLink ?? null,+ createdTime: file.createdTime ?? null,+ modifiedTime: file.modifiedTime ?? null,+ ownerName: file.owners?.[0]?.displayName ?? null,+ ownerEmail: file.owners?.[0]?.emailAddress ?? null,+ folderId: file.parents?.[0] ?? null,+ }))+ );+ pageToken = response.data.nextPageToken ?? undefined;+ } while (pageToken && presentations.length < limit);++ return {+ presentations,+ count: presentations.length,+ hasMore: pageToken !== undefined,+ nextPageToken: pageToken ?? null,+ };+ },+});+++type PresentationListItem = {+ id: string | null;+ name: string | null;+ webViewLink: string | null;+ createdTime: string | null;+ modifiedTime: string | null;+ ownerName: string | null;+ ownerEmail: string | null;+ folderId: string | null;+};diff --git a/packages/pieces/community/google-slides/src/lib/actions/generate-from-template.ts b/packages/pieces/community/google-slides/src/lib/actions/generate-from-template.tsindex a1f699e1ad8..a722ea68c80 100644--- a/packages/pieces/community/google-slides/src/lib/actions/generate-from-template.ts+++ b/packages/pieces/community/google-slides/src/lib/actions/generate-from-template.ts@@ -1,165 +1,128 @@-import { createGoogleClient, getAccessToken, googleSlidesAuth, GoogleSlidesAuthValue } from '../auth';-import { createAction, DynamicPropsValue, Property } from "@activepieces/pieces-framework";-import { getSlide, PageElement, batchUpdate, TableCell, TextElement } from '../commons/common';+import { createAction, DynamicPropsValue, Property } from '@activepieces/pieces-framework';import { drive as googleDrive } from '@googleapis/drive';--function extractPlaceholders(content: string, fields: Record<string, any>, placeholder_format: string) {- const regex = placeholder_format === '[[]]'- ? /\[\[([^\]]+)\]\]/g- : /\{\{([^}]+)\}\}/g;-- const matches = content.match(regex);- if (matches) {- matches.forEach((match: string) => {- const matchValue = placeholder_format === '[[]]'- ? match.replace(/[[\]]/g, '')- : match.replace(/[{}]/g, '');-- const varName = matchValue.trim();- fields[matchValue] = Property.ShortText({- displayName: varName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),- description: `Value for "${placeholder_format === '[[]]' ? `[[${varName}]]` : `{{${varName}}}`}"`,- required: false,- });- });- }-}+import { createGoogleClient, getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesText } from '../commons/presentation-text';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { generateFromTemplateOutputSchema } from '../output-schemas';export const generateFromTemplate = createAction({- name: 'generate_from_template',- classification: 'WRITE',- displayName: 'Generate from template',- description: 'Generate a new slide from a template',- audience: 'both',- aiMetadata: { description: 'Create a new Google Slides presentation by copying a template presentation, then substituting its placeholder tokens with supplied values. Use this for mail-merge style document generation from a reusable deck. The template\'s placeholder syntax must be selected (curly braces {{}} or square brackets [[]]); placeholders are discovered from the template\'s text and table cells, and matching is case-sensitive. Not idempotent: each call copies the template into a brand-new presentation file.', idempotent: false },- auth: googleSlidesAuth,- props: {- template_presentation_id: Property.ShortText({- displayName: 'Template presentation ID',- description: 'The ID of the templated presentation',- required: true,- }),- placeholder_format: Property.StaticDropdown({- displayName: 'Placeholder Format',- description: 'Choose the format of placeholders in your template',- required: true,- defaultValue: '{{}}',- options: {- disabled: false,- options: [- { label: 'Curly Braces {{}}', value: '{{}}' },- { label: 'Square Brackets [[]]', value: '[[]]' }- ],- },- }),- table_data: Property.DynamicProperties({- auth: googleSlidesAuth,- displayName: 'Table Data',- required: true,- refreshers: ['template_presentation_id', 'placeholder_format'],- props: async ({auth, template_presentation_id, placeholder_format}) => {- if (!template_presentation_id || !auth)- return {};-- const accessToken = await getAccessToken(auth as GoogleSlidesAuthValue);- const presentation = await getSlide(accessToken, template_presentation_id as unknown as string);- if (!presentation)- return {}+ name: 'generate_from_template',+ classification: 'WRITE',+ displayName: 'Generate from template',+ description: 'Generate a new slide from a template',+ audience: 'both',+ aiMetadata: {+ description:+ "Create a new Google Slides presentation by copying a template presentation, then substituting its placeholder tokens with supplied values. Use this for mail-merge style document generation from a reusable deck; to copy without replacing text use Copy Presentation. The template's placeholder syntax must be selected (curly braces {{}} or square brackets [[]]); placeholders are discovered in slide text, grouped shapes, table cells and speaker notes, and matching is case-sensitive. The Presentation Title value also fills a {{title}} placeholder. A service account needs a Shared Drive folder to write the copy into. Not idempotent: each call copies the template into a brand-new presentation file.",+ idempotent: false,+ },+ auth: googleSlidesAuth,+ outputSchema: generateFromTemplateOutputSchema,+ props: {+ template_presentation_id: Property.ShortText({+ displayName: 'Template presentation ID',+ description: 'The template presentation ID (between /d/ and /edit in its URL), or the full URL.',+ required: true,+ }),+ placeholder_format: Property.StaticDropdown({+ displayName: 'Placeholder Format',+ description: 'Choose the format of placeholders in your template',+ required: true,+ defaultValue: '{{}}',+ options: {+ disabled: false,+ options: [+ { label: 'Curly Braces {{}}', value: '{{}}' },+ { label: 'Square Brackets [[]]', value: '[[]]' },+ ],+ },+ }),+ table_data: Property.DynamicProperties({+ auth: googleSlidesAuth,+ displayName: 'Table Data',+ required: true,+ refreshers: ['template_presentation_id', 'placeholder_format'],+ props: async ({ auth, template_presentation_id, placeholder_format }) => {+ if (!template_presentation_id || !auth) return {};- const fields = {- title: Property.ShortText({- displayName: 'Presentation Title',- description: 'Title of the new presentation',- defaultValue: `Copy of: ${presentation.title}`,- required: true,- })- } as DynamicPropsValue;-- presentation.slides?.forEach(slide => {- slide.pageElements?.forEach((element: PageElement) => {- if (element.shape?.text?.textElements) {- element.shape.text.textElements.forEach(textElement => {- const content = textElement?.textRun?.content;- if (content) {- extractPlaceholders(content, fields, placeholder_format as unknown as string);- }- });- }-- if (element.table) {- element.table.tableRows?.forEach(row => {- row.tableCells?.forEach((cell: TableCell) => {- if (cell.text?.textElements) {- cell.text.textElements.forEach((textElement: TextElement) => {- const content = textElement?.textRun?.content;- if (content) {- extractPlaceholders(content, fields, placeholder_format as unknown as string);- }- });- }- });- });- }- });- });-- return fields;- }- })- },- async run(context) {- const { template_presentation_id, placeholder_format, table_data } = context.propsValue;-- try {- const authClient = await createGoogleClient(context.auth);+ const accessToken = await getAccessToken(auth);+ const presentation = await slidesApi.getPresentation({+ accessToken,+ presentationId: slidesIds.parsePresentationId(template_presentation_id),+ });+ if (!presentation) return {};- const drive = googleDrive({ version: 'v3', auth: authClient });-- const copyResponse = await drive.files.copy({- fileId: template_presentation_id as string,- requestBody: {- name: table_data["title"] || "New Presentation"- },- supportsAllDrives: true- });-- const newPresentationId = copyResponse.data.id;- if (!newPresentationId)- return+ const format = String(placeholder_format) === '[[]]' ? '[[]]' : '{{}}';+ const placeholderFields = slidesText+ .discoverPlaceholders({ presentation, format })+ .filter((name) => name !== 'title')+ .map((name): [string, DynamicPropsValue[string]] => [+ name,+ Property.ShortText({+ displayName: name.trim().replace(/_/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase()),+ description: `Value for "${slidesRequests.toPlaceholder({ name: name.trim(), format })}"`,+ required: false,+ }),+ ]);+ return {+ title: Property.ShortText({+ displayName: 'Presentation Title',+ description: `Title of the new presentation. It also fills a ${slidesRequests.toPlaceholder({ name: 'title', format })} placeholder if the template has one.`,+ defaultValue: `Copy of: ${presentation.title}`,+ required: true,+ }),+ ...Object.fromEntries(placeholderFields),+ };+ },+ }),+ folder_id: slidesProps.folderIdProp(+ 'Optional Drive folder for the new presentation: its ID or URL (https://drive.google.com/drive/folders/<id>). Leave empty to use the default location. A service account needs a folder in a Shared Drive here.'+ ),+ },+ async run(context) {+ const { placeholder_format, table_data } = context.propsValue;+ const templateId = slidesIds.parsePresentationId(context.propsValue.template_presentation_id);+ const folderId = slidesIds.parseFolderId(context.propsValue.folder_id);+ const tableData: Record<string, unknown> = table_data ?? {};+ const title = typeof tableData['title'] === 'string' ? tableData['title'] : '';- const requests = Object.entries(table_data)- .map(([key, value]): { replaceAllText: unknown } => {- const placeholder = placeholder_format === '[[]]'- ? `[[${key}]]`- : `{{${key}}}`;+ const drive = googleDrive({ version: 'v3', auth: await createGoogleClient(context.auth) });+ const copyResponse = await drive.files+ .copy({+ fileId: templateId,+ requestBody: {+ name: title || 'New Presentation',+ ...(folderId ? { parents: [folderId] } : {}),+ },+ supportsAllDrives: true,+ fields: 'id',+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'copy the template' });+ });+ const newPresentationId = copyResponse.data.id;+ if (!newPresentationId) {+ throw new Error('Google Drive copied the template but returned no file ID, so no placeholders were replaced.');+ }- return {- replaceAllText: {- containsText: {- text: placeholder,- matchCase: true- },- replaceText: value as string- }- };- });--- if (requests.length > 0) {- await batchUpdate(- await getAccessToken(context.auth),- newPresentationId,- requests- );- }-- return {- presentationId: newPresentationId,- presentationUrl: `https://docs.google.com/presentation/d/${newPresentationId}/edit`- };- } catch (error) {- console.error('Error creating presentation:', error);- throw error;- }+ const requests = slidesRequests.buildTemplateRequests({ tableData, format: placeholder_format });+ if (requests.length > 0) {+ await slidesApi+ .batchUpdate({ accessToken: await getAccessToken(context.auth), presentationId: newPresentationId, requests })+ .catch((error: unknown) => {+ const reason = slidesApi.googleApiError({ error, action: 'replace the placeholders' }).message;+ throw new Error(+ `${reason} The copy was created (${slidesApi.presentationUrl(newPresentationId)}) but its placeholders were not replaced.`+ );+ });}++ return {+ presentationId: newPresentationId,+ presentationUrl: slidesApi.presentationUrl(newPresentationId),+ };+ },});diff --git a/packages/pieces/community/google-slides/src/lib/actions/get-presentation-outline.ts b/packages/pieces/community/google-slides/src/lib/actions/get-presentation-outline.tsnew file mode 100644index 00000000000..43be57eb0dc--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/get-presentation-outline.ts@@ -0,0 +1,44 @@+import { createAction } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesText } from '../commons/presentation-text';+import { slidesProps } from '../commons/props';+import { FIELD_MASKS } from '../commons/requests';+import { getPresentationOutlineOutputSchema } from '../output-schemas';++export const getPresentationOutline = createAction({+ auth: googleSlidesAuth,+ name: 'get_presentation_outline',+ classification: 'READ',+ displayName: 'Get Presentation Outline',+ description: "Get each slide's number, object ID, title, text and speaker notes.",+ audience: 'both',+ aiMetadata: {+ description:+ 'Read a compact outline of a Google Slides presentation: for every slide its number, object ID, layout, title, all text (including grouped shapes and table cells), speaker notes, and the object IDs of its elements. Pick this to summarise a deck or to find the slide and element object IDs other Slides actions need; use List Slide Elements for positions and sizes, and Get Presentation only when you need raw element detail. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: getPresentationOutlineOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const accessToken = await getAccessToken(context.auth);+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.outline })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'read the presentation outline' });+ });+ const outline = slidesText.buildOutline(presentation);+ return {+ presentationId: outline.presentationId,+ title: outline.title,+ presentationUrl: slidesApi.presentationUrl(outline.presentationId),+ revisionId: outline.revisionId,+ slideCount: outline.slideCount,+ slides: outline.slides,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/get-presentation.ts b/packages/pieces/community/google-slides/src/lib/actions/get-presentation.tsindex 5200fc3b53a..0fcd80645d9 100644--- a/packages/pieces/community/google-slides/src/lib/actions/get-presentation.ts+++ b/packages/pieces/community/google-slides/src/lib/actions/get-presentation.ts@@ -1,25 +1,43 @@+import { createAction, Property } from '@activepieces/pieces-framework';import { getAccessToken, googleSlidesAuth } from '../auth';-import { createAction, Property } from "@activepieces/pieces-framework";-import { getSlide } from "../commons/common";+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { getPresentationOutputSchema } from '../output-schemas';export const getPresentation = createAction({- name: 'get_presentation',- classification: 'READ',- displayName: 'Get Presentation',- description: 'Get all slides from a presentation',- audience: 'both',- aiMetadata: { description: 'Fetch a Google Slides presentation by its presentation ID, returning its title and the full set of slides and their page elements. Use this to read or inspect a presentation\'s contents before acting on it. Read-only and idempotent. Requires the presentation ID (the string between /d/ and /edit in the URL).', idempotent: true },- auth: googleSlidesAuth,- props: {- presentation_id: Property.ShortText({- displayName: 'Presentation ID',- description: 'The ID of the presentation',- required: true,- })- },- async run(context) {- const { presentation_id } = context.propsValue;- const accessToken = await getAccessToken(context.auth);- return await getSlide(accessToken, presentation_id);- },-});\ No newline at end of file+ name: 'get_presentation',+ classification: 'READ',+ displayName: 'Get Presentation',+ description: 'Get all slides from a presentation',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetch the raw Google Slides presentation resource (title, page size, slides with every page element, layouts, masters). Use it when you need element-level detail such as transforms, styles or table structure; for slide text, speaker notes and object IDs prefer Get Presentation Outline, which is far smaller. An optional Google field mask (e.g. "presentationId,title,slides(objectId)") trims the response. Accepts the presentation ID or URL. Read-only and idempotent.',+ idempotent: true,+ },+ auth: googleSlidesAuth,+ outputSchema: getPresentationOutputSchema,+ props: {+ presentation_id: Property.ShortText({+ displayName: 'Presentation ID',+ description: 'The presentation ID (between /d/ and /edit in its URL), or the full URL.',+ required: true,+ }),+ fields: Property.ShortText({+ displayName: 'Fields',+ description:+ 'Optional Google field mask to return only part of the presentation, e.g. presentationId,title,slides(objectId). Leave empty for the full presentation.',+ required: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const fields = context.propsValue.fields?.trim() || undefined;+ const accessToken = await getAccessToken(context.auth);+ try {+ return await slidesApi.getPresentation({ accessToken, presentationId, fields });+ } catch (error) {+ throw slidesApi.googleApiError({ error, action: 'get the presentation' });+ }+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/get-slide-thumbnail.ts b/packages/pieces/community/google-slides/src/lib/actions/get-slide-thumbnail.tsnew file mode 100644index 00000000000..dea519d5bae--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/get-slide-thumbnail.ts@@ -0,0 +1,109 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { SlideSelector, slidesRequests } from '../commons/requests';+import { getSlideThumbnailOutputSchema } from '../output-schemas';++export const getSlideThumbnail = createAction({+ auth: googleSlidesAuth,+ name: 'get_slide_thumbnail',+ classification: 'READ',+ displayName: 'Get Slide Thumbnail',+ description: 'Get a PNG image of a slide, as a link and optionally as a file.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Render one slide as a PNG thumbnail (LARGE 1600 px, MEDIUM 800 px or SMALL 200 px wide), chosen by slide number or object ID, and return its image link; turn on Save as File to also get a file that does not expire. The link expires after about 30 minutes, so save the file when a later step needs the image. Google counts this as an expensive read for quota. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: getSlideThumbnailOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ size: Property.StaticDropdown({+ displayName: 'Size',+ description: 'Width of the image.',+ required: false,+ defaultValue: 'LARGE',+ options: {+ options: [+ { label: 'Large (1600 px wide)', value: 'LARGE' },+ { label: 'Medium (800 px wide)', value: 'MEDIUM' },+ { label: 'Small (200 px wide)', value: 'SMALL' },+ ],+ },+ }),+ save_as_file: Property.Checkbox({+ displayName: 'Save as File',+ description: 'Also download the image and return it as a file (the image link expires after about 30 minutes).',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const size = context.propsValue.size ?? 'LARGE';+ if (!THUMBNAIL_SIZES.includes(size)) {+ throw new Error(`Size must be one of ${THUMBNAIL_SIZES.join(', ')}.`);+ }+ const accessToken = await getAccessToken(context.auth);+ const { pageObjectId, thumbnail } = await fetchThumbnail({ accessToken, presentationId, selector, size }).catch(+ (error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'get the slide thumbnail' });+ }+ );+ const contentUrl = thumbnail.contentUrl;+ if (!contentUrl) {+ throw new Error('Google returned no thumbnail image link for this slide.');+ }+ const file = context.propsValue.save_as_file+ ? await context.files.write({+ fileName: `slide-${pageObjectId}.png`,+ data: await downloadImage(contentUrl),+ })+ : null;+ return {+ presentationId,+ slideObjectId: pageObjectId,+ width: thumbnail.width ?? null,+ height: thumbnail.height ?? null,+ contentUrl,+ file,+ };+ },+});++async function fetchThumbnail({+ accessToken,+ presentationId,+ selector,+ size,+}: {+ accessToken: string;+ presentationId: string;+ selector: SlideSelector;+ size: string;+}) {+ const { objectId: pageObjectId } = await slidesRequests.lookupSlide({ accessToken, presentationId, selector });+ const thumbnail = await slidesApi.getPageThumbnail({ accessToken, presentationId, pageObjectId, thumbnailSize: size });+ return { pageObjectId, thumbnail };+}++async function downloadImage(contentUrl: string): Promise<Buffer> {+ const response = await httpClient+ .sendRequest<ArrayBuffer>({ method: HttpMethod.GET, url: contentUrl, responseType: 'arraybuffer' })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'download the thumbnail image' });+ });+ return Buffer.from(response.body);+}++const THUMBNAIL_SIZES = ['LARGE', 'MEDIUM', 'SMALL'];diff --git a/packages/pieces/community/google-slides/src/lib/actions/get-slide.ts b/packages/pieces/community/google-slides/src/lib/actions/get-slide.tsnew file mode 100644index 00000000000..b9a05839520--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/get-slide.ts@@ -0,0 +1,41 @@+import { createAction } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { getSlideOutputSchema } from '../output-schemas';++export const getSlide = createAction({+ auth: googleSlidesAuth,+ name: 'get_slide',+ classification: 'READ',+ displayName: 'Get Slide',+ description: 'Get one slide with all of its elements.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Fetch the raw Page resource of one slide (its page elements with sizes, transforms, text and styles, plus slide properties), chosen by slide number or slide object ID. Use it to inspect one slide in detail without loading the whole deck; for text only use Get Presentation Outline, and for positions and sizes in points use List Slide Elements. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: getSlideOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const accessToken = await getAccessToken(context.auth);+ try {+ const { objectId: pageObjectId } = await slidesRequests.lookupSlide({ accessToken, presentationId, selector });+ return await slidesApi.getPage({ accessToken, presentationId, pageObjectId });+ } catch (error) {+ throw slidesApi.googleApiError({ error, action: 'get the slide' });+ }+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/insert-image.ts b/packages/pieces/community/google-slides/src/lib/actions/insert-image.tsnew file mode 100644index 00000000000..327ac5af813--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/insert-image.ts@@ -0,0 +1,81 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { insertImageOutputSchema } from '../output-schemas';++export const insertImage = createAction({+ auth: googleSlidesAuth,+ name: 'insert_image',+ classification: 'WRITE',+ displayName: 'Insert Image',+ description: 'Add an image from a URL to a slide.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Place an image from a public URL on one slide (by number or object ID), optionally at an X/Y position and Width/Height in points (a standard 16:9 slide is 720 x 405 pt; the aspect ratio is kept). Use it to add a picture to a slide; to swap {{placeholder}} boxes for images use Replace Shapes with Image. The URL must be public, PNG/JPEG/GIF, under 50 MB. Not idempotent: each call adds another image.',+ idempotent: false,+ },+ outputSchema: insertImageOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ image_url: Property.ShortText({+ displayName: 'Image URL',+ description: 'Public link to a PNG, JPEG or GIF image (under 50 MB), e.g. https://example.com/chart.png.',+ required: true,+ }),+ x: Property.Number({+ displayName: 'X (pt)',+ description: 'Distance from the left edge of the slide, in points. Set together with Y.',+ required: false,+ }),+ y: Property.Number({+ displayName: 'Y (pt)',+ description: 'Distance from the top edge of the slide, in points. Set together with X.',+ required: false,+ }),+ width: Property.Number({+ displayName: 'Width (pt)',+ description: "Width of the image box, in points. Set together with Height. Leave both empty for the image's own size.",+ required: false,+ }),+ height: Property.Number({+ displayName: 'Height (pt)',+ description: 'Height of the image box, in points. Set together with Width.',+ required: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const url = slidesIds.validateImageUrl(context.propsValue.image_url);+ const { x, y, width, height } = context.propsValue;+ const geometry = slidesRequests.readImageGeometry({ x, y, width, height });+ const imageObjectId = slidesIds.generateObjectId('image');+ const accessToken = await getAccessToken(context.auth);+ const action = 'insert the image';+ const { objectId: slideObjectId, revisionId } = await slidesRequests+ .lookupSlide({ accessToken, presentationId, selector })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ await slidesApi+ .batchUpdate({+ accessToken,+ presentationId,+ requests: [slidesRequests.buildCreateImageRequest({ objectId: imageObjectId, slideObjectId, url, geometry })],+ requiredRevisionId: revisionId,+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ return { presentationId, slideObjectId, imageObjectId };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/insert-table-rows-or-columns.ts b/packages/pieces/community/google-slides/src/lib/actions/insert-table-rows-or-columns.tsnew file mode 100644index 00000000000..2874d36d014--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/insert-table-rows-or-columns.ts@@ -0,0 +1,93 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesElementRequests, TABLE_DIMENSIONS } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { tableLinesOutputSchema } from '../output-schemas';++export const insertTableRowsOrColumns = createAction({+ auth: googleSlidesAuth,+ name: 'insert_table_rows_or_columns',+ classification: 'WRITE',+ displayName: 'Insert Table Rows or Columns',+ description: 'Add rows or columns to a table, optionally filling one new row or column.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Add 1-20 empty rows (Dimension ROW) or columns (COLUMN) to an existing table so that the first new one sits at Position (1-based; leave empty to add at the end), and optionally fill a single new row/column from Values in the same call. Use it to append a data row ("add EMEA, 12, 15"); use Set Element Text to change existing cells. The table objectId comes from Create Table or List Slide Elements. Not idempotent: each call adds more rows or columns.',+ idempotent: false,+ },+ outputSchema: tableLinesOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ table_object_id: slidesProps.elementIdProp({+ displayName: 'Table Object ID',+ description: 'Object ID of the table (from Create Table, List Slide Elements or Get Presentation Outline).',+ }),+ dimension: slidesProps.enumProp({ displayName: 'Dimension', description: 'ROW or COLUMN.', values: TABLE_DIMENSIONS, required: true }),+ position: Property.Number({+ displayName: 'Position',+ description: 'Where the first new row/column goes, starting at 1 (1 = before the first). Leave empty to add at the end.',+ required: false,+ }),+ count: Property.Number({ displayName: 'Count', description: 'How many to add, 1-20. Default 1.', required: false }),+ values: Property.Array({+ displayName: 'Values',+ description: 'Optional cell texts for the new row (left to right) or column (top to bottom). Only with Count 1.',+ required: false,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const tableObjectId = slidesElements.readElementId({ value: propsValue.table_object_id, label: 'Table Object ID' });+ const dimension = slidesElements.readEnum({ value: propsValue.dimension, label: 'Dimension', allowed: TABLE_DIMENSIONS });+ if (!slidesElementRequests.isTableDimension(dimension)) {+ throw new Error('Dimension is required: ROW or COLUMN.');+ }+ const position = slidesRequests.toInteger({ value: propsValue.position, label: 'Position' });+ const count = slidesRequests.toInteger({ value: propsValue.count, label: 'Count' }) ?? 1;+ const values = readValues(propsValue.values);+ if (count < 1 || count > 20) {+ throw new Error(`Count must be between 1 and 20 (Google's limit per request), got ${count}.`);+ }+ if (values && count !== 1) {+ throw new Error('Values fill one new row or column: set Count to 1, or leave Values empty.');+ }+ const accessToken = await getAccessToken(context.auth);+ const action = `insert table ${dimension === 'ROW' ? 'rows' : 'columns'}`;+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId: tableObjectId, action });+ slidesElements.requireType({ located, types: ['TABLE'], purpose: 'this action needs a table' });+ const size = slidesElements.tableSize(located.element);+ const { requests, insertedAt } = slidesElementRequests.buildInsertTableLinesRequests({+ tableObjectId,+ dimension,+ rows: size.rows,+ columns: size.columns,+ position,+ count,+ values,+ });+ await slidesElements.applyRequests({ accessToken, presentationId, requests, revisionId: located.revisionId, action });+ return {+ presentationId,+ slideObjectId: located.slideObjectId,+ tableObjectId,+ dimension,+ position: insertedAt,+ count,+ rows: dimension === 'ROW' ? size.rows + count : size.rows,+ columns: dimension === 'COLUMN' ? size.columns + count : size.columns,+ };+ },+});++function readValues(value: unknown): string[] | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const items = Array.isArray(value) ? value : [value];+ return items.length === 0 ? undefined : items.map((item) => (item === null || item === undefined ? '' : String(item)));+}diff --git a/packages/pieces/community/google-slides/src/lib/actions/insert-text.ts b/packages/pieces/community/google-slides/src/lib/actions/insert-text.tsnew file mode 100644index 00000000000..1d832ffb7b9--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/insert-text.ts@@ -0,0 +1,64 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { insertTextOutputSchema } from '../output-schemas';++export const insertText = createAction({+ auth: googleSlidesAuth,+ name: 'insert_text',+ classification: 'WRITE',+ displayName: 'Insert Text',+ description: 'Insert text into a shape, text box or table cell (appends by default).',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Insert text into one shape, text box, placeholder or table cell (set Row and Column for a cell), at the end by default or at a 0-based character index. Use it to add to existing text; to replace the whole text use Set Element Text, and to change words across the deck use Replace Text. The element objectId comes from List Slide Elements, Get Presentation Outline or Create Shape. Not idempotent: each call inserts the text again.',+ idempotent: false,+ },+ outputSchema: insertTextOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ object_id: slidesProps.textElementIdProp(),+ row: slidesProps.cellRowProp(),+ column: slidesProps.cellColumnProp(),+ text: Property.LongText({+ displayName: 'Text',+ description: 'The text to insert. Start it with \\n to begin a new paragraph after the existing text.',+ required: true,+ }),+ insertion_index: Property.Number({+ displayName: 'Insertion Index',+ description: 'Optional 0-based character position (0 = start). Leave empty to append at the end.',+ required: false,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const objectId = slidesElements.readElementId({ value: propsValue.object_id, label: 'Element Object ID' });+ const text = slidesElements.readText(propsValue.text) ?? '';+ const insertionIndex = slidesRequests.toInteger({ value: propsValue.insertion_index, label: 'Insertion Index' });+ if (text === '') {+ throw new Error('Text is empty. Give the text to insert.');+ }+ const accessToken = await getAccessToken(context.auth);+ const action = 'insert the text';+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId, action });+ const target = slidesElements.resolveTextTarget({ located, row: propsValue.row, column: propsValue.column });+ const { request, insertedAt, newText } = slidesElementRequests.buildInsertTextRequest({ target, text, insertionIndex });+ await slidesElements.applyRequests({ accessToken, presentationId, requests: [request], revisionId: located.revisionId, action });+ return {+ presentationId,+ slideObjectId: located.slideObjectId,+ objectId,+ row: target.cellLocation ? target.cellLocation.rowIndex + 1 : null,+ column: target.cellLocation ? target.cellLocation.columnIndex + 1 : null,+ insertedAt,+ text: newText,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/insert-video.ts b/packages/pieces/community/google-slides/src/lib/actions/insert-video.tsnew file mode 100644index 00000000000..8a373ade126--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/insert-video.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesElementRequests } from '../commons/element-requests';+import { slidesElements, VIDEO_SOURCES } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { insertVideoOutputSchema } from '../output-schemas';++export const insertVideo = createAction({+ auth: googleSlidesAuth,+ name: 'insert_video',+ classification: 'WRITE',+ displayName: 'Insert Video',+ description: 'Embed a YouTube or Google Drive video on a slide.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Embed a YouTube video or a Google Drive video file on one slide, from its URL (youtube.com/watch?v=…, youtu.be/…, drive.google.com/file/d/…) or its ID, optionally at X/Y with Width/Height in points. A Drive video must be viewable by the connected account. Not idempotent: each call adds another video.',+ idempotent: false,+ },+ outputSchema: insertVideoOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ video: Property.ShortText({+ displayName: 'Video',+ description: 'YouTube or Google Drive video URL, or the video ID.',+ required: true,+ }),+ source: slidesProps.enumProp({+ displayName: 'Source',+ description: 'Only needed for a bare Drive file ID: DRIVE. YouTube IDs and URLs are detected.',+ values: VIDEO_SOURCES,+ }),+ x: slidesProps.pointProp({ displayName: 'X (pt)', description: 'Distance from the left edge, in points. Set together with Y.', required: false }),+ y: slidesProps.pointProp({ displayName: 'Y (pt)', description: 'Distance from the top edge, in points. Set together with X.', required: false }),+ width: slidesProps.pointProp({ displayName: 'Width (pt)', description: 'Width in points. Set together with Height.', required: false }),+ height: slidesProps.pointProp({ displayName: 'Height (pt)', description: 'Height in points. Set together with Width.', required: false }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: propsValue.slide_number,+ slideObjectId: propsValue.slide_object_id,+ });+ const video = slidesElements.readVideo({ value: propsValue.video, source: propsValue.source });+ const box = slidesElements.readBox({ x: propsValue.x, y: propsValue.y, width: propsValue.width, height: propsValue.height, required: false });+ const objectId = slidesIds.generateObjectId('video');+ const accessToken = await getAccessToken(context.auth);+ const action = 'insert the video';+ const { objectId: slideObjectId, revisionId } = await slidesRequests+ .lookupSlide({ accessToken, presentationId, selector })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: [slidesElementRequests.buildCreateVideoRequest({ objectId, slideObjectId, video, box })],+ revisionId,+ action,+ });+ return { presentationId, slideObjectId, videoObjectId: objectId, source: video.source, videoId: video.id };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/list-slide-elements.ts b/packages/pieces/community/google-slides/src/lib/actions/list-slide-elements.tsnew file mode 100644index 00000000000..1ad0c110d32--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/list-slide-elements.ts@@ -0,0 +1,79 @@+import { createAction } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesText } from '../commons/presentation-text';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { listSlideElementsOutputSchema } from '../output-schemas';++export const listSlideElements = createAction({+ auth: googleSlidesAuth,+ name: 'list_slide_elements',+ classification: 'READ',+ displayName: 'List Slide Elements',+ description: 'List the elements on one slide with their position, size and text, in points.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'List every element on one slide (including those inside groups) with its object ID, type, position and size in points, rotation, text, table size and cell texts, and parent group, plus the slide size. Pick this before placing, moving, resizing or styling elements, so you know where things are and which object IDs to pass; Get Presentation Outline is enough when you only need text and IDs across the whole deck. Read-only and idempotent.',+ idempotent: true,+ },+ outputSchema: listSlideElementsOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const accessToken = await getAccessToken(context.auth);+ const action = 'list the slide elements';+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: 'presentationId,pageSize,slides(objectId)' })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const { objectId, index } = slidesRequests.resolveSlide({ slides: presentation.slides ?? [], selector });+ const slide = await slidesApi.getPage({ accessToken, presentationId, pageObjectId: objectId }).catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const entries = slidesElements.slideEntries(slide.pageElements);+ const elements = entries.map((entry) => {+ const type = slidesText.elementType(entry.element);+ const size = type === 'TABLE' ? slidesElements.tableSize(entry.element) : null;+ return {+ objectId: entry.element.objectId,+ type,+ shapeType: entry.element.shape?.shapeType ?? null,+ placeholderType: entry.element.shape?.placeholder?.type ?? null,+ parentGroupId: entry.parentGroupId,+ ...slidesElements.entryGeometry({ entry, entries }),+ text: slidesText.elementText(entry.element),+ tableRows: size?.rows ?? null,+ tableColumns: size?.columns ?? null,+ tableCells: entry.element.table+ ? (entry.element.table.tableRows ?? []).map((row) =>+ (row.tableCells ?? []).map((cell) => slidesText.stripTrailingNewlines(slidesText.joinText(cell.text)))+ )+ : null,+ };+ });+ const width = slidesElements.dimensionToEmu(presentation.pageSize?.width);+ const height = slidesElements.dimensionToEmu(presentation.pageSize?.height);+ return {+ presentationId,+ slideObjectId: objectId,+ slideNumber: index + 1,+ slideWidth: width === undefined ? null : slidesElements.emuToPt(width),+ slideHeight: height === undefined ? null : slidesElements.emuToPt(height),+ elementCount: elements.length,+ elements,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/move-resize-element.ts b/packages/pieces/community/google-slides/src/lib/actions/move-resize-element.tsnew file mode 100644index 00000000000..2c21fbb62e2--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/move-resize-element.ts@@ -0,0 +1,58 @@+import { createAction } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { moveResizeElementOutputSchema } from '../output-schemas';++export const moveResizeElement = createAction({+ auth: googleSlidesAuth,+ name: 'move_resize_element',+ classification: 'WRITE',+ displayName: 'Move or Resize Element',+ description: 'Set the position and/or size of an element on a slide, in points.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Move and/or resize one element (shape, text box, image, table, video, line or group) by setting X, Y, Width and/or Height in points; unset values stay as they are, and if only one of Width/Height is set the aspect ratio is kept. Get current positions and the slide size from List Slide Elements. Groups (x/y = the box around their elements), tables and rotated elements can only be moved, not resized; an element inside a group is moved through its group. Idempotent: the same values give the same result.',+ idempotent: true,+ },+ outputSchema: moveResizeElementOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ object_id: slidesProps.elementIdProp({+ displayName: 'Element Object ID',+ description: 'Object ID of the element to move or resize (from List Slide Elements or Get Presentation Outline).',+ }),+ x: slidesProps.pointProp({ displayName: 'X (pt)', description: 'New distance from the left edge of the slide, in points.', required: false }),+ y: slidesProps.pointProp({ displayName: 'Y (pt)', description: 'New distance from the top edge of the slide, in points.', required: false }),+ width: slidesProps.pointProp({ displayName: 'Width (pt)', description: 'New width in points.', required: false }),+ height: slidesProps.pointProp({ displayName: 'Height (pt)', description: 'New height in points.', required: false }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const objectId = slidesElements.readElementId({ value: propsValue.object_id, label: 'Element Object ID' });+ const { x, y, width, height } = propsValue;+ if ([x, y, width, height].every((value) => value === undefined || value === null)) {+ throw new Error('Set at least one of X, Y, Width or Height (in points).');+ }+ const accessToken = await getAccessToken(context.auth);+ const action = 'move or resize the element';+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId, action });+ const { transform, geometry } = slidesElements.computeMoveResize({ located, x, y, width, height });+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: [{ updatePageElementTransform: { objectId, applyMode: 'ABSOLUTE', transform } }],+ revisionId: located.revisionId,+ action,+ });+ return {+ presentationId,+ slideObjectId: located.slideObjectId,+ objectId,+ ...geometry,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/move-slide.ts b/packages/pieces/community/google-slides/src/lib/actions/move-slide.tsnew file mode 100644index 00000000000..29e36aa121a--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/move-slide.ts@@ -0,0 +1,79 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { FIELD_MASKS, slidesRequests } from '../commons/requests';+import { moveSlideOutputSchema } from '../output-schemas';++export const moveSlide = createAction({+ auth: googleSlidesAuth,+ name: 'move_slide',+ classification: 'WRITE',+ displayName: 'Move Slide',+ description: 'Move a slide to a new position in the presentation.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Move one slide (by number or object ID) so it ends up at the given 1-based position. Use it to reorder a deck. Not idempotent when the slide is chosen by number (after the first move that number points at another slide); by object ID a repeat to the same position changes nothing, so prefer the object ID.',+ idempotent: false,+ },+ outputSchema: moveSlideOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ position: Property.Number({+ displayName: 'New Position',+ description: 'Position the slide should end up at, starting at 1 for the first slide.',+ required: true,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const accessToken = await getAccessToken(context.auth);+ const action = 'move the slide';+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.slideIds })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const slides = presentation.slides ?? [];+ const slide = slidesRequests.resolveSlide({ slides, selector });+ const targetIndex = slidesRequests.readPosition({ position: context.propsValue.position, maxPosition: slides.length });+ if (targetIndex === undefined) {+ throw new Error('New Position is required.');+ }+ const moved = targetIndex !== slide.index;+ if (moved) {+ await slidesApi+ .batchUpdate({+ accessToken,+ presentationId,+ requests: [+ {+ updateSlidesPosition: {+ slideObjectIds: [slide.objectId],+ insertionIndex: slidesRequests.moveInsertionIndex({ currentIndex: slide.index, targetIndex }),+ },+ },+ ],+ requiredRevisionId: presentation.revisionId,+ })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ }+ return {+ presentationId,+ slideObjectId: slide.objectId,+ previousSlideNumber: slide.index + 1,+ slideNumber: targetIndex + 1,+ moved,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/refresh-charts.ts b/packages/pieces/community/google-slides/src/lib/actions/refresh-charts.tsindex 66e85509904..2eaf2eac930 100644--- a/packages/pieces/community/google-slides/src/lib/actions/refresh-charts.ts+++ b/packages/pieces/community/google-slides/src/lib/actions/refresh-charts.ts@@ -1,6 +1,10 @@import { createAction, Property } from '@activepieces/pieces-framework';-import { batchUpdate, getSlide, PageElement } from '../commons/common';import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesText } from '../commons/presentation-text';+import { FIELD_MASKS } from '../commons/requests';+import { refreshSheetsChartsOutputSchema } from '../output-schemas';export const refreshSheetsCharts = createAction({name: 'refresh_sheets_charts',@@ -8,47 +12,52 @@ export const refreshSheetsCharts = createAction({displayName: 'Refresh Sheets Charts',description: 'Refresh all Google Sheets charts in the presentation',audience: 'both',- aiMetadata: { description: 'Re-sync every embedded Google Sheets chart in a presentation to its source spreadsheet\'s current data, in a single batch update. Use this after the underlying Sheets data changes to bring the slide charts up to date. Not idempotent: each call issues a fresh refresh against live spreadsheet data, so repeated calls can pull different chart contents. Requires the presentation ID; charts that are not linked to Google Sheets are left untouched.', idempotent: false },+ aiMetadata: {+ description:+ "Re-sync every embedded Google Sheets chart in a presentation (including charts inside groups) to its source spreadsheet's current data, in a single batch update. Use this after the underlying Sheets data changes to bring the slide charts up to date. Not idempotent: each call issues a fresh refresh against live spreadsheet data, so repeated calls can pull different chart contents. Accepts the presentation ID or URL; returns success false (not an error) when the deck has no linked charts.",+ idempotent: false,+ },auth: googleSlidesAuth,+ outputSchema: refreshSheetsChartsOutputSchema,props: {- presentation_id: Property.ShortText({- displayName: 'Presentation ID',- description: 'The ID of the presentation, between /d and /edit',- required: true,- }),+ presentation_id: Property.ShortText({+ displayName: 'Presentation ID',+ description: 'The presentation ID (between /d/ and /edit in its URL), or the full URL.',+ required: true,+ }),},async run(context) {- const { presentation_id } = context.propsValue;- const accessToken = await getAccessToken(context.auth);- const presentation = await getSlide(accessToken, presentation_id);-- const requests: { refreshSheetsChart: { objectId: string; }; }[] = [];-- presentation.slides?.forEach((slide) => {- slide.pageElements?.forEach((element: PageElement) => {- if (element.sheetsChart) {- const refreshRequest = {- refreshSheetsChart: {- objectId: element.objectId- }- };- requests.push(refreshRequest);- }- });+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const accessToken = await getAccessToken(context.auth);+ try {+ const presentation = await slidesApi.getPresentation({+ accessToken,+ presentationId,+ fields: FIELD_MASKS.charts,});-- if (requests.length > 0) {- const result = await batchUpdate(accessToken, presentation_id, requests);- return {- success: true,- message: `Successfully refreshed ${requests.length} Google Sheets charts`,- result: result- };- } else {- return {- success: false,- message: 'No Google Sheets charts found in the presentation'- };+ const requests = slidesText+ .findSheetsCharts(presentation)+ .map((objectId) => ({ refreshSheetsChart: { objectId } }));++ if (requests.length === 0) {+ return {+ success: false,+ message: 'No Google Sheets charts found in the presentation',+ };}- }-});\ No newline at end of file+ const result = await slidesApi.batchUpdate({+ accessToken,+ presentationId,+ requests,+ requiredRevisionId: presentation.revisionId,+ });+ return {+ success: true,+ message: `Successfully refreshed ${requests.length} Google Sheets charts`,+ result,+ };+ } catch (error) {+ throw slidesApi.googleApiError({ error, action: 'refresh the Sheets charts' });+ }+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/replace-image.ts b/packages/pieces/community/google-slides/src/lib/actions/replace-image.tsnew file mode 100644index 00000000000..0885198efee--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/replace-image.ts@@ -0,0 +1,59 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { IMAGE_REPLACE_METHODS, slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { replaceImageOutputSchema } from '../output-schemas';++export const replaceImage = createAction({+ auth: googleSlidesAuth,+ name: 'replace_image',+ classification: 'WRITE',+ displayName: 'Replace Image',+ description: 'Swap an existing image for a new one from a URL, keeping its position and size.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Replace one existing image (by its object ID) with a new image from a public URL; the frame keeps its position and size, and the new picture is fitted (CENTER_INSIDE, default) or cropped to fill (CENTER_CROP). Use it to refresh a logo, chart picture or photo; use Insert Image to add a new image and Replace Shapes with Image to swap {{tag}} text boxes. The image objectId comes from List Slide Elements (type IMAGE). Idempotent.',+ idempotent: true,+ },+ outputSchema: replaceImageOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ image_object_id: slidesProps.elementIdProp({+ displayName: 'Image Object ID',+ description: 'Object ID of the image to replace (type IMAGE in List Slide Elements, or from Insert Image).',+ }),+ image_url: Property.ShortText({+ displayName: 'Image URL',+ description: 'Public link to a PNG, JPEG or GIF image (under 50 MB).',+ required: true,+ }),+ replace_method: slidesProps.enumProp({+ displayName: 'Fit',+ description: 'CENTER_INSIDE (default) fits the whole image in the frame; CENTER_CROP fills the frame and crops.',+ values: IMAGE_REPLACE_METHODS,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const imageObjectId = slidesElements.readElementId({ value: propsValue.image_object_id, label: 'Image Object ID' });+ const url = slidesIds.validateImageUrl(propsValue.image_url);+ const method =+ slidesElements.readEnum({ value: propsValue.replace_method, label: 'Fit', allowed: IMAGE_REPLACE_METHODS }) ?? 'CENTER_INSIDE';+ const accessToken = await getAccessToken(context.auth);+ const action = 'replace the image';+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId: imageObjectId, action });+ slidesElements.requireType({ located, types: ['IMAGE'], purpose: 'this action only replaces images' });+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: [slidesElementRequests.buildReplaceImageRequest({ imageObjectId, url, method })],+ revisionId: located.revisionId,+ action,+ });+ return { presentationId, slideObjectId: located.slideObjectId, imageObjectId, imageUrl: url, fit: method };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/replace-shapes-with-image.ts b/packages/pieces/community/google-slides/src/lib/actions/replace-shapes-with-image.tsnew file mode 100644index 00000000000..ce49558d7ba--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/replace-shapes-with-image.ts@@ -0,0 +1,83 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { replaceShapesWithImageOutputSchema } from '../output-schemas';++export const replaceShapesWithImage = createAction({+ auth: googleSlidesAuth,+ name: 'replace_shapes_with_image',+ classification: 'WRITE',+ displayName: 'Replace Shapes with Image',+ description: 'Replace every shape that contains a text (e.g. {{logo}}) with an image from a URL.',+ audience: 'both',+ aiMetadata: {+ description:+ "Replace every shape whose text contains the search text (e.g. a {{logo}} placeholder box) with an image from a public URL, fitted to the shape's size, optionally only on chosen slides. Use it for the image part of mail-merge decks after Generate from Template or Copy Presentation; to add an image at fixed coordinates use Insert Image. The URL must be public, PNG/JPEG/GIF, under 50 MB and 25 megapixels. Idempotent: replaced shapes are gone, so a repeat changes nothing.",+ idempotent: true,+ },+ outputSchema: replaceShapesWithImageOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ find: Property.ShortText({+ displayName: 'Shape Text',+ description: 'Shapes containing this text are replaced, e.g. [[logo]]. Activepieces reads {{...}} typed into a field as a reference to earlier step data, so search for [[name]]-style tokens or map the text from a previous step.',+ required: true,+ }),+ image_url: Property.ShortText({+ displayName: 'Image URL',+ description: 'Public link to a PNG, JPEG or GIF image (under 50 MB), e.g. https://example.com/logo.png.',+ required: true,+ }),+ replace_method: Property.StaticDropdown({+ displayName: 'Fit',+ description: 'How the image fills the shape.',+ required: false,+ defaultValue: 'CENTER_INSIDE',+ options: {+ options: [+ { label: 'Fit inside the shape (keep the whole image)', value: 'CENTER_INSIDE' },+ { label: 'Fill the shape (crop the image)', value: 'CENTER_CROP' },+ ],+ },+ }),+ match_case: slidesProps.matchCaseProp(),+ slide_object_ids: slidesProps.slideScopeProp(),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const find = context.propsValue.find;+ if (!find) {+ throw new Error('Shape Text is required.');+ }+ const imageUrl = slidesIds.validateImageUrl(context.propsValue.image_url);+ const replaceMethod = context.propsValue.replace_method ?? 'CENTER_INSIDE';+ if (!REPLACE_METHODS.includes(replaceMethod)) {+ throw new Error(`Fit must be one of ${REPLACE_METHODS.join(', ')}.`);+ }+ const request = slidesRequests.buildReplaceShapesRequest({+ find,+ imageUrl,+ replaceMethod,+ matchCase: context.propsValue.match_case !== false,+ pageObjectIds: slidesRequests.readSlideObjectIds(context.propsValue.slide_object_ids),+ });+ const accessToken = await getAccessToken(context.auth);+ const response = await slidesApi+ .batchUpdate({ accessToken, presentationId, requests: [request] })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'replace the shapes with the image' });+ });+ return {+ presentationId,+ occurrencesChanged: slidesRequests.occurrencesChanged({+ replies: response.replies,+ key: 'replaceAllShapesWithImage',+ }),+ };+ },+});++const REPLACE_METHODS = ['CENTER_INSIDE', 'CENTER_CROP'];diff --git a/packages/pieces/community/google-slides/src/lib/actions/replace-text.ts b/packages/pieces/community/google-slides/src/lib/actions/replace-text.tsnew file mode 100644index 00000000000..a60fa62a3ca--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/replace-text.ts@@ -0,0 +1,60 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { replaceTextOutputSchema } from '../output-schemas';++export const replaceText = createAction({+ auth: googleSlidesAuth,+ name: 'replace_text',+ classification: 'WRITE',+ displayName: 'Replace Text',+ description: 'Replace every occurrence of a text in the presentation.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Replace every occurrence of a text (for example a {{placeholder}}) in the shapes and tables of a Google Slides presentation, optionally only on chosen slides, and report how many were changed. Use it to fill or fix text in an existing deck; to copy a template and fill all its placeholders in one step use Generate from Template. An empty replacement deletes the matched text. Idempotent: a repeat finds nothing left to replace, unless the replacement itself contains the search text.',+ idempotent: true,+ },+ outputSchema: replaceTextOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ find: Property.ShortText({+ displayName: 'Find',+ description: 'Text to search for, e.g. [[customer_name]]. Activepieces reads {{...}} typed into a field as a reference to earlier step data, so search for [[name]]-style tokens or map the text from a previous step.',+ required: true,+ }),+ replace_with: Property.LongText({+ displayName: 'Replace With',+ description: 'Replacement text. Leave empty to delete every match.',+ required: false,+ }),+ match_case: slidesProps.matchCaseProp(),+ slide_object_ids: slidesProps.slideScopeProp(),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const find = context.propsValue.find;+ if (!find) {+ throw new Error('Find is required.');+ }+ const request = slidesRequests.buildReplaceTextRequest({+ find,+ replaceWith: context.propsValue.replace_with ?? '',+ matchCase: context.propsValue.match_case !== false,+ pageObjectIds: slidesRequests.readSlideObjectIds(context.propsValue.slide_object_ids),+ });+ const accessToken = await getAccessToken(context.auth);+ const response = await slidesApi+ .batchUpdate({ accessToken, presentationId, requests: [request] })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action: 'replace the text' });+ });+ return {+ presentationId,+ occurrencesChanged: slidesRequests.occurrencesChanged({ replies: response.replies, key: 'replaceAllText' }),+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/set-element-text.ts b/packages/pieces/community/google-slides/src/lib/actions/set-element-text.tsnew file mode 100644index 00000000000..ddf54786fb7--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/set-element-text.ts@@ -0,0 +1,66 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { setElementTextOutputSchema } from '../output-schemas';++export const setElementText = createAction({+ auth: googleSlidesAuth,+ name: 'set_element_text',+ classification: 'WRITE',+ displayName: 'Set Element Text',+ description: 'Replace all text in a shape, text box, placeholder or table cell.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Replace the whole text of one shape, text box, placeholder (e.g. a slide title) or table cell (set Row and Column) with new text, or empty it with Clear Text. Pick it to rewrite one element; use Insert Text to add to existing text and Replace Text to swap a phrase everywhere. Character styling of the old text is not kept: re-apply with Update Text Style. The objectId comes from List Slide Elements or Get Presentation Outline. Idempotent: sends nothing when the text already matches.',+ idempotent: true,+ },+ outputSchema: setElementTextOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ object_id: slidesProps.textElementIdProp(),+ row: slidesProps.cellRowProp(),+ column: slidesProps.cellColumnProp(),+ text: Property.LongText({+ displayName: 'Text',+ description: 'The new text. Use \\n for a new paragraph. Leave empty only together with Clear Text.',+ required: false,+ }),+ clear_text: Property.Checkbox({+ displayName: 'Clear Text',+ description: 'Turn on to remove all text from the element. Leave Text empty when using this.',+ required: false,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const objectId = slidesElements.readElementId({ value: propsValue.object_id, label: 'Element Object ID' });+ const text = slidesElements.readText(propsValue.text) ?? '';+ const clear = slidesElements.readBoolean({ value: propsValue.clear_text, label: 'Clear Text' }) ?? false;+ if (clear && text !== '') {+ throw new Error('Clear Text is on but Text is set. Turn Clear Text off to set new text, or leave Text empty to clear it.');+ }+ if (!clear && text === '') {+ throw new Error('Text is empty. Enter the new text, or turn on Clear Text to remove the text.');+ }+ const accessToken = await getAccessToken(context.auth);+ const action = 'set the element text';+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId, action });+ const target = slidesElements.resolveTextTarget({ located, row: propsValue.row, column: propsValue.column });+ const requests = slidesElementRequests.buildSetTextRequests({ target, text });+ await slidesElements.applyRequests({ accessToken, presentationId, requests, revisionId: located.revisionId, action });+ return {+ presentationId,+ slideObjectId: located.slideObjectId,+ objectId,+ row: target.cellLocation ? target.cellLocation.rowIndex + 1 : null,+ column: target.cellLocation ? target.cellLocation.columnIndex + 1 : null,+ text,+ changed: requests.length > 0,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/set-slide-background.ts b/packages/pieces/community/google-slides/src/lib/actions/set-slide-background.tsnew file mode 100644index 00000000000..97d1dae2327--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/set-slide-background.ts@@ -0,0 +1,97 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { Background, slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { FIELD_MASKS, slidesRequests } from '../commons/requests';+import { setSlideBackgroundOutputSchema } from '../output-schemas';++export const setSlideBackground = createAction({+ auth: googleSlidesAuth,+ name: 'set_slide_background',+ classification: 'WRITE',+ displayName: 'Set Slide Background',+ description: 'Set a solid colour or an image as the background of one slide or all slides.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Set the background of one slide (by number or object ID) or of every slide (All Slides) to a solid hex colour or to a public image URL stretched to fill the slide. Use it for slide backgrounds; to add a picture on top of the slide use Insert Image. Set exactly one of Color or Image URL. Idempotent: the same values give the same result.',+ idempotent: true,+ },+ outputSchema: setSlideBackgroundOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ all_slides: Property.Checkbox({+ displayName: 'All Slides',+ description: 'Turn on to change every slide. Leave Slide Number and Slide Object ID empty when using this.',+ required: false,+ }),+ color: slidesProps.colorProp({ displayName: 'Color', description: 'Hex colour, e.g. #0B1F3A.' }),+ image_url: Property.ShortText({+ displayName: 'Image URL',+ description: 'Public PNG, JPEG or GIF URL to stretch over the slide, e.g. https://example.com/bg.png.',+ required: false,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const allSlides = slidesElements.readBoolean({ value: propsValue.all_slides, label: 'All Slides' }) ?? false;+ const hasSlide =+ (propsValue.slide_number !== undefined && propsValue.slide_number !== null) ||+ (typeof propsValue.slide_object_id === 'string' && propsValue.slide_object_id.trim() !== '');+ if (allSlides && hasSlide) {+ throw new Error('All Slides is on: leave Slide Number and Slide Object ID empty.');+ }+ const selector = allSlides+ ? undefined+ : slidesRequests.readSlideSelector({ slideNumber: propsValue.slide_number, slideObjectId: propsValue.slide_object_id });+ const background = readBackground({ color: propsValue.color, imageUrl: propsValue.image_url });+ const accessToken = await getAccessToken(context.auth);+ const action = 'set the slide background';+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.slideIds })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const slides = presentation.slides ?? [];+ const slideObjectIds = selector+ ? [slidesRequests.resolveSlide({ slides, selector }).objectId]+ : slides.map((slide) => slide.objectId);+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: slidesElementRequests.buildBackgroundRequests({ slideObjectIds, background }),+ revisionId: presentation.revisionId,+ action,+ });+ return {+ presentationId,+ slideObjectIds,+ slideCount: slideObjectIds.length,+ backgroundType: background.kind === 'color' ? 'COLOR' : 'IMAGE',+ color: background.kind === 'color' ? background.hex : null,+ imageUrl: background.kind === 'image' ? background.imageUrl : null,+ };+ },+});++function readBackground({ color, imageUrl }: { color: unknown; imageUrl: unknown }): Background {+ const colorText = typeof color === 'string' ? color.trim() : '';+ const imageText = typeof imageUrl === 'string' ? imageUrl.trim() : '';+ if ((colorText === '') === (imageText === '')) {+ throw new Error('Set exactly one of Color (hex, e.g. #0B1F3A) or Image URL.');+ }+ if (colorText) {+ return {+ kind: 'color',+ rgbColor: slidesElements.parseHexColor({ value: colorText, label: 'Color' }),+ hex: slidesElements.normaliseHex(colorText),+ };+ }+ return { kind: 'image', imageUrl: slidesIds.validateImageUrl(imageText) };+}diff --git a/packages/pieces/community/google-slides/src/lib/actions/set-speaker-notes.ts b/packages/pieces/community/google-slides/src/lib/actions/set-speaker-notes.tsnew file mode 100644index 00000000000..a10febd3a8d--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/set-speaker-notes.ts@@ -0,0 +1,86 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesApi } from '../commons/common';+import { slidesIds } from '../commons/ids';+import { slidesText } from '../commons/presentation-text';+import { slidesProps } from '../commons/props';+import { FIELD_MASKS, slidesRequests } from '../commons/requests';+import { setSpeakerNotesOutputSchema } from '../output-schemas';++export const setSpeakerNotes = createAction({+ auth: googleSlidesAuth,+ name: 'set_speaker_notes',+ classification: 'WRITE',+ displayName: 'Set Speaker Notes',+ description: 'Replace the speaker notes of a slide.',+ audience: 'both',+ aiMetadata: {+ description:+ 'Set the speaker notes of one slide (by number or object ID) to the given text, replacing whatever notes it had; to remove the notes turn on Clear Notes instead of passing text. Use it to write talk tracks or presenter instructions; read the current notes with Get Presentation Outline. Idempotent: the notes end up as the given text no matter how often it runs.',+ idempotent: true,+ },+ outputSchema: setSpeakerNotesOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ slide_number: slidesProps.slideNumberProp(),+ slide_object_id: slidesProps.slideObjectIdProp(),+ notes: Property.LongText({+ displayName: 'Notes',+ description: 'The new speaker notes. They replace the current notes.',+ required: false,+ }),+ clear_notes: Property.Checkbox({+ displayName: 'Clear Notes',+ description: 'Turn on to remove the slide\'s speaker notes. Leave Notes empty when using this.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const presentationId = slidesIds.parsePresentationId(context.propsValue.presentation_id);+ const selector = slidesRequests.readSlideSelector({+ slideNumber: context.propsValue.slide_number,+ slideObjectId: context.propsValue.slide_object_id,+ });+ const notes = context.propsValue.notes ?? '';+ const clearNotes = context.propsValue.clear_notes === true;+ if (clearNotes && notes !== '') {+ throw new Error('Set either Notes or Clear Notes, not both.');+ }+ if (!clearNotes && notes === '') {+ throw new Error('Notes is empty. Enter the notes text, or turn on Clear Notes to remove the notes.');+ }+ const accessToken = await getAccessToken(context.auth);+ const action = 'set the speaker notes';+ const presentation = await slidesApi+ .getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.speakerNotes })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ const slides = presentation.slides ?? [];+ const slide = slides[slidesRequests.resolveSlide({ slides, selector }).index];+ const speakerNotesObjectId = slide.slideProperties?.notesPage?.notesProperties?.speakerNotesObjectId;+ if (!speakerNotesObjectId) {+ throw new Error('Google returned no speaker notes area (speakerNotesObjectId) for this slide.');+ }+ const requests = slidesRequests.buildSpeakerNotesRequests({+ speakerNotesObjectId,+ currentNotes: slidesText.speakerNotesText(slide),+ notes,+ });+ if (requests.length > 0) {+ await slidesApi+ .batchUpdate({ accessToken, presentationId, requests, requiredRevisionId: presentation.revisionId })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ }+ return {+ presentationId,+ slideObjectId: slide.objectId,+ speakerNotesObjectId,+ speakerNotes: notes,+ changed: requests.length > 0,+ };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/update-paragraph-style.ts b/packages/pieces/community/google-slides/src/lib/actions/update-paragraph-style.tsnew file mode 100644index 00000000000..420136c62e6--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/update-paragraph-style.ts@@ -0,0 +1,90 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { BULLET_PRESETS, PARAGRAPH_ALIGNMENTS, slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { slidesRequests } from '../commons/requests';+import { updateParagraphStyleOutputSchema } from '../output-schemas';++export const updateParagraphStyle = createAction({+ auth: googleSlidesAuth,+ name: 'update_paragraph_style',+ classification: 'WRITE',+ displayName: 'Update Paragraph Style',+ description: 'Set alignment, line spacing, paragraph spacing and bullets in a shape or table cell.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Format the paragraphs of one shape, text box, placeholder or table cell: horizontal alignment, line spacing (percent, 100 = single), space above/below in pt, and bullets or numbering (Bullets = NONE removes them). Applies to every paragraph touched by all the text, by Match Text or by a Start/End Index range. Use Update Text Style for bold, font, size and colour; use Update Shape Properties for vertical alignment. The element must already have text. Idempotent.',+ idempotent: true,+ },+ outputSchema: updateParagraphStyleOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ object_id: slidesProps.textElementIdProp(),+ row: slidesProps.cellRowProp(),+ column: slidesProps.cellColumnProp(),+ ...slidesProps.textRangeProps(),+ alignment: slidesProps.enumProp({+ displayName: 'Alignment',+ description: 'START (left in left-to-right text), CENTER, END or JUSTIFIED.',+ values: PARAGRAPH_ALIGNMENTS,+ }),+ line_spacing: Property.Number({+ displayName: 'Line Spacing (%)',+ description: 'Line spacing as a percentage of normal: 100 = single, 150 = one and a half.',+ required: false,+ }),+ space_above: Property.Number({ displayName: 'Space Above (pt)', description: 'Space before each paragraph, in points.', required: false }),+ space_below: Property.Number({ displayName: 'Space Below (pt)', description: 'Space after each paragraph, in points.', required: false }),+ bullets: slidesProps.enumProp({+ displayName: 'Bullets',+ description: 'Bullet or numbering preset for the paragraphs, or NONE to remove bullets.',+ values: BULLET_PRESETS,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const objectId = slidesElements.readElementId({ value: propsValue.object_id, label: 'Element Object ID' });+ const input = {+ alignment: slidesElements.readEnum({ value: propsValue.alignment, label: 'Alignment', allowed: PARAGRAPH_ALIGNMENTS }),+ lineSpacing: slidesElements.readPositive({ value: propsValue.line_spacing, label: 'Line Spacing (%)' }),+ spaceAbovePt: readNonNegative({ value: propsValue.space_above, label: 'Space Above (pt)' }),+ spaceBelowPt: readNonNegative({ value: propsValue.space_below, label: 'Space Below (pt)' }),+ bullets: slidesElements.readEnum({ value: propsValue.bullets, label: 'Bullets', allowed: BULLET_PRESETS }),+ };+ if (Object.values(input).every((value) => value === undefined)) {+ throw new Error('Set at least one of Alignment, Line Spacing, Space Above, Space Below or Bullets.');+ }+ const accessToken = await getAccessToken(context.auth);+ const action = 'update the paragraph style';+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId, action });+ const target = slidesElements.resolveTextTarget({ located, row: propsValue.row, column: propsValue.column });+ const ranges = slidesElements.resolveTextRanges({+ target,+ matchText: propsValue.match_text,+ startIndex: propsValue.start_index,+ endIndex: propsValue.end_index,+ });+ const requests = slidesElementRequests.buildParagraphRequests({ target, ranges, input });+ await slidesElements.applyRequests({ accessToken, presentationId, requests, revisionId: located.revisionId, action });+ return {+ presentationId,+ slideObjectId: located.slideObjectId,+ objectId,+ rangesStyled: ranges.length,+ alignment: input.alignment ?? null,+ bullets: input.bullets ?? null,+ };+ },+});++function readNonNegative({ value, label }: { value: unknown; label: string }): number | undefined {+ const number = slidesRequests.toNumber({ value, label });+ if (number !== undefined && number < 0) {+ throw new Error(`${label} cannot be negative, got ${number}.`);+ }+ return number;+}diff --git a/packages/pieces/community/google-slides/src/lib/actions/update-shape-properties.ts b/packages/pieces/community/google-slides/src/lib/actions/update-shape-properties.tsnew file mode 100644index 00000000000..174ddb8eaf7--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/update-shape-properties.ts@@ -0,0 +1,69 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { CONTENT_ALIGNMENTS, DASH_STYLES, slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { updateShapePropertiesOutputSchema } from '../output-schemas';++export const updateShapeProperties = createAction({+ auth: googleSlidesAuth,+ name: 'update_shape_properties',+ classification: 'WRITE',+ displayName: 'Update Shape Properties',+ description: 'Change the fill, outline and vertical text alignment of a shape or text box.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change how one shape or text box looks: fill colour (or "transparent"), outline colour (or "none"), outline weight in pt and dash style, and vertical alignment of its text (TOP, MIDDLE, BOTTOM). Only the properties you set change. Use Update Text Style for the text itself and Move or Resize Element for position and size; it does not work on images, tables or groups. The objectId comes from List Slide Elements or Create Shape. Idempotent.',+ idempotent: true,+ },+ outputSchema: updateShapePropertiesOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ object_id: slidesProps.elementIdProp({+ displayName: 'Shape Object ID',+ description: 'Object ID of the shape or text box (from List Slide Elements, Get Presentation Outline or Create Shape).',+ }),+ fill_color: slidesProps.colorProp({ displayName: 'Fill Color', description: 'Hex colour, e.g. #E8F0FE, or "transparent".' }),+ outline_color: slidesProps.colorProp({ displayName: 'Outline Color', description: 'Hex colour, e.g. #1A73E8, or "none" to hide the outline.' }),+ outline_weight: Property.Number({ displayName: 'Outline Weight (pt)', description: 'Outline thickness in points.', required: false }),+ outline_dash: slidesProps.enumProp({ displayName: 'Outline Dash', description: 'Outline dash style.', values: DASH_STYLES }),+ content_alignment: slidesProps.enumProp({+ displayName: 'Vertical Alignment',+ description: 'Where the text sits inside the shape.',+ values: CONTENT_ALIGNMENTS,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const objectId = slidesElements.readElementId({ value: propsValue.object_id, label: 'Shape Object ID' });+ const { shapeProperties, fields } = slidesElementRequests.buildShapeProperties({+ fillColor: slidesElements.readColor({ value: propsValue.fill_color, label: 'Fill Color' }),+ outlineColor: slidesElements.readColor({ value: propsValue.outline_color, label: 'Outline Color' }),+ outlineWeightPt: slidesElements.readPositive({ value: propsValue.outline_weight, label: 'Outline Weight (pt)' }),+ outlineDash: slidesElements.readEnum({ value: propsValue.outline_dash, label: 'Outline Dash', allowed: DASH_STYLES }),+ contentAlignment: slidesElements.readEnum({+ value: propsValue.content_alignment,+ label: 'Vertical Alignment',+ allowed: CONTENT_ALIGNMENTS,+ }),+ });+ if (fields.length === 0) {+ throw new Error('Set at least one of Fill Color, Outline Color, Outline Weight, Outline Dash or Vertical Alignment.');+ }+ const accessToken = await getAccessToken(context.auth);+ const action = 'update the shape';+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId, action });+ slidesElements.requireType({ located, types: ['SHAPE'], purpose: 'this action only changes shapes and text boxes' });+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: [{ updateShapeProperties: { objectId, shapeProperties, fields: fields.join(',') } }],+ revisionId: located.revisionId,+ action,+ });+ return { presentationId, slideObjectId: located.slideObjectId, objectId, updatedFields: fields };+ },+});diff --git a/packages/pieces/community/google-slides/src/lib/actions/update-text-style.ts b/packages/pieces/community/google-slides/src/lib/actions/update-text-style.tsnew file mode 100644index 00000000000..466a252d0e5--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/actions/update-text-style.ts@@ -0,0 +1,113 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { getAccessToken, googleSlidesAuth } from '../auth';+import { slidesElementRequests } from '../commons/element-requests';+import { slidesElements } from '../commons/elements';+import { slidesIds } from '../commons/ids';+import { slidesProps } from '../commons/props';+import { updateTextStyleOutputSchema } from '../output-schemas';++export const updateTextStyle = createAction({+ auth: googleSlidesAuth,+ name: 'update_text_style',+ classification: 'WRITE',+ displayName: 'Update Text Style',+ description: 'Change bold, italic, font, size, colour or link of text in a shape or table cell.',+ audience: 'ai',+ aiMetadata: {+ description:+ 'Change character formatting (bold, italic, underline, strikethrough, font family, font size in pt, text colour, highlight, link) of the text in one shape, text box, placeholder or table cell, in one call. Applies to all its text, to every occurrence of Match Text, or to a Start/End Index range; only the styles you set change. Use Update Paragraph Style for alignment, spacing and bullets. The element must already have text; its objectId comes from List Slide Elements or Create Shape. Idempotent.',+ idempotent: true,+ },+ outputSchema: updateTextStyleOutputSchema,+ props: {+ presentation_id: slidesProps.presentationIdProp(),+ object_id: slidesProps.textElementIdProp(),+ row: slidesProps.cellRowProp(),+ column: slidesProps.cellColumnProp(),+ ...slidesProps.textRangeProps(),+ bold: Property.Checkbox({ displayName: 'Bold', description: 'true or false; leave unset to keep.', required: false }),+ italic: Property.Checkbox({ displayName: 'Italic', description: 'true or false; leave unset to keep.', required: false }),+ underline: Property.Checkbox({ displayName: 'Underline', description: 'true or false; leave unset to keep.', required: false }),+ strikethrough: Property.Checkbox({+ displayName: 'Strikethrough',+ description: 'true or false; leave unset to keep.',+ required: false,+ }),+ font_family: Property.ShortText({+ displayName: 'Font Family',+ description: 'Google Fonts family name, e.g. "Roboto" or "Montserrat".',+ required: false,+ }),+ font_size: Property.Number({ displayName: 'Font Size (pt)', description: 'Font size in points, e.g. 24.', required: false }),+ text_color: slidesProps.colorProp({ displayName: 'Text Color', description: 'Hex colour, e.g. #202124.' }),+ highlight_color: slidesProps.colorProp({+ displayName: 'Highlight Color',+ description: 'Hex background colour behind the text, or "none" to remove the highlight.',+ }),+ link_url: Property.ShortText({+ displayName: 'Link URL',+ description: 'Make the text a link to this http(s) URL, or "none" to remove an existing link.',+ required: false,+ }),+ },+ async run(context) {+ const { propsValue } = context;+ const presentationId = slidesIds.parsePresentationId(propsValue.presentation_id);+ const objectId = slidesElements.readElementId({ value: propsValue.object_id, label: 'Element Object ID' });+ const textColor = slidesElements.readColor({ value: propsValue.text_color, label: 'Text Color' });+ if (textColor?.kind === 'none') {+ throw new Error('Text Color must be a hex colour like #202124; "none" is only allowed for Highlight Color.');+ }+ const fontSizePt = slidesElements.readPositive({ value: propsValue.font_size, label: 'Font Size (pt)' });+ const fontFamily = propsValue.font_family?.trim() || undefined;+ const { style, fields } = slidesElementRequests.buildTextStyle({+ bold: slidesElements.readBoolean({ value: propsValue.bold, label: 'Bold' }),+ italic: slidesElements.readBoolean({ value: propsValue.italic, label: 'Italic' }),+ underline: slidesElements.readBoolean({ value: propsValue.underline, label: 'Underline' }),+ strikethrough: slidesElements.readBoolean({ value: propsValue.strikethrough, label: 'Strikethrough' }),+ fontFamily,+ fontSizePt,+ textColor,+ highlightColor: slidesElements.readColor({ value: propsValue.highlight_color, label: 'Highlight Color' }),+ link: readLink(propsValue.link_url),+ });+ const accessToken = await getAccessToken(context.auth);+ const action = 'update the text style';+ const located = await slidesElements.loadElement({ accessToken, presentationId, objectId, action });+ const target = slidesElements.resolveTextTarget({ located, row: propsValue.row, column: propsValue.column });+ const ranges = slidesElements.resolveTextRanges({+ target,+ matchText: propsValue.match_text,+ startIndex: propsValue.start_index,+ endIndex: propsValue.end_index,+ });+ await slidesElements.applyRequests({+ accessToken,+ presentationId,+ requests: slidesElementRequests.buildTextStyleRequests({ target, ranges, style, fields }),+ revisionId: located.revisionId,+ action,+ });+ return {+ presentationId,+ slideObjectId: located.slideObjectId,+ objectId,+ rangesStyled: ranges.length,+ updatedFields: fields,+ };+ },+});++function readLink(value: unknown): string | null | undefined {+ const text = typeof value === 'string' ? value.trim() : '';+ if (!text) {+ return undefined;+ }+ if (text.toLowerCase() === 'none') {+ return null;+ }+ if (!/^https?:\/\/\S+$/i.test(text)) {+ throw new Error(`Link URL must start with http:// or https://, got "${text}".`);+ }+ return text;+}diff --git a/packages/pieces/community/google-slides/src/lib/commons/common.ts b/packages/pieces/community/google-slides/src/lib/commons/common.tsindex 571e4bd644f..dd2bb6eb7e9 100644--- a/packages/pieces/community/google-slides/src/lib/commons/common.ts+++ b/packages/pieces/community/google-slides/src/lib/commons/common.ts@@ -1,113 +1,337 @@-import { AuthenticationType, httpClient, HttpMethod } from "@activepieces/pieces-common";--export interface PageElement {- objectId: string;- table?: Table- sheetsChart?: {- spreadsheetId: string;- chartId: number;- };- shape?: Shape+import {+ AuthenticationType,+ httpClient,+ HttpMethod,+ QueryParams,+} from '@activepieces/pieces-common';++function presentationUrl(presentationId: string): string {+ return `https://docs.google.com/presentation/d/${presentationId}/edit`;}-interface Presentation {- slides?: Slide[];+function slideUrl({ presentationId, slideObjectId }: { presentationId: string; slideObjectId: string }): string {+ return `${presentationUrl(presentationId)}#slide=id.${slideObjectId}`;}-interface Slide {- pageElements?: PageElement[];+async function slidesRequest<T>({+ accessToken,+ method,+ path,+ body,+ queryParams,+}: {+ accessToken: string;+ method: HttpMethod;+ path: string;+ body?: unknown;+ queryParams?: QueryParams;+}): Promise<T> {+ const response = await httpClient.sendRequest<T>({+ method,+ url: `${SLIDES_API_BASE}/${path}`,+ body,+ queryParams,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: accessToken,+ },+ });+ return response.body;}+async function getPresentation({+ accessToken,+ presentationId,+ fields,+}: {+ accessToken: string;+ presentationId: string;+ fields?: string;+}): Promise<Presentation> {+ return slidesRequest<Presentation>({+ accessToken,+ method: HttpMethod.GET,+ path: encodeURIComponent(presentationId),+ queryParams: fields ? { fields } : undefined,+ });+}-interface Shape {- text?: Text;+async function getPage({+ accessToken,+ presentationId,+ pageObjectId,+}: {+ accessToken: string;+ presentationId: string;+ pageObjectId: string;+}): Promise<Page> {+ return slidesRequest<Page>({+ accessToken,+ method: HttpMethod.GET,+ path: `${encodeURIComponent(presentationId)}/pages/${encodeURIComponent(pageObjectId)}`,+ });}-interface Text {- textElements?: TextElement[];+async function getPageThumbnail({+ accessToken,+ presentationId,+ pageObjectId,+ thumbnailSize,+}: {+ accessToken: string;+ presentationId: string;+ pageObjectId: string;+ thumbnailSize: string;+}): Promise<Thumbnail> {+ return slidesRequest<Thumbnail>({+ accessToken,+ method: HttpMethod.GET,+ path: `${encodeURIComponent(presentationId)}/pages/${encodeURIComponent(pageObjectId)}/thumbnail`,+ queryParams: {+ 'thumbnailProperties.thumbnailSize': thumbnailSize,+ 'thumbnailProperties.mimeType': 'PNG',+ },+ });}-export interface TextElement {- textRun?: TextRun;+async function batchUpdate({+ accessToken,+ presentationId,+ requests,+ requiredRevisionId,+}: {+ accessToken: string;+ presentationId: string;+ requests: unknown[];+ requiredRevisionId?: string;+}): Promise<BatchUpdateResponse> {+ return slidesRequest<BatchUpdateResponse>({+ accessToken,+ method: HttpMethod.POST,+ path: `${encodeURIComponent(presentationId)}:batchUpdate`,+ body: {+ requests,+ ...(requiredRevisionId ? { writeControl: { requiredRevisionId } } : {}),+ },+ });}-interface TextRun {- content?: string;+function decodeErrorPayload(data: unknown): unknown {+ const buffer = data instanceof ArrayBuffer ? Buffer.from(data) : data;+ const text = Buffer.isBuffer(buffer) ? buffer.toString('utf8') : buffer;+ if (typeof text !== 'string') {+ return text;+ }+ try {+ return JSON.parse(text);+ } catch {+ return text;+ }}-interface Table {- tableRows?: TableRow[];+function describeGoogleError(error: unknown): GoogleErrorInfo {+ if (typeof error !== 'object' || error === null) {+ return {};+ }+ const code = readField({ value: error, key: 'code' });+ const response = readField({ value: error, key: 'response' });+ const responseStatus = readField({ value: response, key: 'status' });+ const status = typeof responseStatus === 'number' ? responseStatus : typeof code === 'number' ? code : undefined;+ if (status === undefined) {+ return {};+ }+ const payload = readErrorPayload(response);+ if (typeof payload === 'string') {+ return { status, message: payload.slice(0, 500) };+ }+ const googleError = readField({ value: payload, key: 'error' });+ const message = readField({ value: googleError, key: 'message' });+ const errors = readField({ value: googleError, key: 'errors' });+ const reason = Array.isArray(errors) ? readField({ value: errors[0], key: 'reason' }) : undefined;+ return {+ status,+ message: typeof message === 'string' ? message : undefined,+ reason: typeof reason === 'string' ? reason : undefined,+ };}-interface TableRow {- tableCells?: TableCell[];+function readErrorPayload(response: unknown): unknown {+ for (const key of ['data', 'body']) {+ const decoded = decodeErrorPayload(readField({ value: response, key }));+ if (typeof decoded === 'string' || readField({ value: decoded, key: 'error' }) !== undefined) {+ return decoded;+ }+ }+ return undefined;}-export interface TableCell {- text?: Text;+function readField({ value, key }: { value: unknown; key: string }): unknown {+ if (typeof value !== 'object' || value === null || !(key in value)) {+ return undefined;+ }+ return Reflect.get(value, key);}-export const googleSheetsCommon = {- baseUrl: 'https://slides.googleapis.com/v1/presentations/',- batchUpdate,- getSlide,- createSlide-};+function googleApiError({ error, action }: { error: unknown; action: string }): Error {+ const { status, message, reason } = describeGoogleError(error);+ if (status === undefined) {+ return error instanceof Error ? error : new Error(String(error));+ }+ const detail = message ? ` Google says: ${message}` : '';+ if (reason === 'exportSizeLimitExceeded') {+ return new Error(+ `Could not ${action}: the presentation is larger than Google Drive's 10 MB export limit.${detail}`+ );+ }+ if (reason === 'storageQuotaExceeded') {+ return new Error(+ `Could not ${action}: the account has no Google Drive storage left. A service account has no storage of its own, so pick a folder in a Shared Drive it is a member of.${detail}`+ );+ }+ if (status === 400 && isRevisionMismatch(message)) {+ return new Error(+ `Could not ${action}: the presentation changed since it was read, so nothing was changed. Run the step again (for Batch Update, first get a fresh Required Revision ID from Get Presentation Outline).${detail}`+ );+ }+ switch (status) {+ case 400:+ return new Error(`Could not ${action}: Google rejected the request (400).${detail}${notFoundHint(message)}`);+ case 401:+ return new Error(+ `Could not ${action}: the Google connection is no longer valid (401). Reconnect the account.${detail}`+ );+ case 403:+ return new Error(+ `Could not ${action}: permission denied (403). Make sure the connected account (or service account) has access to this file, with edit access for changes.${detail}`+ );+ case 404:+ return new Error(+ `Could not ${action}: not found (404). Check the ID, and that the file is shared with the connected account.${detail}`+ );+ case 429:+ return new Error(`Could not ${action}: Google rate limit reached (429). Try again later.${detail}`);+ default:+ return new Error(`Could not ${action} (HTTP ${status}).${detail}`);+ }+}-export async function batchUpdate(access_token: string, slide_id: string, requests: any) {- return (- await httpClient.sendRequest<{- spreadsheetId: string;- }>({- method: HttpMethod.POST,- url: `https://slides.googleapis.com/v1/presentations/${slide_id}:batchUpdate`,- body: {- requests: requests- },- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: access_token,- },- })- ).body;+function isRevisionMismatch(message: string | undefined): boolean {+ return message !== undefined && /required revision ID .* does not match the latest revision/i.test(message);}-export async function getSlide(access_token: string, slide_id: string) {- return (- await httpClient.sendRequest<{- presentationId: string;- title: string;- slides: {- pageElements: any; objectId: object;-}[];- }>({- method: HttpMethod.GET,- url: `https://slides.googleapis.com/v1/presentations/${slide_id}`,- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: access_token,- },- })- ).body;+function notFoundHint(message: string | undefined): string {+ return message && /could not be found|not found/i.test(message)+ ? ' Check the object IDs with Get Presentation Outline or List Slide Elements.'+ : '';}-export async function createSlide(access_token: string, requests: any) {- return (- await httpClient.sendRequest<{- presentationId: string;- title: string;- spreadsheetId: string;- replies: any[];- }>({- method: HttpMethod.POST,- url: `https://slides.googleapis.com/v1/presentations`,- body: {- requests: requests- },- authentication: {- type: AuthenticationType.BEARER_TOKEN,- token: access_token,- },- })- ).body;-}\ No newline at end of file+export const SLIDES_API_BASE = 'https://slides.googleapis.com/v1/presentations';+export const PRESENTATION_MIME_TYPE = 'application/vnd.google-apps.presentation';++export const slidesApi = {+ getPresentation,+ getPage,+ getPageThumbnail,+ batchUpdate,+ presentationUrl,+ slideUrl,+ describeGoogleError,+ googleApiError,+};++type GoogleErrorInfo = { status?: number; message?: string; reason?: string };++export type Thumbnail = { width?: number; height?: number; contentUrl?: string };++export type TextElement = {+ textRun?: { content?: string };+ autoText?: { content?: string };+ paragraphMarker?: unknown;+};++export type TextContent = {+ textElements?: TextElement[];+};++export type Placeholder = {+ type?: string;+ index?: number;+ parentObjectId?: string;+};++export type TableCell = {+ text?: TextContent;+};++export type Dimension = { magnitude?: number; unit?: string };++export type Size = { width?: Dimension; height?: Dimension };++export type AffineTransform = {+ scaleX?: number;+ scaleY?: number;+ shearX?: number;+ shearY?: number;+ translateX?: number;+ translateY?: number;+ unit?: string;+};++export type PageElement = {+ objectId: string;+ size?: Size;+ transform?: AffineTransform;+ shape?: { shapeType?: string; text?: TextContent; placeholder?: Placeholder };+ table?: {+ rows?: number;+ columns?: number;+ tableColumns?: { columnWidth?: Dimension }[];+ tableRows?: { rowHeight?: Dimension; tableCells?: TableCell[] }[];+ };+ elementGroup?: { children?: PageElement[] };+ sheetsChart?: { spreadsheetId?: string; chartId?: number };+ image?: { contentUrl?: string; sourceUrl?: string };+ video?: { source?: string; id?: string; url?: string };+ line?: unknown;+ wordArt?: { renderedText?: string };+};++export type NotesPage = {+ objectId?: string;+ notesProperties?: { speakerNotesObjectId?: string };+ pageElements?: PageElement[];+};++export type Page = {+ objectId: string;+ pageType?: string;+ pageElements?: PageElement[];+ slideProperties?: {+ layoutObjectId?: string;+ masterObjectId?: string;+ isSkipped?: boolean;+ notesPage?: NotesPage;+ };+ layoutProperties?: {+ name?: string;+ displayName?: string;+ masterObjectId?: string;+ };+};++export type Presentation = {+ presentationId: string;+ title?: string;+ revisionId?: string;+ locale?: string;+ pageSize?: Size;+ slides?: Page[];+ layouts?: Page[];+ masters?: Page[];+};++export type BatchUpdateResponse = {+ presentationId: string;+ replies?: Record<string, unknown>[];+ writeControl?: { requiredRevisionId?: string };+};diff --git a/packages/pieces/community/google-slides/src/lib/commons/element-requests.ts b/packages/pieces/community/google-slides/src/lib/commons/element-requests.tsnew file mode 100644index 00000000000..8db6d0ff5d6--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/commons/element-requests.ts@@ -0,0 +1,596 @@+import { slidesElements, Box, ColorChoice, RgbColor, TextRange, TextTarget, VideoRef } from './elements';+import { slidesText } from './presentation-text';++function cellFields(target: TextTarget): Record<string, unknown> {+ return {+ objectId: target.objectId,+ ...(target.cellLocation ? { cellLocation: target.cellLocation } : {}),+ };+}++function solidFill(rgbColor: RgbColor): Record<string, unknown> {+ return { solidFill: { color: { rgbColor }, alpha: 1 } };+}++function appendIndex(text: string): number {+ return text.length > 0 ? text.length - 1 : 0;+}++function buildInsertTextRequest({+ target,+ text,+ insertionIndex,+}: {+ target: TextTarget;+ text: string;+ insertionIndex: number | undefined;+}): { request: Record<string, unknown>; insertedAt: number; newText: string } {+ if (text === '') {+ throw new Error('Text is empty. Give the text to insert.');+ }+ const maxIndex = appendIndex(target.text);+ const index = insertionIndex ?? maxIndex;+ if (index < 0 || index > maxIndex) {+ throw new Error(+ `Insertion Index must be between 0 and ${maxIndex} for "${target.objectId}" (its text has ${maxIndex} character(s)); leave it empty to append.`+ );+ }+ const visible = slidesText.stripTrailingNewlines(target.text);+ return {+ request: { insertText: { ...cellFields(target), text, insertionIndex: index } },+ insertedAt: index,+ newText: slidesText.stripTrailingNewlines(visible.slice(0, index) + text + visible.slice(index)),+ };+}++function buildSetTextRequests({ target, text }: { target: TextTarget; text: string }): Record<string, unknown>[] {+ const current = slidesText.stripTrailingNewlines(target.text);+ if (current === text) {+ return [];+ }+ return [+ ...(current.length > 0 ? [{ deleteText: { ...cellFields(target), textRange: { type: 'ALL' } } }] : []),+ ...(text.length > 0 ? [{ insertText: { ...cellFields(target), text, insertionIndex: 0 } }] : []),+ ];+}++function colorValue(choice: ColorChoice): Record<string, unknown> {+ return choice.kind === 'none' ? {} : { opaqueColor: { rgbColor: choice.rgbColor } };+}++function buildTextStyle(input: TextStyleInput): { style: Record<string, unknown>; fields: string[] } {+ const entries: [string, unknown][] = [+ ...booleanEntries(input),+ ...(input.fontFamily !== undefined ? [['fontFamily', input.fontFamily] satisfies [string, unknown]] : []),+ ...(input.fontSizePt !== undefined+ ? [['fontSize', { magnitude: input.fontSizePt, unit: 'PT' }] satisfies [string, unknown]]+ : []),+ ...(input.textColor !== undefined ? [['foregroundColor', colorValue(input.textColor)] satisfies [string, unknown]] : []),+ ...(input.highlightColor !== undefined+ ? [['backgroundColor', colorValue(input.highlightColor)] satisfies [string, unknown]]+ : []),+ ...(input.link !== undefined+ ? [['link', input.link === null ? undefined : { url: input.link }] satisfies [string, unknown]]+ : []),+ ];+ if (entries.length === 0) {+ throw new Error('Set at least one style to change (e.g. Bold, Font Size, Text Color).');+ }+ return {+ style: Object.fromEntries(entries.filter(([, value]) => value !== undefined)),+ fields: entries.map(([key]) => key),+ };+}++function booleanEntries(input: TextStyleInput): [string, unknown][] {+ return BOOLEAN_STYLES.flatMap((key) => (input[key] !== undefined ? [[key, input[key]] satisfies [string, unknown]] : []));+}++function buildTextStyleRequests({+ target,+ ranges,+ style,+ fields,+}: {+ target: TextTarget;+ ranges: TextRange[];+ style: Record<string, unknown>;+ fields: string[];+}): Record<string, unknown>[] {+ return ranges.map((textRange) => ({+ updateTextStyle: { ...cellFields(target), style, textRange, fields: fields.join(',') },+ }));+}++function buildParagraphRequests({+ target,+ ranges,+ input,+}: {+ target: TextTarget;+ ranges: TextRange[];+ input: ParagraphInput;+}): Record<string, unknown>[] {+ const entries: [string, unknown][] = [+ ...(input.alignment !== undefined ? [['alignment', input.alignment] satisfies [string, unknown]] : []),+ ...(input.lineSpacing !== undefined ? [['lineSpacing', input.lineSpacing] satisfies [string, unknown]] : []),+ ...(input.spaceAbovePt !== undefined+ ? [['spaceAbove', { magnitude: input.spaceAbovePt, unit: 'PT' }] satisfies [string, unknown]]+ : []),+ ...(input.spaceBelowPt !== undefined+ ? [['spaceBelow', { magnitude: input.spaceBelowPt, unit: 'PT' }] satisfies [string, unknown]]+ : []),+ ];+ if (entries.length === 0 && input.bullets === undefined) {+ throw new Error('Set at least one of Alignment, Line Spacing, Space Above, Space Below or Bullets.');+ }+ const styleRequests = entries.length+ ? ranges.map((textRange) => ({+ updateParagraphStyle: {+ ...cellFields(target),+ style: Object.fromEntries(entries),+ textRange,+ fields: entries.map(([key]) => key).join(','),+ },+ }))+ : [];+ const bulletRequests =+ input.bullets === undefined+ ? []+ : ranges.map((textRange) =>+ input.bullets === 'NONE'+ ? { deleteParagraphBullets: { ...cellFields(target), textRange } }+ : { createParagraphBullets: { ...cellFields(target), textRange, bulletPreset: input.bullets } }+ );+ return [...styleRequests, ...bulletRequests];+}++function buildShapeProperties(input: ShapeStyleInput): { shapeProperties: Record<string, unknown>; fields: string[] } {+ const fill = input.fillColor;+ const outlineOff = input.outlineColor?.kind === 'none';+ const outlineSet = input.outlineColor !== undefined || input.outlineWeightPt !== undefined || input.outlineDash !== undefined;+ if (outlineOff && (input.outlineWeightPt !== undefined || input.outlineDash !== undefined)) {+ throw new Error('Outline Color is "none": leave Outline Weight and Outline Dash empty, or pick an outline colour.');+ }+ const outlineColor = input.outlineColor?.kind === 'rgb' ? input.outlineColor.rgbColor : undefined;+ const shapeProperties: Record<string, unknown> = {+ ...(fill+ ? {+ shapeBackgroundFill:+ fill.kind === 'none' ? { propertyState: 'NOT_RENDERED' } : { propertyState: 'RENDERED', ...solidFill(fill.rgbColor) },+ }+ : {}),+ ...(outlineSet+ ? {+ outline: outlineOff+ ? { propertyState: 'NOT_RENDERED' }+ : {+ propertyState: 'RENDERED',+ ...(outlineColor ? { outlineFill: solidFill(outlineColor) } : {}),+ ...(input.outlineWeightPt !== undefined ? { weight: { magnitude: input.outlineWeightPt, unit: 'PT' } } : {}),+ ...(input.outlineDash !== undefined ? { dashStyle: input.outlineDash } : {}),+ },+ }+ : {}),+ ...(input.contentAlignment !== undefined ? { contentAlignment: input.contentAlignment } : {}),+ };+ const fields = [+ ...(fill ? (fill.kind === 'none' ? ['shapeBackgroundFill.propertyState'] : FILL_FIELDS) : []),+ ...(outlineSet ? ['outline.propertyState'] : []),+ ...(outlineColor ? ['outline.outlineFill.solidFill.color', 'outline.outlineFill.solidFill.alpha'] : []),+ ...(!outlineOff && input.outlineWeightPt !== undefined ? ['outline.weight'] : []),+ ...(!outlineOff && input.outlineDash !== undefined ? ['outline.dashStyle'] : []),+ ...(input.contentAlignment !== undefined ? ['contentAlignment'] : []),+ ];+ return { shapeProperties, fields };+}++function buildCreateShapeRequests({+ objectId,+ slideObjectId,+ shapeType,+ box,+ text,+ fillColor,+}: {+ objectId: string;+ slideObjectId: string;+ shapeType: string;+ box: Box;+ text: string | undefined;+ fillColor: ColorChoice | undefined;+}): Record<string, unknown>[] {+ const fill = fillColor ? buildShapeProperties({ fillColor }) : undefined;+ return [+ {+ createShape: {+ objectId,+ shapeType,+ elementProperties: slidesElements.buildElementProperties({ pageObjectId: slideObjectId, box }),+ },+ },+ ...(text ? [{ insertText: { objectId, text, insertionIndex: 0 } }] : []),+ ...(fill ? [{ updateShapeProperties: { objectId, shapeProperties: fill.shapeProperties, fields: fill.fields.join(',') } }] : []),+ ];+}++function readTableData(value: unknown): string[][] | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const parsed = typeof value === 'string' ? parseJsonArray(value) : value;+ if (!Array.isArray(parsed)) {+ throw new Error('Data must be a JSON array of rows, e.g. [["Name","Score"],["Ann","9"]].');+ }+ return parsed.map((row, rowIndex) => {+ if (!Array.isArray(row)) {+ throw new Error(`Data row ${rowIndex + 1} must be an array of cell values, e.g. ["Ann","9"].`);+ }+ return row.map((cell, columnIndex) => cellText({ cell, rowIndex, columnIndex }));+ });+}++function cellText({ cell, rowIndex, columnIndex }: { cell: unknown; rowIndex: number; columnIndex: number }): string {+ if (cell === null || cell === undefined) {+ return '';+ }+ if (typeof cell === 'string' || typeof cell === 'number' || typeof cell === 'boolean') {+ return String(cell);+ }+ throw new Error(`Data cell (row ${rowIndex + 1}, column ${columnIndex + 1}) must be text, a number or a boolean.`);+}++function parseJsonArray(value: string): unknown {+ try {+ return JSON.parse(value);+ } catch {+ throw new Error('Data must be valid JSON: an array of rows, e.g. [["Name","Score"],["Ann","9"]].');+ }+}++function resolveTableSize({+ rows,+ columns,+ data,+}: {+ rows: number | undefined;+ columns: number | undefined;+ data: string[][] | undefined;+}): { rows: number; columns: number } {+ const dataRows = data?.length ?? 0;+ const dataColumns = (data ?? []).reduce((widest, row) => (row.length > widest ? row.length : widest), 0);+ const finalRows = rows ?? dataRows;+ const finalColumns = columns ?? dataColumns;+ if (finalRows < 1 || finalColumns < 1) {+ throw new Error('Set Rows and Columns (at least 1 each), or give Data to size the table from.');+ }+ if (dataRows > finalRows || dataColumns > finalColumns) {+ throw new Error(+ `Data has ${dataRows} row(s) and up to ${dataColumns} column(s), which does not fit a ${finalRows} x ${finalColumns} table. Leave Rows/Columns empty to size the table from Data.`+ );+ }+ return { rows: finalRows, columns: finalColumns };+}++function buildCreateTableRequests({+ objectId,+ slideObjectId,+ rows,+ columns,+ data,+ box,+ headerBold,+ headerFill,+}: {+ objectId: string;+ slideObjectId: string;+ rows: number;+ columns: number;+ data: string[][];+ box: Box;+ headerBold: boolean;+ headerFill: RgbColor | undefined;+}): { requests: Record<string, unknown>[]; filledCells: number } {+ const cells = data.flatMap((row, rowIndex) =>+ row.flatMap((text, columnIndex) => (text === '' ? [] : [{ rowIndex, columnIndex, text }]))+ );+ const insertRequests = cells.map((cell) => ({+ insertText: {+ objectId,+ cellLocation: { rowIndex: cell.rowIndex, columnIndex: cell.columnIndex },+ text: cell.text,+ insertionIndex: 0,+ },+ }));+ const boldRequests = headerBold+ ? cells+ .filter((cell) => cell.rowIndex === 0)+ .map((cell) => ({+ updateTextStyle: {+ objectId,+ cellLocation: { rowIndex: 0, columnIndex: cell.columnIndex },+ style: { bold: true },+ textRange: { type: 'ALL' },+ fields: 'bold',+ },+ }))+ : [];+ const fillRequests = headerFill+ ? [+ {+ updateTableCellProperties: {+ objectId,+ tableRange: { location: { rowIndex: 0, columnIndex: 0 }, rowSpan: 1, columnSpan: columns },+ tableCellProperties: { tableCellBackgroundFill: solidFill(headerFill) },+ fields: 'tableCellBackgroundFill.solidFill.color,tableCellBackgroundFill.solidFill.alpha',+ },+ },+ ]+ : [];+ return {+ requests: [+ {+ createTable: {+ objectId,+ elementProperties: slidesElements.buildElementProperties({ pageObjectId: slideObjectId, box }),+ rows,+ columns,+ },+ },+ ...insertRequests,+ ...boldRequests,+ ...fillRequests,+ ],+ filledCells: cells.length,+ };+}++function buildInsertTableLinesRequests({+ tableObjectId,+ dimension,+ rows,+ columns,+ position,+ count,+ values,+}: {+ tableObjectId: string;+ dimension: TableDimension;+ rows: number;+ columns: number;+ position: number | undefined;+ count: number;+ values: string[] | undefined;+}): { requests: Record<string, unknown>[]; insertedAt: number } {+ const isRow = dimension === 'ROW';+ const total = isRow ? rows : columns;+ const at = position ?? total + 1;+ if (at < 1 || at > total + 1) {+ throw new Error(`Position must be between 1 and ${total + 1} (the table has ${total} ${isRow ? 'row' : 'column'}(s)); leave it empty to add at the end.`);+ }+ if (count < 1 || count > MAX_TABLE_INSERT) {+ throw new Error(`Count must be between 1 and ${MAX_TABLE_INSERT} (Google's limit per request), got ${count}.`);+ }+ const across = isRow ? columns : rows;+ if (values && (count !== 1 || values.length > across)) {+ throw new Error(+ `Values fill one new ${isRow ? 'row' : 'column'}: set Count to 1 and give at most ${across} value(s), got ${values.length}.`+ );+ }+ const before = at <= total;+ const anchor = before ? at - 1 : total - 1;+ const insert = isRow+ ? { insertTableRows: { tableObjectId, cellLocation: { rowIndex: anchor, columnIndex: 0 }, insertBelow: !before, number: count } }+ : { insertTableColumns: { tableObjectId, cellLocation: { rowIndex: 0, columnIndex: anchor }, insertRight: !before, number: count } };+ const fills = (values ?? []).flatMap((text, offset) =>+ text === ''+ ? []+ : [+ {+ insertText: {+ objectId: tableObjectId,+ cellLocation: isRow ? { rowIndex: at - 1, columnIndex: offset } : { rowIndex: offset, columnIndex: at - 1 },+ text,+ insertionIndex: 0,+ },+ },+ ]+ );+ return { requests: [insert, ...fills], insertedAt: at };+}++function buildDeleteTableLinesRequests({+ tableObjectId,+ dimension,+ rows,+ columns,+ position,+ count,+}: {+ tableObjectId: string;+ dimension: TableDimension;+ rows: number;+ columns: number;+ position: number;+ count: number;+}): Record<string, unknown>[] {+ const isRow = dimension === 'ROW';+ const total = isRow ? rows : columns;+ const noun = isRow ? 'row' : 'column';+ if (count < 1) {+ throw new Error(`Count must be at least 1, got ${count}.`);+ }+ if (position < 1 || position + count - 1 > total) {+ throw new Error(`Cannot delete ${count} ${noun}(s) from position ${position}: the table has ${total} ${noun}(s), numbered from 1.`);+ }+ if (count >= total) {+ throw new Error(`A table needs at least one ${noun}. To remove the whole table, use Delete Elements with its object ID.`);+ }+ const location = isRow ? { rowIndex: position - 1, columnIndex: 0 } : { rowIndex: 0, columnIndex: position - 1 };+ return Array.from({ length: count }, () =>+ isRow+ ? { deleteTableRow: { tableObjectId, cellLocation: location } }+ : { deleteTableColumn: { tableObjectId, cellLocation: location } }+ );+}++function buildBackgroundRequests({+ slideObjectIds,+ background,+}: {+ slideObjectIds: string[];+ background: Background;+}): Record<string, unknown>[] {+ const fill =+ background.kind === 'color'+ ? { solidFill: { color: { rgbColor: background.rgbColor }, alpha: 1 } }+ : { stretchedPictureFill: { contentUrl: background.imageUrl } };+ return slideObjectIds.map((objectId) => ({+ updatePageProperties: { objectId, pageProperties: { pageBackgroundFill: fill }, fields: 'pageBackgroundFill' },+ }));+}++function buildCreateVideoRequest({+ objectId,+ slideObjectId,+ video,+ box,+}: {+ objectId: string;+ slideObjectId: string;+ video: VideoRef;+ box: Box;+}): Record<string, unknown> {+ return {+ createVideo: {+ objectId,+ source: video.source,+ id: video.id,+ elementProperties: slidesElements.buildElementProperties({ pageObjectId: slideObjectId, box }),+ },+ };+}++function buildReplaceImageRequest({+ imageObjectId,+ url,+ method,+}: {+ imageObjectId: string;+ url: string;+ method: string;+}): Record<string, unknown> {+ return { replaceImage: { imageObjectId, url, imageReplaceMethod: method } };+}++function isTableDimension(value: unknown): value is TableDimension {+ return value === 'ROW' || value === 'COLUMN';+}++const BOOLEAN_STYLES: BooleanStyle[] = ['bold', 'italic', 'underline', 'strikethrough'];+const FILL_FIELDS = ['shapeBackgroundFill.propertyState', 'shapeBackgroundFill.solidFill.color', 'shapeBackgroundFill.solidFill.alpha'];+const MAX_TABLE_INSERT = 20;++export const SHAPE_TYPES: string[] = [+ 'TEXT_BOX',+ 'RECTANGLE',+ 'ROUND_RECTANGLE',+ 'ELLIPSE',+ 'TRIANGLE',+ 'RIGHT_TRIANGLE',+ 'DIAMOND',+ 'PENTAGON',+ 'HEXAGON',+ 'OCTAGON',+ 'PARALLELOGRAM',+ 'TRAPEZOID',+ 'CHEVRON',+ 'HOME_PLATE',+ 'RIGHT_ARROW',+ 'LEFT_ARROW',+ 'UP_ARROW',+ 'DOWN_ARROW',+ 'LEFT_RIGHT_ARROW',+ 'STAR_5',+ 'HEART',+ 'CLOUD',+ 'PLUS',+ 'DONUT',+ 'WEDGE_RECTANGLE_CALLOUT',+ 'WEDGE_ROUND_RECTANGLE_CALLOUT',+ 'FLOW_CHART_PROCESS',+ 'FLOW_CHART_DECISION',+ 'FLOW_CHART_TERMINATOR',+];++export const BULLET_PRESETS: string[] = [+ 'BULLET_DISC_CIRCLE_SQUARE',+ 'BULLET_ARROW_DIAMOND_DISC',+ 'BULLET_CHECKBOX',+ 'BULLET_STAR_CIRCLE_SQUARE',+ 'NUMBERED_DIGIT_ALPHA_ROMAN',+ 'NUMBERED_DIGIT_ALPHA_ROMAN_PARENS',+ 'NUMBERED_DIGIT_NESTED',+ 'NUMBERED_UPPERALPHA_ALPHA_ROMAN',+ 'NUMBERED_UPPERROMAN_UPPERALPHA_DIGIT',+ 'NONE',+];++export const PARAGRAPH_ALIGNMENTS: string[] = ['START', 'CENTER', 'END', 'JUSTIFIED'];+export const CONTENT_ALIGNMENTS: string[] = ['TOP', 'MIDDLE', 'BOTTOM'];+export const DASH_STYLES: string[] = ['SOLID', 'DOT', 'DASH', 'DASH_DOT', 'LONG_DASH', 'LONG_DASH_DOT'];+export const IMAGE_REPLACE_METHODS: string[] = ['CENTER_INSIDE', 'CENTER_CROP'];+export const TABLE_DIMENSIONS: TableDimension[] = ['ROW', 'COLUMN'];++export const slidesElementRequests = {+ buildInsertTextRequest,+ buildSetTextRequests,+ buildTextStyle,+ buildTextStyleRequests,+ buildParagraphRequests,+ buildShapeProperties,+ buildCreateShapeRequests,+ readTableData,+ resolveTableSize,+ buildCreateTableRequests,+ buildInsertTableLinesRequests,+ buildDeleteTableLinesRequests,+ buildBackgroundRequests,+ buildCreateVideoRequest,+ buildReplaceImageRequest,+ isTableDimension,+};++export type TableDimension = 'ROW' | 'COLUMN';++export type BooleanStyle = 'bold' | 'italic' | 'underline' | 'strikethrough';++export type TextStyleInput = {+ bold?: boolean;+ italic?: boolean;+ underline?: boolean;+ strikethrough?: boolean;+ fontFamily?: string;+ fontSizePt?: number;+ textColor?: ColorChoice;+ highlightColor?: ColorChoice;+ link?: string | null;+};++export type ParagraphInput = {+ alignment?: string;+ lineSpacing?: number;+ spaceAbovePt?: number;+ spaceBelowPt?: number;+ bullets?: string;+};++export type ShapeStyleInput = {+ fillColor?: ColorChoice;+ outlineColor?: ColorChoice;+ outlineWeightPt?: number;+ outlineDash?: string;+ contentAlignment?: string;+};++export type Background = { kind: 'color'; rgbColor: RgbColor; hex: string } | { kind: 'image'; imageUrl: string };diff --git a/packages/pieces/community/google-slides/src/lib/commons/elements.ts b/packages/pieces/community/google-slides/src/lib/commons/elements.tsnew file mode 100644index 00000000000..c432c1196df--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/commons/elements.ts@@ -0,0 +1,732 @@+import { AffineTransform, Dimension, PageElement, Presentation, Size, slidesApi } from './common';+import { slidesText } from './presentation-text';+import { slidesRequests } from './requests';++function ptToEmu(pt: number): number {+ return Math.round(pt * EMU_PER_PT);+}++function emuToPt(emu: number): number {+ return Math.round((emu / EMU_PER_PT) * 100) / 100;+}++function dimensionToEmu(dimension: Dimension | undefined): number | undefined {+ if (dimension?.magnitude === undefined) {+ return undefined;+ }+ return dimension.unit === 'PT' ? dimension.magnitude * EMU_PER_PT : dimension.magnitude;+}++function readElementId({ value, label }: { value: unknown; label: string }): string {+ const id = typeof value === 'string' ? value.trim() : '';+ if (!id) {+ throw new Error(`${label} is required. Get element object IDs from List Slide Elements or Get Presentation Outline.`);+ }+ if (!OBJECT_ID.test(id)) {+ throw new Error(`${label} "${id}" is not a valid object ID (letters, digits, "_", "-" and ":" only).`);+ }+ return id;+}++function readElementIds({ value, label }: { value: unknown; label: string }): string[] {+ const items = Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value];+ const ids = items+ .filter((item) => !(typeof item === 'string' && item.trim() === ''))+ .map((item) => readElementId({ value: item, label }));+ if (ids.length === 0) {+ throw new Error(`${label}: give at least one element object ID.`);+ }+ return Array.from(new Set(ids));+}++function readBoolean({ value, label }: { value: unknown; label: string }): boolean | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ if (typeof value === 'boolean') {+ return value;+ }+ const text = String(value).trim().toLowerCase();+ if (text === 'true' || text === 'false') {+ return text === 'true';+ }+ throw new Error(`${label} must be true or false, got "${String(value)}".`);+}++function readText(value: unknown): string | undefined {+ if (value === undefined || value === null) {+ return undefined;+ }+ return typeof value === 'string' ? value : String(value);+}++function readEnum({ value, label, allowed }: { value: unknown; label: string; allowed: readonly string[] }): string | undefined {+ const text = typeof value === 'string' ? value.trim().toUpperCase() : '';+ if (!text) {+ return undefined;+ }+ if (!allowed.includes(text)) {+ throw new Error(`${label} must be one of ${allowed.join(', ')}, got "${String(value)}".`);+ }+ return text;+}++function normaliseHex(value: string): string {+ const hex = value.trim().replace(/^#/, '');+ const full = /^[0-9a-f]{3}$/i.test(hex) ? hex.replace(/./g, (char) => char + char) : hex;+ return `#${full.toUpperCase()}`;+}++function parseHexColor({ value, label }: { value: string; label: string }): RgbColor {+ const full = normaliseHex(value).slice(1);+ if (!/^[0-9a-f]{6}$/i.test(full)) {+ throw new Error(`${label} must be a hex colour like #1A73E8, got "${value}".`);+ }+ const channel = (offset: number) => Math.round((parseInt(full.slice(offset, offset + 2), 16) / 255) * 10000) / 10000;+ return { red: channel(0), green: channel(2), blue: channel(4) };+}++function readColor({ value, label }: { value: unknown; label: string }): ColorChoice | undefined {+ const text = typeof value === 'string' ? value.trim() : '';+ if (!text) {+ return undefined;+ }+ if (NONE_WORDS.includes(text.toLowerCase())) {+ return { kind: 'none' };+ }+ return { kind: 'rgb', rgbColor: parseHexColor({ value: text, label }) };+}++function readPositive({ value, label }: { value: unknown; label: string }): number | undefined {+ const number = slidesRequests.toNumber({ value, label });+ if (number !== undefined && number <= 0) {+ throw new Error(`${label} must be greater than 0, got ${number}.`);+ }+ return number;+}++function readBox({+ x,+ y,+ width,+ height,+ required,+}: {+ x: unknown;+ y: unknown;+ width: unknown;+ height: unknown;+ required: boolean;+}): Box {+ const left = slidesRequests.toNumber({ value: x, label: 'X (pt)' });+ const top = slidesRequests.toNumber({ value: y, label: 'Y (pt)' });+ const w = readPositive({ value: width, label: 'Width (pt)' });+ const h = readPositive({ value: height, label: 'Height (pt)' });+ if (required && (left === undefined || top === undefined || w === undefined || h === undefined)) {+ throw new Error('Set X, Y, Width and Height in points (a standard 16:9 slide is 720 x 405 pt).');+ }+ if ((left === undefined) !== (top === undefined)) {+ throw new Error('Set both X and Y, or leave both empty.');+ }+ if ((w === undefined) !== (h === undefined)) {+ throw new Error('Set both Width and Height, or leave both empty.');+ }+ return {+ ...(left !== undefined && top !== undefined ? { position: { x: left, y: top } } : {}),+ ...(w !== undefined && h !== undefined ? { size: { width: w, height: h } } : {}),+ };+}++function buildElementProperties({ pageObjectId, box }: { pageObjectId: string; box: Box }): Record<string, unknown> {+ return {+ pageObjectId,+ ...(box.size+ ? {+ size: {+ width: { magnitude: ptToEmu(box.size.width), unit: 'EMU' },+ height: { magnitude: ptToEmu(box.size.height), unit: 'EMU' },+ },+ }+ : {}),+ ...(box.position+ ? {+ transform: {+ scaleX: 1,+ scaleY: 1,+ shearX: 0,+ shearY: 0,+ translateX: ptToEmu(box.position.x),+ translateY: ptToEmu(box.position.y),+ unit: 'EMU',+ },+ }+ : {}),+ };+}++function toMatrix(transform: AffineTransform | undefined): Matrix {+ if (!transform) {+ return IDENTITY;+ }+ const unitFactor = transform.unit === 'PT' ? EMU_PER_PT : 1;+ return {+ a: transform.scaleX ?? 0,+ b: transform.shearY ?? 0,+ c: transform.shearX ?? 0,+ d: transform.scaleY ?? 0,+ e: (transform.translateX ?? 0) * unitFactor,+ f: (transform.translateY ?? 0) * unitFactor,+ };+}++function composeMatrix({ parent, child }: { parent: Matrix; child: Matrix }): Matrix {+ return {+ a: parent.a * child.a + parent.c * child.b,+ b: parent.b * child.a + parent.d * child.b,+ c: parent.a * child.c + parent.c * child.d,+ d: parent.b * child.c + parent.d * child.d,+ e: parent.a * child.e + parent.c * child.f + parent.e,+ f: parent.b * child.e + parent.d * child.f + parent.f,+ };+}++function matrixToTransform(matrix: Matrix): Required<AffineTransform> {+ return {+ scaleX: matrix.a,+ scaleY: matrix.d,+ shearX: matrix.c,+ shearY: matrix.b,+ translateX: Math.round(matrix.e),+ translateY: Math.round(matrix.f),+ unit: 'EMU',+ };+}++function elementGeometry({ matrix, size }: { matrix: Matrix; size: Size | undefined }): ElementGeometry {+ const width = dimensionToEmu(size?.width);+ const height = dimensionToEmu(size?.height);+ return {+ x: emuToPt(matrix.e),+ y: emuToPt(matrix.f),+ width: width === undefined ? null : emuToPt(width * Math.hypot(matrix.a, matrix.b)),+ height: height === undefined ? null : emuToPt(height * Math.hypot(matrix.c, matrix.d)),+ rotationDegrees: rotationOf(matrix),+ };+}++function effectiveSize(element: PageElement): Size | undefined {+ if (!element.table) {+ return element.size;+ }+ const sum = (dimensions: (Dimension | undefined)[]) =>+ dimensions.reduce((total, dimension) => total + (dimensionToEmu(dimension) ?? 0), 0);+ const width = sum((element.table.tableColumns ?? []).map((column) => column.columnWidth));+ const height = sum((element.table.tableRows ?? []).map((row) => row.rowHeight));+ return width > 0 && height > 0+ ? { width: { magnitude: width, unit: 'EMU' }, height: { magnitude: height, unit: 'EMU' } }+ : element.size;+}++function rotationOf(matrix: Matrix): number {+ const rotation = Math.round((Math.atan2(matrix.b, matrix.a) * 180) / Math.PI);+ return rotation === 0 ? 0 : rotation;+}++function groupBounds({ groupId, entries }: { groupId: string; entries: ElementEntry[] }): Bounds | null {+ const corners = entries+ .filter((entry) => entry.ancestorGroupIds.includes(groupId) && !entry.element.elementGroup)+ .flatMap((entry) => {+ const size = effectiveSize(entry.element);+ const width = dimensionToEmu(size?.width) ?? 0;+ const height = dimensionToEmu(size?.height) ?? 0;+ const { a, b, c, d, e, f } = entry.matrix;+ return [+ { x: e, y: f },+ { x: a * width + e, y: b * width + f },+ { x: c * height + e, y: d * height + f },+ { x: a * width + c * height + e, y: b * width + d * height + f },+ ];+ });+ if (corners.length === 0) {+ return null;+ }+ const left = corners.reduce((min, point) => (point.x < min ? point.x : min), Number.POSITIVE_INFINITY);+ const top = corners.reduce((min, point) => (point.y < min ? point.y : min), Number.POSITIVE_INFINITY);+ const right = corners.reduce((max, point) => (point.x > max ? point.x : max), Number.NEGATIVE_INFINITY);+ const bottom = corners.reduce((max, point) => (point.y > max ? point.y : max), Number.NEGATIVE_INFINITY);+ return { left, top, right, bottom };+}++function entryGeometry({ entry, entries }: { entry: ElementEntry; entries: ElementEntry[] }): ElementGeometry {+ if (!entry.element.elementGroup) {+ return elementGeometry({ matrix: entry.matrix, size: effectiveSize(entry.element) });+ }+ const bounds = groupBounds({ groupId: entry.element.objectId, entries });+ if (!bounds) {+ return { ...elementGeometry({ matrix: entry.matrix, size: undefined }) };+ }+ return {+ x: emuToPt(bounds.left),+ y: emuToPt(bounds.top),+ width: emuToPt(bounds.right - bounds.left),+ height: emuToPt(bounds.bottom - bounds.top),+ rotationDegrees: rotationOf(entry.matrix),+ };+}++function flattenWithParents({+ elements,+ parent,+}: {+ elements: PageElement[] | undefined;+ parent: { ancestorGroupIds: string[]; matrix: Matrix };+}): ElementEntry[] {+ return (elements ?? []).flatMap((element) => {+ const matrix = composeMatrix({ parent: parent.matrix, child: toMatrix(element.transform) });+ const parentGroupId = parent.ancestorGroupIds[parent.ancestorGroupIds.length - 1] ?? null;+ return [+ { element, parentGroupId, ancestorGroupIds: parent.ancestorGroupIds, matrix },+ ...flattenWithParents({+ elements: element.elementGroup?.children,+ parent: { ancestorGroupIds: [...parent.ancestorGroupIds, element.objectId], matrix },+ }),+ ];+ });+}++function slideEntries(elements: PageElement[] | undefined): ElementEntry[] {+ return flattenWithParents({ elements, parent: { ancestorGroupIds: [], matrix: IDENTITY } });+}++async function fetchDeck({ accessToken, presentationId }: { accessToken: string; presentationId: string }): Promise<Presentation> {+ return slidesApi.getPresentation({ accessToken, presentationId, fields: DECK_FIELDS });+}++async function loadElement({+ accessToken,+ presentationId,+ objectId,+ action,+}: {+ accessToken: string;+ presentationId: string;+ objectId: string;+ action: string;+}): Promise<LocatedElement> {+ const presentation = await fetchDeck({ accessToken, presentationId }).catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+ return locateElement({ presentation, objectId });+}++async function applyRequests({+ accessToken,+ presentationId,+ requests,+ revisionId,+ action,+}: {+ accessToken: string;+ presentationId: string;+ requests: unknown[];+ revisionId?: string;+ action: string;+}): Promise<void> {+ if (requests.length === 0) {+ return;+ }+ await slidesApi+ .batchUpdate({ accessToken, presentationId, requests, requiredRevisionId: revisionId })+ .catch((error: unknown) => {+ throw slidesApi.googleApiError({ error, action });+ });+}++function locateElement({ presentation, objectId }: { presentation: Presentation; objectId: string }): LocatedElement {+ const slides = presentation.slides ?? [];+ for (const slide of slides) {+ const entries = slideEntries(slide.pageElements);+ const entry = entries.find((candidate) => candidate.element.objectId === objectId);+ if (entry) {+ return {+ ...entry,+ slideEntries: entries,+ slideObjectId: slide.objectId,+ type: slidesText.elementType(entry.element),+ revisionId: presentation.revisionId,+ };+ }+ }+ if (slides.some((slide) => slide.objectId === objectId)) {+ throw new Error(+ `"${objectId}" is a slide, not an element on a slide. Pass element object IDs (from List Slide Elements or Get Presentation Outline elements[].objectId); use the slide actions (e.g. Delete Slide, Set Slide Background) for whole slides.`+ );+ }+ throw new Error(+ `No element with object ID "${objectId}" on any slide of this presentation. Get element object IDs from List Slide Elements or Get Presentation Outline (slides[].elements[].objectId); speaker-notes, layout and master elements are not supported.`+ );+}++function requireType({ located, types, purpose }: { located: LocatedElement; types: string[]; purpose: string }): void {+ if (!types.includes(located.type)) {+ throw new Error(+ `Element "${located.element.objectId}" is ${articleFor(located.type)} ${located.type}; ${purpose}. Use List Slide Elements to see each element's type.`+ );+ }+}++function articleFor(type: string): string {+ return /^[AEIOU]/.test(type) ? 'an' : 'a';+}++function resolveTextTarget({+ located,+ row,+ column,+}: {+ located: LocatedElement;+ row: unknown;+ column: unknown;+}): TextTarget {+ const rowNumber = slidesRequests.toInteger({ value: row, label: 'Row' });+ const columnNumber = slidesRequests.toInteger({ value: column, label: 'Column' });+ const objectId = located.element.objectId;+ if (located.type === 'SHAPE') {+ if (rowNumber !== undefined || columnNumber !== undefined) {+ throw new Error(`Element "${objectId}" is a shape; Row and Column are only for table cells. Leave them empty.`);+ }+ return { objectId, text: slidesText.joinText(located.element.shape?.text) };+ }+ if (located.type === 'TABLE') {+ const { rows, columns } = tableSize(located.element);+ if (rowNumber === undefined || columnNumber === undefined) {+ throw new Error(`Element "${objectId}" is a table (${rows} x ${columns}): set Row and Column (starting at 1) to pick the cell.`);+ }+ if (rowNumber < 1 || rowNumber > rows || columnNumber < 1 || columnNumber > columns) {+ throw new Error(+ `Cell (row ${rowNumber}, column ${columnNumber}) is outside the table "${objectId}", which has ${rows} row(s) and ${columns} column(s). Rows and columns start at 1.`+ );+ }+ const cell = located.element.table?.tableRows?.[rowNumber - 1]?.tableCells?.[columnNumber - 1];+ return {+ objectId,+ cellLocation: { rowIndex: rowNumber - 1, columnIndex: columnNumber - 1 },+ text: slidesText.joinText(cell?.text),+ };+ }+ throw new Error(+ `Element "${objectId}" is ${articleFor(located.type)} ${located.type}; text actions work on shapes, text boxes, placeholders and table cells. Use List Slide Elements to find one.`+ );+}++function tableSize(element: PageElement): { rows: number; columns: number } {+ const tableRows = element.table?.tableRows ?? [];+ return {+ rows: element.table?.rows ?? tableRows.length,+ columns: element.table?.columns ?? tableRows[0]?.tableCells?.length ?? 0,+ };+}++function resolveTextRanges({+ target,+ matchText,+ startIndex,+ endIndex,+}: {+ target: TextTarget;+ matchText: unknown;+ startIndex: unknown;+ endIndex: unknown;+}): TextRange[] {+ const visible = slidesText.stripTrailingNewlines(target.text);+ if (visible.length === 0) {+ throw new Error(`Element "${target.objectId}" has no text yet. Add text with Insert Text or Set Element Text first.`);+ }+ const match = typeof matchText === 'string' && matchText !== '' ? matchText : undefined;+ const start = slidesRequests.toInteger({ value: startIndex, label: 'Start Index' });+ const end = slidesRequests.toInteger({ value: endIndex, label: 'End Index' });+ if (match !== undefined && (start !== undefined || end !== undefined)) {+ throw new Error('Set either Match Text or Start/End Index, not both.');+ }+ if (match !== undefined) {+ const ranges = findOccurrences({ text: visible, match });+ if (ranges.length === 0) {+ throw new Error(`"${match}" does not appear in the text of "${target.objectId}" (match is case-sensitive). Its text is: "${visible.slice(0, 200)}".`);+ }+ return ranges;+ }+ if (start === undefined && end === undefined) {+ return [{ type: 'ALL' }];+ }+ const from = start ?? 0;+ const to = end ?? visible.length;+ if (from < 0 || to > target.text.length || from >= to) {+ throw new Error(+ `Start/End Index must satisfy 0 <= start < end <= ${target.text.length} for "${target.objectId}", got start ${from}, end ${to}.`+ );+ }+ return [{ type: 'FIXED_RANGE', startIndex: from, endIndex: to }];+}++function findOccurrences({ text, match }: { text: string; match: string }): TextRange[] {+ const ranges: TextRange[] = [];+ let index = text.indexOf(match);+ while (index !== -1) {+ ranges.push({ type: 'FIXED_RANGE', startIndex: index, endIndex: index + match.length });+ index = text.indexOf(match, index + match.length);+ }+ return ranges;+}++function computeMoveResize({+ located,+ x,+ y,+ width,+ height,+}: {+ located: LocatedElement;+ x: unknown;+ y: unknown;+ width: unknown;+ height: unknown;+}): MoveResult {+ const objectId = located.element.objectId;+ if (located.parentGroupId) {+ throw new Error(+ `Element "${objectId}" is inside the group "${located.parentGroupId}", whose children are positioned relative to the group. Move the group "${located.parentGroupId}" instead.`+ );+ }+ const left = slidesRequests.toNumber({ value: x, label: 'X (pt)' });+ const top = slidesRequests.toNumber({ value: y, label: 'Y (pt)' });+ const newWidth = readPositive({ value: width, label: 'Width (pt)' });+ const newHeight = readPositive({ value: height, label: 'Height (pt)' });+ if ([left, top, newWidth, newHeight].every((value) => value === undefined)) {+ throw new Error('Set at least one of X, Y, Width or Height (in points).');+ }+ const current = toMatrix(located.element.transform);+ if (located.element.elementGroup) {+ return moveGroup({ located, current, left, top, resize: newWidth !== undefined || newHeight !== undefined });+ }+ if (located.element.table && (newWidth !== undefined || newHeight !== undefined)) {+ throw new Error(+ `Element "${objectId}" is a table: it can only be moved (X/Y) here. Table size comes from its column widths and row heights; change them with Batch Update (updateTableColumnProperties / updateTableRowProperties).`+ );+ }+ const scaled =+ newWidth === undefined && newHeight === undefined+ ? current+ : scaleMatrix({ located, matrix: current, width: newWidth, height: newHeight });+ const matrix = {+ ...scaled,+ e: left === undefined ? current.e : ptToEmu(left),+ f: top === undefined ? current.f : ptToEmu(top),+ };+ return { transform: matrixToTransform(matrix), geometry: elementGeometry({ matrix, size: effectiveSize(located.element) }) };+}++function moveGroup({+ located,+ current,+ left,+ top,+ resize,+}: {+ located: LocatedElement;+ current: Matrix;+ left: number | undefined;+ top: number | undefined;+ resize: boolean;+}): MoveResult {+ const objectId = located.element.objectId;+ const bounds = groupBounds({ groupId: objectId, entries: located.slideEntries });+ if (resize || !bounds) {+ throw new Error(+ `Element "${objectId}" is a group: it can only be moved (X/Y). To resize, resize its elements or use Batch Update.`+ );+ }+ const deltaX = left === undefined ? 0 : ptToEmu(left) - bounds.left;+ const deltaY = top === undefined ? 0 : ptToEmu(top) - bounds.top;+ const matrix = { ...current, e: current.e + deltaX, f: current.f + deltaY };+ return {+ transform: matrixToTransform(matrix),+ geometry: {+ x: emuToPt(bounds.left + deltaX),+ y: emuToPt(bounds.top + deltaY),+ width: emuToPt(bounds.right - bounds.left),+ height: emuToPt(bounds.bottom - bounds.top),+ rotationDegrees: rotationOf(current),+ },+ };+}++function scaleMatrix({+ located,+ matrix,+ width,+ height,+}: {+ located: LocatedElement;+ matrix: Matrix;+ width: number | undefined;+ height: number | undefined;+}): Matrix {+ const objectId = located.element.objectId;+ if (matrix.b !== 0 || matrix.c !== 0) {+ throw new Error(`Element "${objectId}" is rotated or skewed, so it cannot be resized here. Use Batch Update with updatePageElementTransform.`);+ }+ const baseWidth = dimensionToEmu(located.element.size?.width) ?? 0;+ const baseHeight = dimensionToEmu(located.element.size?.height) ?? 0;+ const currentWidth = Math.abs(baseWidth * matrix.a);+ const currentHeight = Math.abs(baseHeight * matrix.d);+ if ((width !== undefined && baseWidth === 0) || (height !== undefined && baseHeight === 0)) {+ throw new Error(`Element "${objectId}" has no width or height to scale (for example a straight line). Only move it, or use Batch Update.`);+ }+ if ((width === undefined && currentWidth === 0) || (height === undefined && currentHeight === 0)) {+ throw new Error(`Element "${objectId}" has a zero width or height, so its aspect ratio cannot be kept. Set both Width and Height.`);+ }+ const widthFactor = width !== undefined ? ptToEmu(width) / currentWidth : ptToEmu(height ?? 0) / currentHeight;+ const heightFactor = height !== undefined ? ptToEmu(height) / currentHeight : widthFactor;+ return { ...matrix, a: matrix.a * widthFactor, d: matrix.d * heightFactor };+}++function readVideo({ value, source }: { value: unknown; source: unknown }): VideoRef {+ const text = typeof value === 'string' ? value.trim() : '';+ const chosen = readEnum({ value: source, label: 'Source', allowed: VIDEO_SOURCES });+ if (!text) {+ throw new Error('Video is required: paste a YouTube or Google Drive video URL, or the video ID.');+ }+ if (/^https?:\/\//i.test(text)) {+ const fromUrl = videoFromUrl(text);+ if (chosen && chosen !== fromUrl.source) {+ throw new Error(`Source is ${chosen} but the URL is a ${fromUrl.source} link. Leave Source empty for URLs.`);+ }+ return fromUrl;+ }+ if (!/^[A-Za-z0-9_-]+$/.test(text)) {+ throw new Error(`"${text}" is not a valid video ID.`);+ }+ if (chosen) {+ return { source: chosen, id: text };+ }+ if (YOUTUBE_ID.test(text)) {+ return { source: 'YOUTUBE', id: text };+ }+ throw new Error(`"${text}" is not an 11-character YouTube ID. For a Google Drive video, set Source to DRIVE or paste its URL.`);+}++function videoFromUrl(text: string): VideoRef {+ let url: URL;+ try {+ url = new URL(text);+ } catch {+ throw new Error(`"${text}" is not a valid URL.`);+ }+ const host = url.hostname.toLowerCase();+ const youtubeId =+ host === 'youtu.be'+ ? url.pathname.split('/')[1]+ : YOUTUBE_HOSTS.includes(host)+ ? url.searchParams.get('v') ?? url.pathname.match(/^\/(?:embed|shorts|live)\/([^/]+)/)?.[1]+ : undefined;+ if (youtubeId && YOUTUBE_ID.test(youtubeId)) {+ return { source: 'YOUTUBE', id: youtubeId };+ }+ const driveId =+ host === 'drive.google.com'+ ? url.pathname.match(/^\/file\/(?:u\/\d+\/)?d\/([A-Za-z0-9_-]{10,})/)?.[1] ??+ (url.pathname === '/open' ? url.searchParams.get('id') : null)+ : null;+ if (driveId && /^[A-Za-z0-9_-]{10,}$/.test(driveId)) {+ return { source: 'DRIVE', id: driveId };+ }+ throw new Error(+ `"${text}" is not a YouTube (youtube.com/watch?v=…, youtu.be/…) or Google Drive (drive.google.com/file/d/…) video URL.`+ );+}++const EMU_PER_PT = 12700;+const OBJECT_ID = /^[A-Za-z0-9_:-]+$/;+const NONE_WORDS = ['none', 'transparent'];+const IDENTITY: Matrix = { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 };+const DECK_FIELDS = 'presentationId,revisionId,pageSize,slides(objectId,pageElements)';+const YOUTUBE_ID = /^[A-Za-z0-9_-]{11}$/;+const YOUTUBE_HOSTS = ['youtube.com', 'www.youtube.com', 'm.youtube.com', 'youtube-nocookie.com', 'www.youtube-nocookie.com'];++export const VIDEO_SOURCES: string[] = ['YOUTUBE', 'DRIVE'];++export const slidesElements = {+ ptToEmu,+ emuToPt,+ dimensionToEmu,+ readElementId,+ readElementIds,+ readBoolean,+ readText,+ readEnum,+ normaliseHex,+ parseHexColor,+ readColor,+ readPositive,+ readBox,+ buildElementProperties,+ toMatrix,+ composeMatrix,+ elementGeometry,+ entryGeometry,+ slideEntries,+ fetchDeck,+ loadElement,+ applyRequests,+ locateElement,+ requireType,+ resolveTextTarget,+ tableSize,+ resolveTextRanges,+ computeMoveResize,+ readVideo,+};++export type RgbColor = { red: number; green: number; blue: number };++export type ColorChoice = { kind: 'none' } | { kind: 'rgb'; rgbColor: RgbColor };++export type Box = { position?: { x: number; y: number }; size?: { width: number; height: number } };++export type Matrix = { a: number; b: number; c: number; d: number; e: number; f: number };++export type ElementGeometry = {+ x: number;+ y: number;+ width: number | null;+ height: number | null;+ rotationDegrees: number;+};++export type Bounds = { left: number; top: number; right: number; bottom: number };++export type MoveResult = { transform: Required<AffineTransform>; geometry: ElementGeometry };++export type ElementEntry = {+ element: PageElement;+ parentGroupId: string | null;+ ancestorGroupIds: string[];+ matrix: Matrix;+};++export type LocatedElement = ElementEntry & {+ slideEntries: ElementEntry[];+ slideObjectId: string;+ type: string;+ revisionId?: string;+};++export type TextTarget = {+ objectId: string;+ cellLocation?: { rowIndex: number; columnIndex: number };+ text: string;+};++export type TextRange = { type: 'ALL' } | { type: 'FIXED_RANGE'; startIndex: number; endIndex: number };++export type VideoRef = { source: string; id: string };diff --git a/packages/pieces/community/google-slides/src/lib/commons/ids.ts b/packages/pieces/community/google-slides/src/lib/commons/ids.tsnew file mode 100644index 00000000000..cff463fb647--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/commons/ids.ts@@ -0,0 +1,139 @@+import { randomUUID } from 'crypto';++function tryParseUrl(input: string): URL | null {+ if (!/^https?:\/\//i.test(input)) {+ return null;+ }+ try {+ return new URL(input);+ } catch {+ return null;+ }+}++function isDriveId(value: string | null): value is string {+ return value !== null && DRIVE_ID.test(value) && value.length >= 10;+}++function idFromSlidesUrl(url: URL): string | null {+ if (url.hostname.toLowerCase() !== 'docs.google.com') {+ return null;+ }+ if (PUBLISHED_PATH.test(url.pathname)) {+ throw new Error(+ 'This is a "Publish to the web" link, which the Slides API cannot open. Use the presentation\'s edit URL instead.'+ );+ }+ return url.pathname.match(SLIDES_PATH)?.[1] ?? null;+}++function idFromDriveUrl(url: URL): string | null {+ if (url.hostname.toLowerCase() !== 'drive.google.com') {+ return null;+ }+ const fromPath = url.pathname.match(DRIVE_FILE_PATH)?.[1] ?? null;+ if (fromPath) {+ return fromPath;+ }+ const fromQuery = url.searchParams.get('id');+ return url.pathname === '/open' && isDriveId(fromQuery) ? fromQuery : null;+}++function parsePresentationId(input: unknown): string {+ const value = typeof input === 'string' ? input.trim() : '';+ if (!value) {+ throw new Error('Presentation is required: paste the presentation ID or its URL.');+ }+ const url = tryParseUrl(value);+ if (!url) {+ if (isDriveId(value)) {+ return value;+ }+ throw new Error(+ `"${value}" is not a valid presentation ID or URL. Use the ID between /d/ and /edit in the presentation URL, or paste the whole URL.`+ );+ }+ const id = idFromSlidesUrl(url) ?? idFromDriveUrl(url);+ if (!id) {+ throw new Error(+ `"${value}" is not a Google Slides URL. Expected https://docs.google.com/presentation/d/<id>/edit.`+ );+ }+ return id;+}++function parseObjectId(input: unknown): string {+ const value = typeof input === 'string' ? input.trim() : '';+ if (!value) {+ throw new Error('Slide object ID is empty.');+ }+ const url = tryParseUrl(value);+ if (url) {+ const match = url.hash.match(SLIDE_HASH);+ if (match && url.hostname.toLowerCase() === 'docs.google.com') {+ return match[1];+ }+ throw new Error(+ 'The URL has no slide reference. Select the slide in Google Slides and copy the URL (it ends in #slide=id.<objectId>), or paste the object ID.'+ );+ }+ if (!OBJECT_ID.test(value)) {+ throw new Error(`"${value}" is not a valid object ID (letters, digits, "_", "-" and ":" only).`);+ }+ return value;+}++function parseFolderId(input: unknown): string | undefined {+ const value = typeof input === 'string' ? input.trim() : '';+ if (!value) {+ return undefined;+ }+ const url = tryParseUrl(value);+ if (!url) {+ if (DRIVE_ID.test(value)) {+ return value;+ }+ throw new Error(`Folder "${value}" is not a valid Drive folder ID or URL.`);+ }+ const match = url.pathname.match(DRIVE_FOLDER_PATH);+ if (url.hostname.toLowerCase() === 'drive.google.com' && match) {+ return match[1];+ }+ throw new Error(+ `Folder: "${value}" is not a Drive folder URL. Expected https://drive.google.com/drive/folders/<id>.`+ );+}++function generateObjectId(prefix: string): string {+ return `${prefix}_${randomUUID().replace(/-/g, '')}`;+}++function validateImageUrl(input: unknown): string {+ const value = typeof input === 'string' ? input.trim() : '';+ if (!tryParseUrl(value)) {+ throw new Error(+ 'Image URL must be a public http(s) URL to a PNG, JPEG or GIF image, e.g. https://example.com/logo.png.'+ );+ }+ if (value.length > MAX_IMAGE_URL_LENGTH) {+ throw new Error('Image URL is longer than the 2 KB Google allows.');+ }+ return value;+}++const DRIVE_ID = /^[A-Za-z0-9_-]+$/;+const OBJECT_ID = /^[A-Za-z0-9_:-]+$/;+const SLIDES_PATH = /^\/presentation\/(?:u\/\d+\/)?d\/([A-Za-z0-9_-]{10,})(?:\/|$)/;+const PUBLISHED_PATH = /^\/presentation\/(?:u\/\d+\/)?d\/e\//;+const DRIVE_FILE_PATH = /^\/file\/(?:u\/\d+\/)?d\/([A-Za-z0-9_-]{10,})(?:\/|$)/;+const DRIVE_FOLDER_PATH = /^\/drive\/(?:u\/\d+\/)?folders\/([A-Za-z0-9_-]+)/;+const SLIDE_HASH = /^#slide=id\.([A-Za-z0-9_:-]+)$/;+const MAX_IMAGE_URL_LENGTH = 2048;++export const slidesIds = {+ parsePresentationId,+ parseObjectId,+ parseFolderId,+ generateObjectId,+ validateImageUrl,+};diff --git a/packages/pieces/community/google-slides/src/lib/commons/presentation-text.ts b/packages/pieces/community/google-slides/src/lib/commons/presentation-text.tsnew file mode 100644index 00000000000..44b0904dda8--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/commons/presentation-text.ts@@ -0,0 +1,191 @@+import { Page, PageElement, Presentation, slidesApi, TextContent } from './common';++function flattenPageElements(elements: PageElement[] | undefined): PageElement[] {+ return (elements ?? []).flatMap((element) => [+ element,+ ...flattenPageElements(element.elementGroup?.children),+ ]);+}++function joinText(text: TextContent | undefined): string {+ return (text?.textElements ?? [])+ .map((element) => element.textRun?.content ?? element.autoText?.content ?? '')+ .join('');+}++function textContainers(elements: PageElement[] | undefined): string[] {+ return flattenPageElements(elements).flatMap((element) => [+ ...(element.shape?.text ? [joinText(element.shape.text)] : []),+ ...(element.table?.tableRows ?? []).flatMap((row) =>+ (row.tableCells ?? []).filter((cell) => cell.text).map((cell) => joinText(cell.text))+ ),+ ]);+}++function discoverPlaceholders({+ presentation,+ format,+}: {+ presentation: Pick<Presentation, 'slides'>;+ format: PlaceholderFormat;+}): string[] {+ const regex = format === '[[]]' ? /\[\[([^\]]+)\]\]/g : /\{\{([^}]+)\}\}/g;+ const names = (presentation.slides ?? []).flatMap((slide) =>+ [+ ...textContainers(slide.pageElements),+ ...textContainers(slide.slideProperties?.notesPage?.pageElements),+ ].flatMap((text) => Array.from(text.matchAll(regex), (match) => match[1]))+ );+ return Array.from(new Set(names));+}++function findSheetsCharts(presentation: Pick<Presentation, 'slides'>): string[] {+ return (presentation.slides ?? []).flatMap((slide) =>+ flattenPageElements(slide.pageElements)+ .filter((element) => element.sheetsChart)+ .map((element) => element.objectId)+ );+}++function stripTrailingNewlines(text: string): string {+ return text.replace(/\n+$/, '');+}++function speakerNotesText(slide: Page): string {+ const notesPage = slide.slideProperties?.notesPage;+ const notesId = notesPage?.notesProperties?.speakerNotesObjectId;+ if (!notesId) {+ return '';+ }+ const shape = (notesPage?.pageElements ?? []).find((element) => element.objectId === notesId);+ return stripTrailingNewlines(joinText(shape?.shape?.text));+}++function elementType(element: PageElement): string {+ if (element.elementGroup) return 'GROUP';+ if (element.sheetsChart) return 'SHEETS_CHART';+ if (element.table) return 'TABLE';+ if (element.image) return 'IMAGE';+ if (element.video) return 'VIDEO';+ if (element.line) return 'LINE';+ if (element.wordArt) return 'WORD_ART';+ if (element.shape) return 'SHAPE';+ return 'OTHER';+}++function elementText(element: PageElement): string | null {+ if (element.shape?.text) {+ return stripTrailingNewlines(joinText(element.shape.text));+ }+ if (element.table) {+ return textContainers([element])+ .map(stripTrailingNewlines)+ .filter((text) => text.length > 0)+ .join(' | ');+ }+ return element.wordArt?.renderedText ?? null;+}++function outlineSlide({+ presentationId,+ slide,+ index,+ layoutNames,+}: {+ presentationId: string;+ slide: Page;+ index: number;+ layoutNames: Map<string, string>;+}): OutlineSlide {+ const elements = flattenPageElements(slide.pageElements).map(+ (element): OutlineElement => ({+ objectId: element.objectId,+ type: elementType(element),+ placeholderType: element.shape?.placeholder?.type ?? null,+ text: elementText(element),+ })+ );+ const titleElement = elements.find(+ (element) => element.placeholderType !== null && TITLE_TYPES.includes(element.placeholderType) && element.text+ );+ const layoutObjectId = slide.slideProperties?.layoutObjectId ?? null;+ return {+ slideNumber: index + 1,+ objectId: slide.objectId,+ slideUrl: slidesApi.slideUrl({ presentationId, slideObjectId: slide.objectId }),+ layoutObjectId,+ layoutName: layoutObjectId ? layoutNames.get(layoutObjectId) ?? null : null,+ isSkipped: slide.slideProperties?.isSkipped ?? false,+ title: titleElement?.text ?? null,+ text: elements+ .filter((element) => element.type !== 'GROUP' && element.text)+ .map((element) => element.text)+ .join('\n'),+ speakerNotes: speakerNotesText(slide),+ elements,+ };+}++function buildOutline(presentation: Presentation): Outline {+ const layoutNames = new Map(+ (presentation.layouts ?? []).flatMap((layout): [string, string][] => {+ const name = layout.layoutProperties?.displayName ?? layout.layoutProperties?.name;+ return name ? [[layout.objectId, name]] : [];+ })+ );+ const slides = (presentation.slides ?? []).map((slide, index) =>+ outlineSlide({ presentationId: presentation.presentationId, slide, index, layoutNames })+ );+ return {+ presentationId: presentation.presentationId,+ title: presentation.title ?? '',+ revisionId: presentation.revisionId ?? null,+ slideCount: slides.length,+ slides,+ };+}++const TITLE_TYPES = ['TITLE', 'CENTERED_TITLE'];++export const slidesText = {+ flattenPageElements,+ elementType,+ elementText,+ stripTrailingNewlines,+ joinText,+ textContainers,+ discoverPlaceholders,+ findSheetsCharts,+ speakerNotesText,+ buildOutline,+};++export type PlaceholderFormat = '{{}}' | '[[]]';++export type OutlineElement = {+ objectId: string;+ type: string;+ placeholderType: string | null;+ text: string | null;+};++export type OutlineSlide = {+ slideNumber: number;+ objectId: string;+ slideUrl: string;+ layoutObjectId: string | null;+ layoutName: string | null;+ isSkipped: boolean;+ title: string | null;+ text: string;+ speakerNotes: string;+ elements: OutlineElement[];+};++export type Outline = {+ presentationId: string;+ title: string;+ revisionId: string | null;+ slideCount: number;+ slides: OutlineSlide[];+};diff --git a/packages/pieces/community/google-slides/src/lib/commons/props.ts b/packages/pieces/community/google-slides/src/lib/commons/props.tsnew file mode 100644index 00000000000..39091c8da4e--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/commons/props.ts@@ -0,0 +1,146 @@+import { Property } from '@activepieces/pieces-framework';++function presentationIdProp(displayName = 'Presentation') {+ return Property.ShortText({+ displayName,+ description:+ 'The presentation ID or its full URL, e.g. https://docs.google.com/presentation/d/1AbC...xyz/edit or just 1AbC...xyz.',+ required: true,+ });+}++function folderIdProp(description: string) {+ return Property.ShortText({+ displayName: 'Folder',+ description,+ required: false,+ });+}++function slideNumberProp() {+ return Property.Number({+ displayName: 'Slide Number',+ description: 'Position of the slide in the deck, starting at 1 for the first slide. Set this or Slide Object ID, not both.',+ required: false,+ });+}++function slideObjectIdProp() {+ return Property.ShortText({+ displayName: 'Slide Object ID',+ description:+ 'The slide object ID (e.g. "g2c8d1e5a7f_0_12", from Get Presentation Outline), or the slide URL copied from the browser while the slide is selected (it ends in #slide=id.<objectId>). Set this or Slide Number, not both.',+ required: false,+ });+}++function matchCaseProp() {+ return Property.Checkbox({+ displayName: 'Match Case',+ description: 'When on, "Name" does not match "name".',+ required: false,+ defaultValue: true,+ });+}++function slideScopeProp() {+ return Property.Array({+ displayName: 'Only on These Slides',+ description:+ 'Optional list of slide object IDs (or slide URLs) to limit the change to. Leave empty for every slide. Speaker notes pages cannot be listed here.',+ required: false,+ });+}++function elementIdProp({ displayName, description }: { displayName: string; description: string }) {+ return Property.ShortText({ displayName, description, required: true });+}++function textElementIdProp() {+ return elementIdProp({+ displayName: 'Element Object ID',+ description:+ 'Object ID of the shape, text box, placeholder or table, e.g. "g2c8d1e5a7f_0_3". Get it from List Slide Elements, Get Presentation Outline (elements[].objectId), or the output of Create Shape / Create Table. For a table also set Row and Column.',+ });+}++function cellRowProp() {+ return Property.Number({+ displayName: 'Row',+ description: 'Table cells only: row number, starting at 1. Leave empty for shapes and text boxes.',+ required: false,+ });+}++function cellColumnProp() {+ return Property.Number({+ displayName: 'Column',+ description: 'Table cells only: column number, starting at 1. Leave empty for shapes and text boxes.',+ required: false,+ });+}++function textRangeProps() {+ return {+ match_text: Property.ShortText({+ displayName: 'Match Text',+ description:+ 'Optional: only change every occurrence of this exact text (case-sensitive) inside the element. Leave empty (and Start/End Index empty) for all of its text.',+ required: false,+ }),+ start_index: Property.Number({+ displayName: 'Start Index',+ description: 'Optional 0-based start of a character range (instead of Match Text).',+ required: false,+ }),+ end_index: Property.Number({+ displayName: 'End Index',+ description: 'Optional 0-based end of the range, exclusive (instead of Match Text).',+ required: false,+ }),+ };+}++function pointProp({ displayName, description, required }: { displayName: string; description: string; required: boolean }) {+ return Property.Number({ displayName, description, required });+}++function colorProp({ displayName, description }: { displayName: string; description: string }) {+ return Property.ShortText({ displayName, description, required: false });+}++function enumProp({+ displayName,+ description,+ values,+ required = false,+}: {+ displayName: string;+ description: string;+ values: readonly string[];+ required?: boolean;+}) {+ return Property.StaticDropdown({+ displayName,+ description,+ required,+ options: { disabled: false, options: values.map((value) => ({ label: value, value })) },+ });+}++export const slidesProps = {+ elementIdProp,+ textElementIdProp,+ textRangeProps,+ cellRowProp,+ cellColumnProp,+ pointProp,+ colorProp,+ enumProp,+ presentationIdProp,+ folderIdProp,+ slideNumberProp,+ slideObjectIdProp,+ matchCaseProp,+ slideScopeProp,+};diff --git a/packages/pieces/community/google-slides/src/lib/commons/requests.ts b/packages/pieces/community/google-slides/src/lib/commons/requests.tsnew file mode 100644index 00000000000..7c3d03df5da--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/commons/requests.ts@@ -0,0 +1,506 @@+import { Page, PageElement, PRESENTATION_MIME_TYPE, slidesApi } from './common';+import { slidesIds } from './ids';++function toInteger({ value, label }: { value: unknown; label: string }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const number = typeof value === 'number' ? value : Number(String(value).trim());+ if (!Number.isInteger(number)) {+ throw new Error(`${label} must be a whole number, got "${String(value)}".`);+ }+ return number;+}++function toNumber({ value, label }: { value: unknown; label: string }): number | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const number = typeof value === 'number' ? value : Number(String(value).trim());+ if (!Number.isFinite(number)) {+ throw new Error(`${label} must be a number, got "${String(value)}".`);+ }+ return number;+}++function readSlideSelector({+ slideNumber,+ slideObjectId,+}: {+ slideNumber: unknown;+ slideObjectId: unknown;+}): SlideSelector {+ const number = toInteger({ value: slideNumber, label: 'Slide Number' });+ const hasObjectId = typeof slideObjectId === 'string' && slideObjectId.trim() !== '';+ if (number === undefined && !hasObjectId) {+ throw new Error('Choose the slide: set either Slide Number or Slide Object ID.');+ }+ if (number !== undefined && hasObjectId) {+ throw new Error('Set only one of Slide Number or Slide Object ID, not both.');+ }+ if (number !== undefined) {+ if (number < 1) {+ throw new Error('Slide Number starts at 1 (the first slide).');+ }+ return { slideNumber: number };+ }+ return { slideObjectId: slidesIds.parseObjectId(slideObjectId) };+}++function resolveSlide({+ slides,+ selector,+}: {+ slides: Pick<Page, 'objectId'>[];+ selector: SlideSelector;+}): SlideRef {+ if (selector.slideNumber !== undefined) {+ if (selector.slideNumber > slides.length) {+ throw new Error(+ `Slide Number ${selector.slideNumber} is out of range: the presentation has ${slides.length} slide(s).`+ );+ }+ const index = selector.slideNumber - 1;+ return { objectId: slides[index].objectId, index };+ }+ const index = slides.findIndex((slide) => slide.objectId === selector.slideObjectId);+ if (index === -1) {+ throw new Error(+ `No slide with object ID "${selector.slideObjectId}" in this presentation. Use Get Presentation Outline to list slide object IDs.`+ );+ }+ return { objectId: slides[index].objectId, index };+}++async function lookupSlide({+ accessToken,+ presentationId,+ selector,+}: {+ accessToken: string;+ presentationId: string;+ selector: SlideSelector;+}): Promise<SlideLookup> {+ if (selector.slideObjectId) {+ return { objectId: selector.slideObjectId };+ }+ const presentation = await slidesApi.getPresentation({ accessToken, presentationId, fields: FIELD_MASKS.slideIds });+ return {+ objectId: resolveSlide({ slides: presentation.slides ?? [], selector }).objectId,+ revisionId: presentation.revisionId,+ };+}++function readPosition({ position, maxPosition }: { position: unknown; maxPosition: number }): number | undefined {+ const value = toInteger({ value: position, label: 'Position' });+ if (value === undefined) {+ return undefined;+ }+ if (value < 1 || value > maxPosition) {+ throw new Error(`Position must be between 1 and ${maxPosition}, got ${value}.`);+ }+ return value - 1;+}++function moveInsertionIndex({ currentIndex, targetIndex }: { currentIndex: number; targetIndex: number }): number {+ return targetIndex > currentIndex ? targetIndex + 1 : targetIndex;+}++function findPlaceholder({+ elements,+ types,+}: {+ elements: PageElement[] | undefined;+ types: string[];+}): LayoutPlaceholder | null {+ const placeholders = (elements ?? []).flatMap((element) =>+ element.shape?.placeholder?.type ? [element.shape.placeholder] : []+ );+ const type = types.find((candidate) => placeholders.some((placeholder) => placeholder.type === candidate));+ if (!type) {+ return null;+ }+ const lowestIndex = placeholders+ .filter((placeholder) => placeholder.type === type)+ .reduce((lowest, placeholder) => Math.min(lowest, placeholder.index ?? 0), Number.POSITIVE_INFINITY);+ return { type, index: lowestIndex };+}++function buildAddSlideRequests({+ layouts,+ predefinedLayout,+ insertionIndex,+ title,+ body,+ newId,+}: {+ layouts: Page[];+ predefinedLayout: string;+ insertionIndex?: number;+ title?: string;+ body?: string;+ newId: (prefix: string) => string;+}): AddSlideRequests {+ const layout = layouts.find((candidate) => candidate.layoutProperties?.name === predefinedLayout);+ if (!layout) {+ const available = layouts.flatMap((candidate) =>+ candidate.layoutProperties?.name ? [candidate.layoutProperties.name] : []+ );+ throw new Error(+ `This presentation's theme has no "${predefinedLayout}" layout. Available layouts: ${available.join(', ') || 'none'}.`+ );+ }+ const wantsTitle = title !== undefined && title !== '';+ const wantsBody = body !== undefined && body !== '';+ const titlePlaceholder = wantsTitle ? findPlaceholder({ elements: layout.pageElements, types: TITLE_PLACEHOLDERS }) : null;+ const bodyPlaceholder = wantsBody ? findPlaceholder({ elements: layout.pageElements, types: BODY_PLACEHOLDERS }) : null;+ if (wantsTitle && !titlePlaceholder) {+ throw new Error(`The "${predefinedLayout}" layout has no title placeholder. Pick another layout or leave Title empty.`);+ }+ if (wantsBody && !bodyPlaceholder) {+ throw new Error(+ `The "${predefinedLayout}" layout has no body or subtitle placeholder. Pick another layout or leave Body empty.`+ );+ }+ const slideObjectId = newId('slide');+ const fills = [+ ...(titlePlaceholder && wantsTitle ? [{ placeholder: titlePlaceholder, objectId: newId('title'), text: title }] : []),+ ...(bodyPlaceholder && wantsBody ? [{ placeholder: bodyPlaceholder, objectId: newId('body'), text: body }] : []),+ ];+ const createSlide = {+ createSlide: {+ objectId: slideObjectId,+ ...(insertionIndex !== undefined ? { insertionIndex } : {}),+ slideLayoutReference: { layoutId: layout.objectId },+ ...(fills.length > 0+ ? { placeholderIdMappings: fills.map((fill) => ({ layoutPlaceholder: fill.placeholder, objectId: fill.objectId })) }+ : {}),+ },+ };+ return {+ requests: [+ createSlide,+ ...fills.map((fill) => ({ insertText: { objectId: fill.objectId, text: fill.text, insertionIndex: 0 } })),+ ],+ slideObjectId,+ titleObjectId: titlePlaceholder ? fills[0].objectId : null,+ bodyObjectId: bodyPlaceholder ? fills[fills.length - 1].objectId : null,+ };+}++function buildDuplicateRequests({+ sourceObjectId,+ sourceIndex,+ newObjectId,+ targetIndex,+}: {+ sourceObjectId: string;+ sourceIndex: number;+ newObjectId: string;+ targetIndex?: number;+}): { requests: unknown[]; finalIndex: number } {+ const duplicate = { duplicateObject: { objectId: sourceObjectId, objectIds: { [sourceObjectId]: newObjectId } } };+ const duplicateIndex = sourceIndex + 1;+ if (targetIndex === undefined || targetIndex === duplicateIndex) {+ return { requests: [duplicate], finalIndex: duplicateIndex };+ }+ return {+ requests: [+ duplicate,+ {+ updateSlidesPosition: {+ slideObjectIds: [newObjectId],+ insertionIndex: moveInsertionIndex({ currentIndex: duplicateIndex, targetIndex }),+ },+ },+ ],+ finalIndex: targetIndex,+ };+}++function buildSpeakerNotesRequests({+ speakerNotesObjectId,+ currentNotes,+ notes,+}: {+ speakerNotesObjectId: string;+ currentNotes: string;+ notes: string;+}): unknown[] {+ if (currentNotes === notes) {+ return [];+ }+ return [+ ...(currentNotes.length > 0+ ? [{ deleteText: { objectId: speakerNotesObjectId, textRange: { type: 'ALL' } } }]+ : []),+ ...(notes.length > 0 ? [{ insertText: { objectId: speakerNotesObjectId, text: notes, insertionIndex: 0 } }] : []),+ ];+}++function readImageGeometry({+ x,+ y,+ width,+ height,+}: {+ x?: unknown;+ y?: unknown;+ width?: unknown;+ height?: unknown;+}): ImageGeometry {+ const left = toNumber({ value: x, label: 'X' });+ const top = toNumber({ value: y, label: 'Y' });+ const w = toNumber({ value: width, label: 'Width' });+ const h = toNumber({ value: height, label: 'Height' });+ if ((w === undefined) !== (h === undefined)) {+ throw new Error('Set both Width and Height, or leave both empty.');+ }+ if ((left === undefined) !== (top === undefined)) {+ throw new Error('Set both X and Y, or leave both empty.');+ }+ if ((w !== undefined && w <= 0) || (h !== undefined && h <= 0)) {+ throw new Error('Width and Height must be greater than 0.');+ }+ return {+ ...(w !== undefined && h !== undefined+ ? { size: { width: { magnitude: w, unit: 'PT' }, height: { magnitude: h, unit: 'PT' } } }+ : {}),+ ...(left !== undefined && top !== undefined+ ? { transform: { scaleX: 1, scaleY: 1, shearX: 0, shearY: 0, translateX: left, translateY: top, unit: 'PT' } }+ : {}),+ };+}++function buildCreateImageRequest({+ objectId,+ slideObjectId,+ url,+ geometry,+}: {+ objectId: string;+ slideObjectId: string;+ url: string;+ geometry: ImageGeometry;+}): unknown {+ return {+ createImage: {+ objectId,+ url,+ elementProperties: { pageObjectId: slideObjectId, ...geometry },+ },+ };+}++function readSlideObjectIds(value: unknown): string[] | undefined {+ if (value === undefined || value === null || value === '') {+ return undefined;+ }+ const items = Array.isArray(value) ? value : [value];+ const ids = items+ .filter((item) => !(typeof item === 'string' && item.trim() === ''))+ .map((item) => slidesIds.parseObjectId(item));+ return ids.length > 0 ? ids : undefined;+}++function buildReplaceTextRequest({+ find,+ replaceWith,+ matchCase,+ pageObjectIds,+}: {+ find: string;+ replaceWith: string;+ matchCase: boolean;+ pageObjectIds?: string[];+}): unknown {+ return {+ replaceAllText: {+ containsText: { text: find, matchCase },+ replaceText: replaceWith,+ ...(pageObjectIds ? { pageObjectIds } : {}),+ },+ };+}++function buildReplaceShapesRequest({+ find,+ imageUrl,+ replaceMethod,+ matchCase,+ pageObjectIds,+}: {+ find: string;+ imageUrl: string;+ replaceMethod: string;+ matchCase: boolean;+ pageObjectIds?: string[];+}): unknown {+ return {+ replaceAllShapesWithImage: {+ containsText: { text: find, matchCase },+ imageUrl,+ imageReplaceMethod: replaceMethod,+ ...(pageObjectIds ? { pageObjectIds } : {}),+ },+ };+}++function occurrencesChanged({+ replies,+ key,+}: {+ replies: Record<string, unknown>[] | undefined;+ key: 'replaceAllText' | 'replaceAllShapesWithImage';+}): number {+ const reply = replies?.[0]?.[key];+ if (typeof reply !== 'object' || reply === null || !('occurrencesChanged' in reply)) {+ return 0;+ }+ return Number(reply.occurrencesChanged) || 0;+}++function toPlaceholder({ name, format }: { name: string; format: string }): string {+ return format === '[[]]' ? `[[${name}]]` : `{{${name}}}`;+}++function buildTemplateRequests({+ tableData,+ format,+}: {+ tableData: Record<string, unknown>;+ format: string;+}): unknown[] {+ return Object.entries(tableData).map(([key, value]) => ({+ replaceAllText: {+ containsText: { text: toPlaceholder({ name: key, format }), matchCase: true },+ replaceText: value === undefined || value === null ? '' : String(value),+ },+ }));+}++function escapeDriveQueryLiteral(value: string): string {+ return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");+}++function buildFindQuery({ nameContains, folderId }: { nameContains?: string; folderId?: string }): string {+ return [+ `mimeType='${PRESENTATION_MIME_TYPE}'`,+ 'trashed=false',+ ...(nameContains ? [`name contains '${escapeDriveQueryLiteral(nameContains)}'`] : []),+ ...(folderId ? [`'${escapeDriveQueryLiteral(folderId)}' in parents`] : []),+ ].join(' and ');+}++function exportFileName({ baseName, extension }: { baseName: string; extension: string }): string {+ const safe = baseName.replace(/[\\/:*?"<>|\r\n]+/g, '_').trim() || 'presentation';+ return safe.toLowerCase().endsWith(`.${extension}`) ? safe : `${safe}.${extension}`;+}++function readBatchRequests(value: unknown): Record<string, unknown>[] {+ const parsed = typeof value === 'string' ? parseJson(value) : value;+ if (!Array.isArray(parsed) || parsed.length === 0) {+ throw new Error('Requests must be a non-empty JSON array, e.g. [{"deleteObject":{"objectId":"g123_0_1"}}].');+ }+ return parsed.map((request, index) => {+ if (!isSingleKeyObject(request)) {+ throw new Error(`Request #${index + 1} must be an object with exactly one request kind, e.g. {"createSlide":{}}.`);+ }+ return request;+ });+}++function parseJson(value: string): unknown {+ try {+ return JSON.parse(value);+ } catch {+ throw new Error('Requests must be a JSON array of Slides API request objects.');+ }+}++function isSingleKeyObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.keys(value).length === 1;+}++const TITLE_PLACEHOLDERS = ['TITLE', 'CENTERED_TITLE'];+const BODY_PLACEHOLDERS = ['BODY', 'SUBTITLE'];++export const PREDEFINED_LAYOUTS = [+ { label: 'Title and body', value: 'TITLE_AND_BODY' },+ { label: 'Title slide (title and subtitle)', value: 'TITLE' },+ { label: 'Title only', value: 'TITLE_ONLY' },+ { label: 'Title and two columns', value: 'TITLE_AND_TWO_COLUMNS' },+ { label: 'Section header', value: 'SECTION_HEADER' },+ { label: 'Section title and description', value: 'SECTION_TITLE_AND_DESCRIPTION' },+ { label: 'One column text', value: 'ONE_COLUMN_TEXT' },+ { label: 'Main point', value: 'MAIN_POINT' },+ { label: 'Big number', value: 'BIG_NUMBER' },+ { label: 'Caption only', value: 'CAPTION_ONLY' },+ { label: 'Blank', value: 'BLANK' },+];++export const EXPORT_FORMATS: Record<string, { mimeType: string; extension: string }> = {+ pdf: { mimeType: 'application/pdf', extension: 'pdf' },+ pptx: {+ mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ extension: 'pptx',+ },+ odp: { mimeType: 'application/vnd.oasis.opendocument.presentation', extension: 'odp' },+ txt: { mimeType: 'text/plain', extension: 'txt' },+};++export const FIELD_MASKS = {+ slideIds: 'revisionId,slides(objectId)',+ addSlide:+ 'presentationId,revisionId,slides(objectId),layouts(objectId,layoutProperties(name),pageElements(objectId,shape(placeholder)))',+ outline:+ 'presentationId,title,revisionId,layouts(objectId,layoutProperties(name,displayName)),slides(objectId,pageElements,slideProperties(layoutObjectId,isSkipped,notesPage(notesProperties,pageElements)))',+ speakerNotes:+ 'revisionId,slides(objectId,slideProperties(notesPage(notesProperties,pageElements(objectId,shape(text)))))',+ charts: 'presentationId,revisionId,slides(objectId,pageElements)',+};++export const slidesRequests = {+ toInteger,+ toNumber,+ readSlideSelector,+ resolveSlide,+ lookupSlide,+ readPosition,+ moveInsertionIndex,+ buildAddSlideRequests,+ buildDuplicateRequests,+ buildSpeakerNotesRequests,+ readImageGeometry,+ buildCreateImageRequest,+ readSlideObjectIds,+ buildReplaceTextRequest,+ buildReplaceShapesRequest,+ occurrencesChanged,+ toPlaceholder,+ buildTemplateRequests,+ escapeDriveQueryLiteral,+ buildFindQuery,+ exportFileName,+ readBatchRequests,+};++export type SlideSelector = { slideNumber?: number; slideObjectId?: string };++export type SlideRef = { objectId: string; index: number };++export type SlideLookup = { objectId: string; revisionId?: string };++export type ImageGeometry = {+ size?: { width: { magnitude: number; unit: string }; height: { magnitude: number; unit: string } };+ transform?: Record<string, number | string>;+};++type LayoutPlaceholder = { type: string; index: number };++type AddSlideRequests = {+ requests: unknown[];+ slideObjectId: string;+ titleObjectId: string | null;+ bodyObjectId: string | null;+};diff --git a/packages/pieces/community/google-slides/src/lib/output-schemas.ts b/packages/pieces/community/google-slides/src/lib/output-schemas.tsnew file mode 100644index 00000000000..f5f89d646a5--- /dev/null+++ b/packages/pieces/community/google-slides/src/lib/output-schemas.ts@@ -0,0 +1,470 @@+import { OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';++const presentationIdField: OutputSchemaField = { key: 'presentationId', label: 'Presentation ID' };++const slideUrlField: OutputSchemaField = { key: 'slideUrl', label: 'Slide URL', format: 'url' };++const createdFileFields: OutputSchemaField[] = [+ presentationIdField,+ { key: 'title', label: 'Title' },+ { key: 'presentationUrl', label: 'Presentation URL', format: 'url' },+ { key: 'folderId', label: 'Folder ID' },+ { key: 'createdTime', label: 'Created Time', format: 'datetime' },+];++const dimensionChildren: OutputSchemaField[] = [+ { key: 'magnitude', label: 'Size', format: 'number' },+ { key: 'unit', label: 'Unit' },+];++const pageElementItems: OutputSchemaField[] = [+ { key: 'objectId', label: 'Object ID' },+ {+ key: 'size',+ label: 'Size',+ children: [+ { key: 'width', label: 'Width', children: dimensionChildren },+ { key: 'height', label: 'Height', children: dimensionChildren },+ ],+ },+ { key: 'transform', label: 'Transform' },+ { key: 'shape', label: 'Shape' },+ { key: 'table', label: 'Table' },+ { key: 'image', label: 'Image' },+ { key: 'elementGroup', label: 'Group' },+];++const slideProperties: OutputSchemaField = {+ key: 'slideProperties',+ label: 'Slide Properties',+ children: [+ { key: 'layoutObjectId', label: 'Layout Object ID' },+ { key: 'masterObjectId', label: 'Master Object ID' },+ ],+};++export const getPresentationOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'title', label: 'Title' },+ { key: 'locale', label: 'Locale' },+ { key: 'revisionId', label: 'Revision ID' },+ {+ key: 'pageSize',+ label: 'Page Size',+ children: [+ { key: 'width', label: 'Width', children: dimensionChildren },+ { key: 'height', label: 'Height', children: dimensionChildren },+ ],+ },+ {+ key: 'slides',+ label: 'Slides',+ labelKey: 'objectId',+ listItems: [+ { key: 'objectId', label: 'Slide Object ID' },+ slideProperties,+ { key: 'pageElements', label: 'Elements', labelKey: 'objectId', listItems: pageElementItems },+ ],+ },+ {+ key: 'layouts',+ label: 'Layouts',+ labelKey: 'objectId',+ listItems: [+ { key: 'objectId', label: 'Layout Object ID' },+ {+ key: 'layoutProperties',+ label: 'Layout Properties',+ children: [+ { key: 'name', label: 'Name' },+ { key: 'displayName', label: 'Display Name' },+ ],+ },+ ],+ },+ {+ key: 'masters',+ label: 'Masters',+ labelKey: 'objectId',+ listItems: [{ key: 'objectId', label: 'Master Object ID' }],+ },+ ],+};++export const getSlideOutputSchema: OutputSchema = {+ fields: [+ { key: 'objectId', label: 'Slide Object ID' },+ { key: 'revisionId', label: 'Revision ID' },+ slideProperties,+ { key: 'pageElements', label: 'Elements', labelKey: 'objectId', listItems: pageElementItems },+ ],+};++export const getPresentationOutlineOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'title', label: 'Title' },+ { key: 'presentationUrl', label: 'Presentation URL', format: 'url' },+ { key: 'revisionId', label: 'Revision ID' },+ { key: 'slideCount', label: 'Slide Count', format: 'number' },+ {+ key: 'slides',+ label: 'Slides',+ labelKey: 'title',+ listItems: [+ { key: 'slideNumber', label: 'Slide Number', format: 'number' },+ { key: 'objectId', label: 'Slide Object ID' },+ slideUrlField,+ { key: 'title', label: 'Title' },+ { key: 'text', label: 'Text' },+ { key: 'speakerNotes', label: 'Speaker Notes' },+ { key: 'layoutName', label: 'Layout' },+ { key: 'layoutObjectId', label: 'Layout Object ID' },+ { key: 'isSkipped', label: 'Skipped in Presentation', format: 'boolean' },+ {+ key: 'elements',+ label: 'Elements',+ labelKey: 'objectId',+ listItems: [+ { key: 'objectId', label: 'Object ID' },+ { key: 'type', label: 'Type' },+ { key: 'placeholderType', label: 'Placeholder Type' },+ { key: 'text', label: 'Text' },+ ],+ },+ ],+ },+ ],+};++export const getSlideThumbnailOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'slideObjectId', label: 'Slide Object ID' },+ { key: 'contentUrl', label: 'Image (link expires in 30 minutes)', format: 'image' },+ { key: 'width', label: 'Width (px)', format: 'number' },+ { key: 'height', label: 'Height (px)', format: 'number' },+ { key: 'file', label: 'Image File', format: 'url' },+ ],+};++export const createPresentationOutputSchema: OutputSchema = {+ fields: createdFileFields,+};++export const copyPresentationOutputSchema: OutputSchema = {+ fields: [...createdFileFields, { key: 'sourcePresentationId', label: 'Source Presentation ID' }],+};++export const generateFromTemplateOutputSchema: OutputSchema = {+ fields: [presentationIdField, { key: 'presentationUrl', label: 'Presentation URL', format: 'url' }],+};++export const findPresentationsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'presentations',+ label: 'Presentations',+ labelKey: 'name',+ listItems: [+ { key: 'id', label: 'Presentation ID' },+ { key: 'name', label: 'Name' },+ { key: 'webViewLink', label: 'Presentation URL', format: 'url' },+ { key: 'createdTime', label: 'Created Time', format: 'datetime' },+ { key: 'modifiedTime', label: 'Modified Time', format: 'datetime' },+ { key: 'ownerName', label: 'Owner Name' },+ { key: 'ownerEmail', label: 'Owner Email', format: 'email' },+ { key: 'folderId', label: 'Folder ID' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'hasMore', label: 'Has More', format: 'boolean' },+ { key: 'nextPageToken', label: 'Next Page Token' },+ ],+};++export const addSlideOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'slideObjectId', label: 'Slide Object ID' },+ { key: 'slideNumber', label: 'Slide Number', format: 'number' },+ slideUrlField,+ { key: 'titleObjectId', label: 'Title Object ID' },+ { key: 'bodyObjectId', label: 'Body Object ID' },+ ],+};++export const duplicateSlideOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'slideObjectId', label: 'New Slide Object ID' },+ { key: 'slideNumber', label: 'New Slide Number', format: 'number' },+ slideUrlField,+ { key: 'sourceSlideObjectId', label: 'Original Slide Object ID' },+ ],+};++export const moveSlideOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'slideObjectId', label: 'Slide Object ID' },+ { key: 'slideNumber', label: 'New Slide Number', format: 'number' },+ { key: 'previousSlideNumber', label: 'Previous Slide Number', format: 'number' },+ { key: 'moved', label: 'Moved', format: 'boolean' },+ ],+};++export const deleteSlideOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'deletedSlideObjectId', label: 'Deleted Slide Object ID' },+ { key: 'deletedSlideNumber', label: 'Deleted Slide Number', format: 'number' },+ { key: 'remainingSlideCount', label: 'Remaining Slides', format: 'number' },+ ],+};++export const replaceTextOutputSchema: OutputSchema = {+ fields: [presentationIdField, { key: 'occurrencesChanged', label: 'Occurrences Replaced', format: 'number' }],+};++export const replaceShapesWithImageOutputSchema: OutputSchema = {+ fields: [presentationIdField, { key: 'occurrencesChanged', label: 'Shapes Replaced', format: 'number' }],+};++export const insertImageOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'imageObjectId', label: 'Image Object ID' },+ { key: 'slideObjectId', label: 'Slide Object ID' },+ ],+};++export const setSpeakerNotesOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'slideObjectId', label: 'Slide Object ID' },+ { key: 'speakerNotes', label: 'Speaker Notes' },+ { key: 'speakerNotesObjectId', label: 'Speaker Notes Object ID' },+ { key: 'changed', label: 'Changed', format: 'boolean' },+ ],+};++export const exportPresentationOutputSchema: OutputSchema = {+ fields: [+ { key: 'file', label: 'File', format: 'url' },+ { key: 'fileName', label: 'File Name' },+ { key: 'mimeType', label: 'MIME Type' },+ { key: 'sizeBytes', label: 'Size', format: 'filesize' },+ presentationIdField,+ ],+};++export const refreshSheetsChartsOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Charts Refreshed', format: 'boolean' },+ { key: 'message', label: 'Message' },+ {+ key: 'result',+ label: 'Result',+ children: [+ presentationIdField,+ {+ key: 'writeControl',+ label: 'Write Control',+ children: [{ key: 'requiredRevisionId', label: 'Revision ID' }],+ },+ ],+ },+ ],+};++export const batchUpdateOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'appliedRequests', label: 'Requests Applied', format: 'number' },+ { key: 'replies', label: 'Replies' },+ {+ key: 'writeControl',+ label: 'Write Control',+ children: [{ key: 'requiredRevisionId', label: 'Revision ID' }],+ },+ ],+};++const slideObjectIdField: OutputSchemaField = { key: 'slideObjectId', label: 'Slide Object ID' };++const objectIdField: OutputSchemaField = { key: 'objectId', label: 'Element Object ID' };++const geometryFields: OutputSchemaField[] = [+ { key: 'x', label: 'X (pt)', format: 'number' },+ { key: 'y', label: 'Y (pt)', format: 'number' },+ { key: 'width', label: 'Width (pt)', format: 'number' },+ { key: 'height', label: 'Height (pt)', format: 'number' },+];++const cellFields: OutputSchemaField[] = [+ { key: 'row', label: 'Row', format: 'number' },+ { key: 'column', label: 'Column', format: 'number' },+];++export const listSlideElementsOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ { key: 'slideNumber', label: 'Slide Number', format: 'number' },+ { key: 'slideWidth', label: 'Slide Width (pt)', format: 'number' },+ { key: 'slideHeight', label: 'Slide Height (pt)', format: 'number' },+ { key: 'elementCount', label: 'Elements', format: 'number' },+ {+ key: 'elements',+ label: 'Elements',+ labelKey: 'objectId',+ listItems: [+ objectIdField,+ { key: 'type', label: 'Type' },+ { key: 'shapeType', label: 'Shape Type' },+ { key: 'placeholderType', label: 'Placeholder Type' },+ { key: 'parentGroupId', label: 'Parent Group ID' },+ ...geometryFields,+ { key: 'rotationDegrees', label: 'Rotation (degrees)', format: 'number' },+ { key: 'text', label: 'Text' },+ { key: 'tableRows', label: 'Table Rows', format: 'number' },+ { key: 'tableColumns', label: 'Table Columns', format: 'number' },+ { key: 'tableCells', label: 'Table Cells' },+ ],+ },+ ],+};++export const createShapeOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ objectIdField,+ { key: 'shapeType', label: 'Shape Type' },+ ...geometryFields,+ { key: 'text', label: 'Text' },+ ],+};++export const insertTextOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ objectIdField,+ ...cellFields,+ { key: 'insertedAt', label: 'Inserted At Index', format: 'number' },+ { key: 'text', label: 'Text After Insert' },+ ],+};++export const setElementTextOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ objectIdField,+ ...cellFields,+ { key: 'text', label: 'Text' },+ { key: 'changed', label: 'Changed', format: 'boolean' },+ ],+};++export const updateTextStyleOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ objectIdField,+ { key: 'rangesStyled', label: 'Ranges Styled', format: 'number' },+ { key: 'updatedFields', label: 'Updated Styles' },+ ],+};++export const updateParagraphStyleOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ objectIdField,+ { key: 'rangesStyled', label: 'Ranges Styled', format: 'number' },+ { key: 'alignment', label: 'Alignment' },+ { key: 'bullets', label: 'Bullets' },+ ],+};++export const updateShapePropertiesOutputSchema: OutputSchema = {+ fields: [presentationIdField, slideObjectIdField, objectIdField, { key: 'updatedFields', label: 'Updated Properties' }],+};++export const moveResizeElementOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ objectIdField,+ ...geometryFields,+ { key: 'rotationDegrees', label: 'Rotation (degrees)', format: 'number' },+ ],+};++export const deleteElementsOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'deletedObjectIds', label: 'Deleted Object IDs' },+ { key: 'deletedCount', label: 'Deleted', format: 'number' },+ { key: 'slideObjectIds', label: 'Slide Object IDs' },+ ],+};++export const createTableOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ { key: 'tableObjectId', label: 'Table Object ID' },+ { key: 'rows', label: 'Rows', format: 'number' },+ { key: 'columns', label: 'Columns', format: 'number' },+ { key: 'filledCells', label: 'Cells Filled', format: 'number' },+ ],+};++export const tableLinesOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ { key: 'tableObjectId', label: 'Table Object ID' },+ { key: 'dimension', label: 'Dimension' },+ { key: 'position', label: 'Position', format: 'number' },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'rows', label: 'Rows Now', format: 'number' },+ { key: 'columns', label: 'Columns Now', format: 'number' },+ ],+};++export const setSlideBackgroundOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ { key: 'slideObjectIds', label: 'Slide Object IDs' },+ { key: 'slideCount', label: 'Slides Changed', format: 'number' },+ { key: 'backgroundType', label: 'Background Type' },+ { key: 'color', label: 'Color' },+ { key: 'imageUrl', label: 'Image URL', format: 'url' },+ ],+};++export const insertVideoOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ { key: 'videoObjectId', label: 'Video Object ID' },+ { key: 'source', label: 'Source' },+ { key: 'videoId', label: 'Video ID' },+ ],+};++export const replaceImageOutputSchema: OutputSchema = {+ fields: [+ presentationIdField,+ slideObjectIdField,+ { key: 'imageObjectId', label: 'Image Object ID' },+ { key: 'imageUrl', label: 'Image URL', format: 'url' },+ { key: 'fit', label: 'Fit' },+ ],+};diff --git a/packages/pieces/community/google-slides/test/atomics.test.ts b/packages/pieces/community/google-slides/test/atomics.test.tsnew file mode 100644index 00000000000..9916c089e6f--- /dev/null+++ b/packages/pieces/community/google-slides/test/atomics.test.ts@@ -0,0 +1,667 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { HttpError, HttpMethod, HttpRequest, httpClient } from '@activepieces/pieces-common';+import {+ Action,+ AppConnectionType,+ createMockActionContext,+ InputPropertyMap,+ StaticPropsValue,+} from '@activepieces/pieces-framework';+import { googleSlide } from '../src';+import { googleSlidesAuth, GoogleSlidesAuthValue } from '../src/lib/auth';+import { Presentation } from '../src/lib/commons/common';+import { createShape } from '../src/lib/actions/create-shape';+import { createTable } from '../src/lib/actions/create-table';+import { deleteElements } from '../src/lib/actions/delete-elements';+import { deleteTableRowsOrColumns } from '../src/lib/actions/delete-table-rows-or-columns';+import { insertTableRowsOrColumns } from '../src/lib/actions/insert-table-rows-or-columns';+import { insertText } from '../src/lib/actions/insert-text';+import { insertVideo } from '../src/lib/actions/insert-video';+import { listSlideElements } from '../src/lib/actions/list-slide-elements';+import { moveResizeElement } from '../src/lib/actions/move-resize-element';+import { replaceImage } from '../src/lib/actions/replace-image';+import { setElementText } from '../src/lib/actions/set-element-text';+import { setSlideBackground } from '../src/lib/actions/set-slide-background';+import { updateParagraphStyle } from '../src/lib/actions/update-paragraph-style';+import { updateShapeProperties } from '../src/lib/actions/update-shape-properties';+import { updateTextStyle } from '../src/lib/actions/update-text-style';++const PID = '1AbCdEfGhIjKlMnOpQrStUvWxYz';+const URL_INPUT = `https://docs.google.com/presentation/d/${PID}/edit#slide=id.s1`;++const AUTH: GoogleSlidesAuthValue = {+ type: AppConnectionType.OAUTH2,+ access_token: 'test-token',+ client_id: 'client',+ client_secret: 'secret',+ redirect_url: 'https://example.com',+ token_type: 'Bearer',+ claimed_at: 0,+ refresh_token: 'refresh',+ scope: '',+ token_url: 'https://oauth2.googleapis.com/token',+ data: {},+};++const TABLE_DATA: Record<string, unknown> = JSON.parse('[["Region","Q1"],["EMEA",12]]');++const size = { width: { magnitude: 3000000, unit: 'EMU' }, height: { magnitude: 1000000, unit: 'EMU' } };++function deck(): Presentation {+ return {+ presentationId: PID,+ revisionId: 'rev1',+ pageSize: { width: { magnitude: 9144000, unit: 'EMU' }, height: { magnitude: 5143500, unit: 'EMU' } },+ slides: [+ {+ objectId: 's1',+ pageElements: [+ {+ objectId: 'box1',+ size,+ transform: { scaleX: 1, scaleY: 1, translateX: 127000, translateY: 254000, unit: 'EMU' },+ shape: { shapeType: 'TEXT_BOX', text: { textElements: [{ paragraphMarker: {} }, { textRun: { content: 'Hello world\n' } }] } },+ },+ {+ objectId: 'tbl1',+ size,+ transform: { scaleX: 1, scaleY: 1, unit: 'EMU' },+ table: {+ rows: 2,+ columns: 2,+ tableColumns: [{ columnWidth: { magnitude: 1270000, unit: 'EMU' } }, { columnWidth: { magnitude: 1270000, unit: 'EMU' } }],+ tableRows: [+ { rowHeight: { magnitude: 254000, unit: 'EMU' }, tableCells: [{ text: { textElements: [{ textRun: { content: 'A\n' } }] } }, {}] },+ { rowHeight: { magnitude: 254000, unit: 'EMU' }, tableCells: [{}, { text: { textElements: [{ textRun: { content: 'D\n' } }] } }] },+ ],+ },+ },+ { objectId: 'img1', size, transform: { scaleX: 1, scaleY: 1, unit: 'EMU' }, image: { contentUrl: 'https://lh3.googleusercontent.com/x' } },+ {+ objectId: 'grp1',+ transform: { scaleX: 1, scaleY: 1, translateX: 1270000, unit: 'EMU' },+ elementGroup: {+ children: [+ { objectId: 'child1', size, transform: { scaleX: 2, scaleY: 1, translateX: 127000, unit: 'EMU' }, shape: { shapeType: 'RECTANGLE' } },+ ],+ },+ },+ {+ objectId: 'rot1',+ size,+ transform: { scaleX: 0, scaleY: 0, shearX: -1, shearY: 1, unit: 'EMU' },+ shape: { shapeType: 'RECTANGLE' },+ },+ ],+ },+ { objectId: 's2', pageElements: [] },+ ],+ };+}++let posts: unknown[] = [];+let gets: HttpRequest[] = [];+let failBatchWith: HttpError | undefined;++beforeEach(() => {+ posts = [];+ gets = [];+ failBatchWith = undefined;+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {+ if (request.method === HttpMethod.POST) {+ if (failBatchWith) {+ throw failBatchWith;+ }+ posts.push(request.body);+ return { status: 200, headers: {}, body: { presentationId: PID, replies: [] } };+ }+ gets.push(request);+ const pageId = request.url.split('/pages/')[1];+ const page = pageId ? deck().slides?.find((slide) => slide.objectId === pageId) : undefined;+ return { status: 200, headers: {}, body: page ?? deck() };+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++function run<Props extends InputPropertyMap>({+ action,+ propsValue,+}: {+ action: Action<typeof googleSlidesAuth, Props>;+ propsValue: StaticPropsValue<Props>;+}): Promise<unknown> {+ return action.run({ ...createMockActionContext<Props>({ propsValue }), auth: AUTH });+}++describe('registration and metadata', () => {+ const atomics = [+ listSlideElements,+ createShape,+ insertText,+ setElementText,+ updateTextStyle,+ updateParagraphStyle,+ updateShapeProperties,+ moveResizeElement,+ deleteElements,+ createTable,+ insertTableRowsOrColumns,+ deleteTableRowsOrColumns,+ setSlideBackground,+ insertVideo,+ replaceImage,+ ];++ it('registers the 15 atomics as ai-only with an output schema', () => {+ const registered = Object.keys(googleSlide.actions());+ for (const action of atomics) {+ expect(registered).toContain(action.name);+ expect(action.audience).toBe('ai');+ expect(action.outputSchema?.fields.length).toBeGreaterThan(0);+ expect(action.aiMetadata?.description?.length).toBeGreaterThan(100);+ }+ expect(registered).toHaveLength(35);+ });++ it('classifies by side effect', () => {+ expect(listSlideElements.classification).toBe('READ');+ expect(deleteElements.classification).toBe('DESTRUCTIVE');+ expect(deleteTableRowsOrColumns.classification).toBe('DESTRUCTIVE');+ expect(createShape.classification).toBe('WRITE');+ expect(createShape.aiMetadata?.idempotent).toBe(false);+ expect(setElementText.aiMetadata?.idempotent).toBe(true);+ });+});++describe('list_slide_elements', () => {+ it('returns geometry in points, composing group transforms', async () => {+ const output = await run({ action: listSlideElements, propsValue: { presentation_id: URL_INPUT, slide_number: 1, slide_object_id: undefined } });+ expect(gets.map((request) => request.url)).toEqual([+ `https://slides.googleapis.com/v1/presentations/${PID}`,+ `https://slides.googleapis.com/v1/presentations/${PID}/pages/s1`,+ ]);+ expect(gets[0].queryParams).toEqual({ fields: 'presentationId,pageSize,slides(objectId)' });+ expect(output).toMatchObject({ presentationId: PID, slideObjectId: 's1', slideWidth: 720, slideHeight: 405, elementCount: 6 });+ expect(output).toHaveProperty('elements', expect.arrayContaining([+ expect.objectContaining({ objectId: 'box1', type: 'SHAPE', x: 10, y: 20, width: 236.22, height: 78.74, text: 'Hello world' }),+ expect.objectContaining({ objectId: 'tbl1', type: 'TABLE', width: 200, height: 40, tableRows: 2, tableColumns: 2, tableCells: [['A', ''], ['', 'D']] }),+ expect.objectContaining({ objectId: 'child1', parentGroupId: 'grp1', x: 110, width: 472.44 }),+ expect.objectContaining({ objectId: 'grp1', type: 'GROUP', x: 110, y: 0, width: 472.44, height: 78.74 }),+ expect.objectContaining({ objectId: 'rot1', rotationDegrees: 90 }),+ ]));+ });+});++describe('create_shape', () => {+ it('sends createShape, insertText and the fill in one batch, in EMU', async () => {+ const output = await run({+ action: createShape,+ propsValue: { presentation_id: PID, slide_number: undefined, slide_object_id: 's2', shape_type: 'ELLIPSE', x: 40, y: 24, width: 100, height: 50, text: 'Hi', fill_color: '#ffffff' },+ });+ expect(gets).toHaveLength(0);+ const objectId = expect.stringMatching(/^shape_[0-9a-f]{32}$/);+ expect(posts).toEqual([+ {+ requests: [+ {+ createShape: {+ objectId,+ shapeType: 'ELLIPSE',+ elementProperties: {+ pageObjectId: 's2',+ size: { width: { magnitude: 1270000, unit: 'EMU' }, height: { magnitude: 635000, unit: 'EMU' } },+ transform: { scaleX: 1, scaleY: 1, shearX: 0, shearY: 0, translateX: 508000, translateY: 304800, unit: 'EMU' },+ },+ },+ },+ { insertText: { objectId, text: 'Hi', insertionIndex: 0 } },+ {+ updateShapeProperties: {+ objectId,+ shapeProperties: { shapeBackgroundFill: { propertyState: 'RENDERED', solidFill: { color: { rgbColor: { red: 1, green: 1, blue: 1 } }, alpha: 1 } } },+ fields: 'shapeBackgroundFill.propertyState,shapeBackgroundFill.solidFill.color,shapeBackgroundFill.solidFill.alpha',+ },+ },+ ],+ },+ ]);+ expect(output).toMatchObject({ presentationId: PID, slideObjectId: 's2', shapeType: 'ELLIPSE', x: 40, width: 100, text: 'Hi', objectId });+ });++ it('defaults to a text box and refuses a missing size before any request', async () => {+ await expect(+ run({ action: createShape, propsValue: { presentation_id: PID, slide_number: 1, slide_object_id: undefined, shape_type: undefined, x: 1, y: 1, width: 0, height: 5, text: undefined, fill_color: undefined } })+ ).rejects.toThrow(/greater than 0/);+ expect(gets).toHaveLength(0);+ await run({ action: createShape, propsValue: { presentation_id: PID, slide_number: 1, slide_object_id: undefined, shape_type: undefined, x: 1, y: 1, width: 5, height: 5, text: undefined, fill_color: undefined } });+ expect(gets[0].queryParams).toEqual({ fields: 'revisionId,slides(objectId)' });+ expect(posts).toEqual([+ { requests: [expect.objectContaining({ createShape: expect.objectContaining({ shapeType: 'TEXT_BOX' }) })], writeControl: { requiredRevisionId: 'rev1' } },+ ]);+ });++ it('adds a hint when Google cannot find an object', async () => {+ failBatchWith = new HttpError({}, { status: 400, responseBody: { error: { code: 400, message: 'The object (s9) could not be found.' } } });+ await expect(+ run({ action: createShape, propsValue: { presentation_id: PID, slide_number: undefined, slide_object_id: 's9', shape_type: undefined, x: 1, y: 1, width: 5, height: 5, text: undefined, fill_color: undefined } })+ ).rejects.toThrow('Could not create the shape: Google rejected the request (400). Google says: The object (s9) could not be found. Check the object IDs with Get Presentation Outline or List Slide Elements.');+ });+});++describe('insert_text and set_element_text', () => {+ it('appends before the trailing newline and pins the revision', async () => {+ const output = await run({ action: insertText, propsValue: { presentation_id: PID, object_id: 'box1', row: undefined, column: undefined, text: '!', insertion_index: undefined } });+ expect(gets[0].queryParams).toEqual({ fields: 'presentationId,revisionId,pageSize,slides(objectId,pageElements)' });+ expect(posts).toEqual([{ requests: [{ insertText: { objectId: 'box1', text: '!', insertionIndex: 11 } }], writeControl: { requiredRevisionId: 'rev1' } }]);+ expect(output).toEqual({ presentationId: PID, slideObjectId: 's1', objectId: 'box1', row: null, column: null, insertedAt: 11, text: 'Hello world!' });+ });++ it('explains wrong ids, kinds and cells', async () => {+ const base = { presentation_id: PID, row: undefined, column: undefined, text: 'x', insertion_index: undefined };+ await expect(run({ action: insertText, propsValue: { ...base, object_id: 'nope' } })).rejects.toThrow(/No element with object ID "nope".*List Slide Elements/);+ await expect(run({ action: insertText, propsValue: { ...base, object_id: 's1' } })).rejects.toThrow(/"s1" is a slide, not an element/);+ await expect(run({ action: insertText, propsValue: { ...base, object_id: 'img1' } })).rejects.toThrow(/is an IMAGE; text actions work on shapes/);+ await expect(run({ action: insertText, propsValue: { ...base, object_id: 'tbl1' } })).rejects.toThrow(/is a table \(2 x 2\): set Row and Column/);+ await expect(run({ action: insertText, propsValue: { ...base, object_id: 'tbl1', row: 3, column: 1 } })).rejects.toThrow(/outside the table/);+ await expect(run({ action: insertText, propsValue: { ...base, object_id: 'box1', insertion_index: 12 } })).rejects.toThrow(/between 0 and 11/);+ expect(posts).toHaveLength(0);+ });++ it('rewrites a table cell, and sends nothing when unchanged', async () => {+ const output = await run({ action: setElementText, propsValue: { presentation_id: PID, object_id: 'tbl1', row: 1, column: 1, text: 'B', clear_text: undefined } });+ expect(posts).toEqual([+ {+ requests: [+ { deleteText: { objectId: 'tbl1', cellLocation: { rowIndex: 0, columnIndex: 0 }, textRange: { type: 'ALL' } } },+ { insertText: { objectId: 'tbl1', cellLocation: { rowIndex: 0, columnIndex: 0 }, text: 'B', insertionIndex: 0 } },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ expect(output).toMatchObject({ row: 1, column: 1, changed: true, text: 'B' });+ posts = [];+ const same = await run({ action: setElementText, propsValue: { presentation_id: PID, object_id: 'box1', row: undefined, column: undefined, text: 'Hello world', clear_text: undefined } });+ expect(posts).toHaveLength(0);+ expect(same).toMatchObject({ changed: false });+ });++ it('needs Clear Text to empty an element', async () => {+ await expect(+ run({ action: setElementText, propsValue: { presentation_id: PID, object_id: 'box1', row: undefined, column: undefined, text: undefined, clear_text: undefined } })+ ).rejects.toThrow(/turn on Clear Text/);+ await run({ action: setElementText, propsValue: { presentation_id: PID, object_id: 'box1', row: undefined, column: undefined, text: undefined, clear_text: true } });+ expect(posts).toEqual([{ requests: [{ deleteText: { objectId: 'box1', textRange: { type: 'ALL' } } }], writeControl: { requiredRevisionId: 'rev1' } }]);+ });+});++describe('update_text_style and update_paragraph_style', () => {+ it('styles every match with a computed field mask', async () => {+ const output = await run({+ action: updateTextStyle,+ propsValue: {+ presentation_id: PID,+ object_id: 'box1',+ row: undefined,+ column: undefined,+ match_text: 'world',+ start_index: undefined,+ end_index: undefined,+ bold: true,+ italic: undefined,+ underline: undefined,+ strikethrough: undefined,+ font_family: undefined,+ font_size: 32,+ text_color: '#1A73E8',+ highlight_color: undefined,+ link_url: undefined,+ },+ });+ expect(posts).toEqual([+ {+ requests: [+ {+ updateTextStyle: {+ objectId: 'box1',+ style: { bold: true, fontSize: { magnitude: 32, unit: 'PT' }, foregroundColor: { opaqueColor: { rgbColor: { red: 0.102, green: 0.451, blue: 0.9098 } } } },+ textRange: { type: 'FIXED_RANGE', startIndex: 6, endIndex: 11 },+ fields: 'bold,fontSize,foregroundColor',+ },+ },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ expect(output).toEqual({ presentationId: PID, slideObjectId: 's1', objectId: 'box1', rangesStyled: 1, updatedFields: ['bold', 'fontSize', 'foregroundColor'] });+ });++ it('refuses no styles, a bad link and text-less elements', async () => {+ const base = {+ presentation_id: PID,+ object_id: 'box1',+ row: undefined,+ column: undefined,+ match_text: undefined,+ start_index: undefined,+ end_index: undefined,+ bold: undefined,+ italic: undefined,+ underline: undefined,+ strikethrough: undefined,+ font_family: undefined,+ font_size: undefined,+ text_color: undefined,+ highlight_color: undefined,+ link_url: undefined,+ };+ await expect(run({ action: updateTextStyle, propsValue: base })).rejects.toThrow(/at least one style/);+ await expect(run({ action: updateTextStyle, propsValue: { ...base, link_url: 'javascript:alert(1)' } })).rejects.toThrow(/http/);+ await expect(run({ action: updateTextStyle, propsValue: { ...base, object_id: 'child1', bold: true } })).rejects.toThrow(/no text yet/);+ expect(gets).toHaveLength(1);+ await run({ action: updateTextStyle, propsValue: { ...base, link_url: 'none' } });+ expect(posts).toEqual([+ { requests: [{ updateTextStyle: { objectId: 'box1', style: {}, textRange: { type: 'ALL' }, fields: 'link' } }], writeControl: { requiredRevisionId: 'rev1' } },+ ]);+ });++ it('sets alignment and bullets on a table cell', async () => {+ await run({+ action: updateParagraphStyle,+ propsValue: {+ presentation_id: PID,+ object_id: 'tbl1',+ row: 2,+ column: 2,+ match_text: undefined,+ start_index: undefined,+ end_index: undefined,+ alignment: 'CENTER',+ line_spacing: undefined,+ space_above: undefined,+ space_below: undefined,+ bullets: 'BULLET_CHECKBOX',+ },+ });+ const cellLocation = { rowIndex: 1, columnIndex: 1 };+ expect(posts).toEqual([+ {+ requests: [+ { updateParagraphStyle: { objectId: 'tbl1', cellLocation, style: { alignment: 'CENTER' }, textRange: { type: 'ALL' }, fields: 'alignment' } },+ { createParagraphBullets: { objectId: 'tbl1', cellLocation, textRange: { type: 'ALL' }, bulletPreset: 'BULLET_CHECKBOX' } },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ });+});++describe('update_shape_properties', () => {+ it('updates a shape and refuses other kinds', async () => {+ const base = { presentation_id: PID, fill_color: undefined, outline_color: '#000000', outline_weight: undefined, outline_dash: undefined, content_alignment: 'BOTTOM' };+ await run({ action: updateShapeProperties, propsValue: { ...base, object_id: 'box1' } });+ expect(posts).toEqual([+ {+ requests: [+ {+ updateShapeProperties: {+ objectId: 'box1',+ shapeProperties: {+ outline: { propertyState: 'RENDERED', outlineFill: { solidFill: { color: { rgbColor: { red: 0, green: 0, blue: 0 } }, alpha: 1 } } },+ contentAlignment: 'BOTTOM',+ },+ fields: 'outline.propertyState,outline.outlineFill.solidFill.color,outline.outlineFill.solidFill.alpha,contentAlignment',+ },+ },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ await expect(run({ action: updateShapeProperties, propsValue: { ...base, object_id: 'tbl1' } })).rejects.toThrow(/is a TABLE; this action only changes shapes/);+ });+});++describe('move_resize_element', () => {+ it('keeps the aspect ratio when only the width is given', async () => {+ const output = await run({ action: moveResizeElement, propsValue: { presentation_id: PID, object_id: 'box1', x: undefined, y: undefined, width: 472.44, height: undefined } });+ expect(posts).toEqual([+ {+ requests: [+ {+ updatePageElementTransform: {+ objectId: 'box1',+ applyMode: 'ABSOLUTE',+ transform: { scaleX: expect.closeTo(2, 4), scaleY: expect.closeTo(2, 4), shearX: 0, shearY: 0, translateX: 127000, translateY: 254000, unit: 'EMU' },+ },+ },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ expect(output).toMatchObject({ objectId: 'box1', x: 10, y: 20, width: 472.44, height: 157.48 });+ });++ it('moves a group by its bounding box and refuses group children, tables and rotated resizes', async () => {+ const moved = await run({ action: moveResizeElement, propsValue: { presentation_id: PID, object_id: 'grp1', x: 0, y: 36, width: undefined, height: undefined } });+ expect(moved).toMatchObject({ objectId: 'grp1', x: 0, y: 36, width: 472.44, height: 78.74 });+ expect(posts).toEqual([+ {+ requests: [+ {+ updatePageElementTransform: {+ objectId: 'grp1',+ applyMode: 'ABSOLUTE',+ transform: { scaleX: 1, scaleY: 1, shearX: 0, shearY: 0, translateX: -127000, translateY: 457200, unit: 'EMU' },+ },+ },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ const base = { presentation_id: PID, x: undefined, y: undefined, width: 10, height: undefined };+ await expect(run({ action: moveResizeElement, propsValue: { ...base, object_id: 'child1' } })).rejects.toThrow(/inside the group "grp1"/);+ await expect(run({ action: moveResizeElement, propsValue: { ...base, object_id: 'rot1' } })).rejects.toThrow(/rotated or skewed/);+ await expect(run({ action: moveResizeElement, propsValue: { ...base, object_id: 'tbl1' } })).rejects.toThrow(/is a table: it can only be moved/);+ await expect(run({ action: moveResizeElement, propsValue: { ...base, object_id: 'grp1' } })).rejects.toThrow(/is a group: it can only be moved/);+ await expect(+ run({ action: moveResizeElement, propsValue: { presentation_id: PID, object_id: 'box1', x: undefined, y: undefined, width: undefined, height: undefined } })+ ).rejects.toThrow(/at least one of X, Y/);+ });+});++describe('delete_elements', () => {+ it('deletes a group once when its child is listed too, atomically', async () => {+ const output = await run({ action: deleteElements, propsValue: { presentation_id: PID, object_ids: ['child1', 'grp1', 'box1', 'box1'] } });+ expect(posts).toEqual([+ { requests: [{ deleteObject: { objectId: 'grp1' } }, { deleteObject: { objectId: 'box1' } }], writeControl: { requiredRevisionId: 'rev1' } },+ ]);+ expect(output).toEqual({ presentationId: PID, deletedObjectIds: ['child1', 'grp1', 'box1'], deletedCount: 3, slideObjectIds: ['s1'] });+ });++ it('refuses slides, unknown ids and an empty list', async () => {+ await expect(run({ action: deleteElements, propsValue: { presentation_id: PID, object_ids: ['s2'] } })).rejects.toThrow(/Delete Slide/);+ await expect(run({ action: deleteElements, propsValue: { presentation_id: PID, object_ids: ['box1', 'gone'] } })).rejects.toThrow(/"gone"/);+ await expect(run({ action: deleteElements, propsValue: { presentation_id: PID, object_ids: [] } })).rejects.toThrow(/at least one/);+ expect(posts).toHaveLength(0);+ });+});++describe('tables', () => {+ it('creates and fills a table with a styled header', async () => {+ const output = await run({+ action: createTable,+ propsValue: {+ presentation_id: PID,+ slide_number: undefined,+ slide_object_id: 's1',+ data: TABLE_DATA,+ rows: undefined,+ columns: undefined,+ header_bold: true,+ header_fill_color: '#000000',+ x: undefined,+ y: undefined,+ width: undefined,+ height: undefined,+ },+ });+ const objectId = expect.stringMatching(/^table_[0-9a-f]{32}$/);+ const insert = ({ rowIndex, columnIndex, text }: { rowIndex: number; columnIndex: number; text: string }) => ({+ insertText: { objectId, cellLocation: { rowIndex, columnIndex }, text, insertionIndex: 0 },+ });+ const bold = (columnIndex: number) => ({+ updateTextStyle: { objectId, cellLocation: { rowIndex: 0, columnIndex }, style: { bold: true }, textRange: { type: 'ALL' }, fields: 'bold' },+ });+ expect(posts).toEqual([+ {+ requests: [+ { createTable: { objectId, elementProperties: { pageObjectId: 's1' }, rows: 2, columns: 2 } },+ insert({ rowIndex: 0, columnIndex: 0, text: 'Region' }),+ insert({ rowIndex: 0, columnIndex: 1, text: 'Q1' }),+ insert({ rowIndex: 1, columnIndex: 0, text: 'EMEA' }),+ insert({ rowIndex: 1, columnIndex: 1, text: '12' }),+ bold(0),+ bold(1),+ {+ updateTableCellProperties: {+ objectId,+ tableRange: { location: { rowIndex: 0, columnIndex: 0 }, rowSpan: 1, columnSpan: 2 },+ tableCellProperties: { tableCellBackgroundFill: { solidFill: { color: { rgbColor: { red: 0, green: 0, blue: 0 } }, alpha: 1 } } },+ fields: 'tableCellBackgroundFill.solidFill.color,tableCellBackgroundFill.solidFill.alpha',+ },+ },+ ],+ },+ ]);+ expect(output).toMatchObject({ presentationId: PID, slideObjectId: 's1', tableObjectId: objectId, rows: 2, columns: 2, filledCells: 4 });+ });++ it('appends a row with values and reports the new size', async () => {+ const output = await run({+ action: insertTableRowsOrColumns,+ propsValue: { presentation_id: PID, table_object_id: 'tbl1', dimension: 'ROW', position: undefined, count: undefined, values: ['x', 'y'] },+ });+ expect(posts).toEqual([+ {+ requests: [+ { insertTableRows: { tableObjectId: 'tbl1', cellLocation: { rowIndex: 1, columnIndex: 0 }, insertBelow: true, number: 1 } },+ { insertText: { objectId: 'tbl1', cellLocation: { rowIndex: 2, columnIndex: 0 }, text: 'x', insertionIndex: 0 } },+ { insertText: { objectId: 'tbl1', cellLocation: { rowIndex: 2, columnIndex: 1 }, text: 'y', insertionIndex: 0 } },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ expect(output).toMatchObject({ tableObjectId: 'tbl1', position: 3, count: 1, rows: 3, columns: 2 });+ await expect(+ run({ action: insertTableRowsOrColumns, propsValue: { presentation_id: PID, table_object_id: 'box1', dimension: 'ROW', position: undefined, count: undefined, values: undefined } })+ ).rejects.toThrow(/needs a table/);+ });++ it('deletes a column and refuses emptying the table', async () => {+ const output = await run({+ action: deleteTableRowsOrColumns,+ propsValue: { presentation_id: PID, table_object_id: 'tbl1', dimension: 'COLUMN', position: 2, count: undefined },+ });+ expect(posts).toEqual([+ { requests: [{ deleteTableColumn: { tableObjectId: 'tbl1', cellLocation: { rowIndex: 0, columnIndex: 1 } } }], writeControl: { requiredRevisionId: 'rev1' } },+ ]);+ expect(output).toMatchObject({ rows: 2, columns: 1 });+ await expect(+ run({ action: deleteTableRowsOrColumns, propsValue: { presentation_id: PID, table_object_id: 'tbl1', dimension: 'ROW', position: 1, count: 2 } })+ ).rejects.toThrow(/at least one row/);+ await expect(+ run({ action: deleteTableRowsOrColumns, propsValue: { presentation_id: PID, table_object_id: 'tbl1', dimension: 'DIAGONAL', position: 1, count: 1 } })+ ).rejects.toThrow(/ROW, COLUMN/);+ });+});++describe('set_slide_background', () => {+ it('sets every slide to an image', async () => {+ const output = await run({+ action: setSlideBackground,+ propsValue: { presentation_id: PID, slide_number: undefined, slide_object_id: undefined, all_slides: true, color: undefined, image_url: 'https://example.com/bg.png' },+ });+ const request = (objectId: string) => ({+ updatePageProperties: { objectId, pageProperties: { pageBackgroundFill: { stretchedPictureFill: { contentUrl: 'https://example.com/bg.png' } } }, fields: 'pageBackgroundFill' },+ });+ expect(posts).toEqual([{ requests: [request('s1'), request('s2')], writeControl: { requiredRevisionId: 'rev1' } }]);+ expect(output).toEqual({ presentationId: PID, slideObjectIds: ['s1', 's2'], slideCount: 2, backgroundType: 'IMAGE', color: null, imageUrl: 'https://example.com/bg.png' });+ });++ it('sets one slide to a colour and refuses mixed inputs', async () => {+ const output = await run({+ action: setSlideBackground,+ propsValue: { presentation_id: PID, slide_number: 2, slide_object_id: undefined, all_slides: undefined, color: 'fff', image_url: undefined },+ });+ expect(posts).toEqual([+ {+ requests: [+ { updatePageProperties: { objectId: 's2', pageProperties: { pageBackgroundFill: { solidFill: { color: { rgbColor: { red: 1, green: 1, blue: 1 } }, alpha: 1 } } }, fields: 'pageBackgroundFill' } },+ ],+ writeControl: { requiredRevisionId: 'rev1' },+ },+ ]);+ expect(output).toMatchObject({ color: '#FFFFFF', backgroundType: 'COLOR' });+ await expect(+ run({ action: setSlideBackground, propsValue: { presentation_id: PID, slide_number: 1, slide_object_id: undefined, all_slides: true, color: '#000', image_url: undefined } })+ ).rejects.toThrow(/All Slides is on/);+ await expect(+ run({ action: setSlideBackground, propsValue: { presentation_id: PID, slide_number: 1, slide_object_id: undefined, all_slides: undefined, color: '#000', image_url: 'https://e.com/a.png' } })+ ).rejects.toThrow(/exactly one/);+ await expect(+ run({ action: setSlideBackground, propsValue: { presentation_id: PID, slide_number: 3, slide_object_id: undefined, all_slides: undefined, color: '#000', image_url: undefined } })+ ).rejects.toThrow(/out of range/);+ });+});++describe('insert_video and replace_image', () => {+ it('creates a YouTube video from a URL', async () => {+ const output = await run({+ action: insertVideo,+ propsValue: { presentation_id: PID, slide_number: undefined, slide_object_id: 's1', video: 'https://youtu.be/M7lc1UVf-VE', source: undefined, x: 10, y: 10, width: undefined, height: undefined },+ });+ const objectId = expect.stringMatching(/^video_[0-9a-f]{32}$/);+ expect(posts).toEqual([+ {+ requests: [+ {+ createVideo: {+ objectId,+ source: 'YOUTUBE',+ id: 'M7lc1UVf-VE',+ elementProperties: { pageObjectId: 's1', transform: { scaleX: 1, scaleY: 1, shearX: 0, shearY: 0, translateX: 127000, translateY: 127000, unit: 'EMU' } },+ },+ },+ ],+ },+ ]);+ expect(output).toMatchObject({ slideObjectId: 's1', videoObjectId: objectId, source: 'YOUTUBE', videoId: 'M7lc1UVf-VE' });+ });++ it('replaces an image and refuses non-images', async () => {+ const output = await run({+ action: replaceImage,+ propsValue: { presentation_id: PID, image_object_id: 'img1', image_url: 'https://example.com/new.png', replace_method: undefined },+ });+ expect(posts).toEqual([+ { requests: [{ replaceImage: { imageObjectId: 'img1', url: 'https://example.com/new.png', imageReplaceMethod: 'CENTER_INSIDE' } }], writeControl: { requiredRevisionId: 'rev1' } },+ ]);+ expect(output).toEqual({ presentationId: PID, slideObjectId: 's1', imageObjectId: 'img1', imageUrl: 'https://example.com/new.png', fit: 'CENTER_INSIDE' });+ await expect(+ run({ action: replaceImage, propsValue: { presentation_id: PID, image_object_id: 'box1', image_url: 'https://example.com/new.png', replace_method: undefined } })+ ).rejects.toThrow(/is a SHAPE; this action only replaces images/);+ });+});++describe('error mapping on the read', () => {+ it('maps a 404 on the deck read', async () => {+ vi.spyOn(httpClient, 'sendRequest').mockRejectedValue(+ new HttpError({}, { status: 404, responseBody: { error: { code: 404, message: 'Requested entity was not found.' } } })+ );+ await expect(+ run({ action: insertText, propsValue: { presentation_id: PID, object_id: 'box1', row: undefined, column: undefined, text: 'x', insertion_index: undefined } })+ ).rejects.toThrow('Could not insert the text: not found (404).');+ });+});diff --git a/packages/pieces/community/google-slides/test/element-requests.test.ts b/packages/pieces/community/google-slides/test/element-requests.test.tsnew file mode 100644index 00000000000..cebffdff72e--- /dev/null+++ b/packages/pieces/community/google-slides/test/element-requests.test.ts@@ -0,0 +1,243 @@+import { describe, expect, it } from 'vitest';+import { slidesElementRequests } from '../src/lib/commons/element-requests';+import { slidesElements } from '../src/lib/commons/elements';++describe('units and colours', () => {+ it('converts points to EMU and back', () => {+ expect(slidesElements.ptToEmu(1)).toBe(12700);+ expect(slidesElements.ptToEmu(720)).toBe(9144000);+ expect(slidesElements.emuToPt(5143500)).toBe(405);+ expect(slidesElements.dimensionToEmu({ magnitude: 10, unit: 'PT' })).toBe(127000);+ expect(slidesElements.dimensionToEmu({ magnitude: 500, unit: 'EMU' })).toBe(500);+ });++ it('builds element properties in EMU', () => {+ const box = slidesElements.readBox({ x: 40, y: '24', width: 640, height: 80, required: true });+ expect(slidesElements.buildElementProperties({ pageObjectId: 's1', box })).toEqual({+ pageObjectId: 's1',+ size: { width: { magnitude: 8128000, unit: 'EMU' }, height: { magnitude: 1016000, unit: 'EMU' } },+ transform: { scaleX: 1, scaleY: 1, shearX: 0, shearY: 0, translateX: 508000, translateY: 304800, unit: 'EMU' },+ });+ });++ it('validates boxes', () => {+ expect(() => slidesElements.readBox({ x: 1, y: undefined, width: undefined, height: undefined, required: false })).toThrow(/both X and Y/);+ expect(() => slidesElements.readBox({ x: 1, y: 1, width: 5, height: undefined, required: false })).toThrow(/both Width and Height/);+ expect(() => slidesElements.readBox({ x: 1, y: 1, width: 0, height: 5, required: false })).toThrow(/greater than 0/);+ expect(() => slidesElements.readBox({ x: 1, y: 1, width: undefined, height: undefined, required: true })).toThrow(/720 x 405/);+ expect(slidesElements.readBox({ x: undefined, y: undefined, width: undefined, height: undefined, required: false })).toEqual({});+ });++ it('parses hex colours', () => {+ expect(slidesElements.parseHexColor({ value: '#FFFFFF', label: 'c' })).toEqual({ red: 1, green: 1, blue: 1 });+ expect(slidesElements.parseHexColor({ value: '1a73e8', label: 'c' })).toEqual({ red: 0.102, green: 0.451, blue: 0.9098 });+ expect(slidesElements.parseHexColor({ value: '#f00', label: 'c' })).toEqual({ red: 1, green: 0, blue: 0 });+ expect(() => slidesElements.parseHexColor({ value: 'blue', label: 'Fill Color' })).toThrow(/Fill Color must be a hex colour/);+ expect(slidesElements.readColor({ value: 'transparent', label: 'c' })).toEqual({ kind: 'none' });+ expect(slidesElements.readColor({ value: '', label: 'c' })).toBeUndefined();+ });++ it('reads booleans in three states', () => {+ expect(slidesElements.readBoolean({ value: undefined, label: 'Bold' })).toBeUndefined();+ expect(slidesElements.readBoolean({ value: false, label: 'Bold' })).toBe(false);+ expect(slidesElements.readBoolean({ value: 'true', label: 'Bold' })).toBe(true);+ expect(() => slidesElements.readBoolean({ value: 'yes', label: 'Bold' })).toThrow(/true or false/);+ });+});++describe('text ranges', () => {+ const target = { objectId: 'box', text: 'Revenue up, Revenue down\n' };++ it('defaults to ALL and finds every match', () => {+ expect(slidesElements.resolveTextRanges({ target, matchText: undefined, startIndex: undefined, endIndex: undefined })).toEqual([{ type: 'ALL' }]);+ expect(slidesElements.resolveTextRanges({ target, matchText: 'Revenue', startIndex: undefined, endIndex: undefined })).toEqual([+ { type: 'FIXED_RANGE', startIndex: 0, endIndex: 7 },+ { type: 'FIXED_RANGE', startIndex: 12, endIndex: 19 },+ ]);+ expect(slidesElements.resolveTextRanges({ target, matchText: undefined, startIndex: 3, endIndex: undefined })).toEqual([+ { type: 'FIXED_RANGE', startIndex: 3, endIndex: 24 },+ ]);+ });++ it('refuses empty text, no match, bad ranges and mixed modes', () => {+ expect(() => slidesElements.resolveTextRanges({ target: { objectId: 'e', text: '' }, matchText: undefined, startIndex: undefined, endIndex: undefined })).toThrow(/no text yet/);+ expect(() => slidesElements.resolveTextRanges({ target, matchText: 'revenue', startIndex: undefined, endIndex: undefined })).toThrow(/does not appear/);+ expect(() => slidesElements.resolveTextRanges({ target, matchText: undefined, startIndex: 5, endIndex: 2 })).toThrow(/0 <= start < end <= 25/);+ expect(() => slidesElements.resolveTextRanges({ target, matchText: 'up', startIndex: 0, endIndex: undefined })).toThrow(/not both/);+ });+});++describe('text request builders', () => {+ const cell = { objectId: 't1', cellLocation: { rowIndex: 1, columnIndex: 0 }, text: 'Old\n' };++ it('inserts at the end before the trailing newline, or at an index', () => {+ expect(slidesElementRequests.buildInsertTextRequest({ target: cell, text: '!', insertionIndex: undefined })).toEqual({+ request: { insertText: { objectId: 't1', cellLocation: { rowIndex: 1, columnIndex: 0 }, text: '!', insertionIndex: 3 } },+ insertedAt: 3,+ newText: 'Old!',+ });+ expect(slidesElementRequests.buildInsertTextRequest({ target: { objectId: 'b', text: '' }, text: 'Hi', insertionIndex: undefined }).insertedAt).toBe(0);+ expect(() => slidesElementRequests.buildInsertTextRequest({ target: cell, text: 'x', insertionIndex: 4 })).toThrow(/between 0 and 3/);+ });++ it('replaces text only when it changed', () => {+ expect(slidesElementRequests.buildSetTextRequests({ target: cell, text: 'New' })).toEqual([+ { deleteText: { objectId: 't1', cellLocation: { rowIndex: 1, columnIndex: 0 }, textRange: { type: 'ALL' } } },+ { insertText: { objectId: 't1', cellLocation: { rowIndex: 1, columnIndex: 0 }, text: 'New', insertionIndex: 0 } },+ ]);+ expect(slidesElementRequests.buildSetTextRequests({ target: cell, text: 'Old' })).toEqual([]);+ expect(slidesElementRequests.buildSetTextRequests({ target: { objectId: 'b', text: '\n' }, text: 'A' })).toEqual([+ { insertText: { objectId: 'b', text: 'A', insertionIndex: 0 } },+ ]);+ expect(slidesElementRequests.buildSetTextRequests({ target: cell, text: '' })).toEqual([+ { deleteText: { objectId: 't1', cellLocation: { rowIndex: 1, columnIndex: 0 }, textRange: { type: 'ALL' } } },+ ]);+ });++ it('builds a text style with only the fields that were set', () => {+ expect(+ slidesElementRequests.buildTextStyle({+ bold: false,+ fontSizePt: 18,+ textColor: { kind: 'rgb', rgbColor: { red: 1, green: 0, blue: 0 } },+ highlightColor: { kind: 'none' },+ link: null,+ })+ ).toEqual({+ style: { bold: false, fontSize: { magnitude: 18, unit: 'PT' }, foregroundColor: { opaqueColor: { rgbColor: { red: 1, green: 0, blue: 0 } } }, backgroundColor: {} },+ fields: ['bold', 'fontSize', 'foregroundColor', 'backgroundColor', 'link'],+ });+ expect(() => slidesElementRequests.buildTextStyle({})).toThrow(/at least one style/);+ });++ it('builds paragraph and bullet requests per range', () => {+ const requests = slidesElementRequests.buildParagraphRequests({+ target: { objectId: 'b', text: 'A\nB\n' },+ ranges: [{ type: 'ALL' }],+ input: { alignment: 'CENTER', spaceBelowPt: 6, bullets: 'NONE' },+ });+ expect(requests).toEqual([+ {+ updateParagraphStyle: {+ objectId: 'b',+ style: { alignment: 'CENTER', spaceBelow: { magnitude: 6, unit: 'PT' } },+ textRange: { type: 'ALL' },+ fields: 'alignment,spaceBelow',+ },+ },+ { deleteParagraphBullets: { objectId: 'b', textRange: { type: 'ALL' } } },+ ]);+ expect(+ slidesElementRequests.buildParagraphRequests({ target: { objectId: 'b', text: 'A\n' }, ranges: [{ type: 'ALL' }], input: { bullets: 'BULLET_CHECKBOX' } })+ ).toEqual([{ createParagraphBullets: { objectId: 'b', textRange: { type: 'ALL' }, bulletPreset: 'BULLET_CHECKBOX' } }]);+ });+});++describe('shape properties', () => {+ it('renders a fill and an outline', () => {+ expect(+ slidesElementRequests.buildShapeProperties({+ fillColor: { kind: 'rgb', rgbColor: { red: 0, green: 0, blue: 1 } },+ outlineWeightPt: 2,+ outlineDash: 'DASH',+ contentAlignment: 'MIDDLE',+ })+ ).toEqual({+ shapeProperties: {+ shapeBackgroundFill: { propertyState: 'RENDERED', solidFill: { color: { rgbColor: { red: 0, green: 0, blue: 1 } }, alpha: 1 } },+ outline: { propertyState: 'RENDERED', weight: { magnitude: 2, unit: 'PT' }, dashStyle: 'DASH' },+ contentAlignment: 'MIDDLE',+ },+ fields: [+ 'shapeBackgroundFill.propertyState',+ 'shapeBackgroundFill.solidFill.color',+ 'shapeBackgroundFill.solidFill.alpha',+ 'outline.propertyState',+ 'outline.weight',+ 'outline.dashStyle',+ 'contentAlignment',+ ],+ });+ });++ it('hides fill and outline', () => {+ expect(slidesElementRequests.buildShapeProperties({ fillColor: { kind: 'none' }, outlineColor: { kind: 'none' } })).toEqual({+ shapeProperties: { shapeBackgroundFill: { propertyState: 'NOT_RENDERED' }, outline: { propertyState: 'NOT_RENDERED' } },+ fields: ['shapeBackgroundFill.propertyState', 'outline.propertyState'],+ });+ expect(() => slidesElementRequests.buildShapeProperties({ outlineColor: { kind: 'none' }, outlineWeightPt: 1 })).toThrow(/leave Outline Weight/);+ });+});++describe('tables', () => {+ it('reads data and sizes the table from it', () => {+ const data = slidesElementRequests.readTableData('[["a","b"],[1,null,true]]');+ expect(data).toEqual([['a', 'b'], ['1', '', 'true']]);+ expect(slidesElementRequests.resolveTableSize({ rows: undefined, columns: undefined, data })).toEqual({ rows: 2, columns: 3 });+ expect(() => slidesElementRequests.resolveTableSize({ rows: 1, columns: undefined, data })).toThrow(/does not fit/);+ expect(() => slidesElementRequests.resolveTableSize({ rows: undefined, columns: undefined, data: undefined })).toThrow(/at least 1/);+ expect(() => slidesElementRequests.readTableData([['a', { x: 1 }]])).toThrow(/row 1, column 2/);+ expect(() => slidesElementRequests.readTableData('{nope')).toThrow(/valid JSON/);+ });++ it('builds the inserts for rows and columns', () => {+ expect(+ slidesElementRequests.buildInsertTableLinesRequests({+ tableObjectId: 't',+ dimension: 'ROW',+ rows: 3,+ columns: 2,+ position: undefined,+ count: 1,+ values: ['x', ''],+ })+ ).toEqual({+ requests: [+ { insertTableRows: { tableObjectId: 't', cellLocation: { rowIndex: 2, columnIndex: 0 }, insertBelow: true, number: 1 } },+ { insertText: { objectId: 't', cellLocation: { rowIndex: 3, columnIndex: 0 }, text: 'x', insertionIndex: 0 } },+ ],+ insertedAt: 4,+ });+ expect(+ slidesElementRequests.buildInsertTableLinesRequests({ tableObjectId: 't', dimension: 'COLUMN', rows: 3, columns: 2, position: 1, count: 2, values: undefined })+ .requests+ ).toEqual([{ insertTableColumns: { tableObjectId: 't', cellLocation: { rowIndex: 0, columnIndex: 0 }, insertRight: false, number: 2 } }]);+ expect(() =>+ slidesElementRequests.buildInsertTableLinesRequests({ tableObjectId: 't', dimension: 'ROW', rows: 3, columns: 2, position: 5, count: 1, values: undefined })+ ).toThrow(/between 1 and 4/);+ expect(() =>+ slidesElementRequests.buildInsertTableLinesRequests({ tableObjectId: 't', dimension: 'ROW', rows: 3, columns: 2, position: undefined, count: 21, values: undefined })+ ).toThrow(/between 1 and 20/);+ expect(() =>+ slidesElementRequests.buildInsertTableLinesRequests({ tableObjectId: 't', dimension: 'ROW', rows: 3, columns: 2, position: undefined, count: 1, values: ['a', 'b', 'c'] })+ ).toThrow(/at most 2/);+ });++ it('deletes at a fixed index and keeps at least one line', () => {+ expect(+ slidesElementRequests.buildDeleteTableLinesRequests({ tableObjectId: 't', dimension: 'ROW', rows: 4, columns: 2, position: 2, count: 2 })+ ).toEqual([+ { deleteTableRow: { tableObjectId: 't', cellLocation: { rowIndex: 1, columnIndex: 0 } } },+ { deleteTableRow: { tableObjectId: 't', cellLocation: { rowIndex: 1, columnIndex: 0 } } },+ ]);+ expect(() =>+ slidesElementRequests.buildDeleteTableLinesRequests({ tableObjectId: 't', dimension: 'COLUMN', rows: 4, columns: 2, position: 1, count: 2 })+ ).toThrow(/at least one column/);+ expect(() =>+ slidesElementRequests.buildDeleteTableLinesRequests({ tableObjectId: 't', dimension: 'ROW', rows: 4, columns: 2, position: 4, count: 2 })+ ).toThrow(/has 4 row/);+ });+});++describe('videos', () => {+ it('detects YouTube and Drive sources', () => {+ expect(slidesElements.readVideo({ value: 'https://www.youtube.com/watch?v=M7lc1UVf-VE&t=3', source: undefined })).toEqual({ source: 'YOUTUBE', id: 'M7lc1UVf-VE' });+ expect(slidesElements.readVideo({ value: 'https://youtu.be/M7lc1UVf-VE', source: undefined })).toEqual({ source: 'YOUTUBE', id: 'M7lc1UVf-VE' });+ expect(slidesElements.readVideo({ value: 'https://www.youtube.com/shorts/M7lc1UVf-VE', source: undefined }).id).toBe('M7lc1UVf-VE');+ expect(slidesElements.readVideo({ value: 'https://drive.google.com/file/d/1AbCdEfGhIjKlMnOp/view', source: undefined })).toEqual({ source: 'DRIVE', id: '1AbCdEfGhIjKlMnOp' });+ expect(slidesElements.readVideo({ value: '1AbCdEfGhIjKlMnOp', source: 'DRIVE' })).toEqual({ source: 'DRIVE', id: '1AbCdEfGhIjKlMnOp' });+ expect(() => slidesElements.readVideo({ value: '1AbCdEfGhIjKlMnOp', source: undefined })).toThrow(/set Source to DRIVE/);+ expect(() => slidesElements.readVideo({ value: 'https://www.youtube.com.evil.io/watch?v=M7lc1UVf-VE', source: undefined })).toThrow(/not a YouTube/);+ expect(() => slidesElements.readVideo({ value: 'https://youtu.be/M7lc1UVf-VE', source: 'DRIVE' })).toThrow(/YOUTUBE link/);+ });+});diff --git a/packages/pieces/community/google-slides/test/errors.test.ts b/packages/pieces/community/google-slides/test/errors.test.tsnew file mode 100644index 00000000000..f0ab60b6ba8--- /dev/null+++ b/packages/pieces/community/google-slides/test/errors.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';+import { HttpError } from '@activepieces/pieces-common';+import { slidesApi } from '../src/lib/commons/common';++function gaxiosError({ status, data }: { status: number; data: unknown }) {+ return Object.assign(new Error('Request failed'), { code: status, response: { status, data } });+}++describe('googleApiError', () => {+ it('reads Google message from gaxios data when body is an already-read stream', () => {+ const error = Object.assign(new Error('Request failed'), {+ code: 403,+ response: {+ status: 403,+ body: { locked: true, readable: false },+ data: { error: { code: 403, message: "The user's Drive storage quota has been exceeded.", errors: [{ reason: 'storageQuotaExceeded' }] } },+ },+ });+ expect(slidesApi.googleApiError({ error, action: 'create the presentation' }).message).toBe(+ "Could not create the presentation: the account has no Google Drive storage left. A service account has no storage of its own, so pick a folder in a Shared Drive it is a member of. Google says: The user's Drive storage quota has been exceeded."+ );+ });++ it('keeps Google message for a gaxios 403 with a stream body', () => {+ const error = Object.assign(new Error('Request failed'), {+ code: 403,+ response: { status: 403, body: { locked: true }, data: { error: { code: 403, message: 'The caller does not have permission' } } },+ });+ expect(slidesApi.googleApiError({ error, action: 'add the slide' }).message).toMatch(/permission denied \(403\).*Google says: The caller does not have permission/);+ });++ it('maps httpClient errors with Google message', () => {+ const error = new HttpError({}, { status: 404, responseBody: { error: { code: 404, message: 'Requested entity was not found.' } } });+ const mapped = slidesApi.googleApiError({ error, action: 'get the presentation' });+ expect(mapped.message).toBe(+ 'Could not get the presentation: not found (404). Check the ID, and that the file is shared with the connected account. Google says: Requested entity was not found.'+ );+ });++ it.each([+ [400, /rejected the request \(400\)/],+ [401, /Reconnect the account/],+ [403, /permission denied \(403\)/],+ [429, /rate limit/],+ [500, /\(HTTP 500\)/],+ ])('maps gaxios status %i', (status, pattern) => {+ expect(slidesApi.googleApiError({ error: gaxiosError({ status, data: { error: { message: 'x' } } }), action: 'copy' }).message).toMatch(pattern);+ });++ it('explains a stale revision instead of a generic 400', () => {+ const error = new HttpError(+ {},+ { status: 400, responseBody: { error: { code: 400, message: "The required revision ID 'abc' does not match the latest revision." } } }+ );+ expect(slidesApi.googleApiError({ error, action: 'move the slide' }).message).toBe(+ "Could not move the slide: the presentation changed since it was read, so nothing was changed. Run the step again (for Batch Update, first get a fresh Required Revision ID from Get Presentation Outline). Google says: The required revision ID 'abc' does not match the latest revision."+ );+ const other = new HttpError({}, { status: 400, responseBody: { error: { code: 400, message: 'Invalid requests[0].createShape' } } });+ expect(slidesApi.googleApiError({ error: other, action: 'x' }).message).toMatch(/rejected the request \(400\)/);+ });++ it('decodes an arraybuffer error body and spots the export size limit', () => {+ const body = Buffer.from(JSON.stringify({ error: { message: 'too big', errors: [{ reason: 'exportSizeLimitExceeded' }] } }));+ const arrayBuffer = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);+ expect(slidesApi.googleApiError({ error: gaxiosError({ status: 403, data: arrayBuffer }), action: 'export the presentation' }).message).toMatch(+ /10 MB export limit/+ );+ });++ it('returns errors without an HTTP status unchanged', () => {+ const original = new Error('Set both X and Y, or leave both empty.');+ expect(slidesApi.googleApiError({ error: original, action: 'x' })).toBe(original);+ expect(slidesApi.googleApiError({ error: 'boom', action: 'x' }).message).toBe('boom');+ });++ it('builds slide URLs', () => {+ expect(slidesApi.slideUrl({ presentationId: 'abc', slideObjectId: 'p' })).toBe('https://docs.google.com/presentation/d/abc/edit#slide=id.p');+ });+});diff --git a/packages/pieces/community/google-slides/test/ids.test.ts b/packages/pieces/community/google-slides/test/ids.test.tsnew file mode 100644index 00000000000..2abb11d748c--- /dev/null+++ b/packages/pieces/community/google-slides/test/ids.test.ts@@ -0,0 +1,91 @@+import { describe, expect, it } from 'vitest';+import { slidesIds } from '../src/lib/commons/ids';++const ID = '1uZH8nHgfKRCkQNbLxdEwNnT9b2eIinM4igBaMT9RWlc';++describe('parsePresentationId', () => {+ it.each([+ [ID],+ [`https://docs.google.com/presentation/d/${ID}/edit`],+ [`https://docs.google.com/presentation/d/${ID}/edit#slide=id.p`],+ [`https://docs.google.com/presentation/u/1/d/${ID}/edit?usp=sharing`],+ [`https://docs.google.com/presentation/d/${ID}`],+ [`https://drive.google.com/file/d/${ID}/view`],+ [`https://drive.google.com/open?id=${ID}`],+ [` ${ID} `],+ ])('reads %s', (input) => {+ expect(slidesIds.parsePresentationId(input)).toBe(ID);+ });++ it('rejects published-to-web links with a specific message', () => {+ expect(() => slidesIds.parsePresentationId('https://docs.google.com/presentation/d/e/2PACX-1vabc/pub')).toThrow(+ /Publish to the web/+ );+ });++ it.each([+ [''],+ [undefined],+ ['short'],+ ['../../etc/passwd'],+ [`${ID}/../x`],+ [`https://docs.google.com.evil.io/presentation/d/${ID}/edit`],+ [`https://evil.io/presentation/d/${ID}/edit`],+ [`https://docs.google.com/document/d/${ID}/edit`],+ ])('rejects %s', (input) => {+ expect(() => slidesIds.parsePresentationId(input)).toThrow();+ });+});++describe('parseObjectId', () => {+ it('reads bare IDs including the 1-character default slide ID', () => {+ expect(slidesIds.parseObjectId('p')).toBe('p');+ expect(slidesIds.parseObjectId('g2c8d1e5a7f_0_12')).toBe('g2c8d1e5a7f_0_12');+ expect(slidesIds.parseObjectId('SLIDES_API1:x-y')).toBe('SLIDES_API1:x-y');+ });++ it('reads the slide ID from a slide URL', () => {+ expect(slidesIds.parseObjectId(`https://docs.google.com/presentation/d/${ID}/edit#slide=id.g12_0_3`)).toBe('g12_0_3');+ });++ it.each([['bad id!'], ['a/b'], [`https://docs.google.com/presentation/d/${ID}/edit`], ['https://evil.io/x#slide=id.p']])(+ 'rejects %s',+ (input) => {+ expect(() => slidesIds.parseObjectId(input)).toThrow();+ }+ );+});++describe('parseFolderId', () => {+ it('returns undefined for empty input', () => {+ expect(slidesIds.parseFolderId('')).toBeUndefined();+ expect(slidesIds.parseFolderId(undefined)).toBeUndefined();+ });++ it('reads bare IDs and folder URLs', () => {+ expect(slidesIds.parseFolderId('0AITOlPXvClRfUk9PVA')).toBe('0AITOlPXvClRfUk9PVA');+ expect(slidesIds.parseFolderId('https://drive.google.com/drive/folders/0AITOlPXvClRfUk9PVA')).toBe('0AITOlPXvClRfUk9PVA');+ expect(slidesIds.parseFolderId('https://drive.google.com/drive/u/0/folders/abc_DEF-123?usp=sharing')).toBe('abc_DEF-123');+ });++ it("rejects values that could break out of the Drive query", () => {+ expect(() => slidesIds.parseFolderId("x' or name contains '")).toThrow();+ });+});++describe('generateObjectId', () => {+ it('follows the Slides object ID rule (5-50 chars, [a-zA-Z0-9_] first)', () => {+ const id = slidesIds.generateObjectId('slide');+ expect(id).toMatch(/^[a-zA-Z0-9_][a-zA-Z0-9_\-:]{4,49}$/);+ expect(slidesIds.generateObjectId('image')).not.toBe(slidesIds.generateObjectId('image'));+ });+});++describe('validateImageUrl', () => {+ it('accepts http(s) URLs and rejects others', () => {+ expect(slidesIds.validateImageUrl(' https://cdn.example.com/a.png ')).toBe('https://cdn.example.com/a.png');+ expect(() => slidesIds.validateImageUrl('ftp://x/y.png')).toThrow();+ expect(() => slidesIds.validateImageUrl('not a url')).toThrow();+ expect(() => slidesIds.validateImageUrl(`https://x.io/${'a'.repeat(2100)}`)).toThrow(/2 KB/);+ });+});diff --git a/packages/pieces/community/google-slides/test/presentation-text.test.ts b/packages/pieces/community/google-slides/test/presentation-text.test.tsnew file mode 100644index 00000000000..dcd8668cfa8--- /dev/null+++ b/packages/pieces/community/google-slides/test/presentation-text.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from 'vitest';+import { slidesText } from '../src/lib/commons/presentation-text';+import { Presentation } from '../src/lib/commons/common';++function shape({ objectId, runs }: { objectId: string; runs: string[] }) {+ return { objectId, shape: { text: { textElements: runs.map((content) => ({ textRun: { content } })) } } };+}++const presentation: Presentation = {+ presentationId: 'pres_1',+ title: 'Deck',+ revisionId: 'rev1',+ layouts: [{ objectId: 'lay1', layoutProperties: { name: 'TITLE_AND_BODY', displayName: 'Title and body' } }],+ slides: [+ {+ objectId: 's1',+ slideProperties: {+ layoutObjectId: 'lay1',+ notesPage: {+ notesProperties: { speakerNotesObjectId: 'n1' },+ pageElements: [shape({ objectId: 'n1', runs: ['Say {{notes_token}}\n'] })],+ },+ },+ pageElements: [+ {+ objectId: 'title1',+ shape: {+ placeholder: { type: 'TITLE' },+ text: { textElements: [{ paragraphMarker: {} }, { textRun: { content: 'Hello {{name}}\n' } }] },+ },+ },+ {+ objectId: 'group1',+ elementGroup: {+ children: [+ shape({ objectId: 'g1', runs: ['Grouped {{grouped}}'] }),+ { objectId: 'inner', elementGroup: { children: [shape({ objectId: 'g2', runs: ['{{deep}}'] }), { objectId: 'c1', sheetsChart: { chartId: 1 } }] } },+ ],+ },+ },+ shape({ objectId: 'split', runs: ['Split {{spl', 'it_token}} here\n'] }),+ {+ objectId: 'table1',+ table: { tableRows: [{ tableCells: [{ text: { textElements: [{ textRun: { content: 'Cell {{cell}}\n' } }] } }, {}] }] },+ },+ { objectId: 'chart_top', sheetsChart: { chartId: 2 } },+ shape({ objectId: 'dupe', runs: ['{{name}} again [[bracket]] {{ spaced }}'] }),+ ],+ },+ ],+};++describe('discoverPlaceholders', () => {+ it('finds tokens in groups (any depth), split runs, table cells and speaker notes, once each', () => {+ expect(slidesText.discoverPlaceholders({ presentation, format: '{{}}' })).toEqual([+ 'name',+ 'grouped',+ 'deep',+ 'split_token',+ 'cell',+ ' spaced ',+ 'notes_token',+ ]);+ });++ it('uses the square-bracket syntax when chosen', () => {+ expect(slidesText.discoverPlaceholders({ presentation, format: '[[]]' })).toEqual(['bracket']);+ });+});++describe('findSheetsCharts', () => {+ it('includes charts inside nested groups', () => {+ expect(slidesText.findSheetsCharts(presentation)).toEqual(['c1', 'chart_top']);+ });+});++describe('buildOutline', () => {+ it('flattens slides with title, text, notes, layout name and element IDs', () => {+ const outline = slidesText.buildOutline(presentation);+ expect(outline.slideCount).toBe(1);+ const slide = outline.slides[0];+ expect(slide).toMatchObject({+ slideNumber: 1,+ objectId: 's1',+ slideUrl: 'https://docs.google.com/presentation/d/pres_1/edit#slide=id.s1',+ layoutName: 'Title and body',+ title: 'Hello {{name}}',+ speakerNotes: 'Say {{notes_token}}',+ isSkipped: false,+ });+ expect(slide.elements.map((element) => element.objectId)).toEqual([+ 'title1', 'group1', 'g1', 'inner', 'g2', 'c1', 'split', 'table1', 'chart_top', 'dupe',+ ]);+ expect(slide.elements.find((element) => element.objectId === 'table1')?.text).toBe('Cell {{cell}}');+ expect(slide.text).toContain('Split {{split_token}} here');+ });++ it('returns empty notes when the notes shape does not exist yet', () => {+ expect(+ slidesText.speakerNotesText({+ objectId: 's',+ slideProperties: { notesPage: { notesProperties: { speakerNotesObjectId: 'missing' }, pageElements: [] } },+ })+ ).toBe('');+ });+});diff --git a/packages/pieces/community/google-slides/test/requests.test.ts b/packages/pieces/community/google-slides/test/requests.test.tsnew file mode 100644index 00000000000..c2177b0b49d--- /dev/null+++ b/packages/pieces/community/google-slides/test/requests.test.ts@@ -0,0 +1,244 @@+import { describe, expect, it } from 'vitest';+import { slidesRequests } from '../src/lib/commons/requests';+import { Page } from '../src/lib/commons/common';++const slides = [{ objectId: 'a' }, { objectId: 'b' }, { objectId: 'c' }];++describe('slide selection', () => {+ it('needs exactly one of number or object ID', () => {+ expect(() => slidesRequests.readSlideSelector({ slideNumber: undefined, slideObjectId: '' })).toThrow(/either/);+ expect(() => slidesRequests.readSlideSelector({ slideNumber: 1, slideObjectId: 'a' })).toThrow(/only one/);+ expect(slidesRequests.readSlideSelector({ slideNumber: '2', slideObjectId: undefined })).toEqual({ slideNumber: 2 });+ expect(() => slidesRequests.readSlideSelector({ slideNumber: 0, slideObjectId: undefined })).toThrow(/starts at 1/);+ expect(() => slidesRequests.readSlideSelector({ slideNumber: 1.5, slideObjectId: undefined })).toThrow(/whole number/);+ });++ it('resolves numbers and object IDs and refuses unknown ones', () => {+ expect(slidesRequests.resolveSlide({ slides, selector: { slideNumber: 3 } })).toEqual({ objectId: 'c', index: 2 });+ expect(slidesRequests.resolveSlide({ slides, selector: { slideObjectId: 'b' } })).toEqual({ objectId: 'b', index: 1 });+ expect(() => slidesRequests.resolveSlide({ slides, selector: { slideNumber: 4 } })).toThrow(/out of range/);+ expect(() => slidesRequests.resolveSlide({ slides, selector: { slideObjectId: 'shape_1' } })).toThrow(/No slide/);+ });++ it('reads 1-based positions into 0-based indexes', () => {+ expect(slidesRequests.readPosition({ position: undefined, maxPosition: 3 })).toBeUndefined();+ expect(slidesRequests.readPosition({ position: 1, maxPosition: 3 })).toBe(0);+ expect(() => slidesRequests.readPosition({ position: 4, maxPosition: 3 })).toThrow(/between 1 and 3/);+ });+});++describe('moveInsertionIndex', () => {+ it('accounts for the "arrangement before the move" rule', () => {+ expect(slidesRequests.moveInsertionIndex({ currentIndex: 0, targetIndex: 3 })).toBe(4);+ expect(slidesRequests.moveInsertionIndex({ currentIndex: 3, targetIndex: 0 })).toBe(0);+ expect(slidesRequests.moveInsertionIndex({ currentIndex: 2, targetIndex: 2 })).toBe(2);+ });+});++describe('buildAddSlideRequests', () => {+ const layouts: Page[] = [+ {+ objectId: 'lay_title',+ layoutProperties: { name: 'TITLE' },+ pageElements: [+ { objectId: 'x1', shape: { placeholder: { type: 'CENTERED_TITLE', index: 0 } } },+ { objectId: 'x2', shape: { placeholder: { type: 'SUBTITLE', index: 0 } } },+ ],+ },+ {+ objectId: 'lay_tb',+ layoutProperties: { name: 'TITLE_AND_BODY' },+ pageElements: [+ { objectId: 'y1', shape: { placeholder: { type: 'TITLE' } } },+ { objectId: 'y2', shape: { placeholder: { type: 'BODY', index: 2 } } },+ { objectId: 'y3', shape: { placeholder: { type: 'BODY', index: 1 } } },+ ],+ },+ { objectId: 'lay_blank', layoutProperties: { name: 'BLANK' }, pageElements: [] },+ ];+ const newId = (prefix: string) => `${prefix}_00001`;++ it('maps the TITLE layout to CENTERED_TITLE + SUBTITLE and sends one atomic batch', () => {+ const built = slidesRequests.buildAddSlideRequests({+ layouts,+ predefinedLayout: 'TITLE',+ insertionIndex: 0,+ title: 'Hello',+ body: 'World',+ newId,+ });+ expect(built.requests).toEqual([+ {+ createSlide: {+ objectId: 'slide_00001',+ insertionIndex: 0,+ slideLayoutReference: { layoutId: 'lay_title' },+ placeholderIdMappings: [+ { layoutPlaceholder: { type: 'CENTERED_TITLE', index: 0 }, objectId: 'title_00001' },+ { layoutPlaceholder: { type: 'SUBTITLE', index: 0 }, objectId: 'body_00001' },+ ],+ },+ },+ { insertText: { objectId: 'title_00001', text: 'Hello', insertionIndex: 0 } },+ { insertText: { objectId: 'body_00001', text: 'World', insertionIndex: 0 } },+ ]);+ expect(built).toMatchObject({ titleObjectId: 'title_00001', bodyObjectId: 'body_00001' });+ });++ it('uses the lowest-index BODY placeholder and omits empty fields', () => {+ const built = slidesRequests.buildAddSlideRequests({ layouts, predefinedLayout: 'TITLE_AND_BODY', body: 'B', newId });+ expect(built.requests).toEqual([+ {+ createSlide: {+ objectId: 'slide_00001',+ slideLayoutReference: { layoutId: 'lay_tb' },+ placeholderIdMappings: [{ layoutPlaceholder: { type: 'BODY', index: 1 }, objectId: 'body_00001' }],+ },+ },+ { insertText: { objectId: 'body_00001', text: 'B', insertionIndex: 0 } },+ ]);+ expect(built.titleObjectId).toBeNull();+ });++ it('fails before writing when the layout or placeholder is missing', () => {+ expect(() => slidesRequests.buildAddSlideRequests({ layouts, predefinedLayout: 'BLANK', title: 'x', newId })).toThrow(+ /no title placeholder/+ );+ expect(() => slidesRequests.buildAddSlideRequests({ layouts, predefinedLayout: 'MAIN_POINT', newId })).toThrow(+ /Available layouts: TITLE, TITLE_AND_BODY, BLANK/+ );+ });+});++describe('buildDuplicateRequests', () => {+ it('only duplicates when no position is given', () => {+ expect(+ slidesRequests.buildDuplicateRequests({ sourceObjectId: 'a', sourceIndex: 0, newObjectId: 'slide_new1' })+ ).toEqual({ requests: [{ duplicateObject: { objectId: 'a', objectIds: { a: 'slide_new1' } } }], finalIndex: 1 });+ });++ it('moves the copy in the same batch', () => {+ expect(+ slidesRequests.buildDuplicateRequests({ sourceObjectId: 'b', sourceIndex: 1, newObjectId: 'slide_new1', targetIndex: 0 })+ ).toEqual({+ requests: [+ { duplicateObject: { objectId: 'b', objectIds: { b: 'slide_new1' } } },+ { updateSlidesPosition: { slideObjectIds: ['slide_new1'], insertionIndex: 0 } },+ ],+ finalIndex: 0,+ });+ });+});++describe('buildSpeakerNotesRequests', () => {+ it('deletes only when there is text, inserts only when there are notes, and no-ops when unchanged', () => {+ const id = 'n1';+ expect(slidesRequests.buildSpeakerNotesRequests({ speakerNotesObjectId: id, currentNotes: '', notes: 'Hi' })).toEqual([+ { insertText: { objectId: id, text: 'Hi', insertionIndex: 0 } },+ ]);+ expect(slidesRequests.buildSpeakerNotesRequests({ speakerNotesObjectId: id, currentNotes: 'Old', notes: '' })).toEqual([+ { deleteText: { objectId: id, textRange: { type: 'ALL' } } },+ ]);+ expect(slidesRequests.buildSpeakerNotesRequests({ speakerNotesObjectId: id, currentNotes: 'Same', notes: 'Same' })).toEqual([]);+ });+});++describe('image geometry', () => {+ it('requires size and position as pairs', () => {+ expect(() => slidesRequests.readImageGeometry({ width: 10 })).toThrow(/Width and Height/);+ expect(() => slidesRequests.readImageGeometry({ x: 10 })).toThrow(/X and Y/);+ expect(() => slidesRequests.readImageGeometry({ width: 0, height: 5 })).toThrow(/greater than 0/);+ expect(slidesRequests.readImageGeometry({})).toEqual({});+ });++ it('builds the createImage request in points', () => {+ const geometry = slidesRequests.readImageGeometry({ x: '10', y: 20, width: 100, height: 50 });+ expect(slidesRequests.buildCreateImageRequest({ objectId: 'image_1', slideObjectId: 'p', url: 'https://x.io/a.png', geometry })).toEqual({+ createImage: {+ objectId: 'image_1',+ url: 'https://x.io/a.png',+ elementProperties: {+ pageObjectId: 'p',+ size: { width: { magnitude: 100, unit: 'PT' }, height: { magnitude: 50, unit: 'PT' } },+ transform: { scaleX: 1, scaleY: 1, shearX: 0, shearY: 0, translateX: 10, translateY: 20, unit: 'PT' },+ },+ },+ });+ });+});++describe('replace requests', () => {+ it('sends an empty replacement as a real clear and scopes pages only when given', () => {+ expect(slidesRequests.buildReplaceTextRequest({ find: '[[x]]', replaceWith: '', matchCase: true })).toEqual({+ replaceAllText: { containsText: { text: '[[x]]', matchCase: true }, replaceText: '' },+ });+ expect(+ slidesRequests.buildReplaceShapesRequest({+ find: '[[logo]]',+ imageUrl: 'https://x.io/l.png',+ replaceMethod: 'CENTER_CROP',+ matchCase: false,+ pageObjectIds: ['p'],+ })+ ).toEqual({+ replaceAllShapesWithImage: {+ containsText: { text: '[[logo]]', matchCase: false },+ imageUrl: 'https://x.io/l.png',+ imageReplaceMethod: 'CENTER_CROP',+ pageObjectIds: ['p'],+ },+ });+ });++ it('reads slide scopes from IDs or URLs and ignores blanks', () => {+ expect(slidesRequests.readSlideObjectIds(undefined)).toBeUndefined();+ expect(slidesRequests.readSlideObjectIds(['', ' '])).toBeUndefined();+ expect(+ slidesRequests.readSlideObjectIds(['p', 'https://docs.google.com/presentation/d/1234567890ab/edit#slide=id.g1_0_2'])+ ).toEqual(['p', 'g1_0_2']);+ });++ it('reads occurrencesChanged, defaulting to 0 when Google omits it', () => {+ expect(slidesRequests.occurrencesChanged({ replies: [{ replaceAllText: { occurrencesChanged: 3 } }], key: 'replaceAllText' })).toBe(3);+ expect(slidesRequests.occurrencesChanged({ replies: [{ replaceAllText: {} }], key: 'replaceAllText' })).toBe(0);+ expect(slidesRequests.occurrencesChanged({ replies: [], key: 'replaceAllShapesWithImage' })).toBe(0);+ });+});++describe('buildTemplateRequests', () => {+ it('replaces every field, including title, with strings and keeps inner spacing', () => {+ expect(slidesRequests.buildTemplateRequests({ tableData: { title: 'Deck', ' name ': 'Ann', n: 5, empty: undefined }, format: '{{}}' })).toEqual([+ { replaceAllText: { containsText: { text: '{{title}}', matchCase: true }, replaceText: 'Deck' } },+ { replaceAllText: { containsText: { text: '{{ name }}', matchCase: true }, replaceText: 'Ann' } },+ { replaceAllText: { containsText: { text: '{{n}}', matchCase: true }, replaceText: '5' } },+ { replaceAllText: { containsText: { text: '{{empty}}', matchCase: true }, replaceText: '' } },+ ]);+ expect(slidesRequests.toPlaceholder({ name: 'x', format: '[[]]' })).toBe('[[x]]');+ });+});++describe('Drive helpers', () => {+ it('escapes quotes and backslashes in the search query', () => {+ expect(slidesRequests.buildFindQuery({ nameContains: "it's \\ odd", folderId: 'f1' })).toBe(+ "mimeType='application/vnd.google-apps.presentation' and trashed=false and name contains 'it\\'s \\\\ odd' and 'f1' in parents"+ );+ expect(slidesRequests.buildFindQuery({})).toBe("mimeType='application/vnd.google-apps.presentation' and trashed=false");+ });++ it('makes safe export file names', () => {+ expect(slidesRequests.exportFileName({ baseName: 'deck/q3: final', extension: 'pptx' })).toBe('deck_q3_ final.pptx');+ expect(slidesRequests.exportFileName({ baseName: 'a.pdf', extension: 'pdf' })).toBe('a.pdf');+ expect(slidesRequests.exportFileName({ baseName: ' ', extension: 'pdf' })).toBe('presentation.pdf');+ });+});++describe('readBatchRequests', () => {+ it('accepts a non-empty array of single-kind request objects, also as a JSON string', () => {+ expect(slidesRequests.readBatchRequests([{ deleteObject: { objectId: 'x' } }])).toHaveLength(1);+ expect(slidesRequests.readBatchRequests('[{"deleteObject":{"objectId":"x"}}]')).toHaveLength(1);+ });++ it.each([[[]], [{}], ['not json'], [[{ a: 1, b: 2 }]], [[null]], [[[1]]]])('rejects %j', (value) => {+ expect(() => slidesRequests.readBatchRequests(value)).toThrow();+ });+});diff --git a/packages/pieces/community/google-slides/test/revision-pinning.test.ts b/packages/pieces/community/google-slides/test/revision-pinning.test.tsnew file mode 100644index 00000000000..560335fdde5--- /dev/null+++ b/packages/pieces/community/google-slides/test/revision-pinning.test.ts@@ -0,0 +1,214 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { HttpError, HttpMethod, httpClient } from '@activepieces/pieces-common';+import {+ Action,+ AppConnectionType,+ createMockActionContext,+ InputPropertyMap,+ StaticPropsValue,+} from '@activepieces/pieces-framework';+import { googleSlidesAuth, GoogleSlidesAuthValue } from '../src/lib/auth';+import { Presentation } from '../src/lib/commons/common';+import { addSlide } from '../src/lib/actions/add-slide';+import { createShape } from '../src/lib/actions/create-shape';+import { createTable } from '../src/lib/actions/create-table';+import { deleteSlide } from '../src/lib/actions/delete-slide';+import { duplicateSlide } from '../src/lib/actions/duplicate-slide';+import { insertImage } from '../src/lib/actions/insert-image';+import { insertVideo } from '../src/lib/actions/insert-video';+import { moveSlide } from '../src/lib/actions/move-slide';+import { refreshSheetsCharts } from '../src/lib/actions/refresh-charts';+import { setSpeakerNotes } from '../src/lib/actions/set-speaker-notes';++const PID = '1AbCdEfGhIjKlMnOpQrStUvWxYz';+const REVISION = 'rev-read-1';+const PINNED = { requiredRevisionId: REVISION };++const AUTH: GoogleSlidesAuthValue = {+ type: AppConnectionType.OAUTH2,+ access_token: 'test-token',+ client_id: 'client',+ client_secret: 'secret',+ redirect_url: 'https://example.com',+ token_type: 'Bearer',+ claimed_at: 0,+ refresh_token: 'refresh',+ scope: '',+ token_url: 'https://oauth2.googleapis.com/token',+ data: {},+};++const STALE = new HttpError(+ {},+ {+ status: 400,+ responseBody: {+ error: { code: 400, message: `The required revision ID '${REVISION}' does not match the latest revision.`, status: 'INVALID_ARGUMENT' },+ },+ }+);++function deck(): Presentation {+ return {+ presentationId: PID,+ revisionId: REVISION,+ layouts: [{ objectId: 'layout_blank', layoutProperties: { name: 'BLANK' }, pageElements: [] }],+ slides: [+ {+ objectId: 's1',+ pageElements: [{ objectId: 'chart1', sheetsChart: { spreadsheetId: 'sheet', chartId: 1 } }],+ slideProperties: {+ notesPage: {+ notesProperties: { speakerNotesObjectId: 'notes1' },+ pageElements: [{ objectId: 'notes1', shape: { text: { textElements: [{ textRun: { content: 'Old\n' } }] } } }],+ },+ },+ },+ { objectId: 's2', pageElements: [] },+ ],+ };+}++let posts: unknown[] = [];+let getCount = 0;+let failBatchWith: HttpError | undefined;++beforeEach(() => {+ posts = [];+ getCount = 0;+ failBatchWith = undefined;+ vi.spyOn(httpClient, 'sendRequest').mockImplementation(async (request) => {+ if (request.method === HttpMethod.POST) {+ if (failBatchWith) {+ throw failBatchWith;+ }+ posts.push(request.body);+ return { status: 200, headers: {}, body: { presentationId: PID, replies: [] } };+ }+ getCount += 1;+ return { status: 200, headers: {}, body: deck() };+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++function run<Props extends InputPropertyMap>({+ action,+ propsValue,+}: {+ action: Action<typeof googleSlidesAuth, Props>;+ propsValue: StaticPropsValue<Props>;+}): Promise<unknown> {+ return action.run({ ...createMockActionContext<Props>({ propsValue }), auth: AUTH });+}++const box = { x: 10, y: 10, width: 100, height: 50 };++const writesAfterRead: { name: string; call: () => Promise<unknown> }[] = [+ {+ name: 'create_shape',+ call: () =>+ run({+ action: createShape,+ propsValue: { presentation_id: PID, slide_number: 2, slide_object_id: undefined, shape_type: undefined, ...box, text: undefined, fill_color: undefined },+ }),+ },+ {+ name: 'create_table',+ call: () =>+ run({+ action: createTable,+ propsValue: {+ presentation_id: PID,+ slide_number: 2,+ slide_object_id: undefined,+ data: undefined,+ rows: 2,+ columns: 2,+ header_bold: undefined,+ header_fill_color: undefined,+ x: undefined,+ y: undefined,+ width: undefined,+ height: undefined,+ },+ }),+ },+ {+ name: 'insert_image',+ call: () =>+ run({+ action: insertImage,+ propsValue: { presentation_id: PID, slide_number: 2, slide_object_id: undefined, image_url: 'https://example.com/a.png', x: undefined, y: undefined, width: undefined, height: undefined },+ }),+ },+ {+ name: 'insert_video',+ call: () =>+ run({+ action: insertVideo,+ propsValue: { presentation_id: PID, slide_number: 2, slide_object_id: undefined, video: 'M7lc1UVf-VE', source: undefined, x: undefined, y: undefined, width: undefined, height: undefined },+ }),+ },+ {+ name: 'add_slide',+ call: () => run({ action: addSlide, propsValue: { presentation_id: PID, layout: 'BLANK', position: 1, title: undefined, body: undefined } }),+ },+ {+ name: 'duplicate_slide',+ call: () => run({ action: duplicateSlide, propsValue: { presentation_id: PID, slide_number: 1, slide_object_id: undefined, position: undefined } }),+ },+ {+ name: 'move_slide',+ call: () => run({ action: moveSlide, propsValue: { presentation_id: PID, slide_number: 1, slide_object_id: undefined, position: 2 } }),+ },+ {+ name: 'delete_slide',+ call: () => run({ action: deleteSlide, propsValue: { presentation_id: PID, slide_number: 2, slide_object_id: undefined } }),+ },+ {+ name: 'set_speaker_notes',+ call: () => run({ action: setSpeakerNotes, propsValue: { presentation_id: PID, slide_number: 1, slide_object_id: undefined, notes: 'New', clear_notes: undefined } }),+ },+ {+ name: 'refresh_sheets_charts',+ call: () => run({ action: refreshSheetsCharts, propsValue: { presentation_id: PID } }),+ },+];++describe('writes that follow a read pin the revision they read', () => {+ it.each(writesAfterRead)('$name sends writeControl.requiredRevisionId', async ({ call }) => {+ await call();+ expect(getCount).toBe(1);+ expect(posts).toHaveLength(1);+ expect(posts[0]).toMatchObject({ writeControl: PINNED });+ });++ it.each(writesAfterRead)('$name explains a revision mismatch', async ({ call }) => {+ failBatchWith = STALE;+ await expect(call()).rejects.toThrow(/the presentation changed since it was read, so nothing was changed\. Run the step again/);+ });++ it('skips the read and the pin when the slide is chosen by object ID', async () => {+ await run({+ action: insertImage,+ propsValue: { presentation_id: PID, slide_number: undefined, slide_object_id: 's2', image_url: 'https://example.com/a.png', x: undefined, y: undefined, width: undefined, height: undefined },+ });+ expect(getCount).toBe(0);+ expect(posts).toHaveLength(1);+ expect(posts[0]).not.toHaveProperty('writeControl');+ });++ it('places content on the slide that was read by number', async () => {+ await run({+ action: insertImage,+ propsValue: { presentation_id: PID, slide_number: 2, slide_object_id: undefined, image_url: 'https://example.com/a.png', x: undefined, y: undefined, width: undefined, height: undefined },+ });+ expect(posts[0]).toMatchObject({+ requests: [{ createImage: { elementProperties: { pageObjectId: 's2' } } }],+ writeControl: PINNED,+ });+ });+});diff --git a/packages/pieces/community/google-slides/vitest.config.ts b/packages/pieces/community/google-slides/vitest.config.tsnew file mode 100644index 00000000000..79c97261904--- /dev/null+++ b/packages/pieces/community/google-slides/vitest.config.ts@@ -0,0 +1,19 @@+import path from 'path'+import { defineConfig } from 'vitest/config'++const repoRoot = path.resolve(__dirname, '../../../..')++export default defineConfig({+ root: __dirname,+ test: {+ globals: true,+ environment: 'node',+ include: ['test/**/*.test.ts'],+ },+ resolve: {+ alias: {+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),+ },+ },+})