Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

14.5 KB
Raw Blame
import { IInputs, IOutputs } from "./generated/ManifestTypes";
import {
    AttachmentAdapters,
    AnnotationPayload,
    createBrowserFilePicker,
    createDataverseNoteClient,
    SelectedAttachmentFile,
} from "./adapters";
import "./css/{{name}}.css";

const DEFAULT_MAX_KB = 1024;
const MIN_MAX_KB = 1;
const MAX_DIRECT_CREATE_KB = 3072;
const ODATA_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
const STRINGS = {
    label: "AttachmentUploader_Label",
    button: "AttachmentUploader_Button",
    unsaved: "AttachmentUploader_Unsaved",
    permissionDenied: "AttachmentUploader_PermissionDenied",
    configMissing: "AttachmentUploader_ConfigMissing",
    invalidODataName: "AttachmentUploader_InvalidODataName",
    fileTooLarge: "AttachmentUploader_FileTooLarge",
    typeNotAllowed: "AttachmentUploader_TypeNotAllowed",
    uploading: "AttachmentUploader_Uploading",
    success: "AttachmentUploader_Success",
    error: "AttachmentUploader_Error",
    serverSizeLimit: "AttachmentUploader_ServerSizeLimit",
} as const;

type ResourceContext = ComponentFramework.Context<IInputs> & {
    resources?: {
        getString: (key: string) => string;
    };
};

type RenderState = "ready" | "blocked" | "uploading" | "success" | "error";

interface Configuration {
    recordId: string | null;
    entityName: string;
    entitySetName: string;
    navigationProperty: string;
    maxBytes: number;
    maxKb: number;
    acceptedMimeTypes: string[];
}

interface OperationToken {
    operationId: number;
    signature: string;
}

export class {{name}} implements ComponentFramework.StandardControl<IInputs, IOutputs> {
    private container: HTMLDivElement | null = null;
    private root: HTMLDivElement | null = null;
    private context: ComponentFramework.Context<IInputs> | null = null;
    private readonly adapters: Partial<AttachmentAdapters>;
    private value: string | null = null;
    private readable = true;
    private editable = true;
    private disabled = false;
    private uploading = false;
    private operationId = 0;
    private destroyed = false;
    private activeOperationSignature: string | null = null;
    private state: RenderState = "ready";
    private messageKey: string | null = null;
    private messageValue: string | null = null;

    public constructor(adapters: Partial<AttachmentAdapters> = {}) {
        this.adapters = adapters;
    }

    public init(
        context: ComponentFramework.Context<IInputs>,
        _notifyOutputChanged: () => void,
        _state: ComponentFramework.Dictionary,
        container: HTMLDivElement,
    ): void {
        this.container = container;
        this.context = context;
        this.destroyed = false;

        this.root = container.ownerDocument.createElement("div");
        this.root.className = "{{cssClass}}";
        container.append(this.root);
        this.updateView(context);
    }

    public updateView(context: ComponentFramework.Context<IInputs>): void {
        this.context = context;
        const valueParameter = context.parameters.value;
        this.value = typeof valueParameter?.raw === "string" ? valueParameter.raw : null;
        this.readable = valueParameter?.security?.readable ?? true;
        this.editable = valueParameter?.security?.editable ?? true;
        this.disabled = context.mode.isControlDisabled;
        const config = this.readConfiguration();
        if (this.uploading && this.activeOperationSignature !== this.operationSignature(config)) this.cancelActiveOperation();
        if (!this.uploading) {
            const nextState = this.evaluateState(config);
            this.state = nextState.state;
            this.messageKey = nextState.messageKey;
            this.messageValue = null;
        }
        this.render();
    }

    public getOutputs(): IOutputs {
        return {
            value: this.value ?? undefined,
        };
    }

    public destroy(): void {
        this.operationId += 1;
        this.uploading = false;
        this.activeOperationSignature = null;
        this.destroyed = true;
        this.container?.replaceChildren();
        this.root = null;
        this.container = null;
        this.context = null;
    }

