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(microsoft-onedrive): let agents manage files, sharing, versions and albums (#15781)
Odai Ahmadf0383d5f5229
diff --git a/bun.lock b/bun.lockindex 832ab0ebd9e..bf4312062fa 100644--- a/bun.lock+++ b/bun.lock@@ -5789,7 +5789,7 @@},"packages/pieces/community/microsoft-onedrive": {"name": "@activepieces/piece-microsoft-onedrive",- "version": "0.5.0",+ "version": "0.6.0","dependencies": {"@activepieces/core-piece-types": "workspace:*","@activepieces/core-utils": "workspace:*",diff --git a/packages/pieces/community/microsoft-onedrive/package.json b/packages/pieces/community/microsoft-onedrive/package.jsonindex 74a379a2c77..d04ee7310fa 100644--- a/packages/pieces/community/microsoft-onedrive/package.json+++ b/packages/pieces/community/microsoft-onedrive/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/piece-microsoft-onedrive",- "version": "0.5.0",+ "version": "0.6.0","main": "./dist/src/index.js","types": "./dist/src/index.d.ts","dependencies": {diff --git a/packages/pieces/community/microsoft-onedrive/src/i18n/translation.json b/packages/pieces/community/microsoft-onedrive/src/i18n/translation.jsonindex 473b92b3ca4..dfde4c57e45 100644--- a/packages/pieces/community/microsoft-onedrive/src/i18n/translation.json+++ b/packages/pieces/community/microsoft-onedrive/src/i18n/translation.json@@ -10,12 +10,82 @@"Copy File": "Copy File","List Files": "List Files","List Folders": "List Folders",+ "Add Item to Bundle": "Add Item to Bundle",+ "Check In File": "Check In File",+ "Check Out File": "Check Out File",+ "Copy File or Folder": "Copy File or Folder",+ "Create Bundle": "Create Bundle",+ "Create Folder": "Create Folder",+ "Create Sharing Link": "Create Sharing Link",+ "Create Text File": "Create Text File",+ "Remove Permission (Stop Sharing)": "Remove Permission (Stop Sharing)",+ "Delete File or Folder (to Recycle Bin)": "Delete File or Folder (to Recycle Bin)",+ "Discard Check-Out": "Discard Check-Out",+ "Convert and Download File": "Convert and Download File",+ "Download File": "Download File",+ "Download File Version": "Download File Version",+ "Get Copy Status": "Get Copy Status",+ "Get Drive": "Get Drive",+ "Get File or Folder": "Get File or Folder",+ "Get Special Folder": "Get Special Folder",+ "Share with People (Invite)": "Share with People (Invite)",+ "List Albums and Bundles": "List Albums and Bundles",+ "List Drive Changes (Delta)": "List Drive Changes (Delta)",+ "List My Drives": "List My Drives",+ "List Folder Contents": "List Folder Contents",+ "List File Permissions": "List File Permissions",+ "Get File Thumbnails": "Get File Thumbnails",+ "List File Versions": "List File Versions",+ "Move File or Folder": "Move File or Folder",+ "Remove Item from Bundle": "Remove Item from Bundle",+ "Replace File Content": "Replace File Content",+ "Resolve Sharing Link": "Resolve Sharing Link",+ "Restore File Version": "Restore File Version",+ "Search Files and Folders": "Search Files and Folders",+ "Update Permission Role": "Update Permission Role",+ "Rename / Update File or Folder": "Rename / Update File or Folder",+ "Upload File": "Upload File","Custom API Call": "Custom API Call","Upload a file to your Microsoft OneDrive with chunked upload if the file is larger than 4MiB": "Upload a file to your Microsoft OneDrive with chunked upload if the file is larger than 4MiB","Get and download a file using a File ID or filename.": "Get and download a file using a File ID or filename.","Create a copy of a file in your OneDrive, optionally in a different folder or with a new name.": "Create a copy of a file in your OneDrive, optionally in a different folder or with a new name.","List files in a OneDrive folder": "List files in a OneDrive folder","List folders in a OneDrive folder": "List folders in a OneDrive folder",+ "Add an existing file to a bundle or album.": "Add an existing file to a bundle or album.",+ "Check in a checked-out file so its changes become visible to others.": "Check in a checked-out file so its changes become visible to others.",+ "Check out a file so others cannot edit it until it is checked in.": "Check out a file so others cannot edit it until it is checked in.",+ "Start copying a OneDrive file or folder. The copy runs in the background; check it with Get Copy Status.": "Start copying a OneDrive file or folder. The copy runs in the background; check it with Get Copy Status.",+ "Create a bundle that groups existing files so they can be shared together.": "Create a bundle that groups existing files so they can be shared together.",+ "Create a folder in OneDrive, or return it if a folder with that name already exists.": "Create a folder in OneDrive, or return it if a folder with that name already exists.",+ "Create a view, edit or embed sharing link for a OneDrive file or folder.": "Create a view, edit or embed sharing link for a OneDrive file or folder.",+ "Create a plain-text file in a OneDrive folder from text you provide.": "Create a plain-text file in a OneDrive folder from text you provide.",+ "Remove a person's access or revoke a sharing link on a OneDrive file or folder.": "Remove a person's access or revoke a sharing link on a OneDrive file or folder.",+ "Move a OneDrive file or folder to the recycle bin. Deleting a folder also deletes everything in it.": "Move a OneDrive file or folder to the recycle bin. Deleting a folder also deletes everything in it.",+ "Undo a check-out and throw away any changes made while the file was checked out.": "Undo a check-out and throw away any changes made while the file was checked out.",+ "Convert a file to PDF, HTML or JPG and download the result.": "Convert a file to PDF, HTML or JPG and download the result.",+ "Download a file by its ID or path.": "Download a file by its ID or path.",+ "Download the content of a previous version of a file.": "Download the content of a previous version of a file.",+ "Check the progress of a copy started with Copy File or Folder.": "Check the progress of a copy started with Copy File or Folder.",+ "Get the connected OneDrive drive, including its type and storage quota.": "Get the connected OneDrive drive, including its type and storage quota.",+ "Get the metadata of a file or folder by its ID or path.": "Get the metadata of a file or folder by its ID or path.",+ "Get a well-known OneDrive folder such as Documents or Photos.": "Get a well-known OneDrive folder such as Documents or Photos.",+ "Grant specific people read or write access to a OneDrive file or folder.": "Grant specific people read or write access to a OneDrive file or folder.",+ "List the photo albums and file bundles in a personal OneDrive.": "List the photo albums and file bundles in a personal OneDrive.",+ "List items that changed in the drive since a saved delta token, one page at a time.": "List items that changed in the drive since a saved delta token, one page at a time.",+ "List the drives available to the signed-in user.": "List the drives available to the signed-in user.",+ "List the files and folders inside a folder, one page at a time.": "List the files and folders inside a folder, one page at a time.",+ "List who has access to a OneDrive file or folder, including sharing links.": "List who has access to a OneDrive file or folder, including sharing links.",+ "Get the small, medium and large thumbnail image URLs of a file.": "Get the small, medium and large thumbnail image URLs of a file.",+ "List the saved versions of a file.": "List the saved versions of a file.",+ "Move a OneDrive file or folder to another folder, optionally renaming it.": "Move a OneDrive file or folder to another folder, optionally renaming it.",+ "Remove a file from a bundle or album without deleting the file.": "Remove a file from a bundle or album without deleting the file.",+ "Overwrite the content of an existing OneDrive file, keeping its ID and sharing links.": "Overwrite the content of an existing OneDrive file, keeping its ID and sharing links.",+ "Look up the file or folder behind a OneDrive or SharePoint sharing link.": "Look up the file or folder behind a OneDrive or SharePoint sharing link.",+ "Make a previous version of a file the current version.": "Make a previous version of a file the current version.",+ "Search OneDrive for files and folders by name, metadata or content.": "Search OneDrive for files and folders by name, metadata or content.",+ "Change a permission on a OneDrive file or folder to read or write.": "Change a permission on a OneDrive file or folder to read or write.",+ "Rename a OneDrive file or folder, or set its description.": "Rename a OneDrive file or folder, or set its description.",+ "Upload a file to a OneDrive folder, replacing any file with the same name.": "Upload a file to a OneDrive folder, replacing any file with the same name.","Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint","File name": "File name","File": "File",@@ -27,14 +97,52 @@"Destination Folder": "Destination Folder","New Name": "New Name","Conflict Behavior": "Conflict Behavior",+ "Bundle ID": "Bundle ID",+ "Item ID": "Item ID",+ "Path": "Path",+ "Comment": "Comment",+ "Destination Folder ID": "Destination Folder ID",+ "If the Name Exists": "If the Name Exists",+ "Bundle Name": "Bundle Name",+ "Item IDs": "Item IDs",+ "Parent Folder ID": "Parent Folder ID",+ "Folder Name": "Folder Name",+ "Link Type": "Link Type",+ "Scope": "Scope",+ "Password": "Password",+ "Expiration": "Expiration",+ "Folder ID": "Folder ID",+ "File Name": "File Name",+ "Content": "Content",+ "Permission ID": "Permission ID",+ "File ID": "File ID",+ "Target Format": "Target Format",+ "Width": "Width",+ "Height": "Height",+ "Version ID": "Version ID",+ "Monitor URL": "Monitor URL",+ "Folder": "Folder",+ "Recipient Emails": "Recipient Emails",+ "Role": "Role",+ "Send Invitation Email": "Send Invitation Email",+ "Message": "Message",+ "Page Token": "Page Token",+ "Page or Delta Token": "Page or Delta Token",+ "Start From Now": "Start From Now",+ "Folder Path": "Folder Path",+ "Item Type": "Item Type",+ "Page Size": "Page Size",+ "Sharing Link or Share Token": "Sharing Link or Share Token",+ "Search Text": "Search Text",+ "Description": "Description","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 name the file should be saved as (e.g. file.txt)": "The name the file should be saved as (e.g. file.txt)","The file URL or base64 to upload": "The file URL or base64 to upload",@@ -45,23 +153,105 @@"The folder to copy the file into. Leave empty to copy it into the same folder as the source file.": "The folder to copy the file into. Leave empty to copy it into the same folder as the source file.","A new name for the copied file (e.g. report-copy.xlsx). If left empty, the original name is used.": "A new name for the copied file (e.g. report-copy.xlsx). If left empty, the original name is used.","What to do if a file with the same name already exists in the destination folder. Note: personal OneDrive (consumer) accounts do not support this option and may fail on name conflicts regardless of the selection.": "What to do if a file with the same name already exists in the destination folder. Note: personal OneDrive (consumer) accounts do not support this option and may fail on name conflicts regardless of the selection.",+ "Bundle ID from List Albums and Bundles or Create Bundle.": "Bundle ID from List Albums and Bundles or Create Bundle.",+ "ID of the file to add, from Search or List Folder Contents.": "ID of the file to add, from Search or List Folder Contents.",+ "File ID from Search or List Folder Contents. Or use Path.": "File ID from Search or List Folder Contents. Or use Path.",+ "File path from the drive root. Use this or Item ID.": "File path from the drive root. Use this or Item ID.",+ "Optional check-in comment saved with the new version.": "Optional check-in comment saved with the new version.",+ "ID of the item to copy, from Search or List Folder Contents.": "ID of the item to copy, from Search or List Folder Contents.",+ "Path from the drive root. Use this or Item ID.": "Path from the drive root. Use this or Item ID.",+ "Folder to copy into. Leave empty for the drive root.": "Folder to copy into. Leave empty for the drive root.",+ "Optional name for the copy. Leave empty to keep the original name.": "Optional name for the copy. Leave empty to keep the original name.",+ "What to do on a name clash. Not supported on personal OneDrive.": "What to do on a name clash. Not supported on personal OneDrive.",+ "IDs of at least two files, from Search or List Folder Contents.": "IDs of at least two files, from Search or List Folder Contents.",+ "Parent folder ID. Leave empty for the drive root.": "Parent folder ID. Leave empty for the drive root.",+ "Folder name (a single name, not a path).": "Folder name (a single name, not a path).",+ "File or folder ID from Search or List Folder Contents. Or use Path.": "File or folder ID from Search or List Folder Contents. Or use Path.",+ "View, Edit, or Embed (Embed is personal OneDrive only).": "View, Edit, or Embed (Embed is personal OneDrive only).",+ "Who can open the link. Leave empty for the account default.": "Who can open the link. Leave empty for the account default.",+ "Optional password required to open the link. Personal OneDrive only.": "Optional password required to open the link. Personal OneDrive only.",+ "Optional date and time after which the link stops working.": "Optional date and time after which the link stops working.",+ "Destination folder ID. Leave empty for the drive root.": "Destination folder ID. Leave empty for the drive root.",+ "File name including its extension.": "File name including its extension.",+ "The text to write into the file (up to 4 MiB).": "The text to write into the file (up to 4 MiB).",+ "What to do when the folder already has an item with this name.": "What to do when the folder already has an item with this name.",+ "Permission ID from List File Permissions. Access ends at once.": "Permission ID from List File Permissions. Access ends at once.",+ "ID of the item to delete, from Search or List Folder Contents.": "ID of the item to delete, from Search or List Folder Contents.",+ "File path from the drive root. Used when File ID is empty.": "File path from the drive root. Used when File ID is empty.",+ "Image width in pixels. Required when Target Format is JPG.": "Image width in pixels. Required when Target Format is JPG.",+ "Image height in pixels. Required when Target Format is JPG.": "Image height in pixels. Required when Target Format is JPG.",+ "Earlier version ID from List File Versions (not the current one).": "Earlier version ID from List File Versions (not the current one).",+ "The monitorUrl returned by Copy File or Folder.": "The monitorUrl returned by Copy File or Folder.",+ "Item ID from Search or List Folder Contents, or \"root\". Or use Path.": "Item ID from Search or List Folder Contents, or \"root\". Or use Path.",+ "Path from the drive root. Used when Item ID is empty.": "Path from the drive root. Used when Item ID is empty.",+ "Email addresses of the people to share with.": "Email addresses of the people to share with.",+ "Read lets recipients view, Write lets them edit.": "Read lets recipients view, Write lets them edit.",+ "If on, OneDrive emails each recipient. Off grants access silently.": "If on, OneDrive emails each recipient. Off grants access silently.",+ "Message for the invitation email (only sent when emails are on).": "Message for the invitation email (only sent when emails are on).",+ "nextPageToken from the previous call. Empty for the first page.": "nextPageToken from the previous call. Empty for the first page.",+ "nextPageToken or deltaToken from a previous call. Empty to start.": "nextPageToken or deltaToken from a previous call. Empty to start.",+ "Without a token, skip current items and return only a deltaToken.": "Without a token, skip current items and return only a deltaToken.",+ "Folder ID. Leave this and Folder Path empty for the drive root.": "Folder ID. Leave this and Folder Path empty for the drive root.",+ "Folder path from the drive root. Used when Folder ID is empty.": "Folder path from the drive root. Used when Folder ID is empty.",+ "How many items to request per page (1-999). Defaults to 100.": "How many items to request per page (1-999). Defaults to 100.",+ "File path from the drive root. Used when Item ID is empty.": "File path from the drive root. Used when Item ID is empty.",+ "ID of the item to move, from Search or List Folder Contents.": "ID of the item to move, from Search or List Folder Contents.",+ "Folder to move into. Leave empty for the drive root.": "Folder to move into. Leave empty for the drive root.",+ "Optional new name for the item. Leave empty to keep its current name.": "Optional new name for the item. Leave empty to keep its current name.",+ "The ID of the bundle or album, from List Albums and Bundles.": "The ID of the bundle or album, from List Albums and Bundles.",+ "The ID of the file to remove from the bundle. The file itself is kept.": "The ID of the file to remove from the bundle. The file itself is kept.",+ "ID of the file to overwrite. Or use Path.": "ID of the file to overwrite. Or use Path.",+ "The new content, as a file URL or base64.": "The new content, as a file URL or base64.",+ "The sharing URL, or a share token starting with u! or s!.": "The sharing URL, or a share token starting with u! or s!.",+ "The ID of the version to restore, from List File Versions.": "The ID of the version to restore, from List File Versions.",+ "The text to search for in file names, metadata and content.": "The text to search for in file names, metadata and content.",+ "How many results to request per page (1-999). Defaults to 50.": "How many results to request per page (1-999). Defaults to 50.",+ "The ID of the permission to change, from List File Permissions.": "The ID of the permission to change, from List File Permissions.",+ "The new role. Replaces the roles the permission has today.": "The new role. Replaces the roles the permission has today.",+ "New name, with the extension for files. Empty keeps the name.": "New name, with the extension for files. Empty keeps the name.",+ "New description (personal OneDrive only). Empty keeps it.": "New description (personal OneDrive only). Empty keeps it.",+ "The file URL or base64 content to upload.": "The file URL or base64 content to upload.","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.",- "File ID": "File ID",- "File Name": "File Name",+ "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.","Rename with a number": "Rename with a number","Overwrite existing file": "Overwrite existing file","Fail on conflict": "Fail on conflict",+ "Fail": "Fail",+ "Rename the copy": "Rename the copy",+ "Replace the existing item": "Replace the existing item",+ "View": "View",+ "Edit": "Edit",+ "Embed (personal OneDrive only)": "Embed (personal OneDrive only)",+ "Anyone with the link": "Anyone with the link",+ "People in my organization": "People in my organization",+ "Existing users only": "Existing users only",+ "Rename the new file": "Rename the new file",+ "Replace the existing file": "Replace the existing file",+ "PDF": "PDF",+ "HTML (Loop, Fluid and whiteboard files only)": "HTML (Loop, Fluid and whiteboard files only)",+ "JPG (requires Width and Height)": "JPG (requires Width and Height)",+ "Documents": "Documents",+ "Photos": "Photos",+ "Camera Roll": "Camera Roll",+ "Music": "Music",+ "Recordings": "Recordings",+ "Read": "Read",+ "Write": "Write",+ "Files and folders": "Files and folders",+ "Files only": "Files only",+ "Folders only": "Folders only",+ "My files only": "My files only",+ "Include items shared with me": "Include items shared with me","GET": "GET","POST": "POST","PATCH": "PATCH","PUT": "PUT","DELETE": "DELETE","HEAD": "HEAD",- "None": "None",- "JSON": "JSON",- "Form Data": "Form Data",- "Raw": "Raw","New File": "New File","Trigger when a new file is uploaded.": "Trigger when a new file is uploaded."}\ No newline at end of filediff --git a/packages/pieces/community/microsoft-onedrive/src/index.ts b/packages/pieces/community/microsoft-onedrive/src/index.tsindex dd312c81a54..8200f53f14a 100644--- a/packages/pieces/community/microsoft-onedrive/src/index.ts+++ b/packages/pieces/community/microsoft-onedrive/src/index.ts@@ -1,8 +1,5 @@import { createCustomApiCallAction } from '@activepieces/pieces-common';-import {- createPiece,- OAuth2PropertyValue,-} from '@activepieces/pieces-framework';+import { createPiece } from '@activepieces/pieces-framework';import { PieceCategory } from '@activepieces/pieces-framework';import { copyFile } from './lib/actions/copy-file';import { downloadFile } from './lib/actions/download-file';@@ -11,13 +8,49 @@ import { listFolders } from './lib/actions/list-folders';import { uploadFile } from './lib/actions/upload-file';import { oneDriveAuth } from './lib/auth';import { oneDriveCommon } from './lib/common/common';+import { getCloudProp } from './lib/common/microsoft-cloud';import { newFile } from './lib/triggers/new-file';+import { onedriveAddItemToBundle } from './lib/actions/onedrive-add-item-to-bundle';+import { onedriveCheckinItem } from './lib/actions/onedrive-checkin-item';+import { onedriveCheckoutItem } from './lib/actions/onedrive-checkout-item';+import { onedriveCopyItem } from './lib/actions/onedrive-copy-item';+import { onedriveCreateBundle } from './lib/actions/onedrive-create-bundle';+import { onedriveCreateFolder } from './lib/actions/onedrive-create-folder';+import { onedriveCreateSharingLink } from './lib/actions/onedrive-create-sharing-link';+import { onedriveCreateTextFile } from './lib/actions/onedrive-create-text-file';+import { onedriveDeleteItemPermission } from './lib/actions/onedrive-delete-item-permission';+import { onedriveDeleteItem } from './lib/actions/onedrive-delete-item';+import { onedriveDiscardCheckout } from './lib/actions/onedrive-discard-checkout';+import { onedriveDownloadFileAsFormat } from './lib/actions/onedrive-download-file-as-format';+import { onedriveDownloadFile } from './lib/actions/onedrive-download-file';+import { onedriveDownloadItemVersion } from './lib/actions/onedrive-download-item-version';+import { onedriveGetCopyStatus } from './lib/actions/onedrive-get-copy-status';+import { onedriveGetDrive } from './lib/actions/onedrive-get-drive';+import { onedriveGetItem } from './lib/actions/onedrive-get-item';+import { onedriveGetSpecialFolder } from './lib/actions/onedrive-get-special-folder';+import { onedriveInviteToItem } from './lib/actions/onedrive-invite-to-item';+import { onedriveListBundles } from './lib/actions/onedrive-list-bundles';+import { onedriveListDriveChanges } from './lib/actions/onedrive-list-drive-changes';+import { onedriveListDrives } from './lib/actions/onedrive-list-drives';+import { onedriveListFolderChildren } from './lib/actions/onedrive-list-folder-children';+import { onedriveListItemPermissions } from './lib/actions/onedrive-list-item-permissions';+import { onedriveListItemThumbnails } from './lib/actions/onedrive-list-item-thumbnails';+import { onedriveListItemVersions } from './lib/actions/onedrive-list-item-versions';+import { onedriveMoveItem } from './lib/actions/onedrive-move-item';+import { onedriveRemoveItemFromBundle } from './lib/actions/onedrive-remove-item-from-bundle';+import { onedriveReplaceFileContent } from './lib/actions/onedrive-replace-file-content';+import { onedriveResolveSharingLink } from './lib/actions/onedrive-resolve-sharing-link';+import { onedriveRestoreItemVersion } from './lib/actions/onedrive-restore-item-version';+import { onedriveSearchItems } from './lib/actions/onedrive-search-items';+import { onedriveUpdateItemPermission } from './lib/actions/onedrive-update-item-permission';+import { onedriveUpdateItem } from './lib/actions/onedrive-update-item';+import { onedriveUploadFile } from './lib/actions/onedrive-upload-file';export const microsoftOneDrive = createPiece({displayName: 'Microsoft OneDrive',description: 'Cloud storage by Microsoft',auth: oneDriveAuth,- minimumSupportedRelease: '0.30.0',+ minimumSupportedRelease: '0.87.0',logoUrl: 'https://cdn.activepieces.com/pieces/oneDrive.png',categories: [PieceCategory.CONTENT_AND_FILES],authors: ['BastienMe', 'kishanprmr', 'MoShizzle', 'abuaboud', 'ikus060'],@@ -27,14 +60,48 @@ export const microsoftOneDrive = createPiece({copyFile,listFiles,listFolders,+ onedriveAddItemToBundle,+ onedriveCheckinItem,+ onedriveCheckoutItem,+ onedriveCopyItem,+ onedriveCreateBundle,+ onedriveCreateFolder,+ onedriveCreateSharingLink,+ onedriveCreateTextFile,+ onedriveDeleteItemPermission,+ onedriveDeleteItem,+ onedriveDiscardCheckout,+ onedriveDownloadFileAsFormat,+ onedriveDownloadFile,+ onedriveDownloadItemVersion,+ onedriveGetCopyStatus,+ onedriveGetDrive,+ onedriveGetItem,+ onedriveGetSpecialFolder,+ onedriveInviteToItem,+ onedriveListBundles,+ onedriveListDriveChanges,+ onedriveListDrives,+ onedriveListFolderChildren,+ onedriveListItemPermissions,+ onedriveListItemThumbnails,+ onedriveListItemVersions,+ onedriveMoveItem,+ onedriveRemoveItemFromBundle,+ onedriveReplaceFileContent,+ onedriveResolveSharingLink,+ onedriveRestoreItemVersion,+ onedriveSearchItems,+ onedriveUpdateItemPermission,+ onedriveUpdateItem,+ onedriveUploadFile,createCustomApiCallAction({baseUrl: (auth) => {- const cloud = (auth as OAuth2PropertyValue).props?.['cloud'] as string | undefined;- return oneDriveCommon.getBaseUrl(cloud);+ return oneDriveCommon.getBaseUrl(getCloudProp(auth));},auth: oneDriveAuth,authMapping: async (auth) => ({- Authorization: `Bearer ${(auth as OAuth2PropertyValue).access_token}`,+ Authorization: `Bearer ${auth.access_token}`,}),}),],diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/copy-file.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/copy-file.tsindex f83fd9398e1..b32f12fc39a 100644--- a/packages/pieces/community/microsoft-onedrive/src/lib/actions/copy-file.ts+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/copy-file.ts@@ -1,23 +1,24 @@import {createAction,DropdownOption,- OAuth2PropertyValue,Property,} from '@activepieces/pieces-framework';import { tryCatch } from '@activepieces/pieces-framework';import { Client, PageCollection, ResponseType } from '@microsoft/microsoft-graph-client';import { DriveItem } from '@microsoft/microsoft-graph-types';-import { getGraphBaseUrl } from '../common/microsoft-cloud';+import { getCloudProp, getGraphBaseUrl } from '../common/microsoft-cloud';import { oneDriveAuth } from '../auth';import { oneDriveCommon } from '../common/common';+import { copyFileOutputSchema } from '../output-schemas';export const copyFile = createAction({auth: oneDriveAuth,name: 'copy_file',classification: 'WRITE',displayName: 'Copy File',+ outputSchema: copyFileOutputSchema,description: 'Create a copy of a file in your OneDrive, optionally in a different folder or with a new name.',- audience: 'both',+ audience: 'human',aiMetadata: {description:'Creates a copy of a OneDrive file, optionally into a different folder and/or under a new name, and returns the copied item once the asynchronous copy completes. Use to duplicate a file or stamp out copies of a template document. Not idempotent: each run creates another copy — with the default rename conflict behavior, repeated runs produce numbered duplicates.',@@ -45,8 +46,8 @@ export const copyFile = createAction({};}- const authValue = auth as OAuth2PropertyValue;- const cloud = authValue.props?.['cloud'] as string | undefined;+ const authValue = auth;+ const cloud = getCloudProp(authValue);const client = Client.initWithMiddleware({authProvider: {getAccessToken: () => Promise.resolve(authValue.access_token),@@ -57,16 +58,14 @@ export const copyFile = createAction({const folderId = sourceFolderId || 'root';const options: DropdownOption<string>[] = [];- // A page can be empty (or contain only folders) and still carry- // @odata.nextLink, so keep following the link instead of stopping- // at the first empty page.let response: PageCollection | undefined = await client.api(`/me/drive/items/${folderId}/children`).select('id,name,file').get();while (response && options.length < MAX_DROPDOWN_FILES) {- for (const item of (response.value ?? []) as DriveItem[]) {+ const items: DriveItem[] = response.value ?? [];+ for (const item of items) {if (item.file) {options.push({ label: item.name!, value: item.id! });}@@ -104,7 +103,7 @@ export const copyFile = createAction({},async run(context) {const { fileId, destinationFolderId, newName, conflictBehavior } = context.propsValue;- const cloud = context.auth.props?.['cloud'] as string | undefined;+ const cloud = getCloudProp(context.auth);if (!fileId) {throw new Error('Please select a file to copy.');@@ -119,8 +118,6 @@ export const copyFile = createAction({const body: { parentReference?: { driveId: string; id: string }; name?: string } = {};if (destinationFolderId) {- // Docs: "The parentReference parameter should include the driveId and id- // parameters for the target folder."const drive = await client.api('/me/drive').select('id').get();body.parentReference = { driveId: drive.id, id: destinationFolderId };}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/download-file.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/download-file.tsindex 5cbb02c62cf..5c8c14dd454 100644--- a/packages/pieces/community/microsoft-onedrive/src/lib/actions/download-file.ts+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/download-file.ts@@ -6,32 +6,19 @@ import {} from '@activepieces/pieces-common';import { oneDriveAuth } from '../auth';import { oneDriveCommon } from '../common/common';+import { getCloudProp } from '../common/microsoft-cloud';+import { getFileOutputSchema } from '../output-schemas';-type SearchItem = {- id: string;- name: string;- file?: { mimeType: string };-};--type DriveItem = {- id: string;- name: string;- size: number;- createdDateTime: string;- lastModifiedDateTime: string;- webUrl: string;- file?: { mimeType: string };- parentReference?: { path: string; driveId: string };-};export const downloadFile = createAction({auth: oneDriveAuth,name: 'download_file',classification: 'READ',description: 'Get and download a file using a File ID or filename.',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Retrieve a single file from Microsoft OneDrive and download its content, looking it up either by its File ID or by its exact file name (a name lookup searches the drive and resolves to the matching file). Use when you need the file bytes plus its metadata; when only metadata is needed prefer a list action. Read-only and idempotent.', idempotent: true },displayName: 'Get File',+ outputSchema: getFileOutputSchema,props: {lookupBy: Property.StaticDropdown({displayName: 'Look Up By',@@ -53,7 +40,7 @@ export const downloadFile = createAction({},async run(context) {const { lookupBy, fileIdentifier } = context.propsValue;- const cloud = context.auth.props?.['cloud'] as string | undefined;+ const cloud = getCloudProp(context.auth);const baseUrl = oneDriveCommon.getBaseUrl(cloud);let fileId: string;@@ -124,3 +111,20 @@ export const downloadFile = createAction({};},});++type SearchItem = {+ id: string;+ name: string;+ file?: { mimeType: string };+};++type DriveItem = {+ id: string;+ name: string;+ size: number;+ createdDateTime: string;+ lastModifiedDateTime: string;+ webUrl: string;+ file?: { mimeType: string };+ parentReference?: { path: string; driveId: string };+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-files.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-files.tsindex 82a1f38a8db..9aeb00e1408 100644--- a/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-files.ts+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-files.ts@@ -1,7 +1,8 @@-import { createAction, OAuth2PropertyValue } from '@activepieces/pieces-framework';-import { getGraphBaseUrl } from '../common/microsoft-cloud';+import { createAction } from '@activepieces/pieces-framework';+import { getCloudProp, getGraphBaseUrl } from '../common/microsoft-cloud';import { oneDriveAuth } from '../auth';import { oneDriveCommon } from '../common/common';+import { listFilesOutputSchema } from '../output-schemas';import { Client, PageCollection } from '@microsoft/microsoft-graph-client';import { DriveItem } from '@microsoft/microsoft-graph-types';@@ -10,9 +11,10 @@ export const listFiles = createAction({name: 'list_files',classification: 'SEARCH',description: 'List files in a OneDrive folder',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'List the files contained in a Microsoft OneDrive folder, returning only file items (subfolders are excluded) and paging through all results. Provide a parent folder ID to scope the listing, or leave it empty to list from the drive root. Read-only and idempotent.', idempotent: true },displayName: 'List Files',+ outputSchema: listFilesOutputSchema,props: {markdown:oneDriveCommon.parentFolderInfo,parentFolder: oneDriveCommon.parentFolder,@@ -24,7 +26,7 @@ export const listFiles = createAction({const files = [];- const cloud = (context.auth as OAuth2PropertyValue).props?.['cloud'] as string | undefined;+ const cloud = getCloudProp(context.auth);const client = Client.initWithMiddleware({authProvider: {getAccessToken: () => Promise.resolve(context.auth.access_token),@@ -34,7 +36,8 @@ export const listFiles = createAction({let response: PageCollection = await client.api(endpoint).get();while (response.value.length > 0) {- for (const item of response.value as DriveItem[]) {+ const items: DriveItem[] = response.value;+ for (const item of items) {if (item.file) {files.push(item);}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-folders.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-folders.tsindex 57a2fd4328f..c24341b884e 100644--- a/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-folders.ts+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/list-folders.ts@@ -1,4 +1,4 @@-import { createAction, Property } from '@activepieces/pieces-framework';+import { createAction } from '@activepieces/pieces-framework';import {httpClient,HttpMethod,@@ -6,22 +6,25 @@ import {} from '@activepieces/pieces-common';import { oneDriveAuth } from '../auth';import { oneDriveCommon } from '../common/common';+import { getCloudProp } from '../common/microsoft-cloud';+import { listFoldersOutputSchema } from '../output-schemas';export const listFolders = createAction({auth: oneDriveAuth,name: 'list_folders',classification: 'SEARCH',description: 'List folders in a OneDrive folder',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'List the subfolders contained in a Microsoft OneDrive folder (file items are excluded). Provide a parent folder ID to scope the listing, or leave it empty to list folders at the drive root; useful for discovering a folder ID to pass to other actions. Read-only and idempotent.', idempotent: true },displayName: 'List Folders',+ outputSchema: listFoldersOutputSchema,props: {markdown:oneDriveCommon.parentFolderInfo,parentFolder: oneDriveCommon.parentFolder,},async run(context) {const parentId = context.propsValue.parentFolder ?? 'root';- const cloud = context.auth.props?.['cloud'] as string | undefined;+ const cloud = getCloudProp(context.auth);const result = await httpClient.sendRequest({method: HttpMethod.GET,diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-add-item-to-bundle.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-add-item-to-bundle.tsnew file mode 100644index 00000000000..a1db84eb6d3--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-add-item-to-bundle.ts@@ -0,0 +1,56 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveBundleMembershipOutputSchema } from '../output-schemas';++export const onedriveAddItemToBundle = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_add_item_to_bundle',+ displayName: 'Add Item to Bundle',+ description: 'Add an existing file to a bundle or album.',+ audience: 'ai',+ outputSchema: onedriveBundleMembershipOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Add one existing file to an existing bundle or photo album in a personal OneDrive; the file stays where it is. Get the bundle ID from List Albums and Bundles or Create Bundle, and the item ID from Search Files and Folders or List Folder Contents; use Create Bundle to start a new one. Works only on personal OneDrive (Microsoft account); adding an item that is already in the bundle succeeds without duplicating it.',+ idempotent: true,+ },+ props: {+ bundleId: Property.ShortText({+ displayName: 'Bundle ID',+ description: 'Bundle ID from List Albums and Bundles or Create Bundle.',+ required: true,+ }),+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'ID of the file to add, from Search or List Folder Contents.',+ required: true,+ }),+ },+ async run(context) {+ const bundleId = context.propsValue.bundleId.trim();+ const itemId = context.propsValue.itemId.trim();+ await assertPersonalDrive({ auth: context.auth });+ await oneDriveApi.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `/me/drive/bundles/${encodeURIComponent(bundleId)}/children`,+ body: { id: itemId },+ });+ return { success: true, bundleId, itemId };+ },+});++async function assertPersonalDrive({ auth }: { auth: OAuth2PropertyValue }): Promise<void> {+ const drive = await oneDriveApi.request<{ driveType?: string }>({+ auth,+ method: HttpMethod.GET,+ path: '/me/drive',+ queryParams: { $select: 'driveType' },+ });+ if (drive.driveType !== 'personal') {+ throw new Error('Bundles are available only on personal OneDrive (Microsoft account) drives. This connection uses OneDrive for Business.');+ }+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-checkin-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-checkin-item.tsnew file mode 100644index 00000000000..8fc6d366e5d--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-checkin-item.ts@@ -0,0 +1,56 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveItemActionOutputSchema } from '../output-schemas';++export const onedriveCheckinItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_checkin_item',+ displayName: 'Check In File',+ description: 'Check in a checked-out file so its changes become visible to others.',+ audience: 'ai',+ outputSchema: onedriveItemActionOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Checks in a file previously checked out with Check Out File, publishing the changes and releasing the lock. Use Discard Check-Out instead to throw the changes away. Works on personal and business drives; checking in a file that is not checked out fails.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ comment: Property.LongText({+ displayName: 'Comment',+ description: 'Optional check-in comment saved with the new version.',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, comment } = context.propsValue;+ const body: Record<string, unknown> = {};+ if (comment) {+ body['comment'] = comment;+ }+ await oneDriveApi.request({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `${oneDriveApi.itemPath({ itemId, path })}/checkin`,+ body,+ });+ return {+ success: true,+ itemId: itemId?.trim() || null,+ path: path?.trim() || null,+ };+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-checkout-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-checkout-item.tsnew file mode 100644index 00000000000..754db6fa057--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-checkout-item.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveItemActionOutputSchema } from '../output-schemas';++export const onedriveCheckoutItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_checkout_item',+ displayName: 'Check Out File',+ description: 'Check out a file so others cannot edit it until it is checked in.',+ audience: 'ai',+ outputSchema: onedriveItemActionOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Checks out a file, locking it for exclusive editing until Check In File or Discard Check-Out is called. Works on personal OneDrive and on OneDrive for Business or SharePoint libraries; checking out a file that is already checked out fails.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ await oneDriveApi.request({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `${oneDriveApi.itemPath({ itemId, path })}/checkout`,+ });+ return {+ success: true,+ itemId: itemId?.trim() || null,+ path: path?.trim() || null,+ };+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-copy-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-copy-item.tsnew file mode 100644index 00000000000..0fcba206ad6--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-copy-item.ts@@ -0,0 +1,99 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { getGraphBaseUrl } from '../common/microsoft-cloud';+import { onedriveCopyItemOutputSchema } from '../output-schemas';++export const onedriveCopyItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_copy_item',+ displayName: 'Copy File or Folder',+ description:+ 'Start copying a OneDrive file or folder. The copy runs in the background; check it with Get Copy Status.',+ audience: 'ai',+ outputSchema: onedriveCopyItemOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Starts an asynchronous copy of a file or a whole folder (with its contents) into a destination folder, optionally under a new name, and returns a monitor URL rather than the new item. Next, call Get Copy Status with that monitor URL until it reports completed; its resourceId is the new copy\'s ID, while the source ID keeps pointing at the original. Each call starts another copy; name conflicts are reported by Get Copy Status as failed, and the conflict setting is not supported on personal OneDrive.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'ID of the item to copy, from Search or List Folder Contents.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ destinationFolderId: Property.ShortText({+ displayName: 'Destination Folder ID',+ description: 'Folder to copy into. Leave empty for the drive root.',+ required: false,+ }),+ newName: Property.ShortText({+ displayName: 'New Name',+ description: 'Optional name for the copy. Leave empty to keep the original name.',+ required: false,+ }),+ conflictBehavior: Property.StaticDropdown({+ displayName: 'If the Name Exists',+ description: 'What to do on a name clash. Not supported on personal OneDrive.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Fail', value: 'fail' },+ { label: 'Rename the copy', value: 'rename' },+ { label: 'Replace the existing item', value: 'replace' },+ ],+ },+ }),+ },+ async run(context) {+ const { itemId, path, destinationFolderId, newName, conflictBehavior } = context.propsValue;+ const sourcePath = oneDriveApi.itemPath({ itemId, path });+ const [parentId, driveId] = await Promise.all([+ oneDriveApi.resolveFolderId({ auth: context.auth, folderId: destinationFolderId }),+ oneDriveApi.getDriveId({ auth: context.auth }),+ ]);+ const body: Record<string, unknown> = {+ parentReference: { driveId, id: parentId },+ };+ const trimmedName = newName?.trim();+ if (trimmedName) {+ body['name'] = trimmedName;+ }+ try {+ const response = await httpClient.sendRequest({+ method: HttpMethod.POST,+ url: `${graphBaseUrl(context.auth)}${sourcePath}/copy`,+ queryParams: conflictBehavior ? { '@microsoft.graph.conflictBehavior': conflictBehavior } : undefined,+ body,+ headers: { 'Content-Type': 'application/json' },+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: context.auth.access_token,+ },+ });+ const location = response.headers?.['location'];+ const monitorUrl = Array.isArray(location) ? location[0] : location;+ if (!monitorUrl) {+ throw new Error('OneDrive accepted the copy but did not return a monitor URL.');+ }+ return { monitorUrl, status: 'inProgress' };+ } catch (error) {+ throw new Error(oneDriveApi.describeError(error));+ }+ },+});++function graphBaseUrl(auth: OAuth2PropertyValue): string {+ const cloud = auth.props?.['cloud'];+ return `${getGraphBaseUrl(typeof cloud === 'string' ? cloud : undefined)}/v1.0`;+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-bundle.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-bundle.tsnew file mode 100644index 00000000000..63d074e7238--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-bundle.ts@@ -0,0 +1,73 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveBundleOutputSchema } from '../output-schemas';++export const onedriveCreateBundle = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_create_bundle',+ displayName: 'Create Bundle',+ description: 'Create a bundle that groups existing files so they can be shared together.',+ audience: 'ai',+ outputSchema: onedriveBundleOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Create a new bundle in a personal OneDrive that groups existing files, identified by at least two item IDs from Search Files and Folders or List Folder Contents, so they can be shared as one set without sharing their folders; the files are not moved or copied. Use Add Item to Bundle to extend an existing bundle instead. Works only on personal OneDrive (Microsoft account); each call creates a new bundle, and a duplicate name gets a number appended, so retries create duplicates.',+ idempotent: false,+ },+ props: {+ name: Property.ShortText({+ displayName: 'Bundle Name',+ required: true,+ }),+ itemIds: Property.Array({+ displayName: 'Item IDs',+ description: 'IDs of at least two files, from Search or List Folder Contents.',+ required: true,+ }),+ },+ async run(context) {+ const { name, itemIds } = context.propsValue;+ const ids = (itemIds ?? [])+ .map((id) => (typeof id === 'string' ? id.trim() : String(id ?? '').trim()))+ .filter((id) => id.length > 0);+ if (ids.length < 2) {+ throw new Error('Provide at least two item IDs. OneDrive does not create a bundle with fewer than two items.');+ }+ await assertPersonalDrive({ auth: context.auth });+ const bundle = await oneDriveApi.request<GraphBundle>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: '/me/drive/bundles',+ body: {+ name,+ '@microsoft.graph.conflictBehavior': 'rename',+ bundle: {},+ children: ids.map((id) => ({ id })),+ },+ });+ return {+ ...oneDriveApi.toItem(bundle),+ bundleChildCount: bundle.bundle?.childCount ?? null,+ isAlbum: bundle.bundle?.album !== undefined && bundle.bundle?.album !== null,+ };+ },+});++async function assertPersonalDrive({ auth }: { auth: OAuth2PropertyValue }): Promise<void> {+ const drive = await oneDriveApi.request<{ driveType?: string }>({+ auth,+ method: HttpMethod.GET,+ path: '/me/drive',+ queryParams: { $select: 'driveType' },+ });+ if (drive.driveType !== 'personal') {+ throw new Error('Bundles are available only on personal OneDrive (Microsoft account) drives. This connection uses OneDrive for Business.');+ }+}++type GraphBundle = GraphDriveItem & {+ bundle?: { childCount?: number; album?: Record<string, unknown> | null };+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-folder.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-folder.tsnew file mode 100644index 00000000000..a823f3682bf--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-folder.ts@@ -0,0 +1,88 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveCreateFolderOutputSchema } from '../output-schemas';++export const onedriveCreateFolder = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_create_folder',+ displayName: 'Create Folder',+ description: 'Create a folder in OneDrive, or return it if a folder with that name already exists.',+ audience: 'ai',+ outputSchema: onedriveCreateFolderOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Gets or creates a folder by name inside a parent folder (the drive root by default): if a folder with that name already exists it is returned with `created` false instead of making a duplicate. Call it before Upload File or Move File or Folder when the destination may not exist. It fails if a file (not a folder) already holds the name; safe to retry.',+ idempotent: true,+ },+ props: {+ parentFolderId: Property.ShortText({+ displayName: 'Parent Folder ID',+ description: 'Parent folder ID. Leave empty for the drive root.',+ required: false,+ }),+ name: Property.ShortText({+ displayName: 'Folder Name',+ description: 'Folder name (a single name, not a path).',+ placeholder: 'Invoices 2026',+ required: true,+ }),+ },+ async run(context) {+ const name = context.propsValue.name.trim();+ if (!name) {+ throw new Error('Folder Name cannot be empty.');+ }+ const parentId = await oneDriveApi.resolveFolderId({+ auth: context.auth,+ folderId: context.propsValue.parentFolderId,+ });+ try {+ const created = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `${oneDriveApi.itemPath({ itemId: parentId })}/children`,+ body: {+ name,+ folder: {},+ '@microsoft.graph.conflictBehavior': 'fail',+ },+ });+ return { ...oneDriveApi.toItem(created), created: true };+ } catch (createError) {+ if (oneDriveApi.statusOf(createError) !== 409) {+ throw createError;+ }+ const existing = await findChild({ auth: context.auth, parentId, name });+ if (!existing) {+ throw createError;+ }+ if (!existing.folder) {+ throw new Error(`A file named "${name}" already exists in this folder, so a folder with that name cannot be created.`);+ }+ return { ...oneDriveApi.toItem(existing), created: false };+ }+ },+});++async function findChild({+ auth,+ parentId,+ name,+}: {+ auth: OAuth2PropertyValue;+ parentId: string;+ name: string;+}): Promise<GraphDriveItem | null> {+ try {+ return await oneDriveApi.request<GraphDriveItem>({+ auth,+ method: HttpMethod.GET,+ path: `${oneDriveApi.itemPath({ itemId: parentId })}:/${encodeURIComponent(name)}:`,+ });+ } catch {+ return null;+ }+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-sharing-link.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-sharing-link.tsnew file mode 100644index 00000000000..6941b65668d--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-sharing-link.ts@@ -0,0 +1,169 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedrivePermissionOutputSchema } from '../output-schemas';++export const onedriveCreateSharingLink = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_create_sharing_link',+ displayName: 'Create Sharing Link',+ description: 'Create a view, edit or embed sharing link for a OneDrive file or folder.',+ audience: 'ai',+ outputSchema: onedrivePermissionOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates (or returns the existing) sharing link of the given type and scope for a file or folder, keeping its existing inherited access. Use it to get a URL anyone or an organization can open; to grant access to specific people by email use Share with People (Invite) instead. Embed links and passwords work on personal OneDrive only, and tenant policy may block anonymous links; calling again with the same type and scope returns the same link.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File or folder ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ type: Property.StaticDropdown({+ displayName: 'Link Type',+ description: 'View, Edit, or Embed (Embed is personal OneDrive only).',+ required: true,+ defaultValue: 'view',+ options: {+ disabled: false,+ options: [+ { label: 'View', value: 'view' },+ { label: 'Edit', value: 'edit' },+ { label: 'Embed (personal OneDrive only)', value: 'embed' },+ ],+ },+ }),+ scope: Property.StaticDropdown({+ displayName: 'Scope',+ description: 'Who can open the link. Leave empty for the account default.',+ required: false,+ options: {+ disabled: false,+ options: [+ { label: 'Anyone with the link', value: 'anonymous' },+ { label: 'People in my organization', value: 'organization' },+ { label: 'Existing users only', value: 'users' },+ ],+ },+ }),+ password: Property.ShortText({+ displayName: 'Password',+ description: 'Optional password required to open the link. Personal OneDrive only.',+ required: false,+ }),+ expirationDateTime: Property.DateTime({+ displayName: 'Expiration',+ description: 'Optional date and time after which the link stops working.',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, type, scope, password, expirationDateTime } = context.propsValue;+ const body: Record<string, unknown> = {+ type,+ retainInheritedPermissions: true,+ };+ if (scope) {+ body['scope'] = scope;+ }+ if (password) {+ body['password'] = password;+ }+ if (expirationDateTime) {+ body['expirationDateTime'] = expirationDateTime;+ }+ try {+ const permission = await oneDriveApi.request<GraphPermission>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `${oneDriveApi.itemPath({ itemId, path })}/createLink`,+ body,+ });+ return toPermission(permission);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (oneDriveApi.statusOf(error) === 403) {+ throw new Error(+ `OneDrive refused to create a ${scope ?? 'default-scope'} ${type} link. Your organization's sharing policy may block this link type or scope (anonymous links are often disabled), or the account type does not support it (embed and passwords are personal-only). Try a narrower scope such as "users". Details: ${message}`,+ );+ }+ throw error;+ }+ },+});++function toPermission(permission: GraphPermission): OneDrivePermission {+ const grantee = permission.grantedToV2?.user ?? permission.grantedTo?.user;+ const identities = permission.grantedToIdentitiesV2 ?? permission.grantedToIdentities ?? [];+ return {+ id: permission.id,+ roles: permission.roles ?? [],+ linkType: permission.link?.type ?? null,+ linkScope: permission.link?.scope ?? null,+ linkWebUrl: permission.link?.webUrl ?? null,+ linkPreventsDownload: permission.link?.preventsDownload ?? null,+ grantedToName: grantee?.displayName ?? null,+ grantedToEmail: grantee?.email ?? null,+ grantedToId: grantee?.id ?? null,+ grantedToIdentities: identities+ .flatMap((identity) => {+ const value = identity.user?.email ?? identity.user?.displayName;+ return value ? [value] : [];+ })+ .join(', '),+ invitationEmail: permission.invitation?.email ?? null,+ inherited: permission.inheritedFrom !== undefined,+ inheritedFromId: permission.inheritedFrom?.id ?? null,+ inheritedFromPath: permission.inheritedFrom?.path ?? null,+ hasPassword: permission.hasPassword ?? null,+ expirationDateTime: permission.expirationDateTime ?? null,+ shareId: permission.shareId ?? null,+ };+}++type GraphPermissionUser = { displayName?: string; email?: string; id?: string };++type GraphPermission = {+ id: string;+ roles?: string[];+ link?: { type?: string; scope?: string; webUrl?: string; preventsDownload?: boolean };+ grantedTo?: { user?: GraphPermissionUser };+ grantedToV2?: { user?: GraphPermissionUser };+ grantedToIdentities?: { user?: GraphPermissionUser }[];+ grantedToIdentitiesV2?: { user?: GraphPermissionUser }[];+ invitation?: { email?: string };+ inheritedFrom?: { id?: string; path?: string; driveId?: string };+ hasPassword?: boolean;+ expirationDateTime?: string;+ shareId?: string;+};++type OneDrivePermission = {+ id: string;+ roles: string[];+ linkType: string | null;+ linkScope: string | null;+ linkWebUrl: string | null;+ linkPreventsDownload: boolean | null;+ grantedToName: string | null;+ grantedToEmail: string | null;+ grantedToId: string | null;+ grantedToIdentities: string;+ invitationEmail: string | null;+ inherited: boolean;+ inheritedFromId: string | null;+ inheritedFromPath: string | null;+ hasPassword: boolean | null;+ expirationDateTime: string | null;+ shareId: string | null;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-text-file.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-text-file.tsnew file mode 100644index 00000000000..f8484c8c834--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-create-text-file.ts@@ -0,0 +1,74 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveItemOutputSchema } from '../output-schemas';++export const onedriveCreateTextFile = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_create_text_file',+ displayName: 'Create Text File',+ description: 'Create a plain-text file in a OneDrive folder from text you provide.',+ audience: 'ai',+ outputSchema: onedriveItemOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Creates a file in a OneDrive folder whose content is the given text (up to 4 MiB), without needing a file object; use Upload File for binary files and Replace File Content to overwrite a known item. It writes plain UTF-8 text only, so naming it `.docx` or `.xlsx` does not produce a real Word or Excel file. By default it fails if the name already exists; Rename or Replace change that, and each Rename call creates another file.',+ idempotent: false,+ },+ props: {+ folderId: Property.ShortText({+ displayName: 'Folder ID',+ description: 'Destination folder ID. Leave empty for the drive root.',+ required: false,+ }),+ fileName: Property.ShortText({+ displayName: 'File Name',+ description: 'File name including its extension.',+ placeholder: 'notes.txt',+ required: true,+ }),+ content: Property.LongText({+ displayName: 'Content',+ description: 'The text to write into the file (up to 4 MiB).',+ required: true,+ }),+ conflictBehavior: Property.StaticDropdown({+ displayName: 'If the Name Exists',+ description: 'What to do when the folder already has an item with this name.',+ required: true,+ defaultValue: 'fail',+ options: {+ disabled: false,+ options: [+ { label: 'Fail', value: 'fail' },+ { label: 'Rename the new file', value: 'rename' },+ { label: 'Replace the existing file', value: 'replace' },+ ],+ },+ }),+ },+ async run(context) {+ const { folderId, fileName, content, conflictBehavior } = context.propsValue;+ const name = fileName.trim();+ if (!name) {+ throw new Error('File Name cannot be empty.');+ }+ const byteLength = Buffer.byteLength(content, 'utf8');+ if (byteLength > SIMPLE_UPLOAD_LIMIT) {+ throw new Error('Content is larger than 4 MiB. Use Upload File for large content.');+ }+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.PUT,+ path: `${oneDriveApi.folderPath({ folderId })}:/${encodeURIComponent(name)}:/content`,+ queryParams: { '@microsoft.graph.conflictBehavior': conflictBehavior ?? 'fail' },+ body: content,+ headers: { 'Content-Type': 'text/plain; charset=utf-8' },+ });+ return oneDriveApi.toItem(item);+ },+});++const SIMPLE_UPLOAD_LIMIT = 4 * 1024 * 1024;diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-delete-item-permission.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-delete-item-permission.tsnew file mode 100644index 00000000000..a47e65f3414--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-delete-item-permission.ts@@ -0,0 +1,60 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveDeletePermissionOutputSchema } from '../output-schemas';++export const onedriveDeleteItemPermission = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_delete_item_permission',+ displayName: 'Remove Permission (Stop Sharing)',+ description: 'Remove a person\'s access or revoke a sharing link on a OneDrive file or folder.',+ audience: 'ai',+ outputSchema: onedriveDeletePermissionOutputSchema,+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Permanently removes one permission from a file or folder, which revokes that person\'s access or disables that sharing link for everyone who has it; it cannot be undone except by sharing again. Get the permission ID from List File Permissions; only non-inherited permissions can be removed, and a retry after success fails with not found.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File or folder ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ permissionId: Property.ShortText({+ displayName: 'Permission ID',+ description: 'Permission ID from List File Permissions. Access ends at once.',+ required: true,+ }),+ },+ async run(context) {+ const { itemId, path, permissionId } = context.propsValue;+ const trimmedPermissionId = permissionId.trim();+ try {+ await oneDriveApi.request({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `${oneDriveApi.itemPath({ itemId, path })}/permissions/${encodeURIComponent(trimmedPermissionId)}`,+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(+ `${message} Only permissions set directly on this item can be removed; inherited ones must be removed on the parent folder they come from.`,+ );+ }+ return {+ success: true,+ itemId: itemId?.trim() || null,+ path: path?.trim() || null,+ permissionId: trimmedPermissionId,+ };+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-delete-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-delete-item.tsnew file mode 100644index 00000000000..77eace42551--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-delete-item.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveItemActionOutputSchema } from '../output-schemas';++export const onedriveDeleteItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_delete_item',+ displayName: 'Delete File or Folder (to Recycle Bin)',+ description: 'Move a OneDrive file or folder to the recycle bin. Deleting a folder also deletes everything in it.',+ audience: 'ai',+ outputSchema: onedriveItemActionOutputSchema,+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Deletes a file or folder by moving it to the OneDrive recycle bin, where the owner can still restore it; deleting a folder also deletes everything inside it. Confirm the exact item first (get its ID from Search Files and Folders or List Folder Contents); retrying after success fails because the item is gone.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'ID of the item to delete, from Search or List Folder Contents.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ await oneDriveApi.request({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: oneDriveApi.itemPath({ itemId, path }),+ });+ return {+ success: true,+ itemId: itemId?.trim() || null,+ path: itemId?.trim() ? null : path?.trim() || null,+ };+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-discard-checkout.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-discard-checkout.tsnew file mode 100644index 00000000000..16834842b30--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-discard-checkout.ts@@ -0,0 +1,46 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveItemActionOutputSchema } from '../output-schemas';++export const onedriveDiscardCheckout = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_discard_checkout',+ displayName: 'Discard Check-Out',+ description: 'Undo a check-out and throw away any changes made while the file was checked out.',+ audience: 'ai',+ outputSchema: onedriveItemActionOutputSchema,+ classification: 'DESTRUCTIVE',+ aiMetadata: {+ description:+ 'Releases the check-out on a file and permanently discards every change made while it was checked out, reverting to the last checked-in version. Use Check In File instead to keep the changes. Works on personal and business drives; a retry fails once the file is no longer checked out.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ await oneDriveApi.request({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `${oneDriveApi.itemPath({ itemId, path })}/discardCheckout`,+ });+ return {+ success: true,+ itemId: itemId?.trim() || null,+ path: path?.trim() || null,+ };+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-file-as-format.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-file-as-format.tsnew file mode 100644index 00000000000..cb1030284b1--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-file-as-format.ts@@ -0,0 +1,152 @@+import { Readable } from 'stream';+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { AuthenticationType, HttpMethod, QueryParams, httpClient } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { getGraphBaseUrl } from '../common/microsoft-cloud';+import { onedriveDownloadFileAsFormatOutputSchema } from '../output-schemas';++export const onedriveDownloadFileAsFormat = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_download_file_as_format',+ displayName: 'Convert and Download File',+ description: 'Convert a file to PDF, HTML or JPG and download the result.',+ audience: 'ai',+ outputSchema: onedriveDownloadFileAsFormatOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Have OneDrive convert one file to another format and download the converted copy; the stored file is not changed. Typical use is Word, Excel or PowerPoint to PDF; HTML works only for Loop, Fluid and whiteboard files, and JPG needs both Width and Height. Provide the item ID (from Search Files and Folders or List Folder Contents) or a path; use Download File for the original bytes. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'File ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Used when File ID is empty.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ format: Property.StaticDropdown({+ displayName: 'Target Format',+ required: true,+ defaultValue: 'pdf',+ options: {+ disabled: false,+ options: [+ { label: 'PDF', value: 'pdf' },+ { label: 'HTML (Loop, Fluid and whiteboard files only)', value: 'html' },+ { label: 'JPG (requires Width and Height)', value: 'jpg' },+ ],+ },+ }),+ width: Property.Number({+ displayName: 'Width',+ description: 'Image width in pixels. Required when Target Format is JPG.',+ required: false,+ }),+ height: Property.Number({+ displayName: 'Height',+ description: 'Image height in pixels. Required when Target Format is JPG.',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, format, width, height } = context.propsValue;+ const conversion = buildConversionParams({ format, width, height });+ const itemPath = oneDriveApi.itemPath({ itemId, path });+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: itemPath,+ });+ if (item.file === undefined) {+ throw new Error(`"${item.name}" is not a file, so it cannot be converted.`);+ }+ const content = await downloadContent({+ auth: context.auth,+ contentPath: `${itemPath}/content`,+ queryParams: conversion,+ }).catch((error: unknown) => {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(`${message} OneDrive may not support converting this file type to ${format.toUpperCase()}.`);+ });+ const fileName = `${item.name.replace(/\.[^.]*$/, '')}.${format}`;+ return {+ ...oneDriveApi.toItem(item),+ convertedFormat: format,+ convertedFileName: fileName,+ data: await context.files.write({ fileName, data: content }),+ };+ },+});++function buildConversionParams({+ format,+ width,+ height,+}: {+ format: string;+ width?: number;+ height?: number;+}): QueryParams {+ if (format !== 'jpg') {+ return { format };+ }+ if (!isPositive(width) || !isPositive(height)) {+ throw new Error('Width and Height are both required, as positive numbers, when Target Format is JPG.');+ }+ return { format, width: String(Math.floor(width)), height: String(Math.floor(height)) };+}++function isPositive(value: number | undefined): value is number {+ return typeof value === 'number' && Number.isFinite(value) && value >= 1;+}++async function downloadContent({+ auth,+ contentPath,+ queryParams,+}: {+ auth: OAuth2PropertyValue;+ contentPath: string;+ queryParams?: QueryParams;+}): Promise<Readable> {+ const cloud = auth.props?.['cloud'];+ const graphBase = `${getGraphBaseUrl(typeof cloud === 'string' ? cloud : undefined)}/v1.0`;+ try {+ const first = await httpClient.sendRequest<Readable>({+ method: HttpMethod.GET,+ url: `${graphBase}${contentPath}`,+ queryParams,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: auth.access_token,+ },+ headers: { Accept: '*/*' },+ responseType: 'stream',+ followRedirects: false,+ });+ if (first.status < 300) {+ return first.body;+ }+ first.body.destroy();+ const location = first.headers?.['location'];+ const downloadUrl = Array.isArray(location) ? location[0] : location;+ if (!downloadUrl) {+ throw new Error('OneDrive did not return a download location for this file.');+ }+ const download = await httpClient.sendRequest<Readable>({+ method: HttpMethod.GET,+ url: downloadUrl,+ responseType: 'stream',+ });+ return download.body;+ } catch (error) {+ throw new Error(oneDriveApi.describeError(error));+ }+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-file.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-file.tsnew file mode 100644index 00000000000..2eafd63af44--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-file.ts@@ -0,0 +1,96 @@+import { Readable } from 'stream';+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { AuthenticationType, HttpMethod, QueryParams, httpClient } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { getGraphBaseUrl } from '../common/microsoft-cloud';+import { onedriveDownloadFileOutputSchema } from '../output-schemas';++export const onedriveDownloadFile = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_download_file',+ displayName: 'Download File',+ description: 'Download a file by its ID or path.',+ audience: 'ai',+ outputSchema: onedriveDownloadFileOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Download the current content of one file together with its metadata, returning a file reference other steps can use. Provide either the item ID (from Search Files and Folders or List Folder Contents) or a path relative to the drive root; use Get File or Folder when you only need metadata, and Convert and Download File to get an Office file as PDF. Folders are rejected. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'File ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Used when File ID is empty.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ const itemPath = oneDriveApi.itemPath({ itemId, path });+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: itemPath,+ });+ if (item.file === undefined) {+ throw new Error(`"${item.name}" is not a file, so it cannot be downloaded. Use List Folder Contents to see what a folder contains.`);+ }+ const content = await downloadContent({ auth: context.auth, contentPath: `${itemPath}/content` });+ return {+ ...oneDriveApi.toItem(item),+ data: await context.files.write({ fileName: item.name, data: content }),+ };+ },+});++async function downloadContent({+ auth,+ contentPath,+ queryParams,+}: {+ auth: OAuth2PropertyValue;+ contentPath: string;+ queryParams?: QueryParams;+}): Promise<Readable> {+ const cloud = auth.props?.['cloud'];+ const graphBase = `${getGraphBaseUrl(typeof cloud === 'string' ? cloud : undefined)}/v1.0`;+ try {+ const first = await httpClient.sendRequest<Readable>({+ method: HttpMethod.GET,+ url: `${graphBase}${contentPath}`,+ queryParams,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: auth.access_token,+ },+ headers: { Accept: '*/*' },+ responseType: 'stream',+ followRedirects: false,+ });+ if (first.status < 300) {+ return first.body;+ }+ first.body.destroy();+ const location = first.headers?.['location'];+ const downloadUrl = Array.isArray(location) ? location[0] : location;+ if (!downloadUrl) {+ throw new Error('OneDrive did not return a download location for this file.');+ }+ const download = await httpClient.sendRequest<Readable>({+ method: HttpMethod.GET,+ url: downloadUrl,+ responseType: 'stream',+ });+ return download.body;+ } catch (error) {+ throw new Error(oneDriveApi.describeError(error));+ }+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-item-version.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-item-version.tsnew file mode 100644index 00000000000..925eb8cb1c8--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-download-item-version.ts@@ -0,0 +1,93 @@+import { Readable } from 'stream';+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod, httpClient } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveDownloadItemVersionOutputSchema } from '../output-schemas';++export const onedriveDownloadItemVersion = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_download_item_version',+ displayName: 'Download File Version',+ description: 'Download the content of a previous version of a file.',+ audience: 'ai',+ outputSchema: onedriveDownloadItemVersionOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Download the content of one earlier version of a file without restoring it. Get the version ID from List File Versions and provide the file ID (from Search Files and Folders or List Folder Contents) or a path; OneDrive does not serve the current version this way, so use Download File for the latest content. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'File ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Used when File ID is empty.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ versionId: Property.ShortText({+ displayName: 'Version ID',+ description: 'Earlier version ID from List File Versions (not the current one).',+ required: true,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ const versionId = context.propsValue.versionId.trim();+ const itemPath = oneDriveApi.itemPath({ itemId, path });+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: itemPath,+ queryParams: { $select: 'id,name,file' },+ });+ if (item.file === undefined) {+ throw new Error(`"${item.name}" is not a file, so it has no versions to download.`);+ }+ const content = await downloadContent({+ auth: context.auth,+ versionPath: `${itemPath}/versions/${encodeURIComponent(versionId)}`,+ });+ return {+ itemId: item.id,+ name: item.name,+ versionId,+ mimeType: item.file.mimeType ?? null,+ data: await context.files.write({ fileName: item.name, data: content }),+ };+ },+});++async function downloadContent({+ auth,+ versionPath,+}: {+ auth: OAuth2PropertyValue;+ versionPath: string;+}): Promise<Readable> {+ const version = await oneDriveApi.request<{ '@microsoft.graph.downloadUrl'?: string }>({+ auth,+ method: HttpMethod.GET,+ path: versionPath,+ });+ const downloadUrl = version['@microsoft.graph.downloadUrl'];+ if (!downloadUrl) {+ throw new Error('OneDrive did not return a download URL for this version.');+ }+ try {+ const download = await httpClient.sendRequest<Readable>({+ method: HttpMethod.GET,+ url: downloadUrl,+ headers: { Accept: '*/*' },+ responseType: 'stream',+ });+ return download.body;+ } catch (error) {+ throw new Error(oneDriveApi.describeError(error));+ }+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-copy-status.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-copy-status.tsnew file mode 100644index 00000000000..c92d9e564f7--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-copy-status.ts@@ -0,0 +1,134 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { httpClient, HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveGetCopyStatusOutputSchema } from '../output-schemas';++export const onedriveGetCopyStatus = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_get_copy_status',+ displayName: 'Get Copy Status',+ description: 'Check the progress of a copy started with Copy File or Folder.',+ audience: 'ai',+ outputSchema: onedriveGetCopyStatusOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Reads the current status of a copy started by Copy File or Folder, once per call, from the monitor URL that action returned. Call it again later while the status is notStarted or inProgress; when it is completed, resourceId is the ID of the new copy, and when it is failed, errorMessage explains why (for example a name conflict). Only accepts monitor URLs on OneDrive and SharePoint hosts.',+ idempotent: true,+ },+ props: {+ monitorUrl: Property.ShortText({+ displayName: 'Monitor URL',+ description: 'The monitorUrl returned by Copy File or Folder.',+ required: true,+ }),+ },+ async run(context) {+ const url = validateMonitorUrl({ monitorUrl: context.propsValue.monitorUrl });+ try {+ const response = await httpClient.sendRequest<MonitorStatus>({+ method: HttpMethod.GET,+ url,+ followRedirects: false,+ });+ if (response.status >= 300 && response.status < 400) {+ const location = response.headers?.['location'];+ const target = Array.isArray(location) ? location[0] : location;+ return {+ status: 'completed',+ percentageComplete: 100,+ resourceId: target ? extractItemId({ location: target }) : null,+ errorCode: null,+ errorMessage: null,+ };+ }+ return toStatus({ body: response.body });+ } catch (error) {+ throw new Error(oneDriveApi.describeError(error));+ }+ },+});++function validateMonitorUrl({ monitorUrl }: { monitorUrl: string }): string {+ let parsed: URL;+ try {+ parsed = new URL(monitorUrl.trim());+ } catch {+ throw new Error('Monitor URL is not a valid URL. Pass the monitorUrl returned by Copy File or Folder.');+ }+ if (parsed.protocol !== 'https:') {+ throw new Error('Monitor URL must use https.');+ }+ const host = parsed.hostname.toLowerCase();+ const allowed =+ ALLOWED_EXACT_HOSTS.includes(host) || ALLOWED_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix));+ if (!allowed) {+ throw new Error(`Monitor URL host "${host}" is not a OneDrive or SharePoint host.`);+ }+ return parsed.toString();+}++function extractItemId({ location }: { location: string }): string | null {+ const match = /\/items\/([^/?#:]+)/.exec(location);+ return match ? decodeURIComponent(match[1]) : null;+}++function toStatus({ body }: { body: MonitorStatus | undefined }): CopyStatus {+ const status = body?.status ?? 'unknown';+ const errorCode = body?.error?.code ?? body?.errorCode ?? null;+ const rawMessage = body?.error?.message ?? null;+ return {+ status,+ percentageComplete: body?.percentageComplete ?? null,+ resourceId: body?.resourceId ?? null,+ errorCode,+ errorMessage: describeFailure({ status, errorCode, rawMessage }),+ };+}++function describeFailure({+ status,+ errorCode,+ rawMessage,+}: {+ status: string;+ errorCode: string | null;+ rawMessage: string | null;+}): string | null {+ if (errorCode === 'nameAlreadyExists') {+ return 'The destination already has an item with this name. Start the copy again with a different New Name.';+ }+ if (rawMessage) {+ return rawMessage;+ }+ if (status === 'failed') {+ return errorCode ? `The copy failed (${errorCode}).` : 'The copy failed.';+ }+ return null;+}++const ALLOWED_EXACT_HOSTS = ['api.onedrive.com'];+const ALLOWED_HOST_SUFFIXES = [+ '.svc.ms',+ '.microsoftpersonalcontent.com',+ '.sharepoint.com',+ '.sharepoint.us',+ '.sharepoint-df.com',+];++type MonitorStatus = {+ status?: string;+ percentageComplete?: number;+ resourceId?: string;+ errorCode?: string;+ error?: { code?: string; message?: string };+};++type CopyStatus = {+ status: string;+ percentageComplete: number | null;+ resourceId: string | null;+ errorCode: string | null;+ errorMessage: string | null;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-drive.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-drive.tsnew file mode 100644index 00000000000..4b6711d2bc3--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-drive.ts@@ -0,0 +1,60 @@+import { createAction } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphIdentity, oneDriveApi } from '../common/graph-api';+import { onedriveGetDriveOutputSchema } from '../output-schemas';++export const onedriveGetDrive = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_get_drive',+ displayName: 'Get Drive',+ description: 'Get the connected OneDrive drive, including its type and storage quota.',+ audience: 'ai',+ outputSchema: onedriveGetDriveOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Read the signed-in user\'s own OneDrive drive: its drive ID, whether it is a personal or business drive, and its storage quota. Use it to check free space or to learn the account type before calling actions that only work on personal OneDrive or only on OneDrive for Business. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {},+ async run(context) {+ const drive = await oneDriveApi.request<GraphDrive>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: '/me/drive',+ });+ return {+ id: drive.id,+ name: drive.name ?? null,+ driveType: drive.driveType ?? null,+ webUrl: drive.webUrl ?? null,+ createdDateTime: drive.createdDateTime ?? null,+ lastModifiedDateTime: drive.lastModifiedDateTime ?? null,+ ownerName: drive.owner?.user?.displayName ?? null,+ ownerEmail: drive.owner?.user?.email ?? null,+ quotaTotal: drive.quota?.total ?? null,+ quotaUsed: drive.quota?.used ?? null,+ quotaRemaining: drive.quota?.remaining ?? null,+ quotaDeleted: drive.quota?.deleted ?? null,+ quotaState: drive.quota?.state ?? null,+ };+ },+});++type GraphDrive = {+ id: string;+ name?: string;+ driveType?: string;+ webUrl?: string;+ createdDateTime?: string;+ lastModifiedDateTime?: string;+ owner?: GraphIdentity;+ quota?: {+ total?: number;+ used?: number;+ remaining?: number;+ deleted?: number;+ state?: string;+ };+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-item.tsnew file mode 100644index 00000000000..f0744e6086d--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-item.ts@@ -0,0 +1,42 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveItemOutputSchema } from '../output-schemas';++export const onedriveGetItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_get_item',+ displayName: 'Get File or Folder',+ description: 'Get the metadata of a file or folder by its ID or path.',+ audience: 'ai',+ outputSchema: onedriveItemOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Read the metadata of one file or folder (name, size, type, parent, dates, web link) without downloading its content. Provide either the item ID (from Search Files and Folders or List Folder Contents; "root" is the drive root) or a path relative to the drive root; use Download File when you need the bytes. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'Item ID from Search or List Folder Contents, or "root". Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Used when Item ID is empty.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: oneDriveApi.itemPath({ itemId, path }),+ });+ return oneDriveApi.toItem(item);+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-special-folder.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-special-folder.tsnew file mode 100644index 00000000000..4063d872be2--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-get-special-folder.ts@@ -0,0 +1,45 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveItemOutputSchema } from '../output-schemas';++export const onedriveGetSpecialFolder = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_get_special_folder',+ displayName: 'Get Special Folder',+ description: 'Get a well-known OneDrive folder such as Documents or Photos.',+ audience: 'ai',+ outputSchema: onedriveItemOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Resolve a well-known OneDrive folder (Documents, Photos, Camera Roll, Music, Recordings) to its folder ID, whatever its localized name is. Use it before listing or uploading into one of these folders instead of guessing a path. If the folder does not exist yet, OneDrive creates it on first access; later calls return the same folder, so it is safe to retry.',+ idempotent: true,+ },+ props: {+ folder: Property.StaticDropdown({+ displayName: 'Folder',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Documents', value: 'documents' },+ { label: 'Photos', value: 'photos' },+ { label: 'Camera Roll', value: 'cameraroll' },+ { label: 'Music', value: 'music' },+ { label: 'Recordings', value: 'recordings' },+ ],+ },+ }),+ },+ async run(context) {+ const { folder } = context.propsValue;+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/me/drive/special/${encodeURIComponent(folder)}`,+ });+ return oneDriveApi.toItem(item);+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-invite-to-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-invite-to-item.tsnew file mode 100644index 00000000000..d4d8b34a0bf--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-invite-to-item.ts@@ -0,0 +1,159 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveInviteToItemOutputSchema } from '../output-schemas';++export const onedriveInviteToItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_invite_to_item',+ displayName: 'Share with People (Invite)',+ description: 'Grant specific people read or write access to a OneDrive file or folder.',+ audience: 'ai',+ outputSchema: onedriveInviteToItemOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Grants read or write access on a file or folder to specific people by email, keeping existing inherited access and requiring them to sign in. Use it for per-person sharing; for a link anyone or the organization can open use Create Sharing Link. No email is sent unless Send Invitation Email is true, and the root folder of a personal drive cannot be shared.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File or folder ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ recipients: Property.Array({+ displayName: 'Recipient Emails',+ description: 'Email addresses of the people to share with.',+ required: true,+ }),+ role: Property.StaticDropdown({+ displayName: 'Role',+ description: 'Read lets recipients view, Write lets them edit.',+ required: true,+ defaultValue: 'read',+ options: {+ disabled: false,+ options: [+ { label: 'Read', value: 'read' },+ { label: 'Write', value: 'write' },+ ],+ },+ }),+ sendInvitation: Property.Checkbox({+ displayName: 'Send Invitation Email',+ description: 'If on, OneDrive emails each recipient. Off grants access silently.',+ required: false,+ defaultValue: false,+ }),+ message: Property.LongText({+ displayName: 'Message',+ description: 'Message for the invitation email (only sent when emails are on).',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, recipients, role, sendInvitation, message } = context.propsValue;+ const emails = (recipients ?? []).flatMap((recipient) =>+ typeof recipient === 'string' && recipient.trim() ? [recipient.trim()] : [],+ );+ if (emails.length === 0) {+ throw new Error('Provide at least one recipient email address.');+ }+ const body: Record<string, unknown> = {+ recipients: emails.map((email) => ({ email })),+ roles: [role],+ requireSignIn: true,+ sendInvitation: sendInvitation === true,+ retainInheritedPermissions: true,+ };+ if (message) {+ body['message'] = message;+ }+ const response = await oneDriveApi.request<{ value?: GraphPermission[] }>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `${oneDriveApi.itemPath({ itemId, path })}/invite`,+ body,+ });+ const permissions = (response.value ?? []).map(toPermission);+ return {+ permissions,+ count: permissions.length,+ invitationSent: sendInvitation === true,+ };+ },+});++function toPermission(permission: GraphPermission): OneDrivePermission {+ const grantee = permission.grantedToV2?.user ?? permission.grantedTo?.user;+ const identities = permission.grantedToIdentitiesV2 ?? permission.grantedToIdentities ?? [];+ return {+ id: permission.id,+ roles: permission.roles ?? [],+ linkType: permission.link?.type ?? null,+ linkScope: permission.link?.scope ?? null,+ linkWebUrl: permission.link?.webUrl ?? null,+ linkPreventsDownload: permission.link?.preventsDownload ?? null,+ grantedToName: grantee?.displayName ?? null,+ grantedToEmail: grantee?.email ?? null,+ grantedToId: grantee?.id ?? null,+ grantedToIdentities: identities+ .flatMap((identity) => {+ const value = identity.user?.email ?? identity.user?.displayName;+ return value ? [value] : [];+ })+ .join(', '),+ invitationEmail: permission.invitation?.email ?? null,+ inherited: permission.inheritedFrom !== undefined,+ inheritedFromId: permission.inheritedFrom?.id ?? null,+ inheritedFromPath: permission.inheritedFrom?.path ?? null,+ hasPassword: permission.hasPassword ?? null,+ expirationDateTime: permission.expirationDateTime ?? null,+ shareId: permission.shareId ?? null,+ };+}++type GraphPermissionUser = { displayName?: string; email?: string; id?: string };++type GraphPermission = {+ id: string;+ roles?: string[];+ link?: { type?: string; scope?: string; webUrl?: string; preventsDownload?: boolean };+ grantedTo?: { user?: GraphPermissionUser };+ grantedToV2?: { user?: GraphPermissionUser };+ grantedToIdentities?: { user?: GraphPermissionUser }[];+ grantedToIdentitiesV2?: { user?: GraphPermissionUser }[];+ invitation?: { email?: string };+ inheritedFrom?: { id?: string; path?: string; driveId?: string };+ hasPassword?: boolean;+ expirationDateTime?: string;+ shareId?: string;+};++type OneDrivePermission = {+ id: string;+ roles: string[];+ linkType: string | null;+ linkScope: string | null;+ linkWebUrl: string | null;+ linkPreventsDownload: boolean | null;+ grantedToName: string | null;+ grantedToEmail: string | null;+ grantedToId: string | null;+ grantedToIdentities: string;+ invitationEmail: string | null;+ inherited: boolean;+ inheritedFromId: string | null;+ inheritedFromPath: string | null;+ hasPassword: boolean | null;+ expirationDateTime: string | null;+ shareId: string | null;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-bundles.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-bundles.tsnew file mode 100644index 00000000000..bb3e5a2409d--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-bundles.ts@@ -0,0 +1,68 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveListBundlesOutputSchema } from '../output-schemas';++export const onedriveListBundles = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_list_bundles',+ displayName: 'List Albums and Bundles',+ description: 'List the photo albums and file bundles in a personal OneDrive.',+ audience: 'ai',+ outputSchema: onedriveListBundlesOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'List the bundles in the user\'s drive, meaning photo albums and multi-file share sets, with each bundle\'s ID and item count, one page per call. Use it to find a bundle ID for Add Item to Bundle or Remove Item from Bundle. Works only on personal OneDrive (Microsoft account); OneDrive for Business has no bundles. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'nextPageToken from the previous call. Empty for the first page.',+ required: false,+ }),+ },+ async run(context) {+ const { pageToken } = context.propsValue;+ await assertPersonalDrive({ auth: context.auth });+ const token = pageToken?.trim();+ const response = await oneDriveApi.request<GraphBundlePage>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: token ? token : '/me/drive/bundles',+ });+ const items = response.value.map((bundle) => ({+ ...oneDriveApi.toItem(bundle),+ bundleChildCount: bundle.bundle?.childCount ?? null,+ isAlbum: bundle.bundle?.album !== undefined && bundle.bundle?.album !== null,+ }));+ return {+ items,+ count: items.length,+ nextPageToken: response['@odata.nextLink'] ?? null,+ };+ },+});++async function assertPersonalDrive({ auth }: { auth: OAuth2PropertyValue }): Promise<void> {+ const drive = await oneDriveApi.request<{ driveType?: string }>({+ auth,+ method: HttpMethod.GET,+ path: '/me/drive',+ queryParams: { $select: 'driveType' },+ });+ if (drive.driveType !== 'personal') {+ throw new Error('Albums and bundles are available only on personal OneDrive (Microsoft account) drives. This connection uses OneDrive for Business.');+ }+}++type GraphBundle = GraphDriveItem & {+ bundle?: { childCount?: number; album?: Record<string, unknown> | null };+};++type GraphBundlePage = {+ value: GraphBundle[];+ '@odata.nextLink'?: string;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-drive-changes.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-drive-changes.tsnew file mode 100644index 00000000000..86fb871d3a4--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-drive-changes.ts@@ -0,0 +1,93 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { AuthenticationType, HttpError, HttpMethod, QueryParams, httpClient } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { getGraphBaseUrl } from '../common/microsoft-cloud';+import { onedriveListDriveChangesOutputSchema } from '../output-schemas';++export const onedriveListDriveChanges = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_list_drive_changes',+ displayName: 'List Drive Changes (Delta)',+ description: 'List items that changed in the drive since a saved delta token, one page at a time.',+ audience: 'ai',+ outputSchema: onedriveListDriveChangesOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Track changes across the whole drive, one page per call: with no token it enumerates every item, with a token it returns only items created, changed or deleted since then (deleted items have deleted = true). Keep calling with nextPageToken until it is null, then save deltaToken and pass it on a later call to get the next changes; set Start From Now to skip the full enumeration and get a deltaToken only. If a token has expired, the action fails and you must start again without a token.',+ idempotent: true,+ },+ props: {+ pageToken: Property.ShortText({+ displayName: 'Page or Delta Token',+ description: 'nextPageToken or deltaToken from a previous call. Empty to start.',+ required: false,+ }),+ startFromNow: Property.Checkbox({+ displayName: 'Start From Now',+ description: 'Without a token, skip current items and return only a deltaToken.',+ required: false,+ defaultValue: false,+ }),+ },+ async run(context) {+ const { pageToken, startFromNow } = context.propsValue;+ const token = pageToken?.trim();+ const graphPrefix = graphV1Prefix({ auth: context.auth });+ if (token && !token.startsWith(graphPrefix)) {+ throw new Error('The token is not a valid OneDrive delta link. Pass the nextPageToken or deltaToken from a previous call unchanged.');+ }+ const response = await fetchDeltaPage({+ auth: context.auth,+ url: token ? token : `${graphPrefix}me/drive/root/delta`,+ queryParams: !token && startFromNow ? { token: 'latest' } : undefined,+ });+ const items = response.value.map((item) => oneDriveApi.toItem(item));+ return {+ items,+ count: items.length,+ nextPageToken: response['@odata.nextLink'] ?? null,+ deltaToken: response['@odata.deltaLink'] ?? null,+ };+ },+});++async function fetchDeltaPage({+ auth,+ url,+ queryParams,+}: {+ auth: OAuth2PropertyValue;+ url: string;+ queryParams?: QueryParams;+}): Promise<GraphDeltaPage> {+ try {+ const response = await httpClient.sendRequest<GraphDeltaPage>({+ method: HttpMethod.GET,+ url,+ queryParams,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: auth.access_token,+ },+ });+ return response.body;+ } catch (error) {+ if (error instanceof HttpError && error.response.status === 410) {+ throw new Error('The delta token has expired or is no longer valid. Call this action again with no token to restart the enumeration from the beginning.');+ }+ throw new Error(oneDriveApi.describeError(error));+ }+}++function graphV1Prefix({ auth }: { auth: OAuth2PropertyValue }): string {+ const cloud = auth.props?.['cloud'];+ return `${getGraphBaseUrl(typeof cloud === 'string' ? cloud : undefined)}/v1.0/`;+}++type GraphDeltaPage = {+ value: GraphDriveItem[];+ '@odata.nextLink'?: string;+ '@odata.deltaLink'?: string;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-drives.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-drives.tsnew file mode 100644index 00000000000..ae6c4c46265--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-drives.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphIdentity, oneDriveApi } from '../common/graph-api';+import { onedriveListDrivesOutputSchema } from '../output-schemas';++export const onedriveListDrives = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_list_drives',+ displayName: 'List My Drives',+ description: 'List the drives available to the signed-in user.',+ audience: 'ai',+ outputSchema: onedriveListDrivesOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'List the drives that belong to the signed-in user, with each drive\'s ID, type and quota. Use Get Drive instead when you only need the default drive; SharePoint site and group drives are not included. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'nextPageToken from the previous call. Empty for the first page.',+ required: false,+ }),+ },+ async run(context) {+ const { pageToken } = context.propsValue;+ const token = pageToken?.trim();+ const response = await oneDriveApi.request<GraphDriveList>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: token ? token : '/me/drives',+ });+ const items = response.value.map((drive) => ({+ id: drive.id,+ name: drive.name ?? null,+ driveType: drive.driveType ?? null,+ webUrl: drive.webUrl ?? null,+ ownerName: drive.owner?.user?.displayName ?? null,+ ownerEmail: drive.owner?.user?.email ?? null,+ quotaTotal: drive.quota?.total ?? null,+ quotaUsed: drive.quota?.used ?? null,+ quotaRemaining: drive.quota?.remaining ?? null,+ quotaState: drive.quota?.state ?? null,+ }));+ return {+ items,+ count: items.length,+ nextPageToken: response['@odata.nextLink'] ?? null,+ };+ },+});++type GraphDriveList = {+ value: {+ id: string;+ name?: string;+ driveType?: string;+ webUrl?: string;+ owner?: GraphIdentity;+ quota?: { total?: number; used?: number; remaining?: number; state?: string };+ }[];+ '@odata.nextLink'?: string;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-folder-children.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-folder-children.tsnew file mode 100644index 00000000000..65651e84c7b--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-folder-children.ts@@ -0,0 +1,105 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveListItemsOutputSchema } from '../output-schemas';++export const onedriveListFolderChildren = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_list_folder_children',+ displayName: 'List Folder Contents',+ description: 'List the files and folders inside a folder, one page at a time.',+ audience: 'ai',+ outputSchema: onedriveListItemsOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'List the direct children of one folder (the drive root when no folder is given), optionally keeping only files or only folders, one page per call. Use Search Files and Folders to find items by name anywhere in the drive. The type filter is applied after the page is fetched, so a page can come back empty while nextPageToken is still set: keep paging until nextPageToken is null.',+ idempotent: true,+ },+ props: {+ folderId: Property.ShortText({+ displayName: 'Folder ID',+ description: 'Folder ID. Leave this and Folder Path empty for the drive root.',+ required: false,+ }),+ folderPath: Property.ShortText({+ displayName: 'Folder Path',+ description: 'Folder path from the drive root. Used when Folder ID is empty.',+ placeholder: 'Documents/Reports',+ required: false,+ }),+ itemType: Property.StaticDropdown({+ displayName: 'Item Type',+ required: false,+ defaultValue: 'all',+ options: {+ disabled: false,+ options: [+ { label: 'Files and folders', value: 'all' },+ { label: 'Files only', value: 'files' },+ { label: 'Folders only', value: 'folders' },+ ],+ },+ }),+ pageSize: Property.Number({+ displayName: 'Page Size',+ description: 'How many items to request per page (1-999). Defaults to 100.',+ required: false,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'nextPageToken from the previous call. Empty for the first page.',+ required: false,+ }),+ },+ async run(context) {+ const { folderId, folderPath, itemType, pageSize, pageToken } = context.propsValue;+ const token = pageToken?.trim();+ const response = await oneDriveApi.request<GraphItemPage>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: token+ ? token+ : `${resolveFolder({ folderId, folderPath })}/children`,+ queryParams: token ? undefined : { $top: String(clampPageSize({ pageSize })) },+ });+ const items = response.value+ .filter((item) => matchesType({ item, itemType: itemType ?? 'all' }))+ .map((item) => oneDriveApi.toItem(item));+ return {+ items,+ count: items.length,+ nextPageToken: response['@odata.nextLink'] ?? null,+ };+ },+});++function resolveFolder({ folderId, folderPath }: { folderId?: string; folderPath?: string }): string {+ if (!folderId?.trim() && folderPath?.trim()) {+ return oneDriveApi.itemPath({ path: folderPath });+ }+ return oneDriveApi.folderPath({ folderId });+}++function matchesType({ item, itemType }: { item: GraphDriveItem; itemType: string }): boolean {+ if (itemType === 'files') {+ return item.file !== undefined;+ }+ if (itemType === 'folders') {+ return item.folder !== undefined;+ }+ return true;+}++function clampPageSize({ pageSize }: { pageSize?: number }): number {+ if (pageSize === undefined || pageSize === null || Number.isNaN(pageSize)) {+ return 100;+ }+ return Math.min(Math.max(Math.floor(pageSize), 1), 999);+}++type GraphItemPage = {+ value: GraphDriveItem[];+ '@odata.nextLink'?: string;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-permissions.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-permissions.tsnew file mode 100644index 00000000000..e4146be5b32--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-permissions.ts@@ -0,0 +1,118 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveListItemPermissionsOutputSchema } from '../output-schemas';++export const onedriveListItemPermissions = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_list_item_permissions',+ displayName: 'List File Permissions',+ description: 'List who has access to a OneDrive file or folder, including sharing links.',+ audience: 'ai',+ outputSchema: onedriveListItemPermissionsOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Lists the permissions on a file or folder: owner, per-person grants, sharing links and access inherited from parent folders. Use it to find the permission ID that Update Permission Role and Remove Permission need; permissions marked inherited can only be changed on the folder they are inherited from.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File or folder ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'nextPageToken from the previous call. Empty for the first page.',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, pageToken } = context.propsValue;+ const response = await oneDriveApi.request<{ value?: GraphPermission[]; '@odata.nextLink'?: string }>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: pageToken?.trim() ? pageToken.trim() : `${oneDriveApi.itemPath({ itemId, path })}/permissions`,+ });+ const items = (response.value ?? []).map(toPermission);+ return {+ items,+ count: items.length,+ nextPageToken: response['@odata.nextLink'] ?? null,+ };+ },+});++function toPermission(permission: GraphPermission): OneDrivePermission {+ const grantee = permission.grantedToV2?.user ?? permission.grantedTo?.user;+ const identities = permission.grantedToIdentitiesV2 ?? permission.grantedToIdentities ?? [];+ return {+ id: permission.id,+ roles: permission.roles ?? [],+ linkType: permission.link?.type ?? null,+ linkScope: permission.link?.scope ?? null,+ linkWebUrl: permission.link?.webUrl ?? null,+ linkPreventsDownload: permission.link?.preventsDownload ?? null,+ grantedToName: grantee?.displayName ?? null,+ grantedToEmail: grantee?.email ?? null,+ grantedToId: grantee?.id ?? null,+ grantedToIdentities: identities+ .flatMap((identity) => {+ const value = identity.user?.email ?? identity.user?.displayName;+ return value ? [value] : [];+ })+ .join(', '),+ invitationEmail: permission.invitation?.email ?? null,+ inherited: permission.inheritedFrom !== undefined,+ inheritedFromId: permission.inheritedFrom?.id ?? null,+ inheritedFromPath: permission.inheritedFrom?.path ?? null,+ hasPassword: permission.hasPassword ?? null,+ expirationDateTime: permission.expirationDateTime ?? null,+ shareId: permission.shareId ?? null,+ };+}++type GraphPermissionUser = { displayName?: string; email?: string; id?: string };++type GraphPermission = {+ id: string;+ roles?: string[];+ link?: { type?: string; scope?: string; webUrl?: string; preventsDownload?: boolean };+ grantedTo?: { user?: GraphPermissionUser };+ grantedToV2?: { user?: GraphPermissionUser };+ grantedToIdentities?: { user?: GraphPermissionUser }[];+ grantedToIdentitiesV2?: { user?: GraphPermissionUser }[];+ invitation?: { email?: string };+ inheritedFrom?: { id?: string; path?: string; driveId?: string };+ hasPassword?: boolean;+ expirationDateTime?: string;+ shareId?: string;+};++type OneDrivePermission = {+ id: string;+ roles: string[];+ linkType: string | null;+ linkScope: string | null;+ linkWebUrl: string | null;+ linkPreventsDownload: boolean | null;+ grantedToName: string | null;+ grantedToEmail: string | null;+ grantedToId: string | null;+ grantedToIdentities: string;+ invitationEmail: string | null;+ inherited: boolean;+ inheritedFromId: string | null;+ inheritedFromPath: string | null;+ hasPassword: boolean | null;+ expirationDateTime: string | null;+ shareId: string | null;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-thumbnails.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-thumbnails.tsnew file mode 100644index 00000000000..8fd8233b053--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-thumbnails.ts@@ -0,0 +1,72 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveListItemThumbnailsOutputSchema } from '../output-schemas';++export const onedriveListItemThumbnails = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_list_item_thumbnails',+ displayName: 'Get File Thumbnails',+ description: 'Get the small, medium and large thumbnail image URLs of a file.',+ audience: 'ai',+ outputSchema: onedriveListItemThumbnailsOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Get the thumbnail image URLs (small, medium, large, with sizes) that OneDrive generated for one file, for previews or image galleries. Provide the item ID (from Search Files and Folders or List Folder Contents) or a path; an empty result is normal for a new file whose thumbnails are not generated yet, or for file types without thumbnails. The URLs are short-lived. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Used when Item ID is empty.',+ placeholder: 'Photos/beach.jpg',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ const response = await oneDriveApi.request<GraphThumbnailList>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `${oneDriveApi.itemPath({ itemId, path })}/thumbnails`,+ });+ const items = response.value.map((set) => ({+ thumbnailSetId: set.id ?? null,+ smallUrl: set.small?.url ?? null,+ smallWidth: set.small?.width ?? null,+ smallHeight: set.small?.height ?? null,+ mediumUrl: set.medium?.url ?? null,+ mediumWidth: set.medium?.width ?? null,+ mediumHeight: set.medium?.height ?? null,+ largeUrl: set.large?.url ?? null,+ largeWidth: set.large?.width ?? null,+ largeHeight: set.large?.height ?? null,+ }));+ return {+ items,+ count: items.length,+ };+ },+});++type GraphThumbnail = {+ url?: string;+ width?: number;+ height?: number;+};++type GraphThumbnailList = {+ value: {+ id?: string;+ small?: GraphThumbnail;+ medium?: GraphThumbnail;+ large?: GraphThumbnail;+ }[];+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-versions.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-versions.tsnew file mode 100644index 00000000000..f4c8a780181--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-list-item-versions.ts@@ -0,0 +1,71 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphIdentity, oneDriveApi } from '../common/graph-api';+import { onedriveListItemVersionsOutputSchema } from '../output-schemas';++export const onedriveListItemVersions = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_list_item_versions',+ displayName: 'List File Versions',+ description: 'List the saved versions of a file.',+ audience: 'ai',+ outputSchema: onedriveListItemVersionsOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'List the version history of one file, newest first, with each version ID, size, modification time and who made it, one page per call. Use it to get the version ID that Download File Version and Restore File Version need. Provide the item ID (from Search Files and Folders or List Folder Contents) or a path; retention is controlled by the account or admin, so the list can be short. Read-only and safe to retry.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'File ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Used when File ID is empty.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'nextPageToken from the previous call. Empty for the first page.',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, pageToken } = context.propsValue;+ const token = pageToken?.trim();+ const response = await oneDriveApi.request<GraphVersionPage>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: token+ ? token+ : `${oneDriveApi.itemPath({ itemId, path })}/versions`,+ });+ const items = response.value.map((version) => ({+ versionId: version.id,+ lastModifiedDateTime: version.lastModifiedDateTime ?? null,+ size: version.size ?? null,+ lastModifiedByName: version.lastModifiedBy?.user?.displayName ?? null,+ lastModifiedByEmail: version.lastModifiedBy?.user?.email ?? null,+ }));+ return {+ items,+ count: items.length,+ nextPageToken: response['@odata.nextLink'] ?? null,+ };+ },+});++type GraphVersionPage = {+ value: {+ id: string;+ lastModifiedDateTime?: string;+ size?: number;+ lastModifiedBy?: GraphIdentity;+ }[];+ '@odata.nextLink'?: string;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-move-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-move-item.tsnew file mode 100644index 00000000000..ed486f001e3--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-move-item.ts@@ -0,0 +1,68 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveItemOutputSchema } from '../output-schemas';++export const onedriveMoveItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_move_item',+ displayName: 'Move File or Folder',+ description: 'Move a OneDrive file or folder to another folder, optionally renaming it.',+ audience: 'ai',+ outputSchema: onedriveItemOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Moves a file or folder (with its contents) into another folder in the same drive, optionally renaming it; the item keeps its ID. Use Rename / Update File or Folder to rename without moving, and Copy File or Folder to keep the original. Fails if the destination already has an item with the same name unless you set New Name; moving between drives is not supported. Retrying by item ID is safe; after a move by path, use the returned item ID, because the old path no longer exists.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'ID of the item to move, from Search or List Folder Contents.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ destinationFolderId: Property.ShortText({+ displayName: 'Destination Folder ID',+ description: 'Folder to move into. Leave empty for the drive root.',+ required: false,+ }),+ newName: Property.ShortText({+ displayName: 'New Name',+ description: 'Optional new name for the item. Leave empty to keep its current name.',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, destinationFolderId, newName } = context.propsValue;+ const itemPath = oneDriveApi.itemPath({ itemId, path });+ const parentId = await oneDriveApi.resolveFolderId({ auth: context.auth, folderId: destinationFolderId });+ const body: Record<string, unknown> = { parentReference: { id: parentId } };+ const trimmedName = newName?.trim();+ if (trimmedName) {+ body['name'] = trimmedName;+ }+ try {+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.PATCH,+ path: itemPath,+ body,+ });+ return oneDriveApi.toItem(item);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ if (message.startsWith('An item with that name already exists')) {+ throw new Error(`${message} Set New Name to move it under a different name.`);+ }+ throw error;+ }+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-remove-item-from-bundle.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-remove-item-from-bundle.tsnew file mode 100644index 00000000000..1d46066a130--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-remove-item-from-bundle.ts@@ -0,0 +1,55 @@+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveBundleMembershipOutputSchema } from '../output-schemas';++export const onedriveRemoveItemFromBundle = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_remove_item_from_bundle',+ displayName: 'Remove Item from Bundle',+ description: 'Remove a file from a bundle or album without deleting the file.',+ audience: 'ai',+ outputSchema: onedriveBundleMembershipOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Take one file out of a bundle or photo album in a personal OneDrive; the file itself is not deleted and stays in its folder. Get the bundle ID from List Albums and Bundles and the item ID from Search Files and Folders or List Folder Contents; to delete the file itself use Delete File or Folder instead. Works only on personal OneDrive (Microsoft account); repeating the call after success fails because the item is no longer in the bundle.',+ idempotent: false,+ },+ props: {+ bundleId: Property.ShortText({+ displayName: 'Bundle ID',+ description: 'The ID of the bundle or album, from List Albums and Bundles.',+ required: true,+ }),+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'The ID of the file to remove from the bundle. The file itself is kept.',+ required: true,+ }),+ },+ async run(context) {+ const bundleId = context.propsValue.bundleId.trim();+ const itemId = context.propsValue.itemId.trim();+ await assertPersonalDrive({ auth: context.auth });+ await oneDriveApi.request<unknown>({+ auth: context.auth,+ method: HttpMethod.DELETE,+ path: `/me/drive/bundles/${encodeURIComponent(bundleId)}/children/${encodeURIComponent(itemId)}`,+ });+ return { success: true, bundleId, itemId };+ },+});++async function assertPersonalDrive({ auth }: { auth: OAuth2PropertyValue }): Promise<void> {+ const drive = await oneDriveApi.request<{ driveType?: string }>({+ auth,+ method: HttpMethod.GET,+ path: '/me/drive',+ queryParams: { $select: 'driveType' },+ });+ if (drive.driveType !== 'personal') {+ throw new Error('Bundles are available only on personal OneDrive (Microsoft account) drives. This connection uses OneDrive for Business.');+ }+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-replace-file-content.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-replace-file-content.tsnew file mode 100644index 00000000000..2299cbacd46--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-replace-file-content.ts@@ -0,0 +1,130 @@+import { Readable } from 'node:stream';+import { buffer as readableToBuffer } from 'node:stream/consumers';+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { httpClient, HttpMethod, streamUtils } from '@activepieces/pieces-common';+import mime from 'mime-types';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveItemOutputSchema } from '../output-schemas';++export const onedriveReplaceFileContent = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_replace_file_content',+ displayName: 'Replace File Content',+ description: 'Overwrite the content of an existing OneDrive file, keeping its ID and sharing links.',+ audience: 'ai',+ outputSchema: onedriveItemOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Overwrites the content of an existing file, identified by Item ID or Path, and keeps its ID, name and sharing links; files over 4 MiB are sent in chunks. Use Upload File to add a new file by folder and name. The item must already exist and be a file (not a folder); get its ID from Search Files and Folders or List Folder Contents. Re-running with the same content converges on the same state.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'ID of the file to overwrite. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ file: Property.File({+ displayName: 'File',+ description: 'The new content, as a file URL or base64.',+ required: true,+ streaming: true,+ }),+ },+ async run(context) {+ const { itemId, path, file } = context.propsValue;+ const existing = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: oneDriveApi.itemPath({ itemId, path }),+ queryParams: { $select: 'id,name,file,folder,package' },+ });+ if (!existing.file) {+ throw new Error(`"${existing.name}" is not a file, so its content cannot be replaced.`);+ }+ const mimeType = mime.lookup(file.extension ?? '') || existing.file.mimeType || 'application/octet-stream';+ let { body, size } = streamUtils.toStreamingBody(file);+ if (size == null) {+ const buffered = await readableToBuffer(body);+ size = buffered.length;+ body = Readable.from(buffered);+ }+ const item = await replaceContent({+ auth: context.auth,+ targetPath: oneDriveApi.itemPath({ itemId: existing.id }),+ body,+ size,+ mimeType,+ });+ return oneDriveApi.toItem(item);+ },+});++async function replaceContent({+ auth,+ targetPath,+ body,+ size,+ mimeType,+}: {+ auth: OAuth2PropertyValue;+ targetPath: string;+ body: Readable;+ size: number;+ mimeType: string;+}): Promise<GraphDriveItem> {+ if (size <= SIMPLE_UPLOAD_LIMIT) {+ return oneDriveApi.request<GraphDriveItem>({+ auth,+ method: HttpMethod.PUT,+ path: `${targetPath}/content`,+ body,+ headers: {+ 'Content-Type': mimeType,+ 'Content-Length': size.toString(),+ },+ });+ }+ const session = await oneDriveApi.request<{ uploadUrl: string }>({+ auth,+ method: HttpMethod.POST,+ path: `${targetPath}/createUploadSession`,+ body: { item: { '@microsoft.graph.conflictBehavior': 'replace' } },+ headers: { 'Content-Type': 'application/json' },+ });+ let start = 0;+ let result: GraphDriveItem | undefined;+ for await (const chunk of streamUtils.readChunks({ readable: body, chunkSize: CHUNK_SIZE })) {+ const end = start + chunk.length - 1;+ try {+ const response = await httpClient.sendRequest<GraphDriveItem>({+ method: HttpMethod.PUT,+ url: session.uploadUrl,+ body: chunk,+ headers: {+ 'Content-Length': chunk.length.toString(),+ 'Content-Range': `bytes ${start}-${end}/${size}`,+ },+ });+ result = response.body;+ } catch (error) {+ throw new Error(oneDriveApi.describeError(error));+ }+ start += chunk.length;+ }+ if (!result?.id) {+ throw new Error('The upload session finished without returning the updated file.');+ }+ return result;+}++const SIMPLE_UPLOAD_LIMIT = 4 * 1024 * 1024;+const CHUNK_SIZE = 10485760;diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-resolve-sharing-link.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-resolve-sharing-link.tsnew file mode 100644index 00000000000..e147d822708--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-resolve-sharing-link.ts@@ -0,0 +1,57 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveResolveSharingLinkOutputSchema } from '../output-schemas';++export const onedriveResolveSharingLink = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_resolve_sharing_link',+ displayName: 'Resolve Sharing Link',+ description: 'Look up the file or folder behind a OneDrive or SharePoint sharing link.',+ audience: 'ai',+ outputSchema: onedriveResolveSharingLinkOutputSchema,+ classification: 'READ',+ aiMetadata: {+ description:+ 'Turns a OneDrive (1drv.ms, onedrive.live.com) or SharePoint sharing URL, or an existing share token, into the item it points to, including its item ID and drive ID. Use it when a user pastes a link and you need the item for other actions; it only peeks at the link and does not add the item to the user\'s drive, and an item in someone else\'s drive has a different drive ID that the other item actions here cannot address.',+ idempotent: true,+ },+ props: {+ sharingUrl: Property.ShortText({+ displayName: 'Sharing Link or Share Token',+ description: 'The sharing URL, or a share token starting with u! or s!.',+ placeholder: 'https://1drv.ms/...',+ required: true,+ }),+ },+ async run(context) {+ const shareId = toShareId({ value: context.propsValue.sharingUrl });+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: `/shares/${encodeURIComponent(shareId)}/driveItem`,+ headers: { Prefer: 'redeemSharingLinkIfNecessary' },+ });+ return {+ ...oneDriveApi.toItem(item),+ shareId,+ };+ },+});++function toShareId({ value }: { value: string }): string {+ const trimmed = value.trim();+ if (!trimmed) {+ throw new Error('Provide a sharing link or share token.');+ }+ if (/^[us]!/.test(trimmed)) {+ return trimmed;+ }+ const encoded = Buffer.from(trimmed, 'utf8')+ .toString('base64')+ .replace(/=+$/, '')+ .replace(/\//g, '_')+ .replace(/\+/g, '-');+ return `u!${encoded}`;+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-restore-item-version.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-restore-item-version.tsnew file mode 100644index 00000000000..1fe20700866--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-restore-item-version.ts@@ -0,0 +1,53 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedriveRestoreItemVersionOutputSchema } from '../output-schemas';++export const onedriveRestoreItemVersion = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_restore_item_version',+ displayName: 'Restore File Version',+ description: 'Make a previous version of a file the current version.',+ audience: 'ai',+ outputSchema: onedriveRestoreItemVersionOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Restore an earlier version of one file by copying it into a new current version; the file keeps its ID and the replaced content stays in the version history. Get the version ID from List File Versions and provide the file ID (from Search Files and Folders or List Folder Contents) or a path; use Download File Version to inspect a version without restoring it. Each call adds another version, so retries are not no-ops.',+ idempotent: false,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'File ID',+ description: 'File ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'File path from the drive root. Used when File ID is empty.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ versionId: Property.ShortText({+ displayName: 'Version ID',+ description: 'The ID of the version to restore, from List File Versions.',+ required: true,+ }),+ },+ async run(context) {+ const { itemId, path } = context.propsValue;+ const versionId = context.propsValue.versionId.trim();+ await oneDriveApi.request<unknown>({+ auth: context.auth,+ method: HttpMethod.POST,+ path: `${oneDriveApi.itemPath({ itemId, path })}/versions/${encodeURIComponent(versionId)}/restoreVersion`,+ });+ return {+ success: true,+ itemId: itemId?.trim() || null,+ path: itemId?.trim() ? null : path?.trim() || null,+ versionId,+ };+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-search-items.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-search-items.tsnew file mode 100644index 00000000000..736468d92ed--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-search-items.ts@@ -0,0 +1,79 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveListItemsOutputSchema } from '../output-schemas';++export const onedriveSearchItems = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_search_items',+ displayName: 'Search Files and Folders',+ description: 'Search OneDrive for files and folders by name, metadata or content.',+ audience: 'ai',+ outputSchema: onedriveListItemsOutputSchema,+ classification: 'SEARCH',+ aiMetadata: {+ description:+ 'Search the user\'s OneDrive for files and folders whose name, metadata or content matches a text query, one page per call; use it to find an item ID when you only know a name. Scope "my_files" searches only the user\'s own drive, while "include_shared" also returns items shared with the user, which come back as remote items whose remoteItemId and remoteDriveId belong to another drive that the other OneDrive actions cannot address. The search index lags, so very recently added files may be missing.',+ idempotent: true,+ },+ props: {+ query: Property.ShortText({+ displayName: 'Search Text',+ description: 'The text to search for in file names, metadata and content.',+ required: true,+ }),+ scope: Property.StaticDropdown({+ displayName: 'Scope',+ required: false,+ defaultValue: 'my_files',+ options: {+ disabled: false,+ options: [+ { label: 'My files only', value: 'my_files' },+ { label: 'Include items shared with me', value: 'include_shared' },+ ],+ },+ }),+ pageSize: Property.Number({+ displayName: 'Page Size',+ description: 'How many results to request per page (1-999). Defaults to 50.',+ required: false,+ }),+ pageToken: Property.ShortText({+ displayName: 'Page Token',+ description: 'nextPageToken from the previous call. Empty for the first page.',+ required: false,+ }),+ },+ async run(context) {+ const { query, scope, pageSize, pageToken } = context.propsValue;+ const token = pageToken?.trim();+ const q = encodeURIComponent(query.replace(/'/g, "''"));+ const searchRoot = scope === 'include_shared' ? '/me/drive' : '/me/drive/root';+ const response = await oneDriveApi.request<GraphItemPage>({+ auth: context.auth,+ method: HttpMethod.GET,+ path: token ? token : `${searchRoot}/search(q='${q}')`,+ queryParams: token ? undefined : { $top: String(clampPageSize({ pageSize })) },+ });+ const items = response.value.map((item) => oneDriveApi.toItem(item));+ return {+ items,+ count: items.length,+ nextPageToken: response['@odata.nextLink'] ?? null,+ };+ },+});++function clampPageSize({ pageSize }: { pageSize?: number }): number {+ if (pageSize === undefined || pageSize === null || Number.isNaN(pageSize)) {+ return 50;+ }+ return Math.min(Math.max(Math.floor(pageSize), 1), 999);+}++type GraphItemPage = {+ value: GraphDriveItem[];+ '@odata.nextLink'?: string;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-update-item-permission.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-update-item-permission.tsnew file mode 100644index 00000000000..f508397a1c0--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-update-item-permission.ts@@ -0,0 +1,133 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { oneDriveApi } from '../common/graph-api';+import { onedrivePermissionOutputSchema } from '../output-schemas';++export const onedriveUpdateItemPermission = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_update_item_permission',+ displayName: 'Update Permission Role',+ description: 'Change a permission on a OneDrive file or folder to read or write.',+ audience: 'ai',+ outputSchema: onedrivePermissionOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Sets the role of one existing permission on a file or folder to read or write, replacing its current roles. Get the permission ID from List File Permissions; inherited permissions cannot be changed here and must be changed on the parent folder they come from. Safe to retry with the same role.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File or folder ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ permissionId: Property.ShortText({+ displayName: 'Permission ID',+ description: 'The ID of the permission to change, from List File Permissions.',+ required: true,+ }),+ role: Property.StaticDropdown({+ displayName: 'Role',+ description: 'The new role. Replaces the roles the permission has today.',+ required: true,+ options: {+ disabled: false,+ options: [+ { label: 'Read', value: 'read' },+ { label: 'Write', value: 'write' },+ ],+ },+ }),+ },+ async run(context) {+ const { itemId, path, permissionId, role } = context.propsValue;+ try {+ const permission = await oneDriveApi.request<GraphPermission>({+ auth: context.auth,+ method: HttpMethod.PATCH,+ path: `${oneDriveApi.itemPath({ itemId, path })}/permissions/${encodeURIComponent(permissionId.trim())}`,+ body: { roles: [role] },+ });+ return toPermission(permission);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ throw new Error(+ `${message} If this permission is inherited from a parent folder (inherited is true in List File Permissions), change it on that folder instead.`,+ );+ }+ },+});++function toPermission(permission: GraphPermission): OneDrivePermission {+ const grantee = permission.grantedToV2?.user ?? permission.grantedTo?.user;+ const identities = permission.grantedToIdentitiesV2 ?? permission.grantedToIdentities ?? [];+ return {+ id: permission.id,+ roles: permission.roles ?? [],+ linkType: permission.link?.type ?? null,+ linkScope: permission.link?.scope ?? null,+ linkWebUrl: permission.link?.webUrl ?? null,+ linkPreventsDownload: permission.link?.preventsDownload ?? null,+ grantedToName: grantee?.displayName ?? null,+ grantedToEmail: grantee?.email ?? null,+ grantedToId: grantee?.id ?? null,+ grantedToIdentities: identities+ .flatMap((identity) => {+ const value = identity.user?.email ?? identity.user?.displayName;+ return value ? [value] : [];+ })+ .join(', '),+ invitationEmail: permission.invitation?.email ?? null,+ inherited: permission.inheritedFrom !== undefined,+ inheritedFromId: permission.inheritedFrom?.id ?? null,+ inheritedFromPath: permission.inheritedFrom?.path ?? null,+ hasPassword: permission.hasPassword ?? null,+ expirationDateTime: permission.expirationDateTime ?? null,+ shareId: permission.shareId ?? null,+ };+}++type GraphPermissionUser = { displayName?: string; email?: string; id?: string };++type GraphPermission = {+ id: string;+ roles?: string[];+ link?: { type?: string; scope?: string; webUrl?: string; preventsDownload?: boolean };+ grantedTo?: { user?: GraphPermissionUser };+ grantedToV2?: { user?: GraphPermissionUser };+ grantedToIdentities?: { user?: GraphPermissionUser }[];+ grantedToIdentitiesV2?: { user?: GraphPermissionUser }[];+ invitation?: { email?: string };+ inheritedFrom?: { id?: string; path?: string; driveId?: string };+ hasPassword?: boolean;+ expirationDateTime?: string;+ shareId?: string;+};++type OneDrivePermission = {+ id: string;+ roles: string[];+ linkType: string | null;+ linkScope: string | null;+ linkWebUrl: string | null;+ linkPreventsDownload: boolean | null;+ grantedToName: string | null;+ grantedToEmail: string | null;+ grantedToId: string | null;+ grantedToIdentities: string;+ invitationEmail: string | null;+ inherited: boolean;+ inheritedFromId: string | null;+ inheritedFromPath: string | null;+ hasPassword: boolean | null;+ expirationDateTime: string | null;+ shareId: string | null;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-update-item.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-update-item.tsnew file mode 100644index 00000000000..ad9a1f4f2e6--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-update-item.ts@@ -0,0 +1,65 @@+import { createAction, Property } from '@activepieces/pieces-framework';+import { HttpMethod } from '@activepieces/pieces-common';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveItemOutputSchema } from '../output-schemas';++export const onedriveUpdateItem = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_update_item',+ displayName: 'Rename / Update File or Folder',+ description: 'Rename a OneDrive file or folder, or set its description.',+ audience: 'ai',+ outputSchema: onedriveItemOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Renames a file or folder and/or sets its description, changing only the fields you provide; the item keeps its ID. Use Move File or Folder to change its folder. Description is supported on personal OneDrive only, and renaming fails if the folder already has an item with the new name. Retrying by item ID is safe; after a rename by path, use the returned item ID, because the old path no longer exists.',+ idempotent: true,+ },+ props: {+ itemId: Property.ShortText({+ displayName: 'Item ID',+ description: 'File or folder ID from Search or List Folder Contents. Or use Path.',+ required: false,+ }),+ path: Property.ShortText({+ displayName: 'Path',+ description: 'Path from the drive root. Use this or Item ID.',+ placeholder: 'Documents/report.docx',+ required: false,+ }),+ name: Property.ShortText({+ displayName: 'New Name',+ description: 'New name, with the extension for files. Empty keeps the name.',+ required: false,+ }),+ description: Property.LongText({+ displayName: 'Description',+ description: 'New description (personal OneDrive only). Empty keeps it.',+ required: false,+ }),+ },+ async run(context) {+ const { itemId, path, name, description } = context.propsValue;+ const itemPath = oneDriveApi.itemPath({ itemId, path });+ const body: Record<string, string> = {};+ const trimmedName = name?.trim();+ if (trimmedName) {+ body['name'] = trimmedName;+ }+ if (description !== undefined && description !== null && description !== '') {+ body['description'] = description;+ }+ if (Object.keys(body).length === 0) {+ throw new Error('Provide a New Name or a Description to update.');+ }+ const item = await oneDriveApi.request<GraphDriveItem>({+ auth: context.auth,+ method: HttpMethod.PATCH,+ path: itemPath,+ body,+ });+ return oneDriveApi.toItem(item);+ },+});diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-upload-file.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-upload-file.tsnew file mode 100644index 00000000000..20fece492d7--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/onedrive-upload-file.ts@@ -0,0 +1,134 @@+import { Readable } from 'node:stream';+import { buffer as readableToBuffer } from 'node:stream/consumers';+import { createAction, OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';+import { httpClient, HttpMethod, streamUtils } from '@activepieces/pieces-common';+import mime from 'mime-types';+import { oneDriveAuth } from '../auth';+import { GraphDriveItem, oneDriveApi } from '../common/graph-api';+import { onedriveItemOutputSchema } from '../output-schemas';++export const onedriveUploadFile = createAction({+ auth: oneDriveAuth,+ name: 'onedrive_upload_file',+ displayName: 'Upload File',+ description: 'Upload a file to a OneDrive folder, replacing any file with the same name.',+ audience: 'ai',+ outputSchema: onedriveItemOutputSchema,+ classification: 'WRITE',+ aiMetadata: {+ description:+ 'Uploads a file (URL or base64) into a OneDrive folder under the given name; files over 4 MiB are sent in chunks automatically. Use Create Text File to write plain text without a file object, and Replace File Content to overwrite a known item by ID. The destination folder must already exist (create it with Create Folder); uploading the same name to the same folder overwrites the existing file, so retries are safe.',+ idempotent: true,+ },+ props: {+ folderId: Property.ShortText({+ displayName: 'Folder ID',+ description: 'Destination folder ID. Leave empty for the drive root.',+ required: false,+ }),+ fileName: Property.ShortText({+ displayName: 'File Name',+ description: 'File name including its extension.',+ placeholder: 'report.pdf',+ required: true,+ }),+ file: Property.File({+ displayName: 'File',+ description: 'The file URL or base64 content to upload.',+ required: true,+ streaming: true,+ }),+ },+ async run(context) {+ const { folderId, fileName, file } = context.propsValue;+ const name = fileName.trim();+ if (!name) {+ throw new Error('File Name cannot be empty.');+ }+ const mimeType = mime.lookup(file.extension ?? '') || 'application/octet-stream';+ let { body, size } = streamUtils.toStreamingBody(file);+ if (size == null) {+ const buffered = await readableToBuffer(body);+ size = buffered.length;+ body = Readable.from(buffered);+ }+ const targetPath = `${oneDriveApi.folderPath({ folderId })}:/${encodeURIComponent(name)}:`;+ const item = await uploadContent({+ auth: context.auth,+ targetPath,+ name,+ body,+ size,+ mimeType,+ });+ return oneDriveApi.toItem(item);+ },+});++async function uploadContent({+ auth,+ targetPath,+ name,+ body,+ size,+ mimeType,+}: {+ auth: OAuth2PropertyValue;+ targetPath: string;+ name: string;+ body: Readable;+ size: number;+ mimeType: string;+}): Promise<GraphDriveItem> {+ if (size <= SIMPLE_UPLOAD_LIMIT) {+ return oneDriveApi.request<GraphDriveItem>({+ auth,+ method: HttpMethod.PUT,+ path: `${targetPath}/content`,+ body,+ headers: {+ 'Content-Type': mimeType,+ 'Content-Length': size.toString(),+ },+ });+ }+ const session = await oneDriveApi.request<{ uploadUrl: string }>({+ auth,+ method: HttpMethod.POST,+ path: `${targetPath}/createUploadSession`,+ body: {+ item: {+ '@microsoft.graph.conflictBehavior': 'replace',+ name,+ },+ },+ headers: { 'Content-Type': 'application/json' },+ });+ let start = 0;+ let result: GraphDriveItem | undefined;+ for await (const chunk of streamUtils.readChunks({ readable: body, chunkSize: CHUNK_SIZE })) {+ const end = start + chunk.length - 1;+ try {+ const response = await httpClient.sendRequest<GraphDriveItem>({+ method: HttpMethod.PUT,+ url: session.uploadUrl,+ body: chunk,+ headers: {+ 'Content-Length': chunk.length.toString(),+ 'Content-Range': `bytes ${start}-${end}/${size}`,+ },+ });+ result = response.body;+ } catch (error) {+ throw new Error(oneDriveApi.describeError(error));+ }+ start += chunk.length;+ }+ if (!result?.id) {+ throw new Error('The upload session finished without returning the uploaded file.');+ }+ return result;+}++const SIMPLE_UPLOAD_LIMIT = 4 * 1024 * 1024;+const CHUNK_SIZE = 10485760;diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/actions/upload-file.ts b/packages/pieces/community/microsoft-onedrive/src/lib/actions/upload-file.tsindex 7b5b4e3d125..be0acf5f7fb 100644--- a/packages/pieces/community/microsoft-onedrive/src/lib/actions/upload-file.ts+++ b/packages/pieces/community/microsoft-onedrive/src/lib/actions/upload-file.ts@@ -10,17 +10,18 @@ import {import { oneDriveAuth } from '../auth';import mime from 'mime-types';import { oneDriveCommon } from '../common/common';--const CHUNK_SIZE = 10485760; // Use 10MiB per chunk (a multiple of 320KiB, as OneDrive requires)+import { getCloudProp } from '../common/microsoft-cloud';+import { uploadFileOutputSchema } from '../output-schemas';export const uploadFile = createAction({auth: oneDriveAuth,name: 'upload_onedrive_file',classification: 'WRITE',description: 'Upload a file to your Microsoft OneDrive with chunked upload if the file is larger than 4MiB',- audience: 'both',+ audience: 'human',aiMetadata: { description: 'Upload a file to a Microsoft OneDrive folder, given a target file name, the file content, and an optional parent folder (defaults to the drive root). Large files (over 4MiB) are uploaded in chunks automatically. Idempotent: uploading the same file name to the same folder overwrites the existing item rather than creating a duplicate.', idempotent: true },displayName: 'Upload file',+ outputSchema: uploadFileOutputSchema,props: {fileName: Property.ShortText({displayName: 'File name',@@ -43,15 +44,12 @@ export const uploadFile = createAction({);const mimeType = mimeTypeLookup? mimeTypeLookup- : 'application/octet-stream'; // Fallback to a default MIME type+ : 'application/octet-stream';const encodedFilename = encodeURIComponent(context.propsValue.fileName);const parentId = context.propsValue.parentId ?? 'root';- const cloud = context.auth.props?.['cloud'] as string | undefined;+ const cloud = getCloudProp(context.auth);const baseUrl = oneDriveCommon.getBaseUrl(cloud);- // Chunked upload needs the total size upfront for the Content-Range header.- // When the source doesn't report a size, buffer once and use its length —- // same behaviour as before streaming — then re-wrap so both paths stream.let { body, size: fileSize } = streamUtils.toStreamingBody(fileData);if (fileSize == null) {const buffered = await readableToBuffer(body);@@ -60,7 +58,6 @@ export const uploadFile = createAction({}if (fileSize <= 4 * 1024 * 1024) {- // If file is smaller than 4MiB, use simple uploadconst result = await httpClient.sendRequest({method: HttpMethod.PUT,url: `${baseUrl}/items/${parentId}:/${encodedFilename}:/content`,@@ -77,7 +74,6 @@ export const uploadFile = createAction({return result.body;} else {- // For files larger than 4MiB, use chunked uploadconst session = await httpClient.sendRequest({method: HttpMethod.POST,url: `${baseUrl}/items/${parentId}:/${encodedFilename}:/createUploadSession`,@@ -119,3 +115,5 @@ export const uploadFile = createAction({}},});++const CHUNK_SIZE = 10485760;diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/common/graph-api.ts b/packages/pieces/community/microsoft-onedrive/src/lib/common/graph-api.tsnew file mode 100644index 00000000000..17a7fca2a03--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/common/graph-api.ts@@ -0,0 +1,254 @@+import {+ AuthenticationType,+ HttpError,+ HttpMessageBody,+ HttpMethod,+ QueryParams,+ httpClient,+} from '@activepieces/pieces-common';+import { OAuth2PropertyValue } from '@activepieces/pieces-framework';+import { getGraphBaseUrl } from './microsoft-cloud';++export const oneDriveApi = {+ request,+ itemPath,+ folderPath,+ getRootId,+ resolveFolderId,+ getDriveId,+ toItem,+ describeError,+ statusOf,+};++export class OneDriveApiError extends Error {+ readonly status: number | null;++ constructor({ message, status }: { message: string; status: number | null }) {+ super(message);+ this.name = 'OneDriveApiError';+ this.status = status;+ }+}++async function request<T extends HttpMessageBody>({+ auth,+ method,+ path,+ body,+ queryParams,+ headers,+}: GraphRequest): Promise<T> {+ const url = resolveUrl({ auth, path });+ try {+ const response = await httpClient.sendRequest<T>({+ method,+ url,+ body,+ queryParams,+ headers,+ authentication: {+ type: AuthenticationType.BEARER_TOKEN,+ token: auth.access_token,+ },+ });+ return response.body;+ } catch (error) {+ throw new OneDriveApiError({+ message: describeError(error),+ status: error instanceof HttpError ? error.response.status : null,+ });+ }+}++function resolveUrl({ auth, path }: { auth: OAuth2PropertyValue; path: string }): string {+ const base = graphBaseUrl(auth);+ if (!/^[a-z][a-z0-9+.-]*:/i.test(path)) {+ return `${base}${path}`;+ }+ if (!path.startsWith(`${base}/`)) {+ throw new OneDriveApiError({+ message: 'The page token or link is not a Microsoft Graph URL for this connection. Pass the token returned by the previous call unchanged.',+ status: null,+ });+ }+ return path;+}++function statusOf(error: unknown): number | null {+ return error instanceof OneDriveApiError ? error.status : null;+}++function graphBaseUrl(auth: OAuth2PropertyValue): string {+ const cloud = auth.props?.['cloud'];+ return `${getGraphBaseUrl(typeof cloud === 'string' ? cloud : undefined)}/v1.0`;+}++function itemPath({ itemId, path }: { itemId?: string; path?: string }): string {+ const trimmedId = itemId?.trim();+ if (trimmedId) {+ return trimmedId === 'root' ? '/me/drive/root' : `/me/drive/items/${encodeURIComponent(trimmedId)}`;+ }+ const trimmedPath = path?.trim().replace(/^\/+|\/+$/g, '');+ if (trimmedPath) {+ return `/me/drive/root:/${trimmedPath.split('/').map(encodeURIComponent).join('/')}:`;+ }+ throw new Error('Provide either an item ID or a path.');+}++function folderPath({ folderId }: { folderId?: string }): string {+ return itemPath({ itemId: folderId?.trim() ? folderId : 'root' });+}++async function getRootId({ auth }: { auth: OAuth2PropertyValue }): Promise<string> {+ const root = await request<{ id: string }>({+ auth,+ method: HttpMethod.GET,+ path: '/me/drive/root',+ queryParams: { $select: 'id' },+ });+ return root.id;+}++async function resolveFolderId({ auth, folderId }: { auth: OAuth2PropertyValue; folderId?: string }): Promise<string> {+ const trimmed = folderId?.trim();+ if (!trimmed || trimmed === 'root') {+ return getRootId({ auth });+ }+ return trimmed;+}++async function getDriveId({ auth }: { auth: OAuth2PropertyValue }): Promise<string> {+ const drive = await request<{ id: string }>({+ auth,+ method: HttpMethod.GET,+ path: '/me/drive',+ queryParams: { $select: 'id' },+ });+ return drive.id;+}++function toItem(item: GraphDriveItem): OneDriveItem {+ return {+ id: item.id,+ name: item.name,+ type: item.folder ? 'folder' : item.package ? 'package' : item.remoteItem ? 'remote' : 'file',+ mimeType: item.file?.mimeType ?? null,+ size: item.size ?? null,+ webUrl: item.webUrl ?? null,+ createdDateTime: item.createdDateTime ?? null,+ lastModifiedDateTime: item.lastModifiedDateTime ?? null,+ childCount: item.folder?.childCount ?? null,+ parentId: item.parentReference?.id ?? null,+ parentPath: item.parentReference?.path ?? null,+ driveId: item.parentReference?.driveId ?? null,+ driveType: item.parentReference?.driveType ?? null,+ createdByName: item.createdBy?.user?.displayName ?? null,+ createdByEmail: item.createdBy?.user?.email ?? null,+ lastModifiedByName: item.lastModifiedBy?.user?.displayName ?? null,+ lastModifiedByEmail: item.lastModifiedBy?.user?.email ?? null,+ description: item.description ?? null,+ deleted: item.deleted !== undefined,+ remoteItemId: item.remoteItem?.id ?? null,+ remoteDriveId: item.remoteItem?.parentReference?.driveId ?? null,+ };+}++function describeError(error: unknown): string {+ if (!(error instanceof HttpError)) {+ return error instanceof Error ? error.message : String(error);+ }+ const status = error.response.status;+ const graphError = readGraphError(error.response.body);+ const detail = graphError ? ` (${graphError})` : '';+ switch (status) {+ case 400:+ return `OneDrive rejected the request${detail}.`;+ case 401:+ return `The OneDrive connection is no longer valid. Reconnect the account${detail}.`;+ case 403:+ return `Access denied. The connection lacks permission for this item or operation, or the account type does not support it${detail}.`;+ case 404:+ return `The item was not found. Check the ID or path${detail}.`;+ case 409:+ return `An item with that name already exists, or the item is in a conflicting state${detail}.`;+ case 410:+ return `The token or resource has expired and must be requested again${detail}.`;+ case 423:+ return `The item is locked, for example checked out by another user${detail}.`;+ case 429:+ return `OneDrive rate limit reached. Retry later${detail}.`;+ default:+ return `OneDrive request failed with status ${status}${detail}.`;+ }+}++function readGraphError(body: unknown): string | null {+ if (typeof body !== 'object' || body === null || !('error' in body)) {+ return null;+ }+ const inner = body.error;+ if (typeof inner !== 'object' || inner === null) {+ return null;+ }+ const code = 'code' in inner && typeof inner.code === 'string' ? inner.code : null;+ const message = 'message' in inner && typeof inner.message === 'string' ? inner.message : null;+ return [code, message].filter(Boolean).join(': ') || null;+}++export type GraphRequest = {+ auth: OAuth2PropertyValue;+ method: HttpMethod;+ path: string;+ body?: unknown;+ queryParams?: QueryParams;+ headers?: Record<string, string>;+};++export type GraphIdentity = {+ user?: { displayName?: string; email?: string; id?: string };+ application?: { displayName?: string; id?: string };+};++export type GraphDriveItem = {+ id: string;+ name: string;+ size?: number;+ webUrl?: string;+ description?: string;+ createdDateTime?: string;+ lastModifiedDateTime?: string;+ createdBy?: GraphIdentity;+ lastModifiedBy?: GraphIdentity;+ parentReference?: { id?: string; path?: string; driveId?: string; driveType?: string; name?: string };+ file?: { mimeType?: string };+ folder?: { childCount?: number };+ package?: { type?: string };+ deleted?: { state?: string };+ remoteItem?: { id?: string; parentReference?: { driveId?: string } };+ '@microsoft.graph.downloadUrl'?: string;+};++export type OneDriveItem = {+ id: string;+ name: string;+ type: 'file' | 'folder' | 'package' | 'remote';+ mimeType: string | null;+ size: number | null;+ webUrl: string | null;+ createdDateTime: string | null;+ lastModifiedDateTime: string | null;+ childCount: number | null;+ parentId: string | null;+ parentPath: string | null;+ driveId: string | null;+ driveType: string | null;+ createdByName: string | null;+ createdByEmail: string | null;+ lastModifiedByName: string | null;+ lastModifiedByEmail: string | null;+ description: string | null;+ deleted: boolean;+ remoteItemId: string | null;+ remoteDriveId: string | null;+};diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/common/microsoft-cloud.ts b/packages/pieces/community/microsoft-onedrive/src/lib/common/microsoft-cloud.tsindex 065a7056060..8d4800e93ae 100644--- a/packages/pieces/community/microsoft-onedrive/src/lib/common/microsoft-cloud.ts+++ b/packages/pieces/community/microsoft-onedrive/src/lib/common/microsoft-cloud.ts@@ -27,7 +27,12 @@ function resolveCloudHost(cloudLoginHost: string | undefined | null): string {}export function getMicrosoftCloudFromAuth(auth: OAuth2PropertyValue): string {- return resolveCloudHost(auth.props?.['cloud'] as string | undefined);+ return resolveCloudHost(getCloudProp(auth));+}++export function getCloudProp(auth: { props?: Record<string, unknown> } | undefined): string | undefined {+ const cloud = auth?.props?.['cloud'];+ return typeof cloud === 'string' ? cloud : undefined;}export function getGraphBaseUrl(cloudLoginHost: string | undefined | null): string {diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/output-schemas.ts b/packages/pieces/community/microsoft-onedrive/src/lib/output-schemas.tsnew file mode 100644index 00000000000..0289f2d4825--- /dev/null+++ b/packages/pieces/community/microsoft-onedrive/src/lib/output-schemas.ts@@ -0,0 +1,365 @@+import { OutputSchema } from '@activepieces/pieces-framework';++export const uploadFileOutputSchema: OutputSchema = {+ fields: driveFileFields(),+};++export const getFileOutputSchema: OutputSchema = {+ fields: [+ { key: 'id', label: 'File ID' },+ { key: 'name', label: 'Name' },+ { key: 'data', label: 'File', format: 'url' },+ { key: 'mimeType', label: 'MIME Type' },+ { key: 'size', label: 'Size', format: 'filesize' },+ { key: 'webUrl', label: 'Web URL', format: 'url' },+ { key: 'createdDateTime', label: 'Created At', format: 'datetime' },+ { key: 'lastModifiedDateTime', label: 'Last Modified At', format: 'datetime' },+ { key: 'folderPath', label: 'Folder Path' },+ { key: 'driveId', label: 'Drive ID' },+ ],+};++export const copyFileOutputSchema: OutputSchema = {+ fields: [+ { key: 'status', label: 'Status' },+ { key: 'file', label: 'Copied File', children: driveFileFields() },+ ],+};++export const listFilesOutputSchema: OutputSchema = {+ itemLabel: '{name}',+ fields: [{ key: 'files', label: 'Files', value: '', listItems: driveFileFields() }],+};++export const listFoldersOutputSchema: OutputSchema = {+ itemLabel: '{name}',+ fields: [{ key: 'folders', label: 'Folders', value: '', listItems: driveFolderFields() }],+};++export const newFileTriggerOutputSchema: OutputSchema = {+ fields: driveFileFields(),+};++export const onedriveItemOutputSchema: OutputSchema = {+ fields: itemFields(),+};++export const onedriveCreateFolderOutputSchema: OutputSchema = {+ fields: [{ key: 'created', label: 'Created', format: 'boolean' }, ...itemFields()],+};++export const onedriveDownloadFileOutputSchema: OutputSchema = {+ fields: [{ key: 'data', label: 'File', format: 'url' }, ...itemFields()],+};++export const onedriveDownloadFileAsFormatOutputSchema: OutputSchema = {+ fields: [+ { key: 'data', label: 'Converted File', format: 'url' },+ { key: 'convertedFormat', label: 'Converted Format' },+ { key: 'convertedFileName', label: 'Converted File Name' },+ ...itemFields(),+ ],+};++export const onedriveDownloadItemVersionOutputSchema: OutputSchema = {+ fields: [+ { key: 'data', label: 'File', format: 'url' },+ { key: 'itemId', label: 'Item ID' },+ { key: 'name', label: 'Name' },+ { key: 'versionId', label: 'Version ID' },+ { key: 'mimeType', label: 'MIME Type' },+ ],+};++export const onedriveResolveSharingLinkOutputSchema: OutputSchema = {+ fields: [{ key: 'shareId', label: 'Share ID' }, ...itemFields()],+};++export const onedriveBundleOutputSchema: OutputSchema = {+ fields: bundleFields(),+};++export const onedriveListItemsOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Items', labelKey: 'name', listItems: itemFields() },+ ...pageFields(),+ ],+};++export const onedriveListDriveChangesOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Changed Items', labelKey: 'name', listItems: itemFields() },+ ...pageFields(),+ { key: 'deltaToken', label: 'Delta Token' },+ ],+};++export const onedriveListBundlesOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Bundles', labelKey: 'name', listItems: bundleFields() },+ ...pageFields(),+ ],+};++export const onedriveGetDriveOutputSchema: OutputSchema = {+ fields: [+ ...driveFields(),+ { key: 'createdDateTime', label: 'Created At', format: 'datetime' },+ { key: 'lastModifiedDateTime', label: 'Last Modified At', format: 'datetime' },+ { key: 'quotaDeleted', label: 'Recycle Bin Size', format: 'filesize' },+ ],+};++export const onedriveListDrivesOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Drives', labelKey: 'name', listItems: driveFields() },+ ...pageFields(),+ ],+};++export const onedriveListItemThumbnailsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'items',+ label: 'Thumbnail Sets',+ labelKey: 'thumbnailSetId',+ listItems: [+ { key: 'thumbnailSetId', label: 'Thumbnail Set ID' },+ { key: 'smallUrl', label: 'Small', format: 'image' },+ { key: 'smallWidth', label: 'Small Width', format: 'number' },+ { key: 'smallHeight', label: 'Small Height', format: 'number' },+ { key: 'mediumUrl', label: 'Medium', format: 'image' },+ { key: 'mediumWidth', label: 'Medium Width', format: 'number' },+ { key: 'mediumHeight', label: 'Medium Height', format: 'number' },+ { key: 'largeUrl', label: 'Large', format: 'image' },+ { key: 'largeWidth', label: 'Large Width', format: 'number' },+ { key: 'largeHeight', label: 'Large Height', format: 'number' },+ ],+ },+ { key: 'count', label: 'Count', format: 'number' },+ ],+};++export const onedriveListItemVersionsOutputSchema: OutputSchema = {+ fields: [+ {+ key: 'items',+ label: 'Versions',+ labelKey: 'versionId',+ listItems: [+ { key: 'versionId', label: 'Version ID' },+ { key: 'lastModifiedDateTime', label: 'Last Modified At', format: 'datetime' },+ { key: 'size', label: 'Size', format: 'filesize' },+ { key: 'lastModifiedByName', label: 'Last Modified By' },+ { key: 'lastModifiedByEmail', label: 'Last Modified By Email', format: 'email' },+ ],+ },+ ...pageFields(),+ ],+};++export const onedrivePermissionOutputSchema: OutputSchema = {+ fields: permissionFields(),+};++export const onedriveListItemPermissionsOutputSchema: OutputSchema = {+ fields: [+ { key: 'items', label: 'Permissions', labelKey: 'id', listItems: permissionFields() },+ ...pageFields(),+ ],+};++export const onedriveInviteToItemOutputSchema: OutputSchema = {+ fields: [+ { key: 'permissions', label: 'Permissions', labelKey: 'grantedToEmail', listItems: permissionFields() },+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'invitationSent', label: 'Invitation Sent', format: 'boolean' },+ ],+};++export const onedriveCopyItemOutputSchema: OutputSchema = {+ fields: [+ { key: 'status', label: 'Status' },+ { key: 'monitorUrl', label: 'Monitor URL', format: 'url' },+ ],+};++export const onedriveGetCopyStatusOutputSchema: OutputSchema = {+ fields: [+ { key: 'status', label: 'Status' },+ { key: 'percentageComplete', label: 'Percentage Complete', format: 'number' },+ { key: 'resourceId', label: 'Copied Item ID' },+ { key: 'errorCode', label: 'Error Code' },+ { key: 'errorMessage', label: 'Error Message' },+ ],+};++export const onedriveItemActionOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'itemId', label: 'Item ID' },+ { key: 'path', label: 'Path' },+ ],+};++export const onedriveDeletePermissionOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'itemId', label: 'Item ID' },+ { key: 'permissionId', label: 'Permission ID' },+ ],+};++export const onedriveRestoreItemVersionOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'itemId', label: 'Item ID' },+ { key: 'versionId', label: 'Restored Version ID' },+ ],+};++export const onedriveBundleMembershipOutputSchema: OutputSchema = {+ fields: [+ { key: 'success', label: 'Success', format: 'boolean' },+ { key: 'bundleId', label: 'Bundle ID' },+ { key: 'itemId', label: 'Item ID' },+ ],+};++function identityFields(): OutputSchema['fields'] {+ return [+ {+ key: 'user',+ label: 'User',+ children: [+ { key: 'displayName', label: 'Name' },+ { key: 'email', label: 'Email', format: 'email' },+ { key: 'id', label: 'User ID' },+ ],+ },+ ];+}++function parentReferenceFields(): OutputSchema['fields'] {+ return [+ { key: 'id', label: 'Folder ID' },+ { key: 'name', label: 'Folder Name' },+ { key: 'path', label: 'Folder Path' },+ { key: 'driveId', label: 'Drive ID' },+ { key: 'driveType', label: 'Drive Type' },+ ];+}++function driveItemBaseFields(): OutputSchema['fields'] {+ return [+ { key: 'id', label: 'Item ID' },+ { key: 'name', label: 'Name' },+ { key: 'webUrl', label: 'Web URL', format: 'url' },+ { key: 'size', label: 'Size', format: 'filesize' },+ { key: 'createdDateTime', label: 'Created At', format: 'datetime' },+ { key: 'lastModifiedDateTime', label: 'Last Modified At', format: 'datetime' },+ { key: 'createdBy', label: 'Created By', children: identityFields() },+ { key: 'lastModifiedBy', label: 'Last Modified By', children: identityFields() },+ { key: 'parentReference', label: 'Parent Folder', children: parentReferenceFields() },+ ];+}++function driveFileFields(): OutputSchema['fields'] {+ return [+ ...driveItemBaseFields(),+ {+ key: 'file',+ label: 'File',+ children: [{ key: 'mimeType', label: 'MIME Type' }],+ },+ ];+}++function driveFolderFields(): OutputSchema['fields'] {+ return [+ ...driveItemBaseFields(),+ {+ key: 'folder',+ label: 'Folder',+ children: [{ key: 'childCount', label: 'Child Count', format: 'number' }],+ },+ ];+}++function itemFields(): OutputSchema['fields'] {+ return [+ { key: 'id', label: 'Item ID' },+ { key: 'name', label: 'Name' },+ { key: 'type', label: 'Type' },+ { key: 'webUrl', label: 'Web URL', format: 'url' },+ { key: 'mimeType', label: 'MIME Type' },+ { key: 'size', label: 'Size', format: 'filesize' },+ { key: 'childCount', label: 'Child Count', format: 'number' },+ { key: 'createdDateTime', label: 'Created At', format: 'datetime' },+ { key: 'lastModifiedDateTime', label: 'Last Modified At', format: 'datetime' },+ { key: 'parentId', label: 'Parent Folder ID' },+ { key: 'parentPath', label: 'Parent Folder Path' },+ { key: 'driveId', label: 'Drive ID' },+ { key: 'driveType', label: 'Drive Type' },+ { key: 'createdByName', label: 'Created By' },+ { key: 'createdByEmail', label: 'Created By Email', format: 'email' },+ { key: 'lastModifiedByName', label: 'Last Modified By' },+ { key: 'lastModifiedByEmail', label: 'Last Modified By Email', format: 'email' },+ { key: 'description', label: 'Description' },+ { key: 'deleted', label: 'Deleted', format: 'boolean' },+ { key: 'remoteItemId', label: 'Remote Item ID' },+ { key: 'remoteDriveId', label: 'Remote Drive ID' },+ ];+}++function bundleFields(): OutputSchema['fields'] {+ return [+ ...itemFields(),+ { key: 'bundleChildCount', label: 'Items in Bundle', format: 'number' },+ { key: 'isAlbum', label: 'Is Album', format: 'boolean' },+ ];+}++function pageFields(): OutputSchema['fields'] {+ return [+ { key: 'count', label: 'Count', format: 'number' },+ { key: 'nextPageToken', label: 'Next Page Token' },+ ];+}++function driveFields(): OutputSchema['fields'] {+ return [+ { key: 'id', label: 'Drive ID' },+ { key: 'name', label: 'Name' },+ { key: 'driveType', label: 'Drive Type' },+ { key: 'webUrl', label: 'Web URL', format: 'url' },+ { key: 'ownerName', label: 'Owner' },+ { key: 'ownerEmail', label: 'Owner Email', format: 'email' },+ { key: 'quotaTotal', label: 'Total Storage', format: 'filesize' },+ { key: 'quotaUsed', label: 'Used Storage', format: 'filesize' },+ { key: 'quotaRemaining', label: 'Remaining Storage', format: 'filesize' },+ { key: 'quotaState', label: 'Storage State' },+ ];+}++function permissionFields(): OutputSchema['fields'] {+ return [+ { key: 'id', label: 'Permission ID' },+ { key: 'roles', label: 'Roles' },+ { key: 'linkType', label: 'Link Type' },+ { key: 'linkScope', label: 'Link Scope' },+ { key: 'linkWebUrl', label: 'Link URL', format: 'url' },+ { key: 'linkPreventsDownload', label: 'Link Prevents Download', format: 'boolean' },+ { key: 'grantedToName', label: 'Granted To' },+ { key: 'grantedToEmail', label: 'Granted To Email', format: 'email' },+ { key: 'grantedToId', label: 'Granted To ID' },+ { key: 'grantedToIdentities', label: 'Granted To (Link Users)' },+ { key: 'invitationEmail', label: 'Invitation Email', format: 'email' },+ { key: 'inherited', label: 'Inherited', format: 'boolean' },+ { key: 'inheritedFromId', label: 'Inherited From Folder ID' },+ { key: 'inheritedFromPath', label: 'Inherited From Path' },+ { key: 'hasPassword', label: 'Has Password', format: 'boolean' },+ { key: 'expirationDateTime', label: 'Expires At', format: 'datetime' },+ { key: 'shareId', label: 'Share ID' },+ ];+}diff --git a/packages/pieces/community/microsoft-onedrive/src/lib/triggers/new-file.ts b/packages/pieces/community/microsoft-onedrive/src/lib/triggers/new-file.tsindex f8f2e258f05..eda46396c10 100644--- a/packages/pieces/community/microsoft-onedrive/src/lib/triggers/new-file.ts+++ b/packages/pieces/community/microsoft-onedrive/src/lib/triggers/new-file.ts@@ -1,66 +1,20 @@-import { AppConnectionValueForAuthProperty, PiecePropValueSchema, Property, createTrigger } from '@activepieces/pieces-framework';+import { AppConnectionValueForAuthProperty, createTrigger } from '@activepieces/pieces-framework';import { TriggerStrategy } from '@activepieces/pieces-framework';import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';-import { getGraphBaseUrl } from '../common/microsoft-cloud';+import { getCloudProp, getGraphBaseUrl } from '../common/microsoft-cloud';import dayjs from 'dayjs';import { oneDriveAuth } from '../auth';import { oneDriveCommon } from '../common/common';+import { newFileTriggerOutputSchema } from '../output-schemas';import { Client, PageCollection } from '@microsoft/microsoft-graph-client';import { DriveItem } from '@microsoft/microsoft-graph-types';-type Props = {- parentFolder?: string;-};--const polling: Polling<AppConnectionValueForAuthProperty<typeof oneDriveAuth>, Props> = {- strategy: DedupeStrategy.TIMEBASED,- items: async ({ auth, propsValue, lastFetchEpochMS }) => {- const cloud = auth.props?.['cloud'] as string | undefined;- const client = Client.initWithMiddleware({- authProvider: {- getAccessToken: () => Promise.resolve(auth.access_token),- },- baseUrl: getGraphBaseUrl(cloud),- });-- const files = [];-- const endpoint = propsValue.parentFolder- ? `/me/drive/items/${propsValue.parentFolder}/children`- : `/me/drive/items/root/children`;- let response: PageCollection = await client.api(endpoint).get();- while (response.value.length > 0) {- for (const item of response.value as DriveItem[]) {- if (item.file) {- files.push(item);- }- }-- if (response['@odata.nextLink']) {- response = await client.api(response['@odata.nextLink']).get();- } else {- break;- }- }-- files.sort((a, b) => {- const aDate = dayjs(a.createdDateTime);- const bDate = dayjs(b.createdDateTime);- return bDate.diff(aDate);- });-- return files.map((file) => ({- epochMilliSeconds: dayjs(file.createdDateTime).valueOf(),- data: file,- }));- },-};-export const newFile = createTrigger({auth: oneDriveAuth,name: 'new_file',classification: 'READ',displayName: 'New File',+ outputSchema: newFileTriggerOutputSchema,description: 'Trigger when a new file is uploaded.',aiMetadata: {description: 'Fires when a new file appears in the watched Microsoft OneDrive folder, polling by file creation time. Scope it to a specific folder via the parent folder ID, or leave it empty to watch the drive root; subfolders are not included and folders themselves do not trigger it.',@@ -71,18 +25,10 @@ export const newFile = createTrigger({},type: TriggerStrategy.POLLING,async onEnable(context) {- await pollingHelper.onEnable(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- });+ await pollingHelper.onEnable(polling, context);},async onDisable(context) {- await pollingHelper.onDisable(polling, {- auth: context.auth,- store: context.store,- propsValue: context.propsValue,- });+ await pollingHelper.onDisable(polling, context);},async test(context) {return await pollingHelper.test(polling, context);@@ -137,3 +83,52 @@ export const newFile = createTrigger({},},});++const polling: Polling<AppConnectionValueForAuthProperty<typeof oneDriveAuth>, Props> = {+ strategy: DedupeStrategy.TIMEBASED,+ items: async ({ auth, propsValue }) => {+ const cloud = getCloudProp(auth);+ const client = Client.initWithMiddleware({+ authProvider: {+ getAccessToken: () => Promise.resolve(auth.access_token),+ },+ baseUrl: getGraphBaseUrl(cloud),+ });++ const files = [];++ const endpoint = propsValue.parentFolder+ ? `/me/drive/items/${propsValue.parentFolder}/children`+ : `/me/drive/items/root/children`;+ let response: PageCollection = await client.api(endpoint).get();+ while (response.value.length > 0) {+ const items: DriveItem[] = response.value;+ for (const item of items) {+ if (item.file) {+ files.push(item);+ }+ }++ if (response['@odata.nextLink']) {+ response = await client.api(response['@odata.nextLink']).get();+ } else {+ break;+ }+ }++ files.sort((a, b) => {+ const aDate = dayjs(a.createdDateTime);+ const bDate = dayjs(b.createdDateTime);+ return bDate.diff(aDate);+ });++ return files.map((file) => ({+ epochMilliSeconds: dayjs(file.createdDateTime).valueOf(),+ data: file,+ }));+ },+};++type Props = {+ parentFolder?: string;+};