Skip to content

Commit

Permalink
Add support for "exports" field for extra languages
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Jun 26, 2021
1 parent 1af4f84 commit b046620
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions tools/lib/external_language.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const fs = require("fs");
const fsProm = require("fs").promises;
const glob = require("glob-promise");
const path = require("path");
const { fileURLToPath, pathToFileURL } = require('url')

const MODULE_DEFINER = /module\.exports\.definer\s*=/;

Expand Down Expand Up @@ -39,15 +40,32 @@ class LanguagePackage {
}
}

resolveExportsField(exports) {
if(typeof exports === 'string') return exports
if(Array.isArray(exports)) return exports[0];
if('.' in exports) return this.resolveExportsField(exports['.'])
if('default' in exports) return this.resolveExportsField(exports.default)
if('highlight-js' in exports) return this.resolveExportsField(exports['highlight-js'])
if('import' in exports) return this.resolveExportsField(exports.import)
if('require' in exports) return this.resolveExportsField(exports.require)
}

// try to find a language module by probing package.json
async tryPackageJSON() {
const pack = path.join(this.dir, "package.json");
if (fs.existsSync(pack)) {
const data = await fsProm.readFile(pack);
const json = JSON.parse(data);
if (json.main) {
this.type = "npm";
const file = path.join(process.cwd(), this.dir, json.main);
if (json.main || json.exports) {
const extraDir = path.join(process.cwd(), this.dir);
const file = json.main ?
require.resolve(extraDir) :
fileURLToPath(new URL(this.resolveExportsField(json.exports), pathToFileURL(extraDir)));

if(!file.endsWith('.js')) throw new Error('Extra language file must use .js extension');

this.type = json.type === "module" ? "npm-esm" : "npm-cjs";

const content = await fsProm.readFile(file, { encoding: "utf8" });
// many existing languages seem to export a `definer` function rather than
// simply export the language module directly. This checks for that and if
Expand Down

0 comments on commit b046620

Please sign in to comment.