-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmod.ts
More file actions
352 lines (328 loc) · 9.22 KB
/
mod.ts
File metadata and controls
352 lines (328 loc) · 9.22 KB
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
/**
* Resolver and loader for Deno code.
*
* This can be used to create bundler plugins or libraries that use deno resolution.
*
* @example
* ```ts
* import { Workspace, ResolutionMode, type LoadResponse, RequestedModuleType } from "@deno/loader";
*
* const workspace = new Workspace({
* // optional options
* });
* const loader = await workspace.createLoader();
* const diagnostics = await loader.addEntrypoints(["./mod.ts"])
* if (diagnostics.length > 0) {
* throw new Error(diagnostics[0].message);
* }
* // alternatively use resolve to resolve npm/jsr specifiers not found
* // in the entrypoints or if not being able to provide entrypoints
* const resolvedUrl = loader.resolveSync(
* "./mod.test.ts",
* "https://deno.land/mod.ts", // referrer
* ResolutionMode.Import,
* );
* const response = await loader.load(resolvedUrl, RequestedModuleType.Default);
* if (response.kind === "module") {
* console.log(response.specifier);
* console.log(response.code);
* console.log(response.mediaType);
* } else if (response.kind === "external") {
* console.log(response.specifier)
* } else {
* const _assertNever = response;
* throw new Error(`Unhandled kind: ${(response as LoadResponse).kind}`);
* }
* ```
* @module
*/
import {
DenoLoader as WasmLoader,
DenoWorkspace as WasmWorkspace,
} from "./lib/rs_lib.js";
/** Options for creating a workspace. */
export interface WorkspaceOptions {
/** Do not do config file discovery. */
noConfig?: boolean;
/** Do not respect the lockfile. */
noLock?: boolean;
/** Path or file: URL to the config file if you do not want to do config file discovery. */
configPath?: string;
/** Node resolution conditions to use for resolving package.json exports. */
nodeConditions?: string[];
/** Date for the newest allowed dependency. */
newestDependencyDate?: Date;
/**
* Platform to bundle for.
* @default "node"
*/
platform?: "node" | "browser";
/** Whether to force using the cache. */
cachedOnly?: boolean;
/**
* Enable debug logs.
*
* @remarks Note that the Rust debug logs are enabled globally
* and can only be enabled by the first workspace that gets
* created. This is a limitation of how the Rust logging works.
*/
debug?: boolean;
/** Whether to preserve JSX syntax in the loaded output. */
preserveJsx?: boolean;
/** Skip transpiling TypeScript and JSX. */
noTranspile?: boolean;
}
export class ResolveError extends Error {
/**
* Possible specifier this would resolve to if the error did not occur.
*
* This is useful for implementing something like `import.meta.resolve` where
* you want the resolution to always occur and not error.
*/
specifier?: string;
/** Node.js error code. */
code?: string;
/**
* If the specifier being resolved was an optional npm dependency.
*
* @remarks This will only be true when the error code is
* `ERR_MODULE_NOT_FOUND`.
*/
isOptionalDependency?: boolean;
}
/** File type. */
export enum MediaType {
JavaScript = 0,
Jsx = 1,
Mjs = 2,
Cjs = 3,
TypeScript = 4,
Mts = 5,
Cts = 6,
Dts = 7,
Dmts = 8,
Dcts = 9,
Tsx = 10,
Css = 11,
Json = 12,
Jsonc = 13,
Json5 = 14,
Html = 15,
Markdown = 16,
Sql = 17,
Wasm = 18,
SourceMap = 19,
Unknown = 20,
}
/** A response received from a load. */
export type LoadResponse = ModuleLoadResponse | ExternalLoadResponse;
/** A response that indicates the module is external.
*
* This will occur for `node:` specifiers for example.
*/
export interface ExternalLoadResponse {
/** Kind of response. */
kind: "external";
/**
* Fully resolved URL.
*
* This may be different than the provided specifier. For example, during loading
* it may encounter redirects and this specifier is the redirected to final specifier.
*/
specifier: string;
}
/** A response that loads a module. */
export interface ModuleLoadResponse {
/** Kind of response. */
kind: "module";
/**
* Fully resolved URL.
*
* This may be different than the provided specifier. For example, during loading
* it may encounter redirects and this specifier is the redirected to final specifier.
*/
specifier: string;
/** Content that was loaded. */
mediaType: MediaType;
/** Code that was loaded. */
code: Uint8Array;
}
/** Kind of resolution. */
export enum ResolutionMode {
/** Resolving from an ESM file. */
Import = 0,
/** Resolving from a CJS file. */
Require = 1,
}
/** Resolves the workspace. */
export class Workspace implements Disposable {
#inner: WasmWorkspace;
#debug: boolean;
/** Creates a `DenoWorkspace` with the provided options. */
constructor(options: WorkspaceOptions = {}) {
this.#inner = new WasmWorkspace(options);
this.#debug = options.debug ?? false;
}
[Symbol.dispose]() {
this.#inner.free();
}
/** Creates a loader that uses this this workspace. */
async createLoader(): Promise<Loader> {
const wasmLoader = await this.#inner.create_loader();
return new Loader(wasmLoader, this.#debug);
}
}
export enum RequestedModuleType {
Default = 0,
Json = 1,
Text = 2,
Bytes = 3,
}
export interface EntrypointDiagnostic {
message: string;
}
/** A loader for resolving and loading urls. */
export class Loader implements Disposable {
#inner: WasmLoader;
#debug: boolean;
/** @internal */
constructor(loader: WasmLoader, debug: boolean) {
if (!(loader instanceof WasmLoader)) {
throw new Error("Get the loader from the workspace.");
}
this.#inner = loader;
this.#debug = debug;
}
[Symbol.dispose]() {
this.#inner.free();
}
/** Adds entrypoints to the loader.
*
* It's useful to specify entrypoints so that the loader can resolve
* npm: and jsr: specifiers the same way that Deno does when not using
* a lockfile.
*/
async addEntrypoints(
entrypoints: string[],
): Promise<EntrypointDiagnostic[]> {
const messages = await this.#inner.add_entrypoints(entrypoints);
return messages.map((message) => ({ message }));
}
/** Synchronously resolves a specifier using the given referrer and resolution mode.
* @throws {ResolveError}
*/
resolveSync(
specifier: string,
referrer: string | undefined,
resolutionMode: ResolutionMode,
): string {
if (this.#debug) {
console.error(
`DEBUG - Resolving '${specifier}' from '${
referrer ?? "<undefined>"
}' (${resolutionModeToString(resolutionMode)})`,
);
}
try {
const value = this.#inner.resolve_sync(
specifier,
referrer,
resolutionMode,
);
if (this.#debug) {
console.error(`DEBUG - Resolved to '${value}'`);
}
return value;
} catch (err) {
Object.setPrototypeOf(err, ResolveError.prototype);
throw err;
}
}
/** Asynchronously resolves a specifier using the given referrer and resolution mode.
*
* This is useful for resolving `jsr:` and `npm:` specifiers on the fly when they can't
* be figured out from entrypoints, but it may cause multiple "npm install"s and different
* npm or jsr resolution than Deno. For that reason it's better to provide the list of
* entrypoints up front so the loader can create the npm and jsr graph, and then after use
* synchronous resolution to resolve jsr and npm specifiers.
*
* @throws {ResolveError}
*/
async resolve(
specifier: string,
referrer: string | undefined,
resolutionMode: ResolutionMode,
): Promise<string> {
if (this.#debug) {
console.error(
`DEBUG - Resolving '${specifier}' from '${
referrer ?? "<undefined>"
}' (${resolutionModeToString(resolutionMode)})`,
);
}
try {
const value = await this.#inner.resolve(
specifier,
referrer,
resolutionMode,
);
if (this.#debug) {
console.error(`DEBUG - Resolved to '${value}'`);
}
return value;
} catch (err) {
Object.setPrototypeOf(err, ResolveError.prototype);
throw err;
}
}
/** Loads a specifier. */
load(
specifier: string,
requestedModuleType: RequestedModuleType,
): Promise<LoadResponse> {
if (this.#debug) {
console.error(
`DEBUG - Loading '${specifier}' with type '${
requestedModuleTypeToString(requestedModuleType) ?? "<default>"
}'`,
);
}
return this.#inner.load(specifier, requestedModuleType);
}
/** Gets the module graph.
*
* WARNING: This function is very unstable and the output may change between
* patch releases.
*/
getGraphUnstable(): unknown {
return this.#inner.get_graph();
}
}
function requestedModuleTypeToString(moduleType: RequestedModuleType) {
switch (moduleType) {
case RequestedModuleType.Bytes:
return "bytes";
case RequestedModuleType.Text:
return "text";
case RequestedModuleType.Json:
return "json";
case RequestedModuleType.Default:
return undefined;
default: {
const _never: never = moduleType;
return undefined;
}
}
}
function resolutionModeToString(mode: ResolutionMode) {
switch (mode) {
case ResolutionMode.Import:
return "import";
case ResolutionMode.Require:
return "require";
default: {
const _assertNever: never = mode;
return "unknown";
}
}
}