All files / src/lib/project loadScriptEventHandlers.ts

85.94% Statements 55/64
48% Branches 12/25
87.5% Functions 7/8
85.94% Lines 55/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 2577x 7x 7x 7x 7x 7x 7x   7x 7x 7x 7x   7x   7x 7x                                                                                                                                                                                                                                             7x           8220x 8220x 8220x             8220x                               7x     8220x     8220x 8220x                 8220x     8220x 24480x 8220x 8220x       8220x 28620x           8220x 11280x 35460x 3060x 32400x 29820x       8220x   8220x     240x   240x 720x       240x 3600x     240x               8220x     7x 60x   60x       60x 60x 8220x 8220x   60x         60x     7x  
import glob from "glob";
import { promisify } from "util";
import { eventsRoot } from "consts";
import * as l10n from "shared/lib/lang/l10n";
import * as eventHelpers from "lib/events/helpers";
import * as eventSystemHelpers from "lib/helpers/eventSystem";
import * as compileEntityEvents from "lib/compiler/compileEntityEvents";
import type { ScriptEventFieldSchema } from "shared/lib/entities/entitiesTypes";
import { readFile } from "fs-extra";
import trimLines from "shared/lib/helpers/trimlines";
import * as scriptValueHelpers from "shared/lib/scriptValue/helpers";
import * as scriptValueTypes from "shared/lib/scriptValue/types";
 
const globAsync = promisify(glob);
 
const VM2 = __non_webpack_require__("vm2");
const NodeVM = VM2.NodeVM;
 
export type ScriptEventHelperDef =
  | {
      type: "position";
      x: string;
      y: string;
      units?: string;
      tileSize?: string;
      tileWidth?: number;
      tileHeight?: number;
    }
  | {
      type: "camera";
      x: string;
      y: string;
      units?: string;
    }
  | {
      type: "overlay";
      x: string;
      y: string;
      color?: string;
      units?: string;
    }
  | {
      type: "scanline";
      y: string;
      units?: string;
    }
  | {
      type: "distance";
      actorId: string;
      distance: string;
      operator: string;
    }
  | {
      type: "bounds";
      actorId: string;
      x: string;
      y: string;
      width: string;
      height: string;
    }
  | {
      type: "text";
      text: string;
      avatarId: string;
      minHeight: string;
      maxHeight: string;
      showFrame: string;
      clearPrevious: string;
      textX: string;
      textY: string;
      textHeight: string;
    }
  | {
      type: "textdraw";
      text: string;
      x: string;
      y: string;
      location: string;
    };
 
export type ScriptEventPresetValue = {
  id: string;
  name: string;
  description?: string;
  groups?: string[] | string;
  subGroups?: Record<string, string>;
  values: Record<string, unknown>;
};
 
export type UserPresetsGroup = {
  id: string;
  label: string;
  fields: string[];
  selected?: boolean;
};
 
export interface ScriptEventDef {
  id: string;
  fields: ScriptEventFieldSchema[];
  name?: string;
  description?: string;
  groups?: string[] | string;
  subGroups?: Record<string, string>;
  deprecated?: boolean;
  isConditional?: boolean;
  editableSymbol?: boolean;
  allowChildrenBeforeInitFade?: boolean;
  waitUntilAfterInitFade?: boolean;
  hasAutoLabel: boolean;
  helper?: ScriptEventHelperDef;
  presets?: ScriptEventPresetValue[];
  userPresetsGroups?: UserPresetsGroup[];
  userPresetsIgnore?: string[];
  fieldsLookup: Record<string, ScriptEventFieldSchema>;
}
 
export type ScriptEventHandlerFieldSchema = ScriptEventFieldSchema & {
  postUpdateFn?: (
    newArgs: Record<string, unknown>,
    prevArgs: Record<string, unknown>
  ) => void | Record<string, unknown>;
};
 
export type ScriptEventHandler = ScriptEventDef & {
  autoLabel?: (
    lookup: (key: string) => string,
    args: Record<string, unknown>
  ) => string;
  compile: (input: unknown, helpers: unknown) => void;
  fields: ScriptEventHandlerFieldSchema[];
  fieldsLookup: Record<string, ScriptEventHandlerFieldSchema>;
};
 
export type ScriptEventHandlers = Record<string, ScriptEventHandler>;
 
const vm = new NodeVM({
  timeout: 1000,
  console: process.env.NODE_ENV !== "development" ? "off" : "inherit",
  sandbox: {},
  compiler: (code: string) => {
    // Convert es6 style modules to commonjs
    let moduleCode = code;
    moduleCode = code.replace(/(^|\n)(\S\s)*export /g, "");
    Iif (moduleCode.indexOf("module.exports") === -1) {
      const moduleExports =
        code
          .match(/export [a-z]* [a-zA-Z_$][0-9a-zA-Z_$]*]*/g)
          ?.map((c) => c.replace(/.* /, "")) ?? [];
      moduleCode += `\nmodule.exports = { ${moduleExports.join(", ")} };`;
    }
    return moduleCode;
  },
  require: {
    mock: {
      "./helpers": eventHelpers,
      "../helpers/l10n": l10n,
      "../helpers/eventSystem": eventSystemHelpers,
      "../compiler/compileEntityEvents": compileEntityEvents,
      "../helpers/trimlines": trimLines,
      "shared/lib/helpers/trimlines": trimLines,
      "shared/lib/scriptValue/helpers": scriptValueHelpers,
      "shared/lib/scriptValue/types": scriptValueTypes,
    },
  },
});
 
const loadScriptEventHandler = async (
  path: string
): Promise<ScriptEventHandler> => {
  const handlerCode = await readFile(path, "utf8");
 
  let handler: ScriptEventHandler;
  try {
    handler = vm.run(handlerCode) as ScriptEventHandler;
  } catch (error) {
    throw new Error(
      `Failed to load script event handler at ${path}: ${
        (error as Error).message
      }`
    );
  }
 
  Iif (!handler.id) {
    throw new Error(`Event handler ${path} is missing id`);
  }
  handler.isConditional =
    handler.fields && !!handler.fields.find((f) => f.type === "events");
  handler.hasAutoLabel = !!handler.autoLabel;
  handler.fieldsLookup = {};
 
  // Add flags for existence of field callsbacks
  // Needed so renderer knows if API call to main process is needed
  for (const field of handler.fields) {
    field.hasPostUpdateFn = !!field.postUpdateFn;
  }
 
  // Build flat lookup table of field keys to field
  // To prevent needing to recursively loop through
  // nested fields at editor runtime
  const buildFieldsLookup = (fields: ScriptEventFieldSchema[]): void => {
    for (const field of fields) {
      if (field.type === "group" && field.fields) {
        buildFieldsLookup(field.fields);
      } else if (field.key) {
        handler.fieldsLookup[field.key] = field;
      }
    }
  };
  buildFieldsLookup(handler.fields);
 
  if (handler.userPresetsGroups) {
    // If an script event supports user presets
    // validate that all fields have been accounted for
    const allFields = Object.keys(handler.fieldsLookup);
 
    const presetFields = handler.userPresetsGroups
      .map((group) => group.fields)
      .flat()
      .concat(handler.userPresetsIgnore ?? []);
 
    const missingFields = allFields.filter(
      (key) => !presetFields.includes(key)
    );
 
    Iif (missingFields.length > 0) {
      console.error(
        `${handler.id} defined userPresetsGroups but did not include some fields in either userPresetsGroups or userPresetsIgnore`
      );
      console.error("Missing fields: " + missingFields.join(", "));
    }
  }
 
  return handler;
};
 
const loadAllScriptEventHandlers = async (projectRoot: string) => {
  const corePaths = await globAsync(`${eventsRoot}/event*.js`);
 
  const pluginPaths = await globAsync(
    `${projectRoot}/plugins/*/**/events/event*.js`
  );
 
  const eventHandlers: ScriptEventHandlers = {};
  for (const path of corePaths) {
    const handler = await loadScriptEventHandler(path);
    eventHandlers[handler.id] = handler;
  }
  for (const path of pluginPaths) {
    const handler = await loadScriptEventHandler(path);
    eventHandlers[handler.id] = handler;
  }
 
  return eventHandlers;
};
 
export default loadAllScriptEventHandlers;