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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
import { {{name}} } from "../{{name}}";
import { createBrowserFilePicker } from "../{{name}}/adapters";
import { IInputs } from "../{{name}}/generated/ManifestTypes";
import { mockContext, mockProperty, mockWebApi } from "../test/pcf-context";
type AdapterFile = {
name: string;
type: string;
size: number;
contentBase64: string;
};
type Mounted = {
control: {{name}};
notify: jest.Mock;
container: HTMLDivElement;
context: ComponentFramework.Context<IInputs>;
createRecord: jest.Mock;
pickFile: jest.Mock<Promise<AdapterFile | null>, [string]>;
};
function withStrings(context: ComponentFramework.Context<IInputs>): ComponentFramework.Context<IInputs> {
(context as ComponentFramework.Context<IInputs> & { resources: ComponentFramework.Resources }).resources = {
getResource: (_id: string, success: (data: string) => void) => success(""),
getString: (key: string) => ({
AttachmentUploader_Label: "Upload attachment",
AttachmentUploader_Button: "Choose file",
AttachmentUploader_Unsaved: "Save this record before uploading attachments.",
AttachmentUploader_PermissionDenied: "You do not have permission to use attachments here.",
AttachmentUploader_ConfigMissing: "Attachment uploader is not fully configured.",
AttachmentUploader_InvalidODataName: "Attachment uploader has an invalid Web API name configuration.",
AttachmentUploader_FileTooLarge: "The selected file is larger than {0} KB.",
AttachmentUploader_TypeNotAllowed: "This file type is not allowed.",
AttachmentUploader_Uploading: "Uploading attachment...",
AttachmentUploader_Success: "Attachment uploaded.",
AttachmentUploader_Error: "Attachment upload failed: {0}",
}[key] ?? key),
} as ComponentFramework.Resources;
return context;
}
function parameters(overrides: Partial<IInputs> = {}): Partial<IInputs> {
return {
value: mockProperty<string>(null) as IInputs["value"],
entityId: mockProperty("{00000000-0000-0000-0000-000000000001}") as IInputs["entityId"],
entityName: mockProperty("account") as IInputs["entityName"],
parentEntitySetName: mockProperty("accounts") as IInputs["parentEntitySetName"],
parentNavigationProperty: mockProperty("objectid_account") as IInputs["parentNavigationProperty"],
maxFileSizeKb: mockProperty(1) as IInputs["maxFileSizeKb"],
acceptedMimeTypes: mockProperty("text/plain,application/pdf") as IInputs["acceptedMimeTypes"],
...overrides,
};
}
function mount(overrides: Partial<IInputs> = {}, options: { disabled?: boolean; editable?: boolean; readable?: boolean; createRecord?: jest.Mock; createAnnotation?: jest.Mock; useDefaults?: boolean } = {}): Mounted {
const createRecord = options.createRecord ?? jest.fn().mockResolvedValue({ id: "note-id", entityType: "annotation" });
const contextParameters = options.useDefaults === false ? overrides : parameters({
value: mockProperty<string>(null, undefined, { editable: options.editable, readable: options.readable }) as IInputs["value"],
...overrides,
});
const context = withStrings(mockContext<IInputs>(contextParameters, {
disabled: options.disabled,
webAPI: mockWebApi({ createRecord }),
}));
const pickFile = jest.fn<Promise<AdapterFile | null>, [string]>();
const control = new {{name}}(options.createAnnotation ? { pickFile, createAnnotation: options.createAnnotation } : { pickFile });
const notify = jest.fn();
const container = document.createElement("div");
control.init(context, notify, {}, container);
return { control, notify, container, context, createRecord, pickFile };
}
function button(container: HTMLElement): HTMLButtonElement {
return container.querySelector("button") as HTMLButtonElement;
}
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (reason: unknown) => void } {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
async function flushPromises(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
}
test("missing parameter objects and unsaved parents render a disabled saved-record message", () => {
const missing = mount({}, { useDefaults: false });
expect(button(missing.container).disabled).toBe(true);
expect(missing.container.textContent).toContain("Save this record");
const unsaved = mount({ entityId: mockProperty("") as IInputs["entityId"] });
expect(button(unsaved.container).disabled).toBe(true);
expect(unsaved.container.textContent).toContain("Save this record");
});
test("security readable or editable false prevents uploads without leaking configuration", async () => {
const unreadable = mount({}, { readable: false });
const readOnly = mount({}, { editable: false });
button(unreadable.container).click();
button(readOnly.container).click();
await Promise.resolve();
expect(unreadable.pickFile).not.toHaveBeenCalled();
expect(readOnly.pickFile).not.toHaveBeenCalled();
expect(unreadable.container.textContent).toContain("permission");
expect(readOnly.container.textContent).toContain("permission");
});
test("uploads a selected small file as an annotation bound with configured navigation property", async () => {
const createRecord = jest.fn().mockResolvedValue({ id: "note-id", entityType: "annotation" });
const { container, pickFile } = mount({}, { createRecord });
pickFile.mockResolvedValue({ name: "readme.txt", type: "text/plain", size: 12, contentBase64: "SGVsbG8=" });
button(container).click();
await Promise.resolve();
await Promise.resolve();
expect(createRecord).toHaveBeenCalledWith("annotation", {
filename: "readme.txt",
mimetype: "text/plain",
documentbody: "SGVsbG8=",
isdocument: true,
subject: "readme.txt",
"[email protected]": "/accounts(00000000-0000-0000-0000-000000000001)",
});
expect(container.textContent).toContain("Attachment uploaded");
});
test("rejects files over the explicit max size before calling WebAPI", async () => {
const createRecord = jest.fn().mockResolvedValue({ id: "note-id", entityType: "annotation" });
const { container, pickFile } = mount({}, { createRecord });
pickFile.mockResolvedValue({ name: "big.txt", type: "text/plain", size: 2048, contentBase64: "AA==" });
button(container).click();
await Promise.resolve();
await Promise.resolve();
expect(createRecord).not.toHaveBeenCalled();
expect(container.textContent).toContain("larger than 1 KB");
});
test("prevents duplicate submit while status is indeterminate", async () => {
let finish!: () => void;
const createRecord = jest.fn(() => new Promise((resolve) => { finish = () => resolve({ id: "note-id", entityType: "annotation" }); }));
const { container, pickFile } = mount({}, { createRecord });
pickFile.mockResolvedValue({ name: "readme.txt", type: "text/plain", size: 12, contentBase64: "SGVsbG8=" });
button(container).click();
button(container).click();
await Promise.resolve();
expect(button(container).getAttribute("aria-busy")).toBe("true");
expect(container.textContent).toContain("Uploading attachment...");
expect(pickFile).toHaveBeenCalledTimes(1);
finish();
await Promise.resolve();
});
test("surfaces WebAPI permission failures", async () => {
const createRecord = jest.fn().mockRejectedValue(new Error("Create privilege is missing"));
const { container, pickFile } = mount({}, { createRecord });
pickFile.mockResolvedValue({ name: "readme.txt", type: "text/plain", size: 12, contentBase64: "SGVsbG8=" });
button(container).click();
await Promise.resolve();
await Promise.resolve();
expect(container.textContent).toContain("Create privilege is missing");
});
test("two instances keep independent adapters and status", async () => {
const first = mount();
const second = mount();
first.pickFile.mockResolvedValue({ name: "one.txt", type: "text/plain", size: 12, contentBase64: "MQ==" });
second.pickFile.mockResolvedValue({ name: "two.txt", type: "text/plain", size: 12, contentBase64: "Mg==" });
button(first.container).click();
await Promise.resolve();
await Promise.resolve();
expect(first.container.textContent).toContain("Attachment uploaded");
expect(second.container.textContent).not.toContain("Attachment uploaded");
expect(first.container.querySelector(".{{cssClass}}")) .not.toBe(second.container.querySelector(".{{cssClass}}"));
});
test("invalid configured OData names disable upload with a localized configuration error", () => {
for (const invalid of ["bad/name", "bad(name", "bad@name", "bad'name", "bad name"]) {
const badSet = mount({ parentEntitySetName: mockProperty(invalid) as IInputs["parentEntitySetName"] });
expect(button(badSet.container).disabled).toBe(true);
expect(badSet.container.textContent).toContain("invalid Web API name");
const badNavigation = mount({ parentNavigationProperty: mockProperty(invalid) as IInputs["parentNavigationProperty"] });
expect(button(badNavigation.container).disabled).toBe(true);
expect(badNavigation.container.textContent).toContain("invalid Web API name");
}
});
test("destroy during file selection abandons upload without creating or mutating DOM", async () => {
const picked = deferred<AdapterFile | null>();
const { control, container, createRecord, pickFile } = mount();
pickFile.mockReturnValue(picked.promise);
button(container).click();
await Promise.resolve();
control.destroy();
picked.resolve({ name: "late.txt", type: "text/plain", size: 12, contentBase64: "bGF0ZQ==" });
await flushPromises();
expect(createRecord).not.toHaveBeenCalled();
expect(container.textContent).toBe("");
});
test("record change before create abandons the stale upload and recovers immediately", async () => {
const picked = deferred<AdapterFile | null>();
const { control, container, context, createRecord, pickFile } = mount();
pickFile.mockReturnValue(picked.promise);
button(container).click();
await Promise.resolve();
const changed = parameters({ entityId: mockProperty("{00000000-0000-0000-0000-000000000002}") as IInputs["entityId"] });
control.updateView(withStrings({ ...context, parameters: changed } as ComponentFramework.Context<IInputs>));
expect(button(container).disabled).toBe(false);
expect(button(container).getAttribute("aria-busy")).toBe("false");
expect(container.textContent).not.toContain("Uploading attachment");
picked.resolve({ name: "stale.txt", type: "text/plain", size: 12, contentBase64: "c3RhbGU=" });
await flushPromises();
expect(createRecord).not.toHaveBeenCalled();
expect(button(container).disabled).toBe(false);
expect(container.textContent).not.toContain("Uploading attachment");
});
test("editability withdrawn before file selection resolves abandons the stale upload", async () => {
const picked = deferred<AdapterFile | null>();
const { control, container, context, createRecord, pickFile } = mount();
pickFile.mockReturnValue(picked.promise);
button(container).click();
await Promise.resolve();
const readOnly = parameters({
value: mockProperty<string>(null, undefined, { editable: false }) as IInputs["value"],
});
control.updateView(withStrings({ ...context, parameters: readOnly } as ComponentFramework.Context<IInputs>));
expect(button(container).disabled).toBe(true);
picked.resolve({ name: "stale.txt", type: "text/plain", size: 12, contentBase64: "c3RhbGU=" });
await flushPromises();
expect(createRecord).not.toHaveBeenCalled();
expect(container.textContent).toContain("permission");
});
test("raw file size is capped at the documented direct-create safety boundary", async () => {
const atCap = mount({ maxFileSizeKb: mockProperty(5120) as IInputs["maxFileSizeKb"] });
atCap.pickFile.mockResolvedValue({ name: "cap.txt", type: "text/plain", size: 3 * 1024 * 1024, contentBase64: "AA==" });
button(atCap.container).click();
await flushPromises();
expect(atCap.createRecord).toHaveBeenCalledTimes(1);
const overCap = mount({ maxFileSizeKb: mockProperty(5120) as IInputs["maxFileSizeKb"] });
overCap.pickFile.mockResolvedValue({ name: "over.txt", type: "text/plain", size: (3 * 1024 * 1024) + 1, contentBase64: "AA==" });
button(overCap.container).click();
await flushPromises();
expect(overCap.createRecord).not.toHaveBeenCalled();
expect(overCap.container.textContent).toContain("larger than 3072 KB");
});
test("button accessible name uses visible text without duplicate ids across instances", () => {
const host = document.createElement("div");
const first = mount();
const second = mount();
host.append(first.container, second.container);
expect(button(first.container).textContent).toBe("Choose file");
expect(button(second.container).textContent).toBe("Choose file");
const ids = Array.from(host.querySelectorAll<HTMLElement>("[id]")).map((element) => element.id);
expect(new Set(ids).size).toBe(ids.length);
expect(button(first.container).getAttribute("aria-labelledby")).toBeNull();
expect(button(second.container).getAttribute("aria-labelledby")).toBeNull();
});
test("native file picker cancel resolves without leaving inputs outside the container", async () => {
const host = document.createElement("div");
document.body.append(host);
const picker = createBrowserFilePicker(host);
const picked = picker.pickFile("text/plain");
const input = host.querySelector("input[type='file']") as HTMLInputElement;
expect(input).not.toBeNull();
expect(document.body.querySelector("body > input[type='file']")).toBeNull();
input.dispatchEvent(new Event("cancel"));
await expect(picked).resolves.toBeNull();
expect(host.querySelector("input[type='file']")).toBeNull();
});
test("native file picker rejects oversize files before FileReader runs", async () => {
const host = document.createElement("div");
document.body.append(host);
const originalFileReader = global.FileReader;
const readAsDataURL = jest.fn();
class ThrowingFileReader extends EventTarget {
result: string | ArrayBuffer | null = null;
error: DOMException | null = null;
readAsDataURL = readAsDataURL;
}
global.FileReader = ThrowingFileReader as unknown as typeof FileReader;
try {
const picker = createBrowserFilePicker(host);
const picked = picker.pickFile("text/plain", {
acceptedMimeTypes: ["text/plain"],
maxBytes: 1,
fileTooLargeMessage: "Too large",
typeNotAllowedMessage: "Wrong type",
});
const input = host.querySelector("input[type='file']") as HTMLInputElement;
Object.defineProperty(input, "files", {
configurable: true,
value: [new File(["too large"], "big.txt", { type: "text/plain" })],
});
input.dispatchEvent(new Event("change"));
await expect(picked).rejects.toThrow("Too large");
expect(readAsDataURL).not.toHaveBeenCalled();
expect(host.querySelector("input[type='file']")).toBeNull();
} finally {
global.FileReader = originalFileReader;
}
});
test("destroy during create annotation resolve or reject does not mutate after destroy", async () => {
for (const outcome of ["resolve", "reject"] as const) {
const pendingCreate = deferred<ComponentFramework.LookupValue>();
const createAnnotation = jest.fn(() => pendingCreate.promise);
const { control, container, pickFile } = mount({}, { createAnnotation });
pickFile.mockResolvedValue({ name: `${outcome}.txt`, type: "text/plain", size: 12, contentBase64: "AA==" });
button(container).click();
await flushPromises();
expect(createAnnotation).toHaveBeenCalledTimes(1);
control.destroy();
if (outcome === "resolve") {
pendingCreate.resolve({ id: "note-id", entityType: "annotation" });
} else {
pendingCreate.reject(new Error("late failure"));
}
await flushPromises();
expect(container.textContent).toBe("");
}
});