    private render(): void {
        if (!this.root || !this.context) return;
        this.root.replaceChildren();

        const label = this.root.ownerDocument.createElement("div");
        label.className = "{{cssInputClass}}-label";
        label.textContent = this.getString(STRINGS.label);

        const button = this.root.ownerDocument.createElement("button");
        button.className = "{{cssInputClass}}-button";
        button.type = "button";
        button.textContent = this.getString(STRINGS.button);
        button.setAttribute("aria-label", `${this.getString(STRINGS.label)}: ${this.getString(STRINGS.button)}`);
        button.disabled = !this.canUpload();
        button.setAttribute("aria-busy", this.uploading ? "true" : "false");
        button.addEventListener("click", () => {
            void this.uploadSelectedFile();
        });

        const status = this.root.ownerDocument.createElement("div");
        status.className = this.state === "error" ? "{{cssMessageClass}} {{cssMessageClass}}-error" : "{{cssMessageClass}}";
        status.setAttribute("role", this.state === "error" ? "alert" : "status");
        status.setAttribute("aria-live", "polite");
        status.textContent = this.messageValue ?? (this.messageKey ? this.getString(this.messageKey) : "");

        this.root.append(label, button, status);
    }

    private async uploadSelectedFile(): Promise<void> {
        if (this.uploading || !this.context) return;
        const config = this.readConfiguration();
        const state = this.evaluateState(config);
        if (state.state !== "ready") {
            this.state = state.state;
            this.messageKey = state.messageKey;
            this.messageValue = null;
            this.render();
            return;
        }

        this.uploading = true;
        const token = this.beginOperation(config);
        this.state = "uploading";
        this.messageKey = STRINGS.uploading;
        this.messageValue = null;
        this.render();

        try {
            const file = await this.pickFile(config.acceptedMimeTypes.join(","));
            if (!this.isOperationCurrent(token)) return;
            if (!file) {
                this.finishOperation(token, "ready", null, null);
                return;
            }
            const validation = this.validateFile(file, config);
            if (validation) {
                this.finishOperation(token, "error", null, validation);
                return;
            }

            if (this.evaluateState(this.readConfiguration()).state !== "ready") {
                this.cancelActiveOperation();
                this.render();
                return;
            }
            if (!this.isOperationCurrent(token)) return;
            await this.createAnnotation(this.toAnnotationPayload(file, config));
            if (!this.isOperationCurrent(token)) return;
            this.finishOperation(token, "success", STRINGS.success, null);
        } catch (error) {
            if (!this.isOperationCurrent(token)) return;
            const message = error instanceof Error ? error.message : String(error);
            this.finishOperation(token, "error", null, this.format(this.isServerSizeLimit(message) ? STRINGS.serverSizeLimit : STRINGS.error, message));
        }
    }

    private canUpload(): boolean {
        return !this.disabled && !this.uploading && this.evaluateState(this.readConfiguration()).state === "ready";
    }

    private evaluateState(config: Configuration): { state: RenderState; messageKey: string | null } {
        if (!this.readable || !this.editable) return { state: "blocked", messageKey: STRINGS.permissionDenied };
        if (!config.recordId) return { state: "blocked", messageKey: STRINGS.unsaved };
        if (!config.entityName || !config.entitySetName || !config.navigationProperty || !this.hasCreateRecord()) {
            return { state: "blocked", messageKey: STRINGS.configMissing };
        }
        if (!this.isWebApiIdentifier(config.entitySetName) || !this.isWebApiIdentifier(config.navigationProperty)) {
            return { state: "blocked", messageKey: STRINGS.invalidODataName };
        }
        return { state: "ready", messageKey: null };
    }

    private readConfiguration(): Configuration {
        const maxKb = this.readWholeNumber("maxFileSizeKb", DEFAULT_MAX_KB, MIN_MAX_KB, MAX_DIRECT_CREATE_KB);
        return {
            recordId: this.normalizeGuid(this.readString("entityId")),
            entityName: this.readString("entityName"),
            entitySetName: this.readString("parentEntitySetName"),
            navigationProperty: this.readString("parentNavigationProperty"),
            maxKb,
            maxBytes: maxKb * 1024,
            acceptedMimeTypes: this.readString("acceptedMimeTypes")
                .split(",")
                .map((item) => item.trim().toLowerCase())
                .filter(Boolean),
        };
    }

    private readString(name: keyof IInputs): string {
        const parameter = this.context?.parameters[name];
        if (parameter?.security?.readable === false) return "";
        const raw = parameter?.raw;
        return typeof raw === "string" ? raw.trim() : "";
    }

    private readWholeNumber(name: keyof IInputs, fallback: number, min: number, max: number): number {
        const parameter = this.context?.parameters[name];
        const raw = parameter?.security?.readable === false ? null : parameter?.raw;
        const numeric = typeof raw === "number" && Number.isFinite(raw) ? Math.trunc(raw) : fallback;
        return Math.min(max, Math.max(min, numeric));
    }

    private isWebApiIdentifier(value: string): boolean {
        return ODATA_IDENTIFIER.test(value);
    }

    private operationSignature(config: Configuration): string {
        return [
            this.readable ? "readable" : "unreadable",
            this.editable ? "editable" : "readonly",
            this.disabled ? "disabled" : "enabled",
            config.recordId ?? "",
            config.entityName,
            config.entitySetName,
            config.navigationProperty,
            String(config.maxBytes),
            config.acceptedMimeTypes.join(","),
        ].join("|");
    }

    private beginOperation(config: Configuration): OperationToken {
        this.operationId += 1;
        this.activeOperationSignature = this.operationSignature(config);
        return { operationId: this.operationId, signature: this.activeOperationSignature };
    }

    private isOperationCurrent(token: OperationToken): boolean {
        return !this.destroyed
            && this.root != null
            && this.context != null
            && this.operationId === token.operationId
            && this.operationSignature(this.readConfiguration()) === token.signature;
    }

    private cancelActiveOperation(): void {
        this.operationId += 1;
        this.uploading = false;
        this.activeOperationSignature = null;
    }

    private finishOperation(token: OperationToken, state: RenderState, messageKey: string | null, messageValue: string | null): void {
        if (!this.isOperationCurrent(token)) return;
        this.uploading = false;
        this.activeOperationSignature = null;
        this.state = state;
        this.messageKey = messageKey;
        this.messageValue = messageValue;
        this.render();
    }

    private normalizeGuid(raw: string): string | null {
        const trimmed = raw.replace(/[{}]/g, "").toLowerCase();
        return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(trimmed) ? trimmed : null;
    }

    private validateFile(file: SelectedAttachmentFile, config: Configuration): string | null {
        if (file.size > config.maxBytes) return this.format(STRINGS.fileTooLarge, String(config.maxKb));
        const fileType = file.type.toLowerCase();
        if (config.acceptedMimeTypes.length > 0 && !config.acceptedMimeTypes.includes(fileType)) {
            return this.getString(STRINGS.typeNotAllowed);
        }
        return null;
    }

    private toAnnotationPayload(file: SelectedAttachmentFile, config: Configuration): AnnotationPayload {
        // Dataverse creates file notes by POSTing an annotation row with documentbody, filename,
        // mimetype and an @odata.bind relationship. The navigation property is maker-configured
        // because the objectid_* name varies by parent table and must not be guessed.
        // See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/annotation
        // See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/create-entity-web-api#associate-table-rows-on-create
        return {
            filename: file.name,
            mimetype: file.type || "application/octet-stream",
            documentbody: file.contentBase64,
            isdocument: true,
            subject: file.name,
            [`${config.navigationProperty}@odata.bind`]: `/${config.entitySetName}(${config.recordId})`,
        };
    }

    private pickFile(accept: string): Promise<SelectedAttachmentFile | null> {
        if (this.adapters.pickFile) return this.adapters.pickFile(accept);
        if (!this.container) return Promise.resolve(null);
        const config = this.readConfiguration();
        return createBrowserFilePicker(this.container).pickFile(accept, {
            acceptedMimeTypes: config.acceptedMimeTypes,
            maxBytes: config.maxBytes,
            fileTooLargeMessage: this.format(STRINGS.fileTooLarge, String(config.maxKb)),
            typeNotAllowedMessage: this.getString(STRINGS.typeNotAllowed),
        });
    }

    private createAnnotation(payload: AnnotationPayload): Promise<ComponentFramework.LookupValue> {
        if (this.adapters.createAnnotation) return this.adapters.createAnnotation(payload);
        if (!this.context) return Promise.reject(new Error(this.getString(STRINGS.configMissing)));
        return createDataverseNoteClient(this.context.webAPI).createAnnotation(payload);
    }

    private hasCreateRecord(): boolean {
        return Boolean(this.adapters.createAnnotation || typeof this.context?.webAPI?.createRecord === "function");
    }

    private isServerSizeLimit(message: string): boolean {
        return /MaxUploadFileSize|maximum file size|exceed/i.test(message);
    }

    private format(key: string, value: string): string {
        return this.getString(key).replace("{0}", value);
    }

    private getString(key: string): string {
        const context = this.context as ResourceContext | null;
        return context?.resources?.getString(key) || key;
    }
}