• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

pmcelhaney / counterfact / 9799751871

04 Jul 2024 08:49PM UTC coverage: 87.297%. Remained the same
9799751871

Pull #967

github

web-flow
chore(deps): update dependency eslint-config-hardcore to v47
Pull Request #967: chore(deps): update dependency eslint-config-hardcore to v47

993 of 1102 branches covered (90.11%)

Branch coverage included in aggregate %.

3247 of 3755 relevant lines covered (86.47%)

44.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.65
/src/server/module-loader.ts
1
import { once } from "node:events";
2✔
2
import { existsSync } from "node:fs";
2✔
3
import fs from "node:fs/promises";
2✔
4
import nodePath, { basename, dirname } from "node:path";
2✔
5

2✔
6
import { type FSWatcher, watch } from "chokidar";
2✔
7
import createDebug from "debug";
2✔
8

2✔
9
import { CHOKIDAR_OPTIONS } from "./constants.js";
2✔
10
import { type Context, ContextRegistry } from "./context-registry.js";
2✔
11
import { determineModuleKind } from "./determine-module-kind.js";
2✔
12
import { ModuleDependencyGraph } from "./module-dependency-graph.js";
2✔
13
import type { Module, Registry } from "./registry.js";
2✔
14
import { uncachedImport } from "./uncached-import.js";
2✔
15

2✔
16
const { uncachedRequire } = await import("./uncached-require.cjs");
2✔
17

2✔
18
const debug = createDebug("counterfact:server:module-loader");
2✔
19

2✔
20
interface ContextModule {
2✔
21
  Context: Context;
2✔
22
}
2✔
23

2✔
24
function isContextModule(
12✔
25
  module: ContextModule | Module,
12✔
26
): module is ContextModule {
12✔
27
  return "Context" in module && typeof module.Context === "function";
12✔
28
}
12✔
29

2✔
30
export class ModuleLoader extends EventTarget {
2✔
31
  private readonly basePath: string;
12✔
32

12✔
33
  public readonly registry: Registry;
12✔
34

12✔
35
  private watcher: FSWatcher | undefined;
12✔
36

12✔
37
  private readonly contextRegistry: ContextRegistry;
12✔
38

12✔
39
  private readonly dependencyGraph = new ModuleDependencyGraph();
12✔
40

12✔
41
  private readonly uncachedImport: (moduleName: string) => Promise<unknown> =
12✔
42
    // eslint-disable-next-line @typescript-eslint/require-await
12✔
43
    async function (moduleName: string) {
12✔
44
      throw new Error(`uncachedImport not set up; importing ${moduleName}`);
×
45
    };
×
46

12✔
47
  public constructor(
12✔
48
    basePath: string,
12✔
49
    registry: Registry,
12✔
50
    contextRegistry = new ContextRegistry(),
12✔
51
  ) {
12✔
52
    super();
12✔
53
    this.basePath = basePath.replaceAll("\\", "/");
12✔
54
    this.registry = registry;
12✔
55
    this.contextRegistry = contextRegistry;
12✔
56
  }
12✔
57

12✔
58
  public async watch(): Promise<void> {
12✔
59
    this.watcher = watch(
4✔
60
      `${this.basePath}/**/*.{js,mjs,ts,mts,cjs,cts}`,
4✔
61
      CHOKIDAR_OPTIONS,
4✔
62
    ).on(
4✔
63
      "all",
4✔
64
      // eslint-disable-next-line max-statements
4✔
65
      (eventName: string, pathNameOriginal: string) => {
4✔
66
        const pathName = pathNameOriginal.replaceAll("\\", "/");
2✔
67

2✔
68
        if (pathName.includes("$.context") && eventName === "add") {
2!
69
          process.stdout.write(
×
70
            `\n\n!!! The file at ${pathName} needs a minor update.\n    See https://github.com/pmcelhaney/counterfact/blob/main/docs/context-change.md\n\n\n`,
×
71
          );
×
72
          return;
×
73
        }
×
74

2✔
75
        if (!["add", "change", "unlink"].includes(eventName)) {
2!
76
          return;
×
77
        }
×
78

2✔
79
        const parts = nodePath.parse(pathName.replace(this.basePath, ""));
2✔
80
        const url = `/${parts.dir}/${parts.name}`
2✔
81
          .replaceAll("\\", "/")
2✔
82
          .replaceAll(/\/+/gu, "/");
2✔
83

2✔
84
        if (eventName === "unlink") {
2✔
85
          this.registry.remove(url);
2✔
86
          this.dispatchEvent(new Event("remove"));
2✔
87
        }
2✔
88
        const dependencies = this.dependencyGraph.dependentsOf(pathName);
2✔
89

2✔
90
        void this.loadEndpoint(pathName);
2✔
91
        for (const dependency of dependencies) {
2!
92
          void this.loadEndpoint(dependency);
×
93
        }
×
94
      },
2✔
95
    );
4✔
96
    await once(this.watcher, "ready");
4✔
97
  }
4✔
98

12✔
99
  public async stopWatching(): Promise<void> {
12✔
100
    await this.watcher?.close();
4✔
101
  }
4✔
102

12✔
103
  public async load(directory = ""): Promise<void> {
12✔
104
    if (
22✔
105
      !existsSync(nodePath.join(this.basePath, directory).replaceAll("\\", "/"))
22✔
106
    ) {
22!
107
      throw new Error(`Directory does not exist ${this.basePath}`);
×
108
    }
×
109

22✔
110
    const files = await fs.readdir(
22✔
111
      nodePath.join(this.basePath, directory).replaceAll("\\", "/"),
22✔
112
      {
22✔
113
        withFileTypes: true,
22✔
114
      },
22✔
115
    );
22✔
116

22✔
117
    const imports = files.flatMap(async (file): Promise<void> => {
22✔
118
      const extension = file.name.split(".").at(-1);
44✔
119

44✔
120
      if (file.isDirectory()) {
44✔
121
        await this.load(
10✔
122
          nodePath.join(directory, file.name).replaceAll("\\", "/"),
10✔
123
        );
10✔
124

10✔
125
        return;
10✔
126
      }
10✔
127

34✔
128
      if (!["cjs", "cts", "js", "mjs", "mts", "ts"].includes(extension ?? "")) {
44✔
129
        return;
14✔
130
      }
14✔
131

20✔
132
      const fullPath = nodePath
20✔
133
        .join(this.basePath, directory, file.name)
20✔
134
        .replaceAll("\\", "/");
20✔
135

20✔
136
      await this.loadEndpoint(fullPath);
20✔
137
    });
20✔
138

22✔
139
    await Promise.all(imports);
22✔
140
  }
22✔
141

12✔
142
  // eslint-disable-next-line max-statements
12✔
143
  private async loadEndpoint(pathName: string) {
12✔
144
    debug("importing module: %s", pathName);
22✔
145

22✔
146
    const directory = dirname(pathName.slice(this.basePath.length)).replaceAll(
22✔
147
      "\\",
22✔
148
      "/",
22✔
149
    );
22✔
150

22✔
151
    const url = `/${nodePath.join(
22✔
152
      directory,
22✔
153
      nodePath.parse(basename(pathName)).name,
22✔
154
    )}`
22✔
155
      .replaceAll("\\", "/")
22✔
156
      .replaceAll(/\/+/gu, "/");
22✔
157

22✔
158
    this.dependencyGraph.load(pathName);
22✔
159

22✔
160
    try {
22✔
161
      const doImport =
22✔
162
        (await determineModuleKind(pathName)) === "commonjs"
22!
163
          ? uncachedRequire
×
164
          : uncachedImport;
22✔
165

22✔
166
      // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
22✔
167
      const endpoint = (await doImport(pathName)) as ContextModule | Module;
22✔
168

22✔
169
      this.dispatchEvent(new Event("add"));
22✔
170

22✔
171
      if (basename(pathName).startsWith("_.context")) {
22✔
172
        if (isContextModule(endpoint)) {
12✔
173
          const loadContext = (path: string) => this.contextRegistry.find(path);
12✔
174

12✔
175
          this.contextRegistry.update(
12✔
176
            directory,
12✔
177

12✔
178
            // @ts-expect-error TS says Context has no constructable signatures but that's not true?
12✔
179
            // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
12✔
180
            new endpoint.Context({
12✔
181
              loadContext,
12✔
182
            }),
12✔
183
          );
12✔
184
        }
12✔
185
      } else {
22✔
186
        // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
10✔
187
        this.registry.add(url, endpoint as Module);
10✔
188
      }
10✔
189
    } catch (error: unknown) {
22!
190
      if (
×
191
        String(error) ===
×
192
        "SyntaxError: Identifier 'Context' has already been declared"
×
193
      ) {
×
194
        // Not sure why Node throws this error. It doesn't seem to matter.
×
195
        return;
×
196
      }
×
197

×
198
      throw error;
×
199

×
200
      process.stdout.write(`\nError loading ${pathName}:\n${String(error)}\n`);
×
201
    }
×
202
  }
22✔
203
}
12✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc