module.exports={name:"yarn-plugin-nixify",factory:function(e){var t;return(()=>{"use strict";var n={d:(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},i={};n.r(i),n.d(i,{default:()=>B});const r=e("@yarnpkg/core"),o=e("clipanion");var a,s,l,c;function d(e,t,n,i,r){var o={};return Object.keys(i).forEach((function(e){o[e]=i[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=n.slice().reverse().reduce((function(n,i){return i(e,t,n)||n}),o),r&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(r):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}let u=(a=o.Command.String(),s=o.Command.Path("nixify","fetch-one"),l=class extends o.Command{constructor(...e){var t;super(...e),(t=c)&&Object.defineProperty(this,"locator",{enumerable:t.enumerable,configurable:t.configurable,writable:t.writable,value:t.initializer?t.initializer.call(this):void 0})}async execute(){const e=await r.Configuration.find(this.context.cwd,this.context.plugins),{project:t}=await r.Project.find(e,this.context.cwd),n=await r.Cache.find(e),i=e.makeFetcher();return(await r.StreamReport.start({configuration:e,stdout:this.context.stdout},(async e=>{const{locatorHash:o}=r.structUtils.parseLocator(this.locator,!0),a=t.originalPackages.get(o);a?await i.fetch(a,{checksums:t.storedChecksums,project:t,cache:n,fetcher:i,report:e}):e.reportError(0,"Invalid locator")}))).exitCode()}},c=d(l.prototype,"locator",[a],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return""}}),d(l.prototype,"execute",[s],Object.getOwnPropertyDescriptor(l.prototype,"execute"),l.prototype),l);const p=e("@yarnpkg/fslib"),h=e("crypto"),f=e("@yarnpkg/parsers");var g,m,b,v,y,x,w,P;function k(e,t,n,i){n&&Object.defineProperty(e,t,{enumerable:n.enumerable,configurable:n.configurable,writable:n.writable,value:n.initializer?n.initializer.call(i):void 0})}function $(e,t,n,i,r){var o={};return Object.keys(i).forEach((function(e){o[e]=i[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=n.slice().reverse().reduce((function(n,i){return i(e,t,n)||n}),o),r&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(r):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}let T=(g=o.Command.String(),m=o.Command.String(),b=o.Command.String(),v=o.Command.Path("nixify","inject-build"),y=class extends o.Command{constructor(...e){super(...e),k(this,"locator",x,this),k(this,"source",w,this),k(this,"installLocation",P,this)}async execute(){const e=await r.Configuration.find(this.context.cwd,this.context.plugins),{project:t}=await r.Project.find(e,this.context.cwd);return(await r.StreamReport.start({configuration:e,stdout:this.context.stdout},(async n=>{await t.resolveEverything({report:n,lockfileOnly:!0});const i=r.structUtils.parseLocator(this.locator,!0),o=t.storedPackages.get(i.locatorHash);if(!o)return void n.reportError(0,"Invalid locator");const a=p.ppath.join(t.cwd,this.installLocation);await p.xfs.mkdirpPromise(p.ppath.dirname(a)),await r.execUtils.execvp("cp",["-R",this.source,a],{cwd:t.cwd,strict:!0}),await r.execUtils.execvp("chmod",["-R","u+w",a],{cwd:t.cwd,strict:!0});const s=(0,h.createHash)("sha512");s.update(process.versions.node),e.triggerHook((e=>e.globalHashGeneration),t,(e=>{s.update("\0"),s.update(e)}));const l=s.digest("hex"),c=new Map,d=e=>{let n=c.get(e.locatorHash);if(void 0!==n)return n;const i=t.storedPackages.get(e.locatorHash);if(void 0===i)throw new Error("Assertion failed: The package should have been registered");const o=(0,h.createHash)("sha512");o.update(e.locatorHash),c.set(e.locatorHash,"");for(const e of i.dependencies.values()){const n=t.storedResolutions.get(e.descriptorHash);if(void 0===n)throw new Error(`Assertion failed: The resolution (${r.structUtils.prettyDescriptor(t.configuration,e)}) should have been registered`);const i=t.storedPackages.get(n);if(void 0===i)throw new Error("Assertion failed: The package should have been registered");o.update(d(i))}return n=o.digest("hex"),c.set(e.locatorHash,n),n},u=(0,h.createHash)("sha512").update(l).update(d(o)).update(a).digest("hex"),g=e.get("bstatePath"),m=p.xfs.existsSync(g)?(0,f.parseSyml)(await p.xfs.readFilePromise(g,"utf8")):{};m[o.locatorHash]=u,await p.xfs.writeFilePromise(g,(0,f.stringifySyml)(m))}))).exitCode()}},x=$(y.prototype,"locator",[g],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return""}}),w=$(y.prototype,"source",[m],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return""}}),P=$(y.prototype,"installLocation",[b],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return""}}),$(y.prototype,"execute",[v],Object.getOwnPropertyDescriptor(y.prototype,"execute"),y.prototype),y);const j=e("@yarnpkg/plugin-pnp"),E=JSON.stringify,O=(e,t,n=!1)=>t.split("\n").map((t=>t||n?e+t:t)).join("\n"),C=(e,t)=>{let n=e;for(const[e,i]of Object.entries(t))if("string"==typeof i&&(n=n.replace(`@@${e}@@`,i)),"boolean"==typeof i){const t=n.split("\n"),r=t.indexOf(`#@@ IF ${e}`),o=t.indexOf(`#@@ ENDIF ${e}`);-1!==r&&o>r&&(i?(t.splice(o,1),t.splice(r,1)):t.splice(r,o-r+1),n=t.join("\n"))}return n};var A,S,N,I;function H(e,t,n,i,r){var o={};return Object.keys(i).forEach((function(e){o[e]=i[e]})),o.enumerable=!!o.enumerable,o.configurable=!!o.configurable,("value"in o||o.initializer)&&(o.writable=!0),o=n.slice().reverse().reduce((function(n,i){return i(e,t,n)||n}),o),r&&void 0!==o.initializer&&(o.value=o.initializer?o.initializer.call(r):void 0,o.initializer=void 0),void 0===o.initializer&&(Object.defineProperty(e,t,o),o=null),o}const D=["pnp","node-modules"];let L=(A=o.Command.String(),S=o.Command.Path("nixify","install-bin"),N=class extends o.Command{constructor(...e){var t;super(...e),(t=I)&&Object.defineProperty(this,"binDir",{enumerable:t.enumerable,configurable:t.configurable,writable:t.writable,value:t.initializer?t.initializer.call(this):void 0})}async execute(){const e=await r.Configuration.find(this.context.cwd,this.context.plugins),{project:t,workspace:n}=await r.Project.find(e,this.context.cwd);return(await r.StreamReport.start({configuration:e,stdout:this.context.stdout},(async i=>{if(!n||0===n.manifest.bin.size)return;let r=e.get("nodeLinker");D.includes(r)||(r="node-modules",i.reportWarning(0,`The nodeLinker ${r} is not supported - executables may have trouble finding dependencies`));const o=p.npath.toPortablePath(this.binDir),a=(0,j.getPnpPath)(t).main;for(const[e,i]of n.manifest.bin){const n=p.ppath.join(o,e),s=p.ppath.join(t.cwd,p.npath.toPortablePath(i));let l;switch(r){case"pnp":l=C("#!/bin/sh\nexport NODE_OPTIONS=\"--require @@PNP_PATH@@\"\nexec '@@NODE_PATH@@' '@@SCRIPT_PATH@@' \"$@\"\n",{NODE_PATH:process.execPath,PNP_PATH:a,SCRIPT_PATH:s});break;case"node-modules":l=C("#!/bin/sh\nexec '@@NODE_PATH@@' '@@SCRIPT_PATH@@' \"$@\"\n",{NODE_PATH:process.execPath,SCRIPT_PATH:s});break;default:throw Error(`Assertion failed: Invalid nodeLinker ${r}`)}await p.xfs.writeFilePromise(n,l),await p.xfs.chmodPromise(n,493)}}))).exitCode()}},I=H(N.prototype,"binDir",[A],{configurable:!0,enumerable:!0,writable:!0,initializer:function(){return""}}),H(N.prototype,"execute",[S],Object.getOwnPropertyDescriptor(N.prototype,"execute"),N.prototype),N);const _=e("@yarnpkg/plugin-patch"),z=(e,t)=>(0,h.createHash)(e).update(t).digest(),F=(e,t,n,i="/nix/store")=>{const r=n.toString("hex"),o=z("sha256",`fixed:out:${t}:${r}:`).toString("hex"),a=(e=>{let t="",n=[...e].reverse().map((e=>e.toString(2).padStart(8,"0"))).join("");for(;n;)t+="0123456789abcdfghijklmnpqrsvwxyz"[parseInt(n.slice(0,5),2)],n=n.slice(5);return t})(((e,t)=>{const n=Buffer.alloc(20);for(let t=0;te.replace(/^\.+/,"").replace(/[^a-zA-Z0-9+._?=-]+/g,"-").slice(0,207)||"unknown",U=e("os"),B={commands:[u,T,L],hooks:{afterAllInstalled:async(e,t)=>{!1!==t.persistProject&&e.configuration.get("enableNixify")&&await(async(e,t,n)=>{const{configuration:i,cwd:o}=e,a=await p.xfs.realpathPromise(p.npath.toPortablePath((0,U.tmpdir)()));if(e.cwd.startsWith(a))return void n.reportInfo(0,`Skipping Nixify, because ${e.cwd} appears to be a temporary directory`);const s=i.get("yarnPath");let l=p.ppath.relative(o,s);l.startsWith("../")&&(l=s,n.reportWarning(0,`The Yarn path ${s} is outside the project - it may not be reachable by the Nix build`));const c=i.get("cacheFolder");let d=p.ppath.relative(o,c);d.startsWith("../")&&(d=c,n.reportWarning(0,`The cache folder ${c} is outside the project - it may not be reachable by the Nix build`));for(const e of i.sources.values())e.startsWith("<")||p.ppath.relative(o,e).startsWith("../")&&n.reportWarning(0,`The config file ${e} is outside the project - it may not be reachable by the Nix build`);const u=i.get("nixExprPath"),h=i.get("lockfileFilename"),g=p.ppath.relative(p.ppath.dirname(u),h),m=p.ppath.relative(p.ppath.dirname(u),l),b=new Map,v=new Set(await p.xfs.readdirPromise(t.cwd));for(const n of e.storedPackages.values()){const{locatorHash:i}=n,o=e.storedChecksums.get(i);if(!o)continue;const a=t.getLocatorPath(n,o);if(!a)continue;const s=p.ppath.basename(a);if(!v.has(s))continue;const l=r.structUtils.stringifyLocator(n),c=o.split("/").pop();b.set(l,{filename:s,sha512:c})}let y="cacheEntries = {\n";for(const[e,t]of b)y+=`${E(e)} = { ${[`filename = ${E(t.filename)};`,`sha512 = ${E(t.sha512)};`].join(" ")} };\n`;y+="};";const x=i.get("isolatedNixBuilds");let w=new Set,P=[],k=[];const $=i.get("nodeLinker"),T=i.get("pnpUnpluggedFolder"),j=i.get("bstatePath"),A=p.xfs.existsSync(j)?(0,f.parseSyml)(await p.xfs.readFilePromise(j,"utf8")):{},S=(t,n=new Set)=>{const i=r.structUtils.stringifyLocator(t);if(b.has(i)&&n.add(i),r.structUtils.isVirtualLocator(t)){const i=e.storedPackages.get(r.structUtils.devirtualizeLocator(t).locatorHash);if(!i)throw Error("Assertion failed: The locator should have been registered");S(i,n)}if(t.reference.startsWith("patch:")){const i=e.storedPackages.get(_.patchUtils.parseLocator(t).sourceLocator.locatorHash);if(!i)throw Error("Assertion failed: The locator should have been registered");S(i,n)}for(const i of t.dependencies.values()){const t=e.storedResolutions.get(i.descriptorHash);if(!t)throw Error("Assertion failed: The descriptor should have been registered");const r=e.storedPackages.get(t);if(!r)throw Error("Assertion failed: The locator should have been registered");S(r,n)}return n};for(const t of Object.keys(A)){const n=e.storedPackages.get(t);if(!n)throw Error("Assertion failed: The locator should have been registered");if(!x.includes(n.name))continue;let i;switch($){case"pnp":i=p.ppath.relative(e.cwd,p.ppath.join(T,r.structUtils.slugifyLocator(n),r.structUtils.getIdentVendorPath(n)));break;default:throw Error(`The nodeLinker ${$} is not supported for isolated Nix builds`)}let o=n;if(r.structUtils.isVirtualLocator(o)){const{locatorHash:t}=r.structUtils.devirtualizeLocator(o),n=e.storedPackages.get(t);if(!n)throw Error("Assertion failed: The locator should have been registered");o=n}const a=r.structUtils.stringifyLocator(o),s=r.structUtils.stringifyLocator(n),l=`isolated.${E(a)}`;if(!w.has(o)){w.add(o);const e=[...S(n)].sort().map((e=>`${E(e)}\n`)).join(""),t=`override${N=n.name,N.split(/[^a-zA-Z0-9]+/g).filter((e=>e)).map((e=>{return(t=e).slice(0,1).toUpperCase()+t.slice(1);var t})).join("")}Attrs`;k.push(`${l} = optionalOverride (args.${t} or null) (mkIsolatedBuild { ${[`pname = ${E(n.name)};`,`version = ${E(n.version)};`,`locators = [\n${e}];`].join(" ")} });`)}0===P.length&&P.push("# Copy in isolated builds."),P.push(`echo 'injecting build for ${n.name}'`,"yarn nixify inject-build \\",` ${E(s)} \\`,` \${${l}} \\`,` ${E(i)}`)}var N;P.length>0&&P.push("echo 'running yarn install'");const I=e.topLevelWorkspace.manifest.name,H=I?r.structUtils.stringifyIdent(I):"workspace",D=C("# This file is generated by running \"yarn install\" inside your project.\n# Manual changes might be lost - proceed with caution!\n\n{ lib, nodejs, stdenv, fetchurl, writeText }:\n{ src, overrideAttrs ? null, ... } @ args:\n\nlet\n\n yarnPath = ./@@YARN_PATH@@;\n lockfile = ./@@LOCKFILE@@;\n cacheFolder = @@CACHE_FOLDER@@;\n\n # Call overrideAttrs on a derivation if a function is provided.\n optionalOverride = fn: drv:\n if fn == null then drv else drv.overrideAttrs fn;\n\n # Common attributes between Yarn derivations.\n drvCommon = {\n # Make sure the build uses the right Node.js version everywhere.\n buildInputs = [ nodejs ];\n # Tell node-gyp to use the provided Node.js headers for native code builds.\n npm_config_nodedir = nodejs;\n # Tell node-pre-gyp to never fetch binaries / always build from source.\n npm_config_build_from_source = \"true\";\n # Defines the shell alias to run Yarn.\n postHook = ''\n yarn() {\n CI=1 node \"${yarnPath}\" \"$@\"\n }\n '';\n };\n\n # Create derivations for fetching dependencies.\n cacheDrvs = let\n builder = builtins.toFile \"builder.sh\" ''\n source $stdenv/setup\n cd \"$src\"\n HOME=\"$TMP\" yarn_cache_folder=\"$TMP\" CI=1 \\\n node '${yarnPath}' nixify fetch-one $locator\n mv \"$TMP/$outputFilename\" $out\n '';\n in lib.mapAttrs (locator: { filename, sha512 }: stdenv.mkDerivation {\n inherit src builder locator;\n name = lib.strings.sanitizeDerivationName locator;\n buildInputs = [ nodejs ];\n outputFilename = filename;\n outputHashMode = \"flat\";\n outputHashAlgo = \"sha512\";\n outputHash = sha512;\n }) cacheEntries;\n\n # Create a shell snippet to copy dependencies from a list of derivations.\n mkCacheBuilderForDrvs = drvs:\n writeText \"collect-cache.sh\" (lib.concatMapStrings (drv: ''\n cp ${drv} '${drv.outputFilename}'\n '') drvs);\n\n#@@ IF NEED_ISOLATED_BUILD_SUPPRORT\n # Create a shell snippet to copy dependencies from a list of locators.\n mkCacheBuilderForLocators = let\n pickCacheDrvs = map (locator: cacheDrvs.${locator});\n in locators:\n mkCacheBuilderForDrvs (pickCacheDrvs locators);\n\n # Create a derivation that builds a node-pre-gyp module in isolation.\n mkIsolatedBuild = { pname, version, locators }: stdenv.mkDerivation (drvCommon // {\n inherit pname version;\n phases = [ \"buildPhase\" \"installPhase\" ];\n\n buildPhase = ''\n mkdir -p .yarn/cache\n pushd .yarn/cache > /dev/null\n source ${mkCacheBuilderForLocators locators}\n popd > /dev/null\n\n echo '{ \"dependencies\": { \"${pname}\": \"${version}\" } }' > package.json\n install -m 0600 ${lockfile} ./yarn.lock\n yarn --immutable-cache\n '';\n\n installPhase = ''\n unplugged=( .yarn/unplugged/${pname}-*/node_modules/* )\n if [[ ! -e \"''${unplugged[@]}\" ]]; then\n echo >&2 \"Could not find the unplugged path for ${pname}\"\n exit 1\n fi\n\n mv \"$unplugged\" $out\n '';\n });\n#@@ ENDIF NEED_ISOLATED_BUILD_SUPPRORT\n\n # Main project derivation.\n project = stdenv.mkDerivation (drvCommon // {\n inherit src;\n name = @@PROJECT_NAME@@;\n # Disable Nixify plugin to save on some unnecessary processing.\n yarn_enable_nixify = \"false\";\n\n configurePhase = ''\n runHook preConfigure\n\n # Copy over the Yarn cache.\n rm -fr '${cacheFolder}'\n mkdir -p '${cacheFolder}'\n pushd '${cacheFolder}' > /dev/null\n source ${mkCacheBuilderForDrvs (lib.attrValues cacheDrvs)}\n popd > /dev/null\n\n@@ISOLATED_INTEGRATION@@\n\n # Run normal Yarn install to complete dependency installation.\n yarn install --immutable --immutable-cache\n\n runHook postConfigure\n '';\n\n buildPhase = ''\n runHook preBuild\n runHook postBuild\n '';\n\n installPhase = ''\n runHook preInstall\n\n mkdir -p $out/libexec $out/bin\n\n # Move the entire project to the output directory.\n mv $PWD \"$out/libexec/$sourceRoot\"\n cd \"$out/libexec/$sourceRoot\"\n\n # Invoke a plugin internal command to setup binaries.\n yarn nixify install-bin $out/bin\n\n runHook postInstall\n '';\n\n passthru = {\n inherit nodejs;\n };\n });\n\n@@CACHE_ENTRIES@@\n@@ISOLATED@@\nin optionalOverride overrideAttrs project\n",{PROJECT_NAME:E(H),YARN_PATH:m,LOCKFILE:g,CACHE_FOLDER:E(d),CACHE_ENTRIES:y,ISOLATED:k.join("\n"),ISOLATED_INTEGRATION:O(" ",P.join("\n")),NEED_ISOLATED_BUILD_SUPPRORT:P.length>0});if(await p.xfs.writeFilePromise(i.get("nixExprPath"),D),i.get("generateDefaultNix")){const e=p.ppath.join(o,"default.nix"),t=p.ppath.join(o,"flake.nix");p.xfs.existsSync(e)||p.xfs.existsSync(t)||(await p.xfs.writeFilePromise(e,"# This is a minimal `default.nix` by yarn-plugin-nixify. You can customize it\n# as needed, it will not be overwritten by the plugin.\n\n{ pkgs ? import { } }:\n\npkgs.callPackage ./yarn-project.nix { } { src = ./.; }\n"),n.reportInfo(0,"A minimal default.nix was created. You may want to customize it."))}i.get("enableNixPreload")&&p.xfs.existsSync(p.npath.toPortablePath("/nix/store"))&&await p.xfs.mktempPromise((async i=>{const o=[];for(const[e,{filename:n,sha512:r}]of b.entries()){const a=R(e),s=Buffer.from(r,"hex"),l=F(a,"sha512",s);if(!p.xfs.existsSync(l)){const e=p.ppath.join(i,r.slice(0,7));await p.xfs.mkdirPromise(e);const s=p.ppath.join(t.cwd,n),l=p.ppath.join(e,a);await p.xfs.copyFilePromise(s,l),o.push(l)}}try{const t=o.length;for(;0!==o.length;){const t=o.splice(0,100);await r.execUtils.execvp("nix-store",["--add-fixed","sha512",...t],{cwd:e.cwd,strict:!0})}0!==t&&n.reportInfo(0,`Preloaded ${t} packages into the Nix store`)}catch(e){if("ENOENT"!==e.code)throw e}}))})(e,t.cache,t.report)}},configuration:{enableNixify:{description:"If false, disables the Nixify plugin hook that generates Nix expressions",type:r.SettingsType.BOOLEAN,default:!0},nixExprPath:{description:"Path of the file where the project Nix expression will be written to",type:r.SettingsType.ABSOLUTE_PATH,default:"./yarn-project.nix"},generateDefaultNix:{description:"If true, a default.nix will be generated if it does not exist",type:r.SettingsType.BOOLEAN,default:!0},enableNixPreload:{description:"If true, cached packages will be preloaded into the Nix store",type:r.SettingsType.BOOLEAN,default:!0},isolatedNixBuilds:{description:"Dependencies with a build step that can be built in an isolated derivation",type:r.SettingsType.STRING,default:[],isArray:!0}}};t=i})(),t}};