create-order-context-loader.mjs 2.16 KB
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)
}