Skip to content

Commit

Permalink
Remove Macro script execution override, add MacroSchema type (fou…
Browse files Browse the repository at this point in the history
…ndryvtt#8421)

The method was made #private in V11, so we're locked out.
  • Loading branch information
stwlam committed Jun 26, 2023
1 parent 48b0cfd commit d646323
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 84 deletions.
4 changes: 2 additions & 2 deletions build/lib/compendium-pack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,14 @@ class CompendiumPack {
if (a._id === b._id) {
throw PackError(`_id collision in ${this.packId}: ${a._id}`);
}
return a._id > b._id ? 1 : -1;
return a._id!.localeCompare(b._id!);
});

this.data = parsedData;

for (const docSource of this.data) {
// Populate CompendiumPack.namesToIds for later conversion of compendium links
packMap.set(docSource.name, docSource._id);
packMap.set(docSource.name, docSource._id!);

// Check img paths
if ("img" in docSource && typeof docSource.img === "string") {
Expand Down
2 changes: 1 addition & 1 deletion build/lib/extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ class PackExtractor {
}

#convertLinks(docSource: PackEntry, packName: string): PackEntry {
this.#newDocIdMap[docSource._id] = docSource.name;
this.#newDocIdMap[docSource._id!] = docSource.name;

const sanitized = this.#sanitizeDocument(docSource);
if (isActorSource(sanitized)) {
Expand Down
2 changes: 1 addition & 1 deletion build/lib/level-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class LevelDatabase extends ClassicLevel<string, DBEntry> {
}
}
}
docBatch.put(source._id, source);
docBatch.put(source._id!, source);
}
await docBatch.write();
if (embeddedBatch?.length) {
Expand Down
24 changes: 0 additions & 24 deletions src/module/macro.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,6 @@
import { ChatMessagePF2e } from "./chat-message/index.ts";

export class MacroPF2e extends Macro {
/** Raise permission requirement of world macro visibility to observer */
override get visible(): boolean {
return this.permission >= CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER;
}

/** Allow unbound variables to be shadowed in script's evaluation scope */
protected override _executeScript({
actor,
token,
}: { actor?: Actor<TokenDocument<Scene | null> | null>; token?: Token | null } = {}): void {
// Add variables to the evaluation scope
const speaker = ChatMessagePF2e.getSpeaker();
const character = game.user.character;
actor ??= game.actors.get(speaker.actor ?? "");
token ??= canvas.ready ? canvas.tokens.get(speaker.token ?? "") : null;

// Attempt script execution
const AsyncFunction = async function () {}.constructor as { new (...args: string[]): Function };
const command = ["{", this.command, "}"].join("\n");
const fn = new AsyncFunction("speaker", "actor", "token", "character", command);
try {
return fn.call(this, speaker, actor, token, character);
} catch {
ui.notifications.error("There was an error in your macro syntax. See the console (F12) for details");
}
}
}
41 changes: 11 additions & 30 deletions types/foundry/client/data/documents/macro.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,30 @@ declare global {
* @see {@link FolderConfig} The Folder configuration application
*/
class Macro extends ClientBaseMacro {
command: string;

/* -------------------------------------------- */
/* Properties */
/* Model Properties */
/* -------------------------------------------- */

/** Is the current User the author of this macro? */
get isAuthor(): boolean;

/** Test whether the current user is capable of executing a Macro script */
get canExecute(): boolean;

/** Provide a thumbnail image path used to represent this document. */
get thumbnail(): ImageFilePath;

/* -------------------------------------------- */
/* Methods */
/* Model Methods */
/* -------------------------------------------- */

/**
* Execute the Macro command.
* @param [scope={}] Provide some additional scope configuration for the Macro
* @param [scope={}] Macro execution scope which is passed to script macros
* @param [scope.actor] An Actor who is the protagonist of the executed action
* @param [scope.token] A Token which is the protagonist of the executed action
* @returns A created ChatMessage from chat macros or returned value from script macros
*/
execute({ actor, token }?: { actor?: Actor<TokenDocument<Scene | null> | null>; token?: Token }): void;

/**
* Execute the command as a chat macro.
* Chat macros simulate the process of the command being entered into the Chat Log input textarea.
*/
protected _executeChat({
actor,
token,
}?: {
actor?: Actor<TokenDocument<Scene | null> | null>;
token?: Token;
}): void;

/**
* Execute the command as a script macro.
* Script Macros are wrapped in an async IIFE to allow the use of asynchronous commands and await statements.
*/
protected _executeScript({
actor,
token,
}?: {
actor?: Actor<TokenDocument<Scene | null> | null>;
token?: Token;
}): void;
execute(scope?: { actor?: Actor<TokenDocument<Scene | null> | null>; token?: Token }): unknown;
}
}
66 changes: 40 additions & 26 deletions types/foundry/common/documents/macro.d.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,67 @@
import type { Document, DocumentMetadata } from "../abstract/module.d.ts";
import type { DataModel, Document, DocumentMetadata } from "../abstract/module.d.ts";
import type { BaseUser } from "./module.d.ts";
import type * as fields from "../data/fields.d.ts";

/** The Macro document model. */
export default class BaseMacro extends Document<null> {
static override get metadata(): MacroMetadata;

static override defineSchema(): MacroSchema;

/** The default icon used for newly created Macro documents. */
static DEFAULT_ICON: ImageFilePath;

/* -------------------------------------------- */
/* Model Methods */
/* -------------------------------------------- */

override testUserPermission(user: BaseUser, permission: unknown, options?: { exact?: boolean }): boolean;

/* -------------------------------------------- */
/* Database Event Handlers */
/* -------------------------------------------- */

protected override _preCreate(
data: PreDocumentId<MacroSource>,
options: DocumentModificationContext<null>,
user: BaseUser
): Promise<void>;

/** Is a user able to update an existing Macro document? */
protected static _canUpdate(user: BaseUser, doc: BaseMacro, data: MacroSource): boolean;
/* -------------------------------------------- */
/* Deprecations and Compatibility */
/* -------------------------------------------- */

/** Is a user able to delete an existing Macro document? */
protected static _canDelete(user: BaseUser, doc: BaseMacro): boolean;
/** @inheritdoc */
static shimData(data: object, options: object): object;
}

export default interface BaseMacro extends Document<null> {
export default interface BaseMacro extends Document<null>, ModelPropsFromSchema<MacroSchema> {
readonly _source: MacroSource;

get documentName(): (typeof BaseMacro)["metadata"]["name"];
}

export interface MacroSource {
_id: string;
name: string;
type: "chat" | "script";
img: ImageFilePath;
actorIds: string[];
author: string;
command: string;
scope: string;
folder?: string | null;
sort: number;
ownership: Record<string, DocumentOwnershipLevel>;
flags: DocumentFlags;
}

interface MacroMetadata extends DocumentMetadata {
name: "Macro";
collection: "macros";
label: "DOCUMENT.Macro";
isPrimary: true;
types: ["script", "chat"];
permissions: {
create: "PLAYER";
update: (typeof BaseMacro)["_canUpdate"];
delete: (typeof BaseMacro)["_canDelete"];
};
}

type MacroSchema = {
_id: fields.DocumentIdField;
name: fields.StringField<string, string, true, false, false>;
type: fields.StringField<MacroType, MacroType, true, false, true>;
author: fields.ForeignDocumentField<DataModel>;
img: fields.FilePathField<ImageFilePath>;
scope: fields.StringField<MacroScope, MacroScope, true, false, true>;
command: fields.StringField<string, string, true, false, true>;
folder: fields.ForeignDocumentField;
sort: fields.IntegerSortField;
ownership: fields.DocumentOwnershipField;
flags: fields.ObjectField<DocumentFlags>;
_stats: fields.DocumentStatsField;
};

type MacroSource = SourceFromSchema<MacroSchema>;

0 comments on commit d646323

Please sign in to comment.