create-order-context-loader.mjs
2.16 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
import { existsSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const shimDir = path.dirname(fileURLToPath(import.meta.url))
const projectRoot = path.resolve(shimDir, '../../..')
const mockApiUrl = pathToFileURL(path.join(shimDir, 'mock-api.mjs')).href
const mockUtilUrl = pathToFileURL(path.join(shimDir, 'mock-util.mjs')).href
function resolveExistingModule(candidate) {
const candidates = [candidate, `${candidate}.js`, path.join(candidate, 'index.js')]
return candidates.find(item => existsSync(item))
}
export async function resolve(specifier, context, nextResolve) {
if (specifier === '~/utils/util' || specifier === '~/utils/util.js') {
return { shortCircuit: true, url: mockUtilUrl }
}
if (
specifier === '~/api/api' ||
specifier === '~/api/api.js' ||
(specifier === '../../api' && context.parentURL?.includes('/createOrder/'))
) {
return { shortCircuit: true, url: mockApiUrl }
}
if (specifier.startsWith('./') || specifier.startsWith('../')) {
const parentPath = fileURLToPath(context.parentURL)
const candidate = path.resolve(path.dirname(parentPath), specifier)
const tabWorkOrderApi = path.join(projectRoot, 'tabWorkOrder', 'api')
const projectApi = path.join(projectRoot, 'api', 'api')
if (
candidate === tabWorkOrderApi ||
candidate === `${tabWorkOrderApi}.js` ||
candidate === projectApi ||
candidate === `${projectApi}.js`
) {
return { shortCircuit: true, url: mockApiUrl }
}
}
if (specifier.startsWith('~/')) {
const mapped = resolveExistingModule(
path.join(projectRoot, specifier.slice(2))
)
if (mapped) {
return { shortCircuit: true, url: pathToFileURL(mapped).href }
}
}
if (
(specifier.startsWith('./') || specifier.startsWith('../')) &&
!/\.(?:m?js|json|node)$/.test(specifier)
) {
const parentPath = fileURLToPath(context.parentURL)
const mapped = resolveExistingModule(
path.resolve(path.dirname(parentPath), specifier)
)
if (mapped) {
return { shortCircuit: true, url: pathToFileURL(mapped).href }
}
}
return nextResolve(specifier, context)
}