Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion deno.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
},
"exclude": [
".coverage/",
"tests/denops/testdata/no_check/"
"tests/denops/testdata/no_check/",
"tests/denops/testdata/with_import_map/"
],
// NOTE: Import maps should only be used from test modules.
"imports": {
Expand Down
183 changes: 183 additions & 0 deletions denops/@denops-private/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import type { Denops, Entrypoint } from "jsr:@denops/core@^7.0.0";
import {
type ImportMap,
ImportMapImporter,
loadImportMap,
} from "jsr:@lambdalisue/import-map-importer@^0.3.1";
import { toFileUrl } from "jsr:@std/path@^1.0.2/to-file-url";
import { fromFileUrl } from "jsr:@std/path@^1.0.2/from-file-url";
import { join } from "jsr:@std/path@^1.0.2/join";
import { dirname } from "jsr:@std/path@^1.0.2/dirname";

type PluginModule = {
main: Entrypoint;
};

export class Plugin {
#denops: Denops;
#loadedWaiter: Promise<void>;
#unloadedWaiter?: Promise<void>;
#disposable: AsyncDisposable = voidAsyncDisposable;

readonly name: string;
readonly script: string;

constructor(denops: Denops, name: string, script: string) {
this.#denops = denops;
this.name = name;
this.script = resolveScriptUrl(script);
this.#loadedWaiter = this.#load();
}

waitLoaded(): Promise<void> {
return this.#loadedWaiter;
}

async #load(): Promise<void> {
await emit(this.#denops, `DenopsSystemPluginPre:${this.name}`);
try {
const mod: PluginModule = await importPlugin(this.script);
this.#disposable = await mod.main(this.#denops) ?? voidAsyncDisposable;
} catch (e) {
// Show a warning message when Deno module cache issue is detected
// https://github.com/vim-denops/denops.vim/issues/358
if (isDenoCacheIssueError(e)) {
console.warn("*".repeat(80));
console.warn(`Deno module cache issue is detected.`);
console.warn(
`Execute 'call denops#cache#update(#{reload: v:true})' and restart Vim/Neovim.`,
);
console.warn(
`See https://github.com/vim-denops/denops.vim/issues/358 for more detail.`,
);
console.warn("*".repeat(80));
}
console.error(`Failed to load plugin '${this.name}': ${e}`);
await emit(this.#denops, `DenopsSystemPluginFail:${this.name}`);
throw e;
}
await emit(this.#denops, `DenopsSystemPluginPost:${this.name}`);
}

unload(): Promise<void> {
if (!this.#unloadedWaiter) {
this.#unloadedWaiter = this.#unload();
}
return this.#unloadedWaiter;
}

async #unload(): Promise<void> {
try {
// Wait for the load to complete to make the events atomically.
await this.#loadedWaiter;
} catch {
// Load failed, do nothing
return;
}
const disposable = this.#disposable;
this.#disposable = voidAsyncDisposable;
await emit(this.#denops, `DenopsSystemPluginUnloadPre:${this.name}`);
try {
await disposable[Symbol.asyncDispose]();
} catch (e) {
console.error(`Failed to unload plugin '${this.name}': ${e}`);
await emit(this.#denops, `DenopsSystemPluginUnloadFail:${this.name}`);
return;
}
await emit(this.#denops, `DenopsSystemPluginUnloadPost:${this.name}`);
}

async call(fn: string, ...args: unknown[]): Promise<unknown> {
try {
return await this.#denops.dispatcher[fn](...args);
} catch (err) {
const errMsg = err instanceof Error
? err.stack ?? err.message // Prefer 'stack' if available
: String(err);
throw new Error(
`Failed to call '${fn}' API in '${this.name}': ${errMsg}`,
);
}
}
}

const voidAsyncDisposable = {
[Symbol.asyncDispose]: () => Promise.resolve(),
} as const satisfies AsyncDisposable;

const loadedScripts = new Set<string>();

function createScriptSuffix(script: string): string {
// Import module with fragment so that reload works properly
// https://github.com/vim-denops/denops.vim/issues/227
const suffix = loadedScripts.has(script) ? `#${performance.now()}` : "";
loadedScripts.add(script);
return suffix;
}

/** NOTE: `emit()` is never throws or rejects. */
async function emit(denops: Denops, name: string): Promise<void> {
try {
await denops.call("denops#_internal#event#emit", name);
} catch (e) {
console.error(`Failed to emit ${name}: ${e}`);
}
}

function resolveScriptUrl(script: string): string {
try {
return toFileUrl(script).href;
} catch {
return new URL(script, import.meta.url).href;
}
}

// See https://github.com/vim-denops/denops.vim/issues/358 for details
function isDenoCacheIssueError(e: unknown): boolean {
const expects = [
"Could not find constraint in the list of versions: ", // Deno 1.40?
"Could not find version of ", // Deno 1.38
] as const;
if (e instanceof TypeError) {
return expects.some((expect) => e.message.startsWith(expect));
}
return false;
}

async function tryLoadImportMap(
scriptUrl: string,
): Promise<ImportMap | undefined> {
const PATTERNS = [
"deno.json",
"deno.jsonc",
"import_map.json",
"import_map.jsonc",
];
// Convert file URL to path for file operations
const scriptPath = fromFileUrl(new URL(scriptUrl));
const parentDir = dirname(scriptPath);
for (const pattern of PATTERNS) {
const importMapPath = join(parentDir, pattern);
try {
return await loadImportMap(importMapPath);
} catch (err: unknown) {
if (err instanceof Deno.errors.NotFound) {
// Ignore NotFound errors and try the next pattern
continue;
}
throw err; // Rethrow other errors
}

Check warning on line 169 in denops/@denops-private/plugin.ts

View check run for this annotation

Codecov / codecov/patch

denops/@denops-private/plugin.ts#L168-L169

Added lines #L168 - L169 were not covered by tests
}
return undefined;
}

async function importPlugin(script: string): Promise<PluginModule> {
const suffix = createScriptSuffix(script);
const importMap = await tryLoadImportMap(script);
if (importMap) {
const importer = new ImportMapImporter(importMap);
return await importer.import<PluginModule>(`${script}${suffix}`);
} else {
return await import(`${script}${suffix}`);
}
}
Loading