All files / src/lib/compiler webBuild.ts

91.61% Statements 131/143
81.16% Branches 56/69
95.65% Functions 22/23
91.79% Lines 123/134

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 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 3622x 2x 2x 2x 2x 2x 2x       2x 2x                 2x 2x 2x         2x 12x   2x 5x   2x 4x   2x       11x 11x 3x     8x 8x 8x 8x       1x     7x     2x       12x 12x 11x     1x                         1x 1x 1x       1x 1x               1x 1x             1x     2x     17x 17x 17x         2x     15x                           2x         12x 12x 12x 12x         1x   11x     5x                                       2x     3x 3x       4x   3x     3x         3x     3x     3x     1x 1x     1x 1x     1x     1x           1x   3x 1x       2x     1x 1x 1x 1x 1x 1x     2x           12x   12x 4x 1x   4x     8x 8x 2x 2x     6x 1x     1x     5x     2x                                 6x           6x   6x       6x         6x         6x 1x     1x     1x     1x                 1x     5x 5x   15x   5x 3x   5x   10x 5x 5x   5x     5x   5x 5x   5x           5x 5x 5x            
import fs from "fs-extra";
import Path from "path";
import glob from "glob";
import { promisify } from "util";
import { binjgbWasmRoot, defaultWebTemplateRoot } from "consts";
import copy from "lib/helpers/fsCopy";
import { pathToPosix } from "shared/lib/helpers/path";
import type { ProjectResources } from "shared/lib/resources/types";
import type { WebTemplateInfo } from "shared/lib/webTemplates/types";
 
export const DEFAULT_WEB_TEMPLATE = "";
export const DEFAULT_WEB_TEMPLATE_NAME = "Default (Binjgb)";
 
type WebTemplateManifest = {
  version: 1;
  name: string;
  romPath: string;
  configPath: string;
};
 
const globAsync = promisify(glob);
const manifestFilename = "gbstudio.web-template.json";
const defaultManifestPaths = {
  romPath: "rom/{{romFilename}}",
  configPath: "gbstudio.json",
};
 
const webTemplatesRoot = (projectRoot: string) =>
  Path.join(projectRoot, "assets", "web");
 
const isDefaultWebTemplate = (templateRoot: string): boolean =>
  Path.resolve(templateRoot) === Path.resolve(defaultWebTemplateRoot);
 
const copyBinjgbRuntime = async (destination: string): Promise<void> =>
  copy(binjgbWasmRoot, Path.join(destination, "js"));
 
const resolveProjectWebTemplate = (
  projectRoot: string,
  template: string,
): string | undefined => {
  const trimmedTemplate = template.trim();
  if (!trimmedTemplate) {
    return undefined;
  }
 
  const templatesRoot = webTemplatesRoot(projectRoot);
  const templatePath = Path.resolve(templatesRoot, trimmedTemplate);
  const relativeTemplatePath = Path.relative(templatesRoot, templatePath);
  if (
    relativeTemplatePath.startsWith("..") ||
    Path.isAbsolute(relativeTemplatePath)
  ) {
    return undefined;
  }
 
  return templatePath;
};
 
const resolvePluginWebTemplate = (
  projectRoot: string,
  template: string,
): string | undefined => {
  const trimmedTemplate = template.trim();
  if (!trimmedTemplate.startsWith("plugins/")) {
    return undefined;
  }
 
  Iif (trimmedTemplate.includes("/assets/web/")) {
    const projectPath = Path.resolve(projectRoot, trimmedTemplate);
    const relativeProjectPath = Path.relative(projectRoot, projectPath);
    Iif (
      relativeProjectPath.startsWith("..") ||
      Path.isAbsolute(relativeProjectPath)
    ) {
      return undefined;
    }
 
    return projectPath;
  }
 
  const templatePathParts = trimmedTemplate.split("/");
  const templateName = templatePathParts.pop();
  Iif (!templateName || templatePathParts.length < 2) {
    return undefined;
  }
 
  const pluginPathParts = templatePathParts.slice(1);
  const projectPath = Path.resolve(
    projectRoot,
    "plugins",
    ...pluginPathParts,
    "assets",
    "web",
    templateName,
  );
  const relativeProjectPath = Path.relative(projectRoot, projectPath);
  Iif (
    relativeProjectPath.startsWith("..") ||
    Path.isAbsolute(relativeProjectPath)
  ) {
    return undefined;
  }
 
  return projectPath;
};
 
const readWebTemplateManifest = async (
  templatePath: string,
): Promise<WebTemplateManifest | undefined> => {
  const manifestPath = Path.join(templatePath, manifestFilename);
  const manifest = await fs.readJSON(manifestPath).catch(() => undefined);
  if (
    !manifest ||
    manifest.version !== 1 ||
    typeof manifest.name !== "string"
  ) {
    return undefined;
  }
 
  return {
    version: 1,
    name: manifest.name,
    romPath:
      typeof manifest.romPath === "string"
        ? manifest.romPath
        : defaultManifestPaths.romPath,
    configPath:
      typeof manifest.configPath === "string"
        ? manifest.configPath
        : defaultManifestPaths.configPath,
  };
};
 
const resolveOutputPath = (
  destination: string,
  templatePath: string,
  romFilename: string,
): string | undefined => {
  const relativePath = templatePath.replace(/{{romFilename}}/g, romFilename);
  const outputPath = Path.resolve(destination, relativePath);
  const relativeOutputPath = Path.relative(destination, outputPath);
  if (
    !relativePath ||
    relativeOutputPath.startsWith("..") ||
    Path.isAbsolute(relativeOutputPath)
  ) {
    return undefined;
  }
  return outputPath;
};
 
const makeWebBuildConfig = (project: ProjectResources, romPath: string) => ({
  version: 1,
  rom: romPath,
  project: {
    name: project.metadata.name,
    author: project.metadata.author,
  },
  colorCorrection: project.settings.colorCorrection,
  customControls: {
    up: project.settings.customControlsUp,
    down: project.settings.customControlsDown,
    left: project.settings.customControlsLeft,
    right: project.settings.customControlsRight,
    a: project.settings.customControlsA,
    b: project.settings.customControlsB,
    start: project.settings.customControlsStart,
    select: project.settings.customControlsSelect,
  },
});
 
export const listProjectWebTemplates = async (
  projectRoot: string,
): Promise<WebTemplateInfo[]> => {
  const templatesRoot = webTemplatesRoot(projectRoot);
  const projectTemplates = (await fs.pathExists(templatesRoot))
    ? (
        await Promise.all(
          (await fs.readdir(templatesRoot, { withFileTypes: true }))
            .filter((entry) => entry.isDirectory())
            .map(async (entry) => {
              const manifest = await readWebTemplateManifest(
                Path.join(templatesRoot, entry.name),
              );
              return manifest
                ? { id: entry.name, name: manifest.name }
                : undefined;
            }),
        )
      ).filter((template): template is WebTemplateInfo => Boolean(template))
    : [];
 
  const pluginTemplatePaths = await globAsync(
    Path.join(projectRoot, "plugins", "**", "assets", "web", "*"),
  );
  const pluginTemplates = (
    await Promise.all(
      pluginTemplatePaths.map(async (templatePath) => {
        const stat = await fs.stat(templatePath).catch(() => undefined);
        Iif (!stat?.isDirectory()) {
          return undefined;
        }
        const manifest = await readWebTemplateManifest(templatePath);
        Iif (!manifest) {
          return undefined;
        }
        const relativeTemplatePath = pathToPosix(
          Path.relative(projectRoot, templatePath),
        );
        return {
          id: relativeTemplatePath.replace("/assets/web/", "/"),
          name: manifest.name,
        };
      }),
    )
  ).filter((template): template is WebTemplateInfo => Boolean(template));
 
  return [...projectTemplates, ...pluginTemplates].sort((a, b) =>
    a.id.localeCompare(b.id),
  );
};
 
export const ejectDefaultWebTemplate = async (
  projectRoot: string,
): Promise<string> => {
  const templateName = "binjgb";
  const outputPath = Path.join(webTemplatesRoot(projectRoot), templateName);
  await fs.remove(outputPath);
  await copy(defaultWebTemplateRoot, outputPath);
  await copyBinjgbRuntime(outputPath);
  return templateName;
};
 
export const getWebTemplateRoot = async (
  projectRoot: string,
  template: string,
  warnings: (msg: string) => void,
): Promise<string> => {
  const templatePath =
    resolvePluginWebTemplate(projectRoot, template) ||
    resolveProjectWebTemplate(projectRoot, template);
  if (!templatePath) {
    if (template.trim()) {
      warnings(`Invalid web template "${template}", using default template.`);
    }
    return defaultWebTemplateRoot;
  }
 
  const stat = await fs.stat(templatePath).catch(() => undefined);
  if (!stat?.isDirectory()) {
    warnings(`Web template "${template}" not found, using default template.`);
    return defaultWebTemplateRoot;
  }
 
  if (!(await readWebTemplateManifest(templatePath))) {
    warnings(
      `Web template "${template}" is missing a valid ${manifestFilename}, using default template.`,
    );
    return defaultWebTemplateRoot;
  }
 
  return templatePath;
};
 
export const exportWebBuild = async ({
  project,
  projectRoot,
  destination,
  romFilename,
  romPath,
  webTemplate,
  warnings,
}: {
  project: ProjectResources;
  projectRoot: string;
  destination: string;
  romFilename: string;
  romPath: string;
  webTemplate?: string;
  warnings: (msg: string) => void;
}) => {
  const templateRoot = await getWebTemplateRoot(
    projectRoot,
    webTemplate ?? project.settings.webTemplate ?? DEFAULT_WEB_TEMPLATE,
    warnings,
  );
  const manifest =
    (await readWebTemplateManifest(templateRoot)) ||
    (await readWebTemplateManifest(defaultWebTemplateRoot));
  Iif (!manifest) {
    throw new Error(`Default web template is missing ${manifestFilename}`);
  }
 
  const romOutputPath = resolveOutputPath(
    destination,
    manifest.romPath,
    romFilename,
  );
  const configOutputPath = resolveOutputPath(
    destination,
    manifest.configPath,
    romFilename,
  );
  if (!romOutputPath || !configOutputPath) {
    warnings(
      `Web template "${manifest.name}" contains unsafe output paths, using default template.`,
    );
    const defaultManifest = await readWebTemplateManifest(
      defaultWebTemplateRoot,
    );
    Iif (!defaultManifest) {
      throw new Error(`Default web template is missing ${manifestFilename}`);
    }
    await exportWebBuild({
      project,
      projectRoot,
      destination,
      romFilename,
      romPath,
      webTemplate: DEFAULT_WEB_TEMPLATE,
      warnings,
    });
    return;
  }
 
  const templateManifestPath = Path.join(templateRoot, manifestFilename);
  await copy(templateRoot, destination, {
    ignore: (sourcePath) =>
      Path.resolve(sourcePath) === Path.resolve(templateManifestPath),
  });
  if (isDefaultWebTemplate(templateRoot)) {
    await copyBinjgbRuntime(destination);
  }
  await copy(romPath, romOutputPath);
 
  const sanitize = (s: string) => String(s || "").replace(/["<>]/g, "");
  const projectName = sanitize(project.metadata.name);
  const author = sanitize(project.metadata.author);
  const colorsHead =
    project.settings.colorMode !== "mono"
      ? `<style type="text/css"> body { background-color:#${project.settings.customColorsBlack}; }</style>`
      : "";
  const customHead = project.settings.customHead || "";
 
  const htmlPath = Path.join(destination, "index.html");
  const romConfigPath = pathToPosix(Path.relative(destination, romOutputPath));
 
  const html = (await fs.readFile(htmlPath, "utf8"))
    .replace(/___PROJECT_NAME___/g, projectName)
    .replace(/___AUTHOR___/g, author)
    .replace(/___COLORS_HEAD___/g, colorsHead)
    .replace(/___PROJECT_HEAD___/g, customHead);
 
  await fs.writeFile(htmlPath, html);
  await fs.ensureDir(Path.dirname(configOutputPath));
  await fs.writeJSON(
    configOutputPath,
    makeWebBuildConfig(project, romConfigPath),
    { spaces: 2 },
  );
};