forked from ayoreis/import
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
236 lines (201 loc) · 5.27 KB
/
mod.ts
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
import type { DenoConfigurationFile } from './_dependencies.ts'
import {
denoPlugin,
dirname,
ErrorStackParser,
join,
nativeEsbuild,
resolveImportMap,
resolveModuleSpecifier,
stripShebang,
toFileUrl,
webAssemblyEsbuild,
} from './_dependencies.ts'
import { readTextFile } from './_read-text-file.ts'
export interface ImportModuleOptions {
/** Use of the ponyfill when native is available */
force?: boolean
}
export interface ImportStringOptions {
/** URL to use as the base for imports and exports */
base?: URL
}
/**
* https://deno.com/blog/v1.22#navigatoruseragent
*
* https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
*/
const DENO_USER_AGENT =
/^Deno\/(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/
const isDeno = DENO_USER_AGENT.test(navigator.userAgent)
const isDenoCLI = isDeno && !!Deno?.run
const isDenoCompiled = isDeno &&
dirname(Deno.execPath()) === Deno.cwd()
const isDenoDeploy = isDeno && !isDenoCLI &&
!!Deno.env.get('DENO_REGION')
const denoCWDURL = isDeno ? toFileUrl(Deno.cwd()) : null
const posibleDenoConfigurationURLs = isDeno
? ([
new URL(`${denoCWDURL}/deno.json`),
new URL(`${denoCWDURL}/deno.jsonc`),
] as const)
: null
const denoConfiguration = isDeno
? await getDenoConfiguration()
: null
const importMapURL = denoConfiguration?.importMap
? toFileUrl(join(Deno.cwd(), denoConfiguration.importMap))
: undefined
const importMap = importMapURL
? resolveImportMap(
JSON.parse(await readTextFile(importMapURL)),
importMapURL,
)
: null
const esbuild: typeof webAssemblyEsbuild = isDenoCLI
? nativeEsbuild
: webAssemblyEsbuild
let checkInitialization: boolean = false;
const sharedEsbuildOptions:
webAssemblyEsbuild.BuildOptions = {
jsx: {
'preserve': 'preserve',
'react': 'transform',
'react-jsx': 'automatic',
'react-jsxdev': 'automatic',
'react-native': 'preserve',
}[
denoConfiguration?.compilerOptions?.jsx ?? 'react'
] as webAssemblyEsbuild.BuildOptions['jsx'],
jsxDev: denoConfiguration?.compilerOptions?.jsx ===
'react-jsxdev',
jsxFactory:
denoConfiguration?.compilerOptions?.jsxFactory ?? 'h',
jsxFragment: denoConfiguration?.compilerOptions
?.jsxFragmentFactory ?? 'Fragment',
jsxImportSource: denoConfiguration?.compilerOptions
?.jsxImportSource,
bundle: true,
platform: 'neutral',
write: false,
logLevel: 'silent',
// @ts-ignore The plugin's types have not been updated
plugins: [
denoPlugin({ importMapURL, loader: 'portable' }),
],
}
const AsyncFunction = async function () {}.constructor
async function getDenoConfiguration() {
for (
const posibleDenoConfigurationURL
of posibleDenoConfigurationURLs!
) {
try {
return JSON.parse(
await readTextFile(posibleDenoConfigurationURL),
) as DenoConfigurationFile
// deno-lint-ignore no-empty
} catch {}
}
return null
}
async function buildAndEvaluate(
options: webAssemblyEsbuild.BuildOptions,
url: URL,
modules: Record<string, unknown> = {},
) {
if (!isDenoCLI && !checkInitialization) {
esbuild.initialize({
worker: typeof Worker !== 'undefined',
})
checkInitialization=true;
}
const buildResult = await esbuild.build(
Object.assign({}, sharedEsbuildOptions, options),
)
if (isDenoCLI) {
esbuild.stop()
}
const { text = '' } = buildResult.outputFiles![0]
const [before, after = '}'] = text.split('export {')
const body = stripShebang(before).replaceAll(
'import.meta',
`{ main: false, url: '${url}', resolve(specifier) { return new URL(specifier, this.url).href } }`,
) +
'return {' +
after.replaceAll(
/(?<local>\w+) as (?<exported>\w+)/g,
'$<exported>: $<local>',
)
const exports = await AsyncFunction('modules',body)(modules)
const prototypedAndToStringTaggedExports = Object.assign(
Object.create(null),
exports,
{
[Symbol.toStringTag]: 'Module',
},
)
const sortedExports = Object.fromEntries(
Object.keys(prototypedAndToStringTaggedExports)
.sort()
.map((
key,
) => [key, prototypedAndToStringTaggedExports[key]]),
)
const sealedExports = Object.seal(sortedExports)
return sealedExports
}
export async function importModule<
Module = Record<string, unknown>,
>(
moduleName: string,
{ force = false }: ImportModuleOptions = {},
) {
try {
if (force) throw new Error('Forced')
return await import(moduleName)
} catch (error) {
if (
!isDenoCompiled && !isDenoDeploy &&
error.message !== 'Forced'
) {
throw error
}
const base =
ErrorStackParser.parse(new Error())[1].fileName
const resolved = resolveModuleSpecifier(
moduleName,
importMap ?? {},
base,
)
return (await buildAndEvaluate(
{
entryPoints: [resolved],
},
new URL(resolved),
)) as Module
}
}
export async function importString<
Module = Record<string, unknown>,
>(
moduleString: string,
{
base = new URL(
ErrorStackParser.parse(new Error())[1].fileName,
),
modules={},
}: ImportStringOptions & { modules?: Record<string, unknown> }= {},
) {
return (await buildAndEvaluate(
{
stdin: {
contents: moduleString,
loader: 'tsx',
sourcefile: base.href,
},
},
base,
modules
)) as Module
}