Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

5.7 KB
Raw Blame
/*
 * Copyright 2026, OpenRemote Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
import baseConfig from "../custom-elements-manifest.config.mjs";
import { cemInheritancePlugin } from "@wc-toolkit/cem-inheritance";
import { fileURLToPath } from "node:url";

/**
 * Custom plugin that we wrote ourselves, that parses the JSDoc format that Vaadin uses,
 * and generates the Custom Elements Manifest JSON fields for it.
 */
const VaadinJSDocParserPlugin = {
  name: "vaadin-jsdoc-parser",
  analyzePhase({ ts, node, moduleDoc }) {
    if (node.kind !== ts.SyntaxKind.ClassDeclaration) return;
    const declaration = moduleDoc.declarations.find((d) => d.name === node.name.getText());
    const description = declaration?.description; // The JSDoc text above the class
    if (!description) return;

    const sections = [
      /* { key: 'shadow DOM parts', category: 'cssParts', inputType: undefined }, */ // TODO: Fix CSS parts to not override HTML attributes
      { key: "state attributes", category: "attributes", inputType: "boolean" },
      { key: "custom CSS properties", category: "cssProperties", inputType: "string" },
    ];

    /**
     * To parse the JSDoc text into categories, we need a complex regex pattern to parse the values out.
     * It extracts backticked names and grabs its description by checking for the `|` symbol.
     * The generated list would be inserted into the custom-elements.json file.
     * Example JSDoc:
     * ---
     * state attributes
     * `is-active` | Whether the component is toggled on.
     * `disabled` | Prevents user interaction.
     * custom CSS properties
     * `--bg-color` | The background color of the button.
     */
    sections.forEach(({ key, category, inputType }, i) => {
      const content = description.split(key)[1]?.split(sections[i + 1]?.key || "$")[0] || "";
      const matches = [...content.matchAll(/`([^`]+)`(?:\s*\|\s*([^\n|]+))?/g)];
      declaration[category] ??= [];

      const entries = matches.flatMap(([_, name, desc]) => {
        return [
          {
            name,
            description: desc?.trim(),
            ...(inputType && { type: { text: inputType } }),
          },
        ];
      });
      declaration[category].push(...entries);
    });
    if (declaration) {
      console.debug(`Injected additional JSDoc documentation for class ${declaration.name}`);
    }
  },
};

/**
 * Custom plugin that we wrote ourselves, that corrects the 'extends' keyword for our Vaadin classes.
 * The analyzer does not understand `extends (TextField as new () => TextField & LitElement)`,
 * so we manually parse the Vaadin class, and link it to the correct Vaadin NPM package.
 */
const VaadinSuperclassParserPlugin = {
  name: "vaadin-superclass-parser",
  analyzePhase({ ts, node, moduleDoc }) {
    if (node.kind !== ts.SyntaxKind.ClassDeclaration || !node.heritageClauses) return;
    if (!node.name) return;

    const className = node.name.getText();
    const declaration = moduleDoc.declarations?.find((d) => d.name === className);
    const extendsClause = node.heritageClauses.find((h) => h.token === ts.SyntaxKind.ExtendsKeyword);
    const baseName = extendsClause?.types[0]?.getText().match(/\(([^ ]+) as/)?.[1];

    if (declaration && baseName) {
      const pkg = baseName.replaceAll(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); // For example, parses TextField to 'text-field'
      declaration.superclass = {
        name: baseName,
        package: `@vaadin/${pkg}`,
      };
      console.debug(`Resolved conflict for super class documentation for: @vaadin/${pkg}`);
    }
  },
};

/**
 * Custom plugin that we wrote ourselves, that marks underscore-prefixed members as
 * protected/private (the Vaadin naming convention), since the inherited Vaadin code
 * carries no privacy metadata. Consumers such as the Storybook helpers rely on the
 * privacy field to skip internals.
 */
const VaadinPrivacyPlugin = {
  name: "vaadin-privacy",
  packageLinkPhase({ customElementsManifest }) {
    for (const module of customElementsManifest.modules ?? []) {
      for (const declaration of module.declarations ?? []) {
        for (const member of declaration.members ?? []) {
          if (!member.privacy && member.name.startsWith("_")) {
            member.privacy = member.name.startsWith("__") ? "private" : "protected";
          }
        }
      }
    }
  },
};

/* -------------------------------- */

// Retrieve path to the Vaadin NPM package
const vaadinFilesURL = new URL("../*/src/*.js", import.meta.resolve("@vaadin/button/package.json"));
const vaadinPath = fileURLToPath(vaadinFilesURL).replaceAll("\\", "/");

export default {
  ...baseConfig,
  globs: [...baseConfig.globs, vaadinPath], // Also analyze the code inside the Vaadin folder
  plugins: [
    ...baseConfig.plugins,
    VaadinSuperclassParserPlugin, // Resolve conflict in package names
    cemInheritancePlugin(), // Inject the analysis of the inherited Vaadin code
    VaadinJSDocParserPlugin, // Inject JSDoc of the inherited Vaadin code
    VaadinPrivacyPlugin, // Mark inherited underscore members as non-public
  ],
};