ng-packagr 22.1.0-next.2 → 22.1.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ng-packagr",
3
- "version": "22.1.0-next.2",
3
+ "version": "22.1.0-next.3",
4
4
  "description": "Compile and package Angular libraries in Angular Package Format (APF)",
5
5
  "keywords": [
6
6
  "apf",
@@ -57,7 +57,7 @@
57
57
  "rollup": "^4.24.0"
58
58
  },
59
59
  "peerDependencies": {
60
- "@angular/compiler-cli": "^22.0.0 || ^22.1.0-next.0",
60
+ "@angular/compiler-cli": "^22.1.0-next",
61
61
  "tailwindcss": "^2.0.0 || ^3.0.0 || ^4.0.0",
62
62
  "tslib": "^2.3.0",
63
63
  "typescript": ">=6.0 <6.1"
@@ -75,7 +75,18 @@ const writePackageTransform = (options) => (0, transform_1.transformFromPromise)
75
75
  spinner.start('Writing package manifest');
76
76
  if (!options.watch) {
77
77
  const primary = ngPackageNode.data.primary;
78
- await (0, fs_1.writeFile)(path.join(primary.destinationPath, '.npmignore'), `# Nested package.json's are only needed for development.\n**/package.json`);
78
+ const nestedPackageJsons = [];
79
+ // Secondary entry-points package.json
80
+ for (const { data } of entryPoints) {
81
+ if (!data.entryPoint.isSecondaryEntryPoint) {
82
+ continue;
83
+ }
84
+ const packageJsonPath = (0, path_1.ensureUnixPath)(path.join(path.relative(primary.destinationPath, data.entryPoint.destinationPath), 'package.json'));
85
+ nestedPackageJsons.push(packageJsonPath);
86
+ }
87
+ if (nestedPackageJsons.length) {
88
+ await (0, fs_1.writeFile)(path.join(primary.destinationPath, '.npmignore'), `# Nested package.json's are only needed for development.\n${nestedPackageJsons.join('\n')}`);
89
+ }
79
90
  }
80
91
  const { compilationMode } = entryPoint.data.tsConfig.options;
81
92
  await writePackageJson(ngEntryPoint, ngPackage, {
@@ -1 +1 @@
1
- {"version":3,"file":"write-package.transform.js","sourceRo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C,CAAC,EAAE,CAAC;YAC3C,GAAG,CAAC,KAAK,CAAC,cAAc,GAAG,mBAAmB,QAAQ,GAAG,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,IAAI,CACV,cAAM,CAAC,MAAM,CACX,mCAAmC,QAAQ,gDAAgD,GAAG,GAAG;gBAC/F,4CAA4C,QAAQ,IAAI,CAC3D,CACF,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,cAAc,GAAG,4EAA4E,CAAC,CAAC;QACjH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import ora, { type Ora } from 'ora';\nimport * as path from 'path';\nimport { glob } from 'tinyglobby';\nimport { AssetPattern } from '../../../ng-package.schema';\nimport { BuildGraph } from '../../graph/build-graph';\nimport { Node } from '../../graph/node';\nimport { isInProgress } from '../../graph/select';\nimport { transformFromPromise } from '../../graph/transform';\nimport { colors } from '../../utils/color';\nimport { copyFile, mkdir, rmdir, stat, writeFile } from '../../utils/fs';\nimport * as log from '../../utils/log';\nimport { ConditionalExport, generatePackageExports, generateWatchVersion } from '../../utils/package-json';\nimport { ensureUnixPath } from '../../utils/path';\nimport { EntryPointNode, PackageNode, fileUrl, findPackageNode, isEntryPoint } from '../nodes';\nimport { NgPackagrOptions } from '../options.di';\nimport { NgPackage } from '../package';\nimport { NgEntryPoint } from './entry-point';\n\ntype CompilationMode = 'partial' | 'full' | undefined;\n\nexport const writePackageTransform = (options: NgPackagrOptions) =>\n transformFromPromise(async graph => {\n const spinner = ora({ hideCursor: false, discardStdin: false });\n const entryPoints = graph.filter(isEntryPoint);\n const entryPoint = entryPoints.find(isInProgress);\n const ngEntryPoint: NgEntryPoint = entryPoint.data.entryPoint;\n const ngPackageNode = findPackageNode(graph);\n const ngPackage = ngPackageNode.data;\n const { destinationFiles } = entryPoint.data;\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n spinner.start('Copying assets');\n try {\n await copyAssets(graph, entryPoint, ngPackageNode, entryPoints);\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n }\n\n // 6. WRITE PACKAGE.JSON\n const relativeUnixFromDestPath = (filePath: string) =>\n ensureUnixPath(path.relative(ngEntryPoint.destinationPath, filePath));\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n try {\n spinner.start('Writing package manifest');\n if (!options.watch) {\n const primary = ngPackageNode.data.primary;\n await writeFile(\n path.join(primary.destinationPath, '.npmignore'),\n `# Nested package.json's are only needed for development.\\n**/package.json`,\n );\n }\n\n const { compilationMode } = entryPoint.data.tsConfig.options;\n\n await writePackageJson(\n ngEntryPoint,\n ngPackage,\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n exports: generatePackageExports(ngEntryPoint, entryPoints),\n // webpack v4+ specific flag to enable advanced optimizations and code splitting\n sideEffects: ngEntryPoint.packageJson.sideEffects ?? false,\n },\n !!options.watch,\n compilationMode as CompilationMode,\n spinner,\n );\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n } else if (ngEntryPoint.isSecondaryEntryPoint) {\n // Write a package.json in each secondary entry-point\n // This is need for esbuild to secondary entry-points in dist correctly.\n await mkdir(ngEntryPoint.destinationPath, { recursive: true });\n await writeFile(\n path.join(ngEntryPoint.destinationPath, 'package.json'),\n JSON.stringify(\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n },\n undefined,\n 2,\n ),\n );\n }\n\n spinner.succeed(`Built ${ngEntryPoint.moduleId}`);\n });\n\ntype AssetEntry = Exclude<AssetPattern, string>;\n\nasync function copyAssets(\n graph: BuildGraph,\n entryPointNode: EntryPointNode,\n ngPackageNode: PackageNode,\n entryPoints: EntryPointNode[],\n): Promise<void> {\n const ngPackage = ngPackageNode.data;\n const globsForceIgnored: string[] = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db', `${ngPackage.dest}/**`];\n const defaultAssets: AssetEntry[] = [\n { glob: 'LICENSE', input: '/', output: '/' },\n ...entryPoints.map(({ data }) => {\n const subpath = data.entryPoint.destinationFiles.directory || '/';\n\n return { glob: 'README.md', input: subpath, output: subpath };\n }),\n ];\n\n const assets: AssetEntry[] = [];\n for (const assetPath of [...ngPackage.assets, ...defaultAssets]) {\n let asset: AssetEntry;\n if (typeof assetPath === 'object') {\n asset = { ...assetPath };\n } else {\n const [isDir, isFile] = await stat(path.join(ngPackage.src, assetPath))\n .then(stats => [stats.isDirectory(), stats.isFile()])\n .catch(() => [false, false]);\n if (isDir) {\n asset = { glob: '**/*', input: assetPath, output: assetPath };\n } else if (isFile) {\n // filenames are their own glob\n asset = { glob: path.basename(assetPath), input: path.dirname(assetPath), output: path.dirname(assetPath) };\n } else {\n asset = { glob: assetPath, input: '/', output: '/' };\n }\n }\n\n asset.input = path.join(ngPackage.src, asset.input);\n asset.output = path.join(ngPackage.dest, asset.output);\n\n const isAncestorPath = (target: string, datum: string) => path.relative(datum, target).startsWith('..');\n if (isAncestorPath(asset.input, ngPackage.src)) {\n throw new Error('Cannot read assets from a location outside of the project root.');\n }\n if (isAncestorPath(asset.output, ngPackage.dest)) {\n throw new Error('Cannot write assets to a location outside of the output path.');\n }\n\n assets.push(asset);\n }\n\n for (const asset of assets) {\n const filePaths = await glob(asset.glob, {\n cwd: asset.input,\n ignore: [...(asset.ignore ?? []), ...globsForceIgnored],\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: asset.followSymlinks,\n });\n for (const filePath of filePaths) {\n const fileSrcFullPath = path.join(asset.input, filePath);\n const fileDestFullPath = path.join(asset.output, filePath);\n const nodeUri = fileUrl(ensureUnixPath(fileSrcFullPath));\n let node = graph.get(nodeUri);\n if (!node) {\n node = new Node(nodeUri);\n graph.put(node);\n }\n entryPointNode.dependsOn(node);\n await copyFile(fileSrcFullPath, fileDestFullPath);\n }\n }\n}\n\n/**\n * Creates and writes a `package.json` file of the entry point used by the `node_module`\n * resolution strategies.\n *\n * #### Example\n *\n * A consumer of the entry point depends on it by `import {..} from '@my/module/id';`.\n * The module id `@my/module/id` will be resolved to the `package.json` file that is written by\n * this build step.\n * The properties `main`, `module`, `typings` (and so on) in the `package.json` point to the\n * flattened JavaScript bundles, type definitions, (...).\n *\n * @param entryPoint An entry point of an Angular package / library\n * @param additionalProperties Additional properties, e.g. binary artefacts (bundle files), to merge into `package.json`\n */\nasync function writePackageJson(\n entryPoint: NgEntryPoint,\n pkg: NgPackage,\n additionalProperties: { [key: string]: string | boolean | string[] | ConditionalExport },\n isWatchMode: boolean,\n compilationMode: CompilationMode,\n spinner: Ora,\n): Promise<void> {\n log.debug('Writing package.json');\n\n // set additional properties\n const packageJson = { ...entryPoint.packageJson, ...additionalProperties };\n packageJson.type ??= 'module';\n\n // read tslib version from `@angular/compiler` so that our tslib\n // version at least matches that of angular if we use require('tslib').version\n // it will get what installed and not the minimum version nor if it is a `~` or `^`\n // this is only required for primary\n if (isWatchMode) {\n // Needed because of Webpack's 5 `cachemanagedpaths`\n // https://github.com/angular/angular-cli/issues/20962\n packageJson.version = generateWatchVersion();\n }\n\n if (!packageJson.peerDependencies?.tslib && !packageJson.dependencies?.tslib) {\n const {\n peerDependencies: angularPeerDependencies = {},\n dependencies: angularDependencies = {},\n } = require('@angular/compiler/package.json');\n const tsLibVersion = angularPeerDependencies.tslib || angularDependencies.tslib;\n\n if (tsLibVersion) {\n packageJson.dependencies = { ...packageJson.dependencies, tslib: tsLibVersion };\n }\n } else if (packageJson.peerDependencies?.tslib) {\n spinner.warn(\n colors.yellow(\n `'tslib' is no longer recommended to be used as a 'peerDependencies'. Moving it to 'dependencies'.`,\n ),\n );\n packageJson.dependencies = { ...(packageJson.dependencies || {}), tslib: packageJson.peerDependencies.tslib };\n\n delete packageJson.peerDependencies.tslib;\n }\n\n // Verify non-peerDependencies as they can easily lead to duplicate installs or version conflicts\n // in the node_modules folder of an application\n const allowedList = pkg.allowedNonPeerDependencies.map(value => new RegExp(value));\n try {\n checkNonPeerDependencies(packageJson, 'dependencies', allowedList, spinner);\n } catch (e) {\n await rmdir(entryPoint.destinationPath, { recursive: true });\n throw e;\n }\n\n // Removes scripts from package.json after build\n if (packageJson.scripts) {\n if (pkg.keepLifecycleScripts !== true) {\n spinner.info(`Removing scripts section in package.json as it's considered a potential security vulnerability.`);\n delete packageJson.scripts;\n } else {\n spinner.warn(\n colors.yellow(\n `You enabled keepLifecycleScripts explicitly. The scripts section in package.json will be published to npm.`,\n ),\n );\n }\n }\n\n if (compilationMode !== 'partial') {\n const scripts = packageJson.scripts || (packageJson.scripts = {});\n scripts.prepublishOnly =\n 'node --eval \"console.error(\\'' +\n 'ERROR: Trying to publish a package that has been compiled in full compilation mode. This is not allowed.\\\\n' +\n 'Please delete and rebuild the package with partial compilation mode, before attempting to publish.\\\\n' +\n '\\')\" ' +\n '&& exit 1';\n }\n\n // keep the dist package.json clean\n // this will not throw if ngPackage field does not exist\n delete packageJson.ngPackage;\n\n const packageJsonPropertiesToDelete = [\n 'stylelint',\n 'prettier',\n 'browserslist',\n 'devDependencies',\n 'jest',\n 'workspaces',\n 'husky',\n ];\n\n for (const prop of packageJsonPropertiesToDelete) {\n if (prop in packageJson) {\n delete packageJson[prop];\n spinner.info(`Removing ${prop} section in package.json.`);\n }\n }\n\n packageJson.name = entryPoint.moduleId;\n await writeFile(path.join(entryPoint.destinationPath, 'package.json'), JSON.stringify(packageJson, undefined, 2));\n}\n\nfunction checkNonPeerDependencies(\n packageJson: Record<string, unknown>,\n property: string,\n allowed: RegExp[],\n spinner: Ora,\n) {\n if (!packageJson[property]) {\n return;\n }\n\n for (const dep of Object.keys(packageJson[property])) {\n if (allowed.some(regex => regex.test(dep))) {\n log.debug(`Dependency ${dep} is allowed in '${property}'`);\n } else {\n spinner.warn(\n colors.yellow(\n `Distributing npm packages with '${property}' is not recommended. Please consider adding ${dep} ` +\n `to 'peerDependencies' or remove it from '${property}'.`,\n ),\n );\n throw new Error(`Dependency ${dep} must be explicitly allowed using the \"allowedNonPeerDependencies\" option.`);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"write-package.transform.js","sourceRoot":"","sources":["../../../../../src/lib/ng-package/entry-point/write-package.transform.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8CAAoC;AACpC,2CAA6B;AAC7B,2CAAkC;AAGlC,2CAAwC;AACxC,+CAAkD;AAClD,qDAA6D;AAC7D,6CAA2C;AAC3C,uCAAyE;AACzE,qDAAuC;AACvC,2DAA2G;AAC3G,2CAAkD;AAClD,oCAA+F;AAOxF,MAAM,qBAAqB,GAAG,CAAC,OAAyB,EAAE,EAAE,CACjE,IAAA,gCAAoB,EAAC,KAAK,EAAC,KAAK,EAAC,EAAE;IACjC,MAAM,OAAO,GAAG,IAAA,aAAG,EAAC,EAAE,UAAU,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;IAChE,MAAM,WAAW,GAAG,KAAK,CAAC,MAAM,CAAC,oBAAY,CAAC,CAAC;IAC/C,MAAM,UAAU,GAAG,WAAW,CAAC,IAAI,CAAC,qBAAY,CAAC,CAAC;IAClD,MAAM,YAAY,GAAiB,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC;IAC9D,MAAM,aAAa,GAAG,IAAA,uBAAe,EAAC,KAAK,CAAC,CAAC;IAC7C,MAAM,SAAS,GAAG,aAAa,CAAC,IAAI,CAAC;IACrC,MAAM,EAAE,gBAAgB,EAAE,GAAG,UAAU,CAAC,IAAI,CAAC;IAE7C,IAAI,CAAC,YAAY,CAAC,qBAAqB,EAAE,CAAC;QACxC,OAAO,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;QAChC,IAAI,CAAC;YACH,MAAM,UAAU,CAAC,KAAK,EAAE,UAAU,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC;QAClE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,IAAI,EAAE,CAAC;YACf,MAA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AY,IAAI,2BAA2B,CAAC,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,WAAW,CAAC,IAAI,GAAG,UAAU,CAAC,QAAQ,CAAC;IACvC,MAAM,IAAA,cAAS,EAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,eAAe,EAAE,cAAc,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC;AACpH,CAAC;AAED,SAAS,wBAAwB,CAC/B,WAAoC,EACpC,QAAgB,EAChB,OAAiB,EACjB,OAAY;IAEZ,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC3B,OAAO;IACT,CAAC;IAED,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC;QACrD,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;YAC3C,GAAG,CAAC,KAAK,CAAC,cAAc,GAAG,mBAAmB,QAAQ,GAAG,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,IAAI,CACV,cAAM,CAAC,MAAM,CACX,mCAAmC,QAAQ,gDAAgD,GAAG,GAAG;gBAC/F,4CAA4C,QAAQ,IAAI,CAC3D,CACF,CAAC;YACF,MAAM,IAAI,KAAK,CAAC,cAAc,GAAG,4EAA4E,CAAC,CAAC;QACjH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import ora, { type Ora } from 'ora';\nimport * as path from 'path';\nimport { glob } from 'tinyglobby';\nimport { AssetPattern } from '../../../ng-package.schema';\nimport { BuildGraph } from '../../graph/build-graph';\nimport { Node } from '../../graph/node';\nimport { isInProgress } from '../../graph/select';\nimport { transformFromPromise } from '../../graph/transform';\nimport { colors } from '../../utils/color';\nimport { copyFile, mkdir, rmdir, stat, writeFile } from '../../utils/fs';\nimport * as log from '../../utils/log';\nimport { ConditionalExport, generatePackageExports, generateWatchVersion } from '../../utils/package-json';\nimport { ensureUnixPath } from '../../utils/path';\nimport { EntryPointNode, PackageNode, fileUrl, findPackageNode, isEntryPoint } from '../nodes';\nimport { NgPackagrOptions } from '../options.di';\nimport { NgPackage } from '../package';\nimport { NgEntryPoint } from './entry-point';\n\ntype CompilationMode = 'partial' | 'full' | undefined;\n\nexport const writePackageTransform = (options: NgPackagrOptions) =>\n transformFromPromise(async graph => {\n const spinner = ora({ hideCursor: false, discardStdin: false });\n const entryPoints = graph.filter(isEntryPoint);\n const entryPoint = entryPoints.find(isInProgress);\n const ngEntryPoint: NgEntryPoint = entryPoint.data.entryPoint;\n const ngPackageNode = findPackageNode(graph);\n const ngPackage = ngPackageNode.data;\n const { destinationFiles } = entryPoint.data;\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n spinner.start('Copying assets');\n try {\n await copyAssets(graph, entryPoint, ngPackageNode, entryPoints);\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n }\n\n // 6. WRITE PACKAGE.JSON\n const relativeUnixFromDestPath = (filePath: string) =>\n ensureUnixPath(path.relative(ngEntryPoint.destinationPath, filePath));\n\n if (!ngEntryPoint.isSecondaryEntryPoint) {\n try {\n spinner.start('Writing package manifest');\n if (!options.watch) {\n const primary = ngPackageNode.data.primary;\n\n const nestedPackageJsons: string[] = [];\n // Secondary entry-points package.json\n for (const { data } of entryPoints) {\n if (!data.entryPoint.isSecondaryEntryPoint) {\n continue;\n }\n\n const packageJsonPath = ensureUnixPath(\n path.join(path.relative(primary.destinationPath, data.entryPoint.destinationPath), 'package.json'),\n );\n nestedPackageJsons.push(packageJsonPath);\n }\n\n if (nestedPackageJsons.length) {\n await writeFile(\n path.join(primary.destinationPath, '.npmignore'),\n `# Nested package.json's are only needed for development.\\n${nestedPackageJsons.join('\\n')}`,\n );\n }\n }\n\n const { compilationMode } = entryPoint.data.tsConfig.options;\n\n await writePackageJson(\n ngEntryPoint,\n ngPackage,\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n exports: generatePackageExports(ngEntryPoint, entryPoints),\n // webpack v4+ specific flag to enable advanced optimizations and code splitting\n sideEffects: ngEntryPoint.packageJson.sideEffects ?? false,\n },\n !!options.watch,\n compilationMode as CompilationMode,\n spinner,\n );\n } catch (error) {\n spinner.fail();\n throw error;\n }\n spinner.succeed();\n } else if (ngEntryPoint.isSecondaryEntryPoint) {\n // Write a package.json in each secondary entry-point\n // This is need for esbuild to secondary entry-points in dist correctly.\n await mkdir(ngEntryPoint.destinationPath, { recursive: true });\n await writeFile(\n path.join(ngEntryPoint.destinationPath, 'package.json'),\n JSON.stringify(\n {\n module: relativeUnixFromDestPath(destinationFiles.fesm2022),\n typings: relativeUnixFromDestPath(destinationFiles.declarationsBundled),\n },\n undefined,\n 2,\n ),\n );\n }\n\n spinner.succeed(`Built ${ngEntryPoint.moduleId}`);\n });\n\ntype AssetEntry = Exclude<AssetPattern, string>;\n\nasync function copyAssets(\n graph: BuildGraph,\n entryPointNode: EntryPointNode,\n ngPackageNode: PackageNode,\n entryPoints: EntryPointNode[],\n): Promise<void> {\n const ngPackage = ngPackageNode.data;\n const globsForceIgnored: string[] = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db', `${ngPackage.dest}/**`];\n const defaultAssets: AssetEntry[] = [\n { glob: 'LICENSE', input: '/', output: '/' },\n ...entryPoints.map(({ data }) => {\n const subpath = data.entryPoint.destinationFiles.directory || '/';\n\n return { glob: 'README.md', input: subpath, output: subpath };\n }),\n ];\n\n const assets: AssetEntry[] = [];\n for (const assetPath of [...ngPackage.assets, ...defaultAssets]) {\n let asset: AssetEntry;\n if (typeof assetPath === 'object') {\n asset = { ...assetPath };\n } else {\n const [isDir, isFile] = await stat(path.join(ngPackage.src, assetPath))\n .then(stats => [stats.isDirectory(), stats.isFile()])\n .catch(() => [false, false]);\n if (isDir) {\n asset = { glob: '**/*', input: assetPath, output: assetPath };\n } else if (isFile) {\n // filenames are their own glob\n asset = { glob: path.basename(assetPath), input: path.dirname(assetPath), output: path.dirname(assetPath) };\n } else {\n asset = { glob: assetPath, input: '/', output: '/' };\n }\n }\n\n asset.input = path.join(ngPackage.src, asset.input);\n asset.output = path.join(ngPackage.dest, asset.output);\n\n const isAncestorPath = (target: string, datum: string) => path.relative(datum, target).startsWith('..');\n if (isAncestorPath(asset.input, ngPackage.src)) {\n throw new Error('Cannot read assets from a location outside of the project root.');\n }\n if (isAncestorPath(asset.output, ngPackage.dest)) {\n throw new Error('Cannot write assets to a location outside of the output path.');\n }\n\n assets.push(asset);\n }\n\n for (const asset of assets) {\n const filePaths = await glob(asset.glob, {\n cwd: asset.input,\n ignore: [...(asset.ignore ?? []), ...globsForceIgnored],\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: asset.followSymlinks,\n });\n for (const filePath of filePaths) {\n const fileSrcFullPath = path.join(asset.input, filePath);\n const fileDestFullPath = path.join(asset.output, filePath);\n const nodeUri = fileUrl(ensureUnixPath(fileSrcFullPath));\n let node = graph.get(nodeUri);\n if (!node) {\n node = new Node(nodeUri);\n graph.put(node);\n }\n entryPointNode.dependsOn(node);\n await copyFile(fileSrcFullPath, fileDestFullPath);\n }\n }\n}\n\n/**\n * Creates and writes a `package.json` file of the entry point used by the `node_module`\n * resolution strategies.\n *\n * #### Example\n *\n * A consumer of the entry point depends on it by `import {..} from '@my/module/id';`.\n * The module id `@my/module/id` will be resolved to the `package.json` file that is written by\n * this build step.\n * The properties `main`, `module`, `typings` (and so on) in the `package.json` point to the\n * flattened JavaScript bundles, type definitions, (...).\n *\n * @param entryPoint An entry point of an Angular package / library\n * @param additionalProperties Additional properties, e.g. binary artefacts (bundle files), to merge into `package.json`\n */\nasync function writePackageJson(\n entryPoint: NgEntryPoint,\n pkg: NgPackage,\n additionalProperties: { [key: string]: string | boolean | string[] | ConditionalExport },\n isWatchMode: boolean,\n compilationMode: CompilationMode,\n spinner: Ora,\n): Promise<void> {\n log.debug('Writing package.json');\n\n // set additional properties\n const packageJson = { ...entryPoint.packageJson, ...additionalProperties };\n packageJson.type ??= 'module';\n\n // read tslib version from `@angular/compiler` so that our tslib\n // version at least matches that of angular if we use require('tslib').version\n // it will get what installed and not the minimum version nor if it is a `~` or `^`\n // this is only required for primary\n if (isWatchMode) {\n // Needed because of Webpack's 5 `cachemanagedpaths`\n // https://github.com/angular/angular-cli/issues/20962\n packageJson.version = generateWatchVersion();\n }\n\n if (!packageJson.peerDependencies?.tslib && !packageJson.dependencies?.tslib) {\n const {\n peerDependencies: angularPeerDependencies = {},\n dependencies: angularDependencies = {},\n } = require('@angular/compiler/package.json');\n const tsLibVersion = angularPeerDependencies.tslib || angularDependencies.tslib;\n\n if (tsLibVersion) {\n packageJson.dependencies = { ...packageJson.dependencies, tslib: tsLibVersion };\n }\n } else if (packageJson.peerDependencies?.tslib) {\n spinner.warn(\n colors.yellow(\n `'tslib' is no longer recommended to be used as a 'peerDependencies'. Moving it to 'dependencies'.`,\n ),\n );\n packageJson.dependencies = { ...(packageJson.dependencies || {}), tslib: packageJson.peerDependencies.tslib };\n\n delete packageJson.peerDependencies.tslib;\n }\n\n // Verify non-peerDependencies as they can easily lead to duplicate installs or version conflicts\n // in the node_modules folder of an application\n const allowedList = pkg.allowedNonPeerDependencies.map(value => new RegExp(value));\n try {\n checkNonPeerDependencies(packageJson, 'dependencies', allowedList, spinner);\n } catch (e) {\n await rmdir(entryPoint.destinationPath, { recursive: true });\n throw e;\n }\n\n // Removes scripts from package.json after build\n if (packageJson.scripts) {\n if (pkg.keepLifecycleScripts !== true) {\n spinner.info(`Removing scripts section in package.json as it's considered a potential security vulnerability.`);\n delete packageJson.scripts;\n } else {\n spinner.warn(\n colors.yellow(\n `You enabled keepLifecycleScripts explicitly. The scripts section in package.json will be published to npm.`,\n ),\n );\n }\n }\n\n if (compilationMode !== 'partial') {\n const scripts = packageJson.scripts || (packageJson.scripts = {});\n scripts.prepublishOnly =\n 'node --eval \"console.error(\\'' +\n 'ERROR: Trying to publish a package that has been compiled in full compilation mode. This is not allowed.\\\\n' +\n 'Please delete and rebuild the package with partial compilation mode, before attempting to publish.\\\\n' +\n '\\')\" ' +\n '&& exit 1';\n }\n\n // keep the dist package.json clean\n // this will not throw if ngPackage field does not exist\n delete packageJson.ngPackage;\n\n const packageJsonPropertiesToDelete = [\n 'stylelint',\n 'prettier',\n 'browserslist',\n 'devDependencies',\n 'jest',\n 'workspaces',\n 'husky',\n ];\n\n for (const prop of packageJsonPropertiesToDelete) {\n if (prop in packageJson) {\n delete packageJson[prop];\n spinner.info(`Removing ${prop} section in package.json.`);\n }\n }\n\n packageJson.name = entryPoint.moduleId;\n await writeFile(path.join(entryPoint.destinationPath, 'package.json'), JSON.stringify(packageJson, undefined, 2));\n}\n\nfunction checkNonPeerDependencies(\n packageJson: Record<string, unknown>,\n property: string,\n allowed: RegExp[],\n spinner: Ora,\n) {\n if (!packageJson[property]) {\n return;\n }\n\n for (const dep of Object.keys(packageJson[property])) {\n if (allowed.some(regex => regex.test(dep))) {\n log.debug(`Dependency ${dep} is allowed in '${property}'`);\n } else {\n spinner.warn(\n colors.yellow(\n `Distributing npm packages with '${property}' is not recommended. Please consider adding ${dep} ` +\n `to 'peerDependencies' or remove it from '${property}'.`,\n ),\n );\n throw new Error(`Dependency ${dep} must be explicitly allowed using the \"allowedNonPeerDependencies\" option.`);\n }\n }\n}\n"]}
@@ -78,9 +78,45 @@ class SassWorkerImplementation {
78
78
  rebase;
79
79
  maxThreads;
80
80
  #workerPool;
81
+ /** Queue of pending transformation tasks waiting for an active concurrency slot. */
82
+ #pendingTasks = [];
83
+ /** Current count of actively executing transformation tasks. */
84
+ #activeTasks = 0;
85
+ /** Maximum number of transformation tasks allowed to execute concurrently. */
86
+ #maxConcurrent;
81
87
  constructor(rebase = false, maxThreads = MAX_RENDER_WORKERS) {
82
88
  this.rebase = rebase;
83
89
  this.maxThreads = maxThreads;
90
+ // Maintain 2 active tasks per worker thread to keep transformation pipelines fully saturated
91
+ this.#maxConcurrent = Math.max(1, maxThreads * 2);
92
+ }
93
+ /**
94
+ * Executes a transformation action using a semaphore-based backpressure throttle.
95
+ * Prevents libuv thread pool saturation and excessive V8 heap accumulation.
96
+ * @param action A callback that produces a promise for the transformation result.
97
+ * @returns A promise resolving to the transformation result.
98
+ */
99
+ async #runWithThrottle(action) {
100
+ if (this.#activeTasks >= this.#maxConcurrent) {
101
+ await new Promise((resolve, reject) => {
102
+ this.#pendingTasks.push({ resolve, reject });
103
+ });
104
+ }
105
+ else {
106
+ this.#activeTasks++;
107
+ }
108
+ try {
109
+ return await action();
110
+ }
111
+ finally {
112
+ const next = this.#pendingTasks.shift();
113
+ if (next) {
114
+ next.resolve();
115
+ }
116
+ else {
117
+ this.#activeTasks--;
118
+ }
119
+ }
84
120
  }
85
121
  #ensureWorkerPool() {
86
122
  this.#workerPool ??= new worker_pool_1.WorkerPool({
@@ -109,63 +145,65 @@ class SassWorkerImplementation {
109
145
  * @param options The `dart-sass` options to use when rendering the stylesheet.
110
146
  */
111
147
  async compileStringAsync(source, options) {
112
- const env_1 = { stack: [], error: void 0, hasError: false };
113
- try {
114
- // The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.
115
- // If any additional function options are added in the future, they must be excluded as well.
116
- const { functions, importers, url, logger, ...serializableOptions } = options;
117
- // The CLI's configuration does not use or expose the ability to define custom Sass functions
118
- if (functions && Object.keys(functions).length > 0) {
119
- throw new Error('Sass custom functions are not supported.');
120
- }
121
- const importerChannel = __addDisposableResource(env_1, importers?.length ? this.#createImporterChannel(importers) : undefined, false);
122
- const response = (await this.#ensureWorkerPool().run({
123
- source,
124
- importerChannel,
125
- hasLogger: !!logger,
126
- rebase: this.rebase,
127
- options: {
128
- ...serializableOptions,
129
- // URL is not serializable so to convert to string here and back to URL in the worker.
130
- url: url ? (0, node_url_1.fileURLToPath)(url) : undefined,
131
- },
132
- }, {
133
- transferList: importerChannel ? [importerChannel.port] : undefined,
134
- }));
135
- const { result, error, warnings } = response;
136
- if (warnings && logger?.warn) {
137
- for (const { message, span, ...options } of warnings) {
138
- logger.warn(message, {
139
- ...options,
140
- span: span && {
141
- ...span,
142
- url: span.url ? (0, node_url_1.pathToFileURL)(span.url) : undefined,
143
- },
144
- });
148
+ // The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.
149
+ // If any additional function options are added in the future, they must be excluded as well.
150
+ const { functions, importers, url, logger, ...serializableOptions } = options;
151
+ // The CLI's configuration does not use or expose the ability to define custom Sass functions
152
+ if (functions && Object.keys(functions).length > 0) {
153
+ throw new Error('Sass custom functions are not supported.');
154
+ }
155
+ return this.#runWithThrottle(async () => {
156
+ const env_1 = { stack: [], error: void 0, hasError: false };
157
+ try {
158
+ const importerChannel = __addDisposableResource(env_1, importers?.length ? this.#createImporterChannel(importers) : undefined, false);
159
+ const response = (await this.#ensureWorkerPool().run({
160
+ source,
161
+ importerChannel,
162
+ hasLogger: !!logger,
163
+ rebase: this.rebase,
164
+ options: {
165
+ ...serializableOptions,
166
+ // URL is not serializable so to convert to string here and back to URL in the worker.
167
+ url: url ? (0, node_url_1.fileURLToPath)(url) : undefined,
168
+ },
169
+ }, {
170
+ transferList: importerChannel ? [importerChannel.port] : undefined,
171
+ }));
172
+ const { result, error, warnings } = response;
173
+ if (warnings && logger?.warn) {
174
+ for (const { message, span, ...options } of warnings) {
175
+ logger.warn(message, {
176
+ ...options,
177
+ span: span && {
178
+ ...span,
179
+ url: span.url ? (0, node_url_1.pathToFileURL)(span.url) : undefined,
180
+ },
181
+ });
182
+ }
145
183
  }
146
- }
147
- if (error) {
148
- // Convert stringified url value required for cloning back to a URL object
149
- const url = error.span?.url;
150
- if (url) {
151
- error.span.url = (0, node_url_1.pathToFileURL)(url);
184
+ if (error) {
185
+ // Convert stringified url value required for cloning back to a URL object
186
+ const url = error.span?.url;
187
+ if (url) {
188
+ error.span.url = (0, node_url_1.pathToFileURL)(url);
189
+ }
190
+ throw error;
152
191
  }
153
- throw error;
192
+ (0, node_assert_1.default)(result, 'Sass render worker should always return a result or an error');
193
+ return {
194
+ ...result,
195
+ // URL is not serializable so in the worker we convert to string and here back to URL.
196
+ loadedUrls: result.loadedUrls.map(p => (0, node_url_1.pathToFileURL)(p)),
197
+ };
154
198
  }
155
- (0, node_assert_1.default)(result, 'Sass render worker should always return a result or an error');
156
- return {
157
- ...result,
158
- // URL is not serializable so in the worker we convert to string and here back to URL.
159
- loadedUrls: result.loadedUrls.map(p => (0, node_url_1.pathToFileURL)(p)),
160
- };
161
- }
162
- catch (e_1) {
163
- env_1.error = e_1;
164
- env_1.hasError = true;
165
- }
166
- finally {
167
- __disposeResources(env_1);
168
- }
199
+ catch (e_1) {
200
+ env_1.error = e_1;
201
+ env_1.hasError = true;
202
+ }
203
+ finally {
204
+ __disposeResources(env_1);
205
+ }
206
+ });
169
207
  }
170
208
  /**
171
209
  * Shutdown the Sass render worker.
@@ -173,6 +211,11 @@ class SassWorkerImplementation {
173
211
  * @returns A void promise that resolves when closing is complete.
174
212
  */
175
213
  async close() {
214
+ const pending = this.#pendingTasks;
215
+ this.#pendingTasks = [];
216
+ for (const task of pending) {
217
+ task.reject(new Error('SassWorkerImplementation closed.'));
218
+ }
176
219
  if (this.#workerPool) {
177
220
  try {
178
221
  await this.#workerPool.destroy();
@@ -1 +1 @@
1
- {"version":3,"file":"sass-service.js","sourceRoot":"","sources":["../../../../../src/lib/styles/sass/sass-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAAiC;AACjC,uCAAwD;AACxD,6DAAqD;AAarD,gDAA4C;AAE5C,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;AAC/D,MAAM,UAAU,GAAG,OAAO,kBAAkB,KAAK,QAAQ,IAAI,kBAAkB,KAAK,EAAE,CA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gBACb,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YACtC,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;gBACpC,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;QAEH,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAEzB,OAAO;YACL,IAAI,EAAE,kBAAkB;YACxB,MAAM,EAAE,cAAc;YACtB,CAAC,MAAM,CAAC,OAAO,CAAC;gBACd,gBAAgB,CAAC,KAAK,EAAE,CAAC;YAC3B,CAAC;SACF,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAC5B,SAA8B,EAC9B,GAAW,EACX,OAA4B;QAE5B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACnC,WAAW;gBACX,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;YACxD,CAAC;YAED,uCAAuC;YACvC,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YACxD,IAAI,MAAM,EAAE,CAAC;gBACX,OAAO,IAAA,wBAAa,EAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,cAAc,CAAC,KAAgB;QACrC,OAAO,aAAa,IAAI,KAAK,CAAC;IAChC,CAAC;CACF;AA5KD,4DA4KC","sourcesContent":["import assert from 'node:assert';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { MessageChannel } from 'node:worker_threads';\nimport type {\n CanonicalizeContext,\n CompileResult,\n Deprecation,\n Exception,\n FileImporter,\n Importer,\n NodePackageImporter,\n SourceSpan,\n StringOptions,\n} from 'sass';\n\nimport { WorkerPool } from '../worker-pool';\n\nconst maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS'];\nconst maxWorkers = typeof maxWorkersVariable === 'string' && maxWorkersVariable !== '' ? +maxWorkersVariable : 4;\n\n// Polyfill Symbol.dispose if not present\n\n(Symbol as any).dispose ??= Symbol('Symbol Dispose');\n\n/**\n * The maximum number of Workers that will be created to execute render requests.\n */\nconst MAX_RENDER_WORKERS = maxWorkers;\n\n/**\n * All available importer types.\n */\ntype Importers =\n | Importer<'sync'>\n | Importer<'async'>\n | FileImporter<'sync'>\n | FileImporter<'async'>\n | NodePackageImporter;\n\nexport interface SerializableVersion {\n major: number;\n minor: number;\n patch: number;\n}\n\nexport interface SerializableDeprecation extends Omit<Deprecation, 'obsoleteIn' | 'deprecatedIn'> {\n /** The version this deprecation first became active in. */\n deprecatedIn: SerializableVersion | null;\n\n /** The version this deprecation became obsolete in. */\n obsoleteIn: SerializableVersion | null;\n}\n\nexport type SerializableWarningMessage = (\n | {\n deprecation: true;\n deprecationType: SerializableDeprecation;\n }\n | { deprecation: false }\n) & {\n message: string;\n span?: Omit<SourceSpan, 'url'> & { url?: string };\n stack?: string;\n};\n\n/**\n * A response from the Sass render Worker containing the result of the operation.\n */\ninterface RenderResponseMessage {\n error?: Exception;\n result?: Omit<CompileResult, 'loadedUrls'> & { loadedUrls: string[] };\n warnings?: SerializableWarningMessage[];\n}\n\n/**\n * A Sass renderer implementation that provides an interface that can be used by Webpack's\n * `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering\n * with the `dart-sass` package. The `dart-sass` synchronous render function is used within\n * the worker which can be up to two times faster than the asynchronous variant.\n */\nexport class SassWorkerImplementation {\n #workerPool: WorkerPool | undefined;\n\n constructor(\n private readonly rebase = false,\n readonly maxThreads = MAX_RENDER_WORKERS,\n ) {}\n\n #ensureWorkerPool(): WorkerPool {\n this.#workerPool ??= new WorkerPool({\n filename: require.resolve('./worker'),\n maxThreads: this.maxThreads,\n });\n\n return this.#workerPool;\n }\n\n /**\n * Provides information about the Sass implementation.\n * This mimics enough of the `dart-sass` value to be used with the `sass-loader`.\n */\n get info(): string {\n return 'dart-sass\\tworker';\n }\n\n /**\n * The synchronous render function is not used by the `sass-loader`.\n */\n compileString(): never {\n throw new Error('Sass compileString is not supported.');\n }\n\n /**\n * Asynchronously request a Sass stylesheet to be renderered.\n *\n * @param source The contents to compile.\n * @param options The `dart-sass` options to use when rendering the stylesheet.\n */\n async compileStringAsync(source: string, options: StringOptions<'async'>): Promise<CompileResult> {\n // The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.\n // If any additional function options are added in the future, they must be excluded as well.\n const { functions, importers, url, logger, ...serializableOptions } = options;\n\n // The CLI's configuration does not use or expose the ability to define custom Sass functions\n if (functions && Object.keys(functions).length > 0) {\n throw new Error('Sass custom functions are not supported.');\n }\n\n using importerChannel = importers?.length ? this.#createImporterChannel(importers) : undefined;\n\n const response = (await this.#ensureWorkerPool().run(\n {\n source,\n importerChannel,\n hasLogger: !!logger,\n rebase: this.rebase,\n options: {\n ...serializableOptions,\n // URL is not serializable so to convert to string here and back to URL in the worker.\n url: url ? fileURLToPath(url) : undefined,\n },\n },\n {\n transferList: importerChannel ? [importerChannel.port] : undefined,\n },\n )) as RenderResponseMessage;\n\n const { result, error, warnings } = response;\n\n if (warnings && logger?.warn) {\n for (const { message, span, ...options } of warnings) {\n logger.warn(message, {\n ...options,\n span: span && {\n ...span,\n url: span.url ? pathToFileURL(span.url) : undefined,\n },\n });\n }\n }\n\n if (error) {\n // Convert stringified url value required for cloning back to a URL object\n const url = error.span?.url as unknown as string | undefined;\n if (url) {\n error.span.url = pathToFileURL(url);\n }\n\n throw error;\n }\n\n assert(result, 'Sass render worker should always return a result or an error');\n\n return {\n ...result,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n loadedUrls: result.loadedUrls.map(p => pathToFileURL(p)),\n };\n }\n\n /**\n * Shutdown the Sass render worker.\n * Executing this method will stop any pending render requests.\n * @returns A void promise that resolves when closing is complete.\n */\n async close(): Promise<void> {\n if (this.#workerPool) {\n try {\n await this.#workerPool.destroy();\n } finally {\n this.#workerPool = undefined;\n }\n }\n }\n\n #createImporterChannel(importers: Iterable<Importers>) {\n const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel();\n const importerSignal = new Int32Array(new SharedArrayBuffer(4));\n\n mainImporterPort.on('message', ({ url, options }: { url: string; options: CanonicalizeContext }) => {\n this.processImporters(importers, url, {\n ...options,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n containingUrl: options.containingUrl ? pathToFileURL(options.containingUrl as unknown as string) : null,\n })\n .then(result => {\n mainImporterPort.postMessage(result);\n })\n .catch(error => {\n mainImporterPort.postMessage(error);\n })\n .finally(() => {\n Atomics.store(importerSignal, 0, 1);\n Atomics.notify(importerSignal, 0);\n });\n });\n\n mainImporterPort.unref();\n\n return {\n port: workerImporterPort,\n signal: importerSignal,\n [Symbol.dispose]() {\n mainImporterPort.close();\n },\n };\n }\n\n private async processImporters(\n importers: Iterable<Importers>,\n url: string,\n options: CanonicalizeContext,\n ): Promise<string | null> {\n for (const importer of importers) {\n if (!this.isFileImporter(importer)) {\n // Importer\n throw new Error('Only File Importers are supported.');\n }\n\n // File importer (Can be sync or aync).\n const result = await importer.findFileUrl(url, options);\n if (result) {\n return fileURLToPath(result);\n }\n }\n\n return null;\n }\n\n private isFileImporter(value: Importers): value is FileImporter {\n return 'findFileUrl' in value;\n }\n}\n"]}
1
+ {"version":3,"file":"sass-service.js","sourceRoot":"","sources":["../../../../../src/lib/styles/sass/sass-service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAAiC;AACjC,uCAAwD;AACxD,6DAAqD;AAarD,gDAA4C;AAE5C,MAAM,kBAAkB,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;A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C,MAAM,CAAC,CAAC;YACvC,CAAC,CAAC;iBACD,KAAK,CAAC,KAAK,CAAC,EAAE;gBACb,gBAAgB,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;YACtC,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACZ,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;gBACpC,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC;YACpC,CAAC,CAAC,CAAC;QACP,CAAC,CAAC,CAAC;QAEH,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAEzB,OAAO;YACL,IAAI,EAAE,kBAAkB;YACxB,MAAM,EAAE,cAAc;YACtB,CAAC,MAAM,CAAC,OAAO,CAAC;gBACd,gBAAgB,CAAC,KAAK,EAAE,CAAC;YAC3B,CAAC;SACF,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,gBAAgB,CAC5B,SAA8B,EAC9B,GAAW,EACX,OAA4B;QAE5B,KAAK,MAAM,QAAQ,IAAI,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACnC,WAAW;gBACX,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;YACxD,CAAC;YAED,uCAAuC;YACvC,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YACxD,IAAI,MAAM,EAAE,CAAC;gBACX,OAAO,IAAA,wBAAa,EAAC,MAAM,CAAC,CAAC;YAC/B,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,cAAc,CAAC,KAAgB;QACrC,OAAO,aAAa,IAAI,KAAK,CAAC;IAChC,CAAC;CACF;AA3ND,4DA2NC","sourcesContent":["import assert from 'node:assert';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { MessageChannel } from 'node:worker_threads';\nimport type {\n CanonicalizeContext,\n CompileResult,\n Deprecation,\n Exception,\n FileImporter,\n Importer,\n NodePackageImporter,\n SourceSpan,\n StringOptions,\n} from 'sass';\n\nimport { WorkerPool } from '../worker-pool';\n\nconst maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS'];\nconst maxWorkers = typeof maxWorkersVariable === 'string' && maxWorkersVariable !== '' ? +maxWorkersVariable : 4;\n\n// Polyfill Symbol.dispose if not present\n\n(Symbol as any).dispose ??= Symbol('Symbol Dispose');\n\n/**\n * The maximum number of Workers that will be created to execute render requests.\n */\nconst MAX_RENDER_WORKERS = maxWorkers;\n\n/**\n * All available importer types.\n */\ntype Importers =\n | Importer<'sync'>\n | Importer<'async'>\n | FileImporter<'sync'>\n | FileImporter<'async'>\n | NodePackageImporter;\n\nexport interface SerializableVersion {\n major: number;\n minor: number;\n patch: number;\n}\n\nexport interface SerializableDeprecation extends Omit<Deprecation, 'obsoleteIn' | 'deprecatedIn'> {\n /** The version this deprecation first became active in. */\n deprecatedIn: SerializableVersion | null;\n\n /** The version this deprecation became obsolete in. */\n obsoleteIn: SerializableVersion | null;\n}\n\nexport type SerializableWarningMessage = (\n | {\n deprecation: true;\n deprecationType: SerializableDeprecation;\n }\n | { deprecation: false }\n) & {\n message: string;\n span?: Omit<SourceSpan, 'url'> & { url?: string };\n stack?: string;\n};\n\n/**\n * A response from the Sass render Worker containing the result of the operation.\n */\ninterface RenderResponseMessage {\n error?: Exception;\n result?: Omit<CompileResult, 'loadedUrls'> & { loadedUrls: string[] };\n warnings?: SerializableWarningMessage[];\n}\n\n/**\n * A Sass renderer implementation that provides an interface that can be used by Webpack's\n * `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering\n * with the `dart-sass` package. The `dart-sass` synchronous render function is used within\n * the worker which can be up to two times faster than the asynchronous variant.\n */\nexport class SassWorkerImplementation {\n #workerPool: WorkerPool | undefined;\n\n /** Queue of pending transformation tasks waiting for an active concurrency slot. */\n #pendingTasks: { resolve: () => void; reject: (reason: Error) => void }[] = [];\n\n /** Current count of actively executing transformation tasks. */\n #activeTasks = 0;\n\n /** Maximum number of transformation tasks allowed to execute concurrently. */\n readonly #maxConcurrent: number;\n\n constructor(\n private readonly rebase = false,\n readonly maxThreads = MAX_RENDER_WORKERS,\n ) {\n // Maintain 2 active tasks per worker thread to keep transformation pipelines fully saturated\n this.#maxConcurrent = Math.max(1, maxThreads * 2);\n }\n\n /**\n * Executes a transformation action using a semaphore-based backpressure throttle.\n * Prevents libuv thread pool saturation and excessive V8 heap accumulation.\n * @param action A callback that produces a promise for the transformation result.\n * @returns A promise resolving to the transformation result.\n */\n async #runWithThrottle<T>(action: () => Promise<T>): Promise<T> {\n if (this.#activeTasks >= this.#maxConcurrent) {\n await new Promise<void>((resolve, reject) => {\n this.#pendingTasks.push({ resolve, reject });\n });\n } else {\n this.#activeTasks++;\n }\n\n try {\n return await action();\n } finally {\n const next = this.#pendingTasks.shift();\n if (next) {\n next.resolve();\n } else {\n this.#activeTasks--;\n }\n }\n }\n\n #ensureWorkerPool(): WorkerPool {\n this.#workerPool ??= new WorkerPool({\n filename: require.resolve('./worker'),\n maxThreads: this.maxThreads,\n });\n\n return this.#workerPool;\n }\n\n /**\n * Provides information about the Sass implementation.\n * This mimics enough of the `dart-sass` value to be used with the `sass-loader`.\n */\n get info(): string {\n return 'dart-sass\\tworker';\n }\n\n /**\n * The synchronous render function is not used by the `sass-loader`.\n */\n compileString(): never {\n throw new Error('Sass compileString is not supported.');\n }\n\n /**\n * Asynchronously request a Sass stylesheet to be renderered.\n *\n * @param source The contents to compile.\n * @param options The `dart-sass` options to use when rendering the stylesheet.\n */\n async compileStringAsync(source: string, options: StringOptions<'async'>): Promise<CompileResult> {\n // The `functions`, `logger` and `importer` options are JavaScript functions that cannot be transferred.\n // If any additional function options are added in the future, they must be excluded as well.\n const { functions, importers, url, logger, ...serializableOptions } = options;\n\n // The CLI's configuration does not use or expose the ability to define custom Sass functions\n if (functions && Object.keys(functions).length > 0) {\n throw new Error('Sass custom functions are not supported.');\n }\n\n return this.#runWithThrottle(async () => {\n using importerChannel = importers?.length ? this.#createImporterChannel(importers) : undefined;\n\n const response = (await this.#ensureWorkerPool().run(\n {\n source,\n importerChannel,\n hasLogger: !!logger,\n rebase: this.rebase,\n options: {\n ...serializableOptions,\n // URL is not serializable so to convert to string here and back to URL in the worker.\n url: url ? fileURLToPath(url) : undefined,\n },\n },\n {\n transferList: importerChannel ? [importerChannel.port] : undefined,\n },\n )) as RenderResponseMessage;\n\n const { result, error, warnings } = response;\n\n if (warnings && logger?.warn) {\n for (const { message, span, ...options } of warnings) {\n logger.warn(message, {\n ...options,\n span: span && {\n ...span,\n url: span.url ? pathToFileURL(span.url) : undefined,\n },\n });\n }\n }\n\n if (error) {\n // Convert stringified url value required for cloning back to a URL object\n const url = error.span?.url as unknown as string | undefined;\n if (url) {\n error.span.url = pathToFileURL(url);\n }\n\n throw error;\n }\n\n assert(result, 'Sass render worker should always return a result or an error');\n\n return {\n ...result,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n loadedUrls: result.loadedUrls.map(p => pathToFileURL(p)),\n };\n });\n }\n\n /**\n * Shutdown the Sass render worker.\n * Executing this method will stop any pending render requests.\n * @returns A void promise that resolves when closing is complete.\n */\n async close(): Promise<void> {\n const pending = this.#pendingTasks;\n this.#pendingTasks = [];\n for (const task of pending) {\n task.reject(new Error('SassWorkerImplementation closed.'));\n }\n\n if (this.#workerPool) {\n try {\n await this.#workerPool.destroy();\n } finally {\n this.#workerPool = undefined;\n }\n }\n }\n\n #createImporterChannel(importers: Iterable<Importers>) {\n const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel();\n const importerSignal = new Int32Array(new SharedArrayBuffer(4));\n\n mainImporterPort.on('message', ({ url, options }: { url: string; options: CanonicalizeContext }) => {\n this.processImporters(importers, url, {\n ...options,\n // URL is not serializable so in the worker we convert to string and here back to URL.\n containingUrl: options.containingUrl ? pathToFileURL(options.containingUrl as unknown as string) : null,\n })\n .then(result => {\n mainImporterPort.postMessage(result);\n })\n .catch(error => {\n mainImporterPort.postMessage(error);\n })\n .finally(() => {\n Atomics.store(importerSignal, 0, 1);\n Atomics.notify(importerSignal, 0);\n });\n });\n\n mainImporterPort.unref();\n\n return {\n port: workerImporterPort,\n signal: importerSignal,\n [Symbol.dispose]() {\n mainImporterPort.close();\n },\n };\n }\n\n private async processImporters(\n importers: Iterable<Importers>,\n url: string,\n options: CanonicalizeContext,\n ): Promise<string | null> {\n for (const importer of importers) {\n if (!this.isFileImporter(importer)) {\n // Importer\n throw new Error('Only File Importers are supported.');\n }\n\n // File importer (Can be sync or aync).\n const result = await importer.findFileUrl(url, options);\n if (result) {\n return fileURLToPath(result);\n }\n }\n\n return null;\n }\n\n private isFileImporter(value: Importers): value is FileImporter {\n return 'findFileUrl' in value;\n }\n}\n"]}
@@ -24,19 +24,18 @@ async function ensureCacheDirExists(cachePath) {
24
24
  await (0, promises_1.mkdir)(cachePath, { recursive: true });
25
25
  }
26
26
  catch (err) {
27
- if (err.code !== 'EEXIST') {
27
+ if (!(typeof err === 'object' && err !== null && 'code' in err && err.code === 'EEXIST')) {
28
28
  throw err;
29
29
  }
30
30
  }
31
31
  }
32
32
  async function readCacheEntry(cachePath, key) {
33
- const filePath = (0, node_path_1.join)(cachePath, key);
34
33
  try {
35
- const data = await (0, promises_1.readFile)(filePath, 'utf8');
34
+ const data = await (0, promises_1.readFile)(getCacheFilePath(cachePath, key), 'utf8');
36
35
  return JSON.parse(data, (_key, value) => {
37
36
  if (typeof value === 'string' && value[0] === '%') {
38
37
  const numPart = value.match(BIGINT_STRING_VALUE_REGEXP);
39
- if (numPart && isFinite(numPart[1])) {
38
+ if (numPart) {
40
39
  return BigInt(numPart[1]);
41
40
  }
42
41
  }
@@ -49,10 +48,12 @@ async function readCacheEntry(cachePath, key) {
49
48
  }
50
49
  }
51
50
  async function saveCacheEntry(cachePath, key, content) {
52
- const filePath = (0, node_path_1.join)(cachePath, key);
53
51
  // Ensure the cache directory exists
54
52
  await ensureCacheDirExists(cachePath);
55
53
  const data = JSON.stringify(content, (_key, value) => (typeof value === 'bigint' ? `%BigInt(${value})` : value));
56
- return (0, promises_1.writeFile)(filePath, data, 'utf8');
54
+ return (0, promises_1.writeFile)(getCacheFilePath(cachePath, key), data, 'utf8');
55
+ }
56
+ function getCacheFilePath(cachePath, key) {
57
+ return (0, node_path_1.join)(cachePath, `${key}.json`);
57
58
  }
58
59
  //# sourceMappingURL=cache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../../src/lib/utils/cache.ts"],"names":[],"mappings":";;AAeA,kCAEC;AAYD,wCAqBC;AAED,wCASC;AA7DD,6CAAyC;AACzC,+CAA8D;AAC9D,yCAAiC;AACjC,+BAA8B;AAE9B,IAAI,gBAAoC,CAAC;AACzC,IAAI,CAAC;IACH,gBAAgB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAC3D,CAAC;AAAC,MAAM,CAAC;IACP,WAAW;IACX,gBAAgB,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC,OAAO,CAAC;AAC9D,CAAC;AAED,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AAEjD,KAAK,UAAU,WAAW,CAAC,GAAG,gBAA0B;IAC7D,OAAO,IAAA,wBAAU,EAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAAC,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACxG,CAAC;AAED,KAAK,UAAU,oBAAoB,CAAC,SAAiB;IACnD,IAAI,CAAC;QACH,MAAM,IAAA,gBAAK,EAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE,C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AAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAEjH,OAAO,IAAA,oBAAS,EAAC,QAAQ,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { debug } from './log';\n\nlet ngPackagrVersion: string | undefined;\ntry {\n ngPackagrVersion = require('../../package.json').version;\n} catch {\n // dev path\n ngPackagrVersion = require('../../../package.json').version;\n}\n\nconst BIGINT_STRING_VALUE_REGEXP = /^%BigInt\\((\\d+)\\)$/;\n\nexport async function generateKey(...valuesToConsider: string[]): Promise<string> {\n return createHash('sha256').update(ngPackagrVersion).update(valuesToConsider.join(':')).digest('hex');\n}\n\nasync function ensureCacheDirExists(cachePath: string): Promise<void> {\n try {\n await mkdir(cachePath, { recursive: true });\n } catch (err) {\n if (err.code !== 'EEXIST') {\n throw err;\n }\n }\n}\n\nexport async function readCacheEntry(cachePath: string, key: string): Promise<any> {\n const filePath = join(cachePath, key);\n\n try {\n const data = await readFile(filePath, 'utf8');\n\n return JSON.parse(data, (_key, value) => {\n if (typeof value === 'string' && value[0] === '%') {\n const numPart = value.match(BIGINT_STRING_VALUE_REGEXP);\n if (numPart && isFinite(numPart[1] as any)) {\n return BigInt(numPart[1]);\n }\n }\n\n return value;\n });\n } catch (err) {\n debug(`[readCacheError]: ${err}`);\n\n return undefined;\n }\n}\n\nexport async function saveCacheEntry(cachePath: string, key: string, content: any): Promise<void> {\n const filePath = join(cachePath, key);\n\n // Ensure the cache directory exists\n await ensureCacheDirExists(cachePath);\n\n const data = JSON.stringify(content, (_key, value) => (typeof value === 'bigint' ? `%BigInt(${value})` : value));\n\n return writeFile(filePath, data, 'utf8');\n}\n"]}
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../../src/lib/utils/cache.ts"],"names":[],"mappings":";;AAeA,kCAEC;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KAAK,EAAE,EAAE;YACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;gBAClD,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;gBACxD,IAAI,OAAO,EAAE,CAAC;oBACZ,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;gBAC5B,CAAC;YACH,CAAC;YAED,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAA,WAAK,EAAC,qBAAqB,GAAG,EAAE,CAAC,CAAC;QAElC,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAEM,KAAK,UAAU,cAAc,CAAC,SAAiB,EAAE,GAAW,EAAE,OAAY;IAC/E,oCAAoC;IACpC,MAAM,oBAAoB,CAAC,SAAS,CAAC,CAAC;IAEtC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,KAAK,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAEjH,OAAO,IAAA,oBAAS,EAAC,gBAAgB,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,gBAAgB,CAAC,SAAiB,EAAE,GAAW;IACtD,OAAO,IAAA,gBAAI,EAAC,SAAS,EAAE,GAAG,GAAG,OAAO,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { debug } from './log';\n\nlet ngPackagrVersion: string | undefined;\ntry {\n ngPackagrVersion = require('../../package.json').version;\n} catch {\n // dev path\n ngPackagrVersion = require('../../../package.json').version;\n}\n\nconst BIGINT_STRING_VALUE_REGEXP = /^%BigInt\\((\\d+)\\)$/;\n\nexport async function generateKey(...valuesToConsider: string[]): Promise<string> {\n return createHash('sha256').update(ngPackagrVersion).update(valuesToConsider.join(':')).digest('hex');\n}\n\nasync function ensureCacheDirExists(cachePath: string): Promise<void> {\n try {\n await mkdir(cachePath, { recursive: true });\n } catch (err: unknown) {\n if (!(typeof err === 'object' && err !== null && 'code' in err && (err as { code?: unknown }).code === 'EEXIST')) {\n throw err;\n }\n }\n}\n\nexport async function readCacheEntry(cachePath: string, key: string): Promise<any> {\n try {\n const data = await readFile(getCacheFilePath(cachePath, key), 'utf8');\n\n return JSON.parse(data, (_key, value) => {\n if (typeof value === 'string' && value[0] === '%') {\n const numPart = value.match(BIGINT_STRING_VALUE_REGEXP);\n if (numPart) {\n return BigInt(numPart[1]);\n }\n }\n\n return value;\n });\n } catch (err) {\n debug(`[readCacheError]: ${err}`);\n\n return undefined;\n }\n}\n\nexport async function saveCacheEntry(cachePath: string, key: string, content: any): Promise<void> {\n // Ensure the cache directory exists\n await ensureCacheDirExists(cachePath);\n\n const data = JSON.stringify(content, (_key, value) => (typeof value === 'bigint' ? `%BigInt(${value})` : value));\n\n return writeFile(getCacheFilePath(cachePath, key), data, 'utf8');\n}\n\nfunction getCacheFilePath(cachePath: string, key: string): string {\n return join(cachePath, `${key}.json`);\n}\n"]}