1 # This file originates from node2nix
3 {lib, stdenv, nodejs, python2, pkgs, libtool, runCommand, writeTextFile, writeShellScript}:
6 python = if nodejs ? python then nodejs.python else python2;
8 # Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise
9 tarWrapper = runCommand "tarWrapper" {} ''
12 cat > $out/bin/tar <<EOF
14 $(type -p tar) "\$@" --warning=no-unknown-keyword --delay-directory-restore
20 # Function that generates a TGZ file from a NPM project
22 { name, version, src, ... }:
25 name = "node-tarball-${name}-${version}";
27 buildInputs = [ nodejs ];
30 tgzFile=$(npm pack | tail -n 1) # Hooks to the pack command will add output (https://docs.npmjs.com/misc/scripts)
33 mkdir -p $out/tarballs
34 mv $tgzFile $out/tarballs
35 mkdir -p $out/nix-support
36 echo "file source-dist $out/tarballs/$tgzFile" >> $out/nix-support/hydra-build-products
41 installPackage = writeShellScript "install-package" ''
43 local packageName=$1 src=$2
52 # Make the base dir in which the target dependency resides first
53 mkdir -p "$(dirname "$DIR/$packageName")"
57 # Figure out what directory has been unpacked
58 packageDir="$(find . -maxdepth 1 -type d | tail -1)"
60 # Restore write permissions to make building work
61 find "$packageDir" -type d -exec chmod u+x {} \;
62 chmod -R u+w "$packageDir"
64 # Move the extracted tarball into the output folder
65 mv "$packageDir" "$DIR/$packageName"
68 # Get a stripped name (without hash) of the source directory.
69 # On old nixpkgs it's already set internally.
70 if [ -z "$strippedName" ]
72 strippedName="$(stripHash $src)"
75 # Restore write permissions to make building work
76 chmod -R u+w "$strippedName"
78 # Move the extracted directory into the output folder
79 mv "$strippedName" "$DIR/$packageName"
82 # Change to the package directory to install dependencies
83 cd "$DIR/$packageName"
87 # Bundle the dependencies of the package
89 # Only include dependencies if they don't exist. They may also be bundled in the package.
90 includeDependencies = {dependencies}:
91 lib.optionalString (dependencies != []) (
96 + (lib.concatMapStrings (dependency:
98 if [ ! -e "${dependency.packageName}" ]; then
99 ${composePackage dependency}
108 # Recursively composes the dependencies of a package
109 composePackage = { name, packageName, src, dependencies ? [], ... }@args:
110 builtins.addErrorContext "while evaluating node package '${packageName}'" ''
111 installPackage "${packageName}" "${src}"
112 ${includeDependencies { inherit dependencies; }}
114 ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
117 pinpointDependencies = {dependencies, production}:
119 pinpointDependenciesFromPackageJSON = writeTextFile {
120 name = "pinpointDependencies.js";
122 var fs = require('fs');
123 var path = require('path');
125 function resolveDependencyVersion(location, name) {
126 if(location == process.env['NIX_STORE']) {
129 var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json");
131 if(fs.existsSync(dependencyPackageJSON)) {
132 var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON));
134 if(dependencyPackageObj.name == name) {
135 return dependencyPackageObj.version;
138 return resolveDependencyVersion(path.resolve(location, ".."), name);
143 function replaceDependencies(dependencies) {
144 if(typeof dependencies == "object" && dependencies !== null) {
145 for(var dependency in dependencies) {
146 var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency);
148 if(resolvedVersion === null) {
149 process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n");
151 dependencies[dependency] = resolvedVersion;
157 /* Read the package.json configuration */
158 var packageObj = JSON.parse(fs.readFileSync('./package.json'));
160 /* Pinpoint all dependencies */
161 replaceDependencies(packageObj.dependencies);
162 if(process.argv[2] == "development") {
163 replaceDependencies(packageObj.devDependencies);
166 packageObj.devDependencies = {};
168 replaceDependencies(packageObj.optionalDependencies);
169 replaceDependencies(packageObj.peerDependencies);
171 /* Write the fixed package.json file */
172 fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2));
177 node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"}
179 ${lib.optionalString (dependencies != [])
181 if [ -d node_modules ]
184 ${lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies}
190 # Recursively traverses all dependencies of a package and pinpoints all
191 # dependencies in the package.json file to the versions that are actually
194 pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args:
196 if [ -d "${packageName}" ]
199 ${pinpointDependencies { inherit dependencies production; }}
201 ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
205 # Extract the Node.js source code which is used to compile packages with
207 nodeSources = runCommand "node-sources" {} ''
208 tar --no-same-owner --no-same-permissions -xf ${nodejs.src}
212 # Script that adds _integrity fields to all package.json files to prevent NPM from consulting the cache (that is empty)
213 addIntegrityFieldsScript = writeTextFile {
214 name = "addintegrityfields.js";
216 var fs = require('fs');
217 var path = require('path');
219 function augmentDependencies(baseDir, dependencies) {
220 for(var dependencyName in dependencies) {
221 var dependency = dependencies[dependencyName];
223 // Open package.json and augment metadata fields
224 var packageJSONDir = path.join(baseDir, "node_modules", dependencyName);
225 var packageJSONPath = path.join(packageJSONDir, "package.json");
227 if(fs.existsSync(packageJSONPath)) { // Only augment packages that exist. Sometimes we may have production installs in which development dependencies can be ignored
228 console.log("Adding metadata fields to: "+packageJSONPath);
229 var packageObj = JSON.parse(fs.readFileSync(packageJSONPath));
231 if(dependency.integrity) {
232 packageObj["_integrity"] = dependency.integrity;
234 packageObj["_integrity"] = "sha1-000000000000000000000000000="; // When no _integrity string has been provided (e.g. by Git dependencies), add a dummy one. It does not seem to harm and it bypasses downloads.
237 if(dependency.resolved) {
238 packageObj["_resolved"] = dependency.resolved; // Adopt the resolved property if one has been provided
240 packageObj["_resolved"] = dependency.version; // Set the resolved version to the version identifier. This prevents NPM from cloning Git repositories.
243 if(dependency.from !== undefined) { // Adopt from property if one has been provided
244 packageObj["_from"] = dependency.from;
247 fs.writeFileSync(packageJSONPath, JSON.stringify(packageObj, null, 2));
250 // Augment transitive dependencies
251 if(dependency.dependencies !== undefined) {
252 augmentDependencies(packageJSONDir, dependency.dependencies);
257 if(fs.existsSync("./package-lock.json")) {
258 var packageLock = JSON.parse(fs.readFileSync("./package-lock.json"));
260 if(![1, 2].includes(packageLock.lockfileVersion)) {
261 process.stderr.write("Sorry, I only understand lock file versions 1 and 2!\n");
265 if(packageLock.dependencies !== undefined) {
266 augmentDependencies(".", packageLock.dependencies);
272 # Reconstructs a package-lock file from the node_modules/ folder structure and package.json files with dummy sha1 hashes
273 reconstructPackageLock = writeTextFile {
274 name = "reconstructpackagelock.js";
276 var fs = require('fs');
277 var path = require('path');
279 var packageObj = JSON.parse(fs.readFileSync("package.json"));
282 name: packageObj.name,
283 version: packageObj.version,
288 name: packageObj.name,
289 version: packageObj.version,
290 license: packageObj.license,
292 dependencies: packageObj.dependencies,
293 engines: packageObj.engines,
294 optionalDependencies: packageObj.optionalDependencies
300 function augmentPackageJSON(filePath, packages, dependencies) {
301 var packageJSON = path.join(filePath, "package.json");
302 if(fs.existsSync(packageJSON)) {
303 var packageObj = JSON.parse(fs.readFileSync(packageJSON));
304 packages[filePath] = {
305 version: packageObj.version,
306 integrity: "sha1-000000000000000000000000000=",
307 dependencies: packageObj.dependencies,
308 engines: packageObj.engines,
309 optionalDependencies: packageObj.optionalDependencies
311 dependencies[packageObj.name] = {
312 version: packageObj.version,
313 integrity: "sha1-000000000000000000000000000=",
316 processDependencies(path.join(filePath, "node_modules"), packages, dependencies[packageObj.name].dependencies);
320 function processDependencies(dir, packages, dependencies) {
321 if(fs.existsSync(dir)) {
322 var files = fs.readdirSync(dir);
324 files.forEach(function(entry) {
325 var filePath = path.join(dir, entry);
326 var stats = fs.statSync(filePath);
328 if(stats.isDirectory()) {
329 if(entry.substr(0, 1) == "@") {
330 // When we encounter a namespace folder, augment all packages belonging to the scope
331 var pkgFiles = fs.readdirSync(filePath);
333 pkgFiles.forEach(function(entry) {
334 if(stats.isDirectory()) {
335 var pkgFilePath = path.join(filePath, entry);
336 augmentPackageJSON(pkgFilePath, packages, dependencies);
340 augmentPackageJSON(filePath, packages, dependencies);
347 processDependencies("node_modules", lockObj.packages, lockObj.dependencies);
349 fs.writeFileSync("package-lock.json", JSON.stringify(lockObj, null, 2));
353 # Script that links bins defined in package.json to the node_modules bin directory
354 # NPM does not do this for top-level packages itself anymore as of v7
355 linkBinsScript = writeTextFile {
356 name = "linkbins.js";
358 var fs = require('fs');
359 var path = require('path');
361 var packageObj = JSON.parse(fs.readFileSync("package.json"));
363 var nodeModules = Array(packageObj.name.split("/").length).fill("..").join(path.sep);
365 if(packageObj.bin !== undefined) {
366 fs.mkdirSync(path.join(nodeModules, ".bin"))
368 if(typeof packageObj.bin == "object") {
369 Object.keys(packageObj.bin).forEach(function(exe) {
370 if(fs.existsSync(packageObj.bin[exe])) {
371 console.log("linking bin '" + exe + "'");
373 path.join("..", packageObj.name, packageObj.bin[exe]),
374 path.join(nodeModules, ".bin", exe)
378 console.log("skipping non-existent bin '" + exe + "'");
383 if(fs.existsSync(packageObj.bin)) {
384 console.log("linking bin '" + packageObj.bin + "'");
386 path.join("..", packageObj.name, packageObj.bin),
387 path.join(nodeModules, ".bin", packageObj.name.split("/").pop())
391 console.log("skipping non-existent bin '" + packageObj.bin + "'");
395 else if(packageObj.directories !== undefined && packageObj.directories.bin !== undefined) {
396 fs.mkdirSync(path.join(nodeModules, ".bin"))
398 fs.readdirSync(packageObj.directories.bin).forEach(function(exe) {
399 if(fs.existsSync(path.join(packageObj.directories.bin, exe))) {
400 console.log("linking bin '" + exe + "'");
402 path.join("..", packageObj.name, packageObj.directories.bin, exe),
403 path.join(nodeModules, ".bin", exe)
407 console.log("skipping non-existent bin '" + exe + "'");
414 prepareAndInvokeNPM = {packageName, bypassCache, reconstructLock, npmFlags, production}:
416 forceOfflineFlag = if bypassCache then "--offline" else "--registry http://www.example.com";
419 # Pinpoint the versions of all dependencies to the ones that are actually being used
420 echo "pinpointing versions of dependencies..."
421 source $pinpointDependenciesScriptPath
423 # Patch the shebangs of the bundled modules to prevent them from
424 # calling executables outside the Nix store as much as possible
427 # Deploy the Node.js package by running npm install. Since the
428 # dependencies have been provided already by ourselves, it should not
429 # attempt to install them again, which is good, because we want to make
430 # it Nix's responsibility. If it needs to install any dependencies
431 # anyway (e.g. because the dependency parameters are
432 # incomplete/incorrect), it fails.
434 # The other responsibilities of NPM are kept -- version checks, build
435 # steps, postprocessing etc.
441 ${lib.optionalString bypassCache ''
442 ${lib.optionalString reconstructLock ''
443 if [ -f package-lock.json ]
445 echo "WARNING: Reconstruct lock option enabled, but a lock file already exists!"
446 echo "This will most likely result in version mismatches! We will remove the lock file and regenerate it!"
449 echo "No package-lock.json file found, reconstructing..."
452 node ${reconstructPackageLock}
455 node ${addIntegrityFieldsScript}
458 npm ${forceOfflineFlag} --nodedir=${nodeSources} ${npmFlags} ${lib.optionalString production "--production"} rebuild
462 if [ "''${dontNpmInstall-}" != "1" ]
464 # NPM tries to download packages even when they already exist if npm-shrinkwrap is used.
465 rm -f npm-shrinkwrap.json
467 npm ${forceOfflineFlag} --nodedir=${nodeSources} --no-bin-links --ignore-scripts ${npmFlags} ${lib.optionalString production "--production"} install
470 # Link executables defined in package.json
471 node ${linkBinsScript}
474 # Builds and composes an NPM package including all its dependencies
483 , dontNpmInstall ? false
484 , bypassCache ? false
485 , reconstructLock ? false
488 , unpackPhase ? "true"
489 , buildPhase ? "true"
494 extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "preRebuild" "unpackPhase" "buildPhase" "meta" ];
496 stdenv.mkDerivation ({
497 name = "${name}${if version == null then "" else "-${version}"}";
498 buildInputs = [ tarWrapper python nodejs ]
499 ++ lib.optional (stdenv.hostPlatform.isLinux) pkgs.util-linux
500 ++ lib.optional (stdenv.hostPlatform.isDarwin) libtool
505 inherit dontStrip; # Stripping may fail a build for some package deployments
506 inherit dontNpmInstall preRebuild unpackPhase buildPhase;
508 compositionScript = composePackage args;
509 pinpointDependenciesScript = pinpointDependenciesOfPackage args;
511 passAsFile = [ "compositionScript" "pinpointDependenciesScript" ];
514 source ${installPackage}
516 # Create and enter a root node_modules/ folder
517 mkdir -p $out/lib/node_modules
518 cd $out/lib/node_modules
520 # Compose the package and all its dependencies
521 source $compositionScriptPath
523 ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }}
525 # Create symlink to the deployed executable folder, if applicable
526 if [ -d "$out/lib/node_modules/.bin" ]
528 ln -s $out/lib/node_modules/.bin $out/bin
530 # Fixup all executables
531 ls $out/bin/* | while read i
533 file="$(readlink -f "$i")"
537 sed -i 's/\r$//' "$file" # convert crlf to lf
542 # Create symlinks to the deployed manual page folders, if applicable
543 if [ -d "$out/lib/node_modules/${packageName}/man" ]
546 for dir in "$out/lib/node_modules/${packageName}/man/"*
548 mkdir -p $out/share/man/$(basename "$dir")
551 ln -s $page $out/share/man/$(basename "$dir")
556 # Run post install hook, if provided
561 # default to Node.js' platforms
562 platforms = nodejs.meta.platforms;
566 # Builds a node environment (a node_modules folder and a set of binaries)
567 buildNodeDependencies =
576 , dontNpmInstall ? false
577 , bypassCache ? false
578 , reconstructLock ? false
580 , unpackPhase ? "true"
581 , buildPhase ? "true"
585 extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" ];
587 stdenv.mkDerivation ({
588 name = "node-dependencies-${name}${if version == null then "" else "-${version}"}";
590 buildInputs = [ tarWrapper python nodejs ]
591 ++ lib.optional (stdenv.hostPlatform.isLinux) pkgs.util-linux
592 ++ lib.optional (stdenv.hostPlatform.isDarwin) libtool
595 inherit dontStrip; # Stripping may fail a build for some package deployments
596 inherit dontNpmInstall unpackPhase buildPhase;
598 includeScript = includeDependencies { inherit dependencies; };
599 pinpointDependenciesScript = pinpointDependenciesOfPackage args;
601 passAsFile = [ "includeScript" "pinpointDependenciesScript" ];
604 source ${installPackage}
606 mkdir -p $out/${packageName}
607 cd $out/${packageName}
609 source $includeScriptPath
611 # Create fake package.json to make the npm commands work properly
612 cp ${src}/package.json .
613 chmod 644 package.json
614 ${lib.optionalString bypassCache ''
615 if [ -f ${src}/package-lock.json ]
617 cp ${src}/package-lock.json .
618 chmod 644 package-lock.json
622 # Go to the parent folder to make sure that all packages are pinpointed
624 ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
626 ${prepareAndInvokeNPM { inherit packageName bypassCache reconstructLock npmFlags production; }}
628 # Expose the executables that were installed
630 ${lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."}
632 mv ${packageName} lib
633 ln -s $out/lib/node_modules/.bin $out/bin
637 # Builds a development shell
647 , dontNpmInstall ? false
648 , bypassCache ? false
649 , reconstructLock ? false
651 , unpackPhase ? "true"
652 , buildPhase ? "true"
656 nodeDependencies = buildNodeDependencies args;
657 extraArgs = removeAttrs args [ "name" "dependencies" "buildInputs" "dontStrip" "dontNpmInstall" "unpackPhase" "buildPhase" ];
659 stdenv.mkDerivation ({
660 name = "node-shell-${name}${if version == null then "" else "-${version}"}";
662 buildInputs = [ python nodejs ] ++ lib.optional (stdenv.hostPlatform.isLinux) pkgs.util-linux ++ buildInputs;
665 cat > $out/bin/shell <<EOF
666 #! ${stdenv.shell} -e
670 chmod +x $out/bin/shell
673 # Provide the dependencies in a development shell through the NODE_PATH environment variable
674 inherit nodeDependencies;
675 shellHook = lib.optionalString (dependencies != []) ''
676 export NODE_PATH=${nodeDependencies}/lib/node_modules
677 export PATH="${nodeDependencies}/bin:$PATH"
682 buildNodeSourceDist = lib.makeOverridable buildNodeSourceDist;
683 buildNodePackage = lib.makeOverridable buildNodePackage;
684 buildNodeDependencies = lib.makeOverridable buildNodeDependencies;
685 buildNodeShell = lib.makeOverridable buildNodeShell;