MCPcopy Create free account
hub / github.com/cypress-io/cypress / keepModuleLocation

Function keepModuleLocation

scripts/binary/start-bundle.js:65–99  ·  view source on GitHub ↗
(buildAppDir, requireResolveTargets)

Source from the content-addressed store, hash-verified

63// Every module keeps its original __filename/__dirname and require.resolve base, so code that reads
64// files next to itself or resolves packages still sees its location on disk rather than the bundle's.
65const keepModuleLocation = (buildAppDir, requireResolveTargets) => {
66 return {
67 name: 'keep-module-location',
68 setup (build) {
69 build.onLoad({ filter: /\.(c?js)$/ }, async (args) => {
70 let contents = await fs.readFile(args.path, 'utf8')
71 const usesRequireResolve = contents.search(REQUIRE_RESOLVE) !== -1
72
73 if (!usesRequireResolve && !/\b__(?:dirname|filename)\b/.test(contents)) {
74 return { contents, loader: 'js' }
75 }
76
77 const relativePath = path.relative(buildAppDir, args.path).split(path.sep).join(path.posix.sep)
78 let header = `var __filename = require('path').join(__cypressAppDir, ${JSON.stringify(relativePath)}), __dirname = require('path').dirname(__filename);`
79
80 if (usesRequireResolve) {
81 for (const [, , request] of contents.matchAll(REQUIRE_RESOLVE_LITERAL)) {
82 try {
83 requireResolveTargets.add(require.resolve(request, { paths: [path.dirname(args.path)] }))
84 } catch {
85 // an optional package that is not installed resolves at runtime the same way it would unbundled
86 }
87 }
88
89 header += `var __cypressRequireResolve = require('module').createRequire(__filename).resolve;`
90 contents = contents.replace(REQUIRE_RESOLVE, '__cypressRequireResolve')
91 }
92
93 const prologue = contents.match(FILE_PROLOGUE)[0]
94
95 return { contents: `${prologue}${header}${contents.slice(prologue.length)}`, loader: 'js' }
96 })
97 },
98 }
99}
100
101// request-promise loads a private copy of @cypress/request by clearing require.cache, which bundled modules
102// bypass, so in the bundle it would patch the copy that every other request uses and reject non-2xx responses.

Callers 1

createStartCypressBundleFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected