1- import { accessSync , existsSync , mkdirSync , readFileSync , writeFileSync } from "node:fs" ;
2- import { join } from "node:path" ;
1+ import { existsSync , mkdirSync , readFileSync , writeFileSync } from "node:fs" ;
2+ import { join , dirname } from "node:path" ;
33import { fileURLToPath } from "node:url" ;
44import { ImportMap } from "@jspm/import-map" ;
55import fetch from "node-fetch" ;
@@ -8,16 +8,41 @@ import { ConstructCachePath, Context, NextResolve, UrlType } from './types'
88// hoist the cache map
99const cacheMap = new Map ( ) ;
1010
11+ /**
12+ * nsureDirSync
13+ * @description a function to ensure the dis exists
14+ * @param dirPath
15+ */
16+
17+ function ensureDirSync ( dirPath : string ) {
18+ if ( existsSync ( dirPath ) ) {
19+ return ;
20+ }
21+
22+ const parentDir = dirname ( dirPath ) ;
23+ if ( parentDir !== dirPath ) {
24+ ensureDirSync ( parentDir ) ;
25+ }
26+
27+ mkdirSync ( dirPath ) ;
28+ }
29+
1130/**
1231 * ensureFileSync
1332 * @description a convenience function to ensure a file exists
1433 * @param path
1534 */
1635function ensureFileSync ( path : string ) {
36+ const dirPath = dirname ( path ) ;
37+
38+ if ( ! existsSync ( dirPath ) ) {
39+ ensureDirSync ( dirPath ) ;
40+ }
41+
1742 try {
18- accessSync ( path ) ;
19- } catch ( err ) {
20- writeFileSync ( path , '' ) ;
43+ writeFileSync ( path , '' , { flag : 'wx' } ) ;
44+ } catch {
45+ console . log ( `Failed in creating ${ path } ` )
2146 }
2247}
2348
@@ -166,13 +191,15 @@ export const parseModule = async (specifier: string, modulePath: string) => {
166191 const { protocol } = new URL ( modulePath ) ;
167192 const isNode = protocol === "node:" ;
168193 const isFile = protocol === "file:" ;
194+
169195 if ( isNode || isFile ) return specifier ;
170196
171197 const cachePath = constructCachePath ( { cache, modulePath } )
198+
172199 cacheMap . set ( `file://${ cachePath } ` , modulePath ) ;
173200 if ( existsSync ( cachePath ) ) return cachePath
174-
175201 const code = await ( await fetch ( modulePath ) ) . text ( ) ;
202+
176203 ensureFileSync ( cachePath ) ;
177204 writeFileSync ( cachePath , code ) ;
178205
0 commit comments