fix(gulp-function): correct forFirst execution behavior, improve async error handling, and modernize package metadata

This commit is contained in:
2026-05-02 10:36:21 +00:00
parent edcb1d114f
commit 60607ce021
12 changed files with 8673 additions and 6831 deletions
+39
View File
@@ -0,0 +1,39 @@
{
"@ship.zone/szci": {
"npmGlobalTools": [],
"npmRegistryUrl": "registry.npmjs.org"
},
"@git.zone/cli": {
"projectType": "npm",
"module": {
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "gulp-function",
"shortDescription": "Function execution for Gulp streams",
"description": "A Gulp plugin to execute functions within a Gulp task pipeline.",
"npmPackagename": "@push.rocks/gulp-function",
"license": "MIT",
"keywords": [
"gulp",
"plugin",
"task automation",
"stream manipulation",
"async function execution",
"pipeline",
"build tool",
"JavaScript",
"TypeScript"
]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
}
},
"@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.\n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.\n\nUse of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District Court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
}
}
+199
View File
@@ -0,0 +1,199 @@
# Changelog
## 2026-05-02 - 3.0.8 - fix(gulp-function)
correct forFirst execution behavior, improve async error handling, and modernize package metadata
- fixes `forFirst` so the callback runs only for the first file instead of every file after the first
- normalizes thrown values into `Error` instances and propagates async failures through the Gulp stream
- adds stronger TypeScript typings, updates tests, and refreshes package/configuration metadata for the current toolchain
## 2024-03-10 - 3.0.7 - maintenance
Release 3.0.7 with repository and configuration maintenance updates.
- Updated package metadata and description
- Updated TypeScript configuration
- Updated npm host configuration
## 2024-03-10 - 3.0.6 - core
Applied a core update fix.
- fix(core): update
## 2023-06-30 - 3.0.5 - maintenance
Released 3.0.5 with a core fix and organization migration updates.
- fix(core): update
- Switched to the new organization scheme
## 2020-01-18 - 3.0.4 - core
Applied a core update fix.
- fix(core): update
## 2020-01-18 - 3.0.3 - core
Applied a core update fix.
- fix(core): update
## 2020-01-18 - 3.0.2 - core
Applied a core update fix.
- fix(core): update
## 2018-12-09 - 3.0.1 - core
Applied a core update fix.
- fix(core): update
## 2018-12-09 - 3.0.0 - npm
Updated npm package permissions.
- fix(npm): permissions
## 2018-12-09 - 2.2.16 - npm scope
Introduced a breaking npm scope change.
- BREAKING CHANGE(npm scope): update
## 2018-12-09 - 2.2.15 - license
Updated licensing metadata.
- Switched from brand name to company name in license information
## 2018-01-29 - 2.2.14 - core
Released 2.2.14 with standards updates and documentation fixes.
- Updated core to latest gitzone standards
- Fixed sample code in README
## 2017-04-30 - 2.2.13 to 2.2.11 - maintenance
Rolled up minor maintenance and documentation updates across these releases.
- Updated CI configuration
- Updated README
- Updated project standards
## 2017-04-30 - 2.2.10 to 2.2.6 - mixed
Delivered a mix of dependency, documentation, and behavior improvements.
- Updated dependencies
- Updated docs, README, and .gitignore
- Fixed pipe cleanup behavior
## 2016-11-25 - 2.2.5 to 2.2.1 - core
Shipped iterative fixes and API improvements in the 2.2.x line.
- Fixed `.forEach` return behavior
- Added `.forEach`, `.atEnd`, and `.forFirst`
- Switched to ES6 default import
- Included testing and documentation improvements as part of the release series
## 2016-10-18 - 2.0.0 - ci
Updated CI base image for the 2.0.0 release.
- Fixed base image for CI
## 2016-06-11 - 1.3.6 - core
Added support for modifying the file object.
- Added possibility to modify the file object
## 2016-06-03 - 1.3.5 to 1.3.1 - maintenance
Bundled dependency, CI, and documentation maintenance updates.
- Updated GitLab CI configuration
- Switched to npmts-g
- Updated README and removed Travis
- Fixed a missing dependency
- Added GitLab CI
- Updated dependencies
## 2016-04-07 - 1.3.0 - dependencies
Adjusted development dependencies.
- Added beautylog back as a dev dependency
## 2016-04-04 - 1.2.5 to 1.2.1 - maintenance
Bundled package, dependency, and README fixes across patch releases.
- Fixed package.json
- Updated dependencies
- Fixed README issues
## 2016-03-26 - 1.2.0 - core
Delivered functional fixes and dependency cleanup.
- Fixed issue #3
- Removed beautylog dependency
- Updated dependencies and coverage badge configuration
## 2016-02-14 - 1.1.1 - core
Added new callback handling functionality.
- Added `forFirst`
- Included badge and README updates in this release cycle
## 2016-02-14 - 1.1.0 - dependencies
Updated promise handling dependency.
- Updated promise
## 2016-02-12 - 1.0.4 - core
Improved async function handling.
- Now accepts promises as return values of supplied functions
- Included README updates
## 2016-02-12 - 1.0.3 - configuration
Added npmts configuration.
- Added `npmts.json`
## 2016-02-02 - 1.0.2 - tests
Improved test coverage.
- Added better tests and coverage
## 2016-02-01 - 1.0.1 to 1.0.0 - maintenance
Initial stable release cycle with tooling and dependency updates.
- Updated dependencies
- Updated Travis configuration
- Updated npmts
## 2015-11-30 - 0.0.12 to 0.0.8 - maintenance
Early project setup and package maintenance updates.
- Updated keywords and package metadata
- Cleaned up project structure
- Updated dependencies
## 2015-10-26 - 0.0.7 - core
Added callback support to `atEnd`.
- Added callback to `function() atEnd`
- Included badge updates
## 2015-10-26 - 0.0.6 to 0.0.4 - tooling
Established release automation and tooling.
- Added automatic version release through Travis for npm
## 2015-10-25 - 0.0.3 - tests
Improved early project quality and stability.
- Added tests
- Included a small fix
## 2015-09-17 - 0.0.2 - core
Made the package functional and added initial project files.
- Now working
- Added `.gitignore`
- Added README
## 2015-09-04 - 0.0.1 - release
Initial package publication and CI setup.
- Published npm package
- Added Travis CI
+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 Lossless GmbH Copyright (c) 2022 Task Venture Capital GmbH <hello@task.vc>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+13 -8
View File
@@ -1,17 +1,15 @@
{ {
"npmts": { "@ship.zone/szci": {
"mode": "default"
},
"npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmRegistryUrl": "registry.npmjs.org"
}, },
"gitzone": { "@git.zone/cli": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "code.foss.global", "githost": "code.foss.global",
"gitscope": "push.rocks", "gitscope": "push.rocks",
"gitrepo": "gulp-function", "gitrepo": "gulp-function",
"shortDescription": "Function execution for Gulp streams",
"description": "A Gulp plugin to execute functions within a Gulp task pipeline.", "description": "A Gulp plugin to execute functions within a Gulp task pipeline.",
"npmPackagename": "@push.rocks/gulp-function", "npmPackagename": "@push.rocks/gulp-function",
"license": "MIT", "license": "MIT",
@@ -26,9 +24,16 @@
"JavaScript", "JavaScript",
"TypeScript" "TypeScript"
] ]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
} }
}, },
"tsdoc": { "@git.zone/tsdoc": {
"legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n" "legal": "\n## License and Legal Information\n\nThis repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.\n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.\n\nUse of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District Court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n"
} }
} }
+24 -20
View File
@@ -1,15 +1,33 @@
{ {
"name": "@push.rocks/gulp-function", "name": "@push.rocks/gulp-function",
"private": false,
"version": "3.0.7", "version": "3.0.7",
"private": false,
"description": "A Gulp plugin to execute functions within a Gulp task pipeline.", "description": "A Gulp plugin to execute functions within a Gulp task pipeline.",
"exports": {
".": "./dist_ts/index.js"
},
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module",
"author": "Task Venture Capital GmbH <hello@task.vc>",
"license": "MIT",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "tstest test/",
"build": "(tsbuild --allowimplicitany)", "build": "tsbuild",
"buildDocs": "tsdoc" "buildDocs": "tsdoc"
}, },
"dependencies": {
"through2": "^4.0.2"
},
"devDependencies": {
"@git.zone/tsbuild": "^4.4.0",
"@git.zone/tsdoc": "^2.0.3",
"@git.zone/tstest": "^3.6.3",
"@types/gulp": "^4.0.18",
"@types/node": "^25.6.0",
"@types/through2": "^2.0.41",
"gulp": "^5.0.1"
},
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://code.foss.global/push.rocks/gulp-function.git" "url": "https://code.foss.global/push.rocks/gulp-function.git"
@@ -25,25 +43,10 @@
"JavaScript", "JavaScript",
"TypeScript" "TypeScript"
], ],
"author": "Lossless GmbH <office@lossless.com> (https://lossless.com)",
"license": "MIT",
"bugs": { "bugs": {
"url": "https://gitlab.com/push.rocks/gulp-function/issues" "url": "https://code.foss.global/push.rocks/gulp-function/issues"
}, },
"homepage": "https://code.foss.global/push.rocks/gulp-function", "homepage": "https://code.foss.global/push.rocks/gulp-function",
"dependencies": {
"@push.rocks/smartpromise": "^4.0.3",
"@types/through2": "^2.0.32",
"through2": "^3.0.1"
},
"devDependencies": {
"@git.zone/tsbuild": "^2.1.17",
"@git.zone/tsrun": "^1.2.46",
"@git.zone/tstest": "^1.0.28",
"@push.rocks/smartgulp": "^3.0.3",
"@push.rocks/tapbundle": "^5.0.15",
"gulp": "^4.0.2"
},
"files": [ "files": [
"ts/**/*", "ts/**/*",
"ts_web/**/*", "ts_web/**/*",
@@ -53,10 +56,11 @@
"dist_ts_web/**/*", "dist_ts_web/**/*",
"assets/**/*", "assets/**/*",
"cli.js", "cli.js",
".smartconfig.json",
"license",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
], ],
"type": "module",
"browserslist": [ "browserslist": [
"last 1 chrome versions" "last 1 chrome versions"
] ]
+8197 -6685
View File
File diff suppressed because it is too large Load Diff
+127 -83
View File
@@ -1,106 +1,150 @@
# @push.rocks/gulp-function # @push.rocks/gulp-function
[@push.rocks/gulp-function](https://www.npmjs.com/package/@push.rocks/gulp-function) is a Gulp plugin designed to execute custom functions within a Gulp pipeline. It accepts a function call as a parameter and allows for flexible task executions, including asynchronous tasks, with easy integration into the Gulp workflow. `@push.rocks/gulp-function` is a tiny, typed Gulp plugin for running your own sync or async functions inside a Gulp object stream without changing the files that flow through it. Use it when a pipeline needs custom side effects: logging, validation, deployment calls, metrics, cache invalidation, or any project-specific action that does not deserve a full custom Gulp plugin.
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install ## Install
To use @push.rocks/gulp-function in your project, you'll first need to install it via npm. You can do this by running the following command in your project's root directory: ```bash
pnpm add -D @push.rocks/gulp-function
```
## What It Does
Gulp streams are great at moving Vinyl files through transforms. Sometimes you need to run code at a specific point in that stream while leaving every file untouched. `@push.rocks/gulp-function` gives you three small helpers for that:
- `forEach(fn)`: run `fn(file, enc)` for every file and pass the file on after the function resolves.
- `forFirst(fn)`: run `fn(file, enc)` only for the first file and pass all files through.
- `atEnd(fn)`: pass all files through immediately, then run `fn(null, null)` once when the stream flushes.
The default export exposes the same behavior as `gulpFunction(fnOrFns, mode)`, where `mode` is `'forEach'`, `'forFirst'`, or `'atEnd'`. The default export also accepts an array of functions and runs them in parallel for the selected mode.
## Quick Start
```ts
import gulp from 'gulp';
import { forEach } from '@push.rocks/gulp-function';
interface IVinylFile {
path: string;
relative: string;
}
export const logFiles = () =>
gulp.src('./src/**/*.ts')
.pipe(forEach<IVinylFile>(async (file) => {
if (!file) return;
console.log(`Processing ${file.relative}`);
}))
.pipe(gulp.dest('./dist'));
```
The function can return a promise or a plain value. If it throws or rejects, the transform reports the error to Gulp and the pipeline fails normally.
## API
### `forEach(func)`
Runs `func(file, enc)` for every Vinyl file in the stream. The file is pushed onward only after `func` has completed.
```ts
import { forEach } from '@push.rocks/gulp-function';
gulp.src('./content/**/*.md')
.pipe(forEach(async (file) => {
console.log(file?.relative);
}))
.pipe(gulp.dest('./public'));
```
### `forFirst(func)`
Runs `func(file, enc)` only for the first file. This is useful for one-time setup that should still be triggered by a stream.
```ts
import { forFirst } from '@push.rocks/gulp-function';
gulp.src('./assets/**/*')
.pipe(forFirst(async (file) => {
console.log(`Starting asset pipeline with ${file?.relative}`);
}))
.pipe(gulp.dest('./dist/assets'));
```
### `atEnd(func)`
Runs `func(null, null)` once after all files have passed through. This is ideal for final notifications, summary output, or flushing external state.
```ts
import { atEnd, forEach } from '@push.rocks/gulp-function';
let fileCount = 0;
gulp.src('./src/**/*')
.pipe(forEach(() => {
fileCount++;
}))
.pipe(atEnd(async () => {
console.log(`Handled ${fileCount} files`);
}))
.pipe(gulp.dest('./dist'));
```
### Default Export
```ts
import gulpFunction from '@push.rocks/gulp-function';
gulp.src('./src/**/*')
.pipe(gulpFunction([
async (file) => console.log(file?.relative),
async () => console.log('side effect complete')
], 'forEach'));
```
Supported TypeScript exports:
- `TExecutionMode`: `'forEach' | 'forFirst' | 'atEnd'`
- `TGulpFunctionEncoding`: `BufferEncoding | string | null`
- `TGulpFunctionResult`: `PromiseLike<unknown> | unknown`
- `IPromiseFunction<TFile = unknown>`: `(file?: TFile | null, enc?: TGulpFunctionEncoding) => TGulpFunctionResult`
## Behavior Notes
- Files are passed through unchanged.
- Async functions are awaited before the relevant transform or flush callback completes.
- `forEach` and `forFirst` receive the current file and stream encoding.
- `atEnd` receives `null` for both arguments because no single file is active during flush.
- Arrays passed to the default export are executed with `Promise.all`.
- Non-`Error` thrown values are normalized to `Error` instances before being passed to Gulp.
## Testing and Build
```bash ```bash
npm install @push.rocks/gulp-function --save-dev pnpm test
pnpm run build
``` ```
This command will add `@push.rocks/gulp-function` as a development dependency to your project, making it available for use in your Gulp tasks.
## Usage
The primary use case for `@push.rocks/gulp-function` is to incorporate custom function executions into your Gulp pipelines. This can be particularly useful for tasks that require conditional processing, external API calls, or any other logic that extends beyond the capabilities of existing Gulp plugins.
Here's how you can use `@push.rocks/gulp-function` within your Gulp setup:
### Basic Example
Let's start with a simple scenario where you want to log the path of files processed by Gulp.
```typescript
import gulp from 'gulp';
import gulpFunction, { forEach } from '@push.rocks/gulp-function';
const logFilePath = async (file: Buffer, enc: string) => {
console.log(`Processing file: ${file.path}`);
};
gulp.task('log', () => {
return gulp.src('./src/**/*.ts')
.pipe(forEach(logFilePath))
.pipe(gulp.dest('./dist'));
});
```
In this example, we're using the `forEach` method exported by `@push.rocks/gulp-function` to execute `logFilePath` for each file matched by `gulp.src`. The file's path is logged to the console during the build process.
### Advanced Use Case: Asynchronous Function Execution
`@push.rocks/gulp-function` truly shines when you need to perform asynchronous operations within your Gulp tasks. Here's an example that demonstrates making an asynchronous API call for each file:
```typescript
import gulp from 'gulp';
import gulpFunction, { forEach } from '@push.rocks/gulp-function';
import axios from 'axios';
const uploadFileToServer = async (file: Buffer, enc: string) => {
const formData = new FormData();
formData.append('file', file.contents, file.relative);
await axios.post('https://example.com/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
console.log(`Uploaded file: ${file.path}`);
};
gulp.task('uploadFiles', () => {
return gulp.src('./uploads/**/*')
.pipe(forEach(uploadFileToServer))
.pipe(gulp.dest('./dist/uploads'));
});
```
In this more advanced example, we use the `forEach` method to upload each file to a remote server using `axios`. The function `uploadFileToServer` is executed for each file, where an HTTP POST request is made to upload the file. This shows how you can integrate asynchronous operations seamlessly into your Gulp pipeline.
### Execution Modes
`@push.rocks/gulp-function` supports three execution modes for your functions: `forEach`, `forFirst`, and `atEnd`.
- **forEach**: Executes the provided function for each file in the stream.
- **forFirst**: Executes the provided function only for the first file that passes through the stream.
- **atEnd**: Executes the provided function once after all files have passed through the stream.
These modes provide flexibility in determining when your custom functions should be triggered during the build process.
### Conclusion
`@push.rocks/gulp-function` is a powerful tool for integrating custom processing logic into Gulp workflows. Whether you need to execute simple synchronous tasks or complex asynchronous operations, `@push.rocks/gulp-function` offers the flexibility and ease of use to enhance your Gulp builds significantly.
Remember, the examples provided are starting points. The real power of `@push.rocks/gulp-function` lies in its ability to adapt to your specific use cases, enabling you to automate and streamline your build processes as never before.
## License and Legal Information ## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks ### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information ### Company Information
Task Venture Capital GmbH Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
+58
View File
@@ -0,0 +1,58 @@
import { finished } from 'node:stream/promises';
import { expect, tap } from '@git.zone/tstest/tapbundle';
import gulp from 'gulp';
import * as gulpFunction from '../ts/index.js';
interface ITestVinylFile {
relative: string;
}
tap.test('should run through smoothly with forEach', async () => {
const processedFiles: string[] = [];
const stream = gulp.src('./test/testfiles/*.md').pipe(
gulpFunction.forEach<ITestVinylFile>(async (fileArg) => {
if (fileArg) {
processedFiles.push(fileArg.relative);
}
})
);
stream.resume();
await finished(stream);
expect(processedFiles).toHaveLength(18);
});
tap.test('should run only once with forFirst', async () => {
const processedFiles: string[] = [];
const stream = gulp.src('./test/testfiles/*.md').pipe(
gulpFunction.forFirst<ITestVinylFile>(async (fileArg) => {
if (fileArg) {
processedFiles.push(fileArg.relative);
}
})
);
stream.resume();
await finished(stream);
expect(processedFiles).toHaveLength(1);
});
tap.test('should run once after all files with atEnd', async () => {
let atEndCounter = 0;
let passthroughCounter = 0;
const stream = gulp.src('./test/testfiles/*.md').pipe(
gulpFunction.atEnd(async () => {
atEndCounter++;
})
);
stream.on('data', () => {
passthroughCounter++;
});
await finished(stream);
expect(atEndCounter).toEqual(1);
expect(passthroughCounter).toEqual(18);
});
export default tap.start();
-35
View File
@@ -1,35 +0,0 @@
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartgulp from '@push.rocks/smartgulp';
import gulp from 'gulp';
import * as gulpFunction from '../ts/index.js';
import * as smartpromise from '@push.rocks/smartpromise';
tap.test('should run through smoothly with ' + "'forEach'", async tools => {
let done = smartpromise.defer();
let counter = 0;
gulp.src('./test/testfiles/*.md').pipe(
gulpFunction.forEach(async () => {
counter++;
if (counter === 2) {
done.resolve();
}
})
);
await done.promise;
});
tap.test('should run through smoothly with ' + "'forEach'", async tools => {
let done = smartpromise.defer();
let counter = 0;
smartgulp.src(['./test/testfiles/*.md']).pipe(
gulpFunction.atEnd(async () => {
console.log('atEnd');
done.resolve();
})
);
await done.promise;
});
tap.start();
+3 -3
View File
@@ -1,8 +1,8 @@
/** /**
* autocreated commitinfo by @pushrocks/commitinfo * autocreated commitinfo by @push.rocks/commitinfo
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/gulp-function', name: '@push.rocks/gulp-function',
version: '3.0.7', version: '3.0.8',
description: 'accepts a function call as parameter to execute in gulp pipeline' description: 'A Gulp plugin to execute functions within a Gulp task pipeline.'
} }
+55 -41
View File
@@ -1,86 +1,100 @@
import * as smartpromise from '@push.rocks/smartpromise'; import type { Transform } from 'node:stream';
import * as through2 from 'through2'; import through2 from 'through2';
import { Transform } from 'stream';
export type TExecutionMode = 'forEach' | 'forFirst' | 'atEnd'; export type TExecutionMode = 'forEach' | 'forFirst' | 'atEnd';
export type TGulpFunctionEncoding = BufferEncoding | string | null;
export type TGulpFunctionResult = PromiseLike<unknown> | unknown;
export interface IPromiseFunction { export interface IPromiseFunction<TFile = unknown> {
(file?, enc?): PromiseLike<any>; (file?: TFile | null, enc?: TGulpFunctionEncoding): TGulpFunctionResult;
} }
let defaultExport = ( type TTransformCallback = (errorArg?: Error | null, dataArg?: unknown) => void;
functionsToExecuteArg: IPromiseFunction | IPromiseFunction[], type TFlushCallback = (errorArg?: Error | null) => void;
const normalizeError = (errorArg: unknown): Error => {
return errorArg instanceof Error ? errorArg : new Error(String(errorArg));
};
const defaultExport = <TFile = unknown>(
functionsToExecuteArg: IPromiseFunction<TFile> | Array<IPromiseFunction<TFile>>,
executionModeArg: TExecutionMode = 'forEach' executionModeArg: TExecutionMode = 'forEach'
): Transform => { ): Transform => {
let promiseArray = []; const runFunction = async (
let runFunction = function(functionArg, file, enc) { functionArg: IPromiseFunction<TFile>,
let returnValue = functionArg(file, enc); fileArg: TFile | null,
if (typeof returnValue !== 'undefined' && typeof returnValue.then !== 'undefined') { encArg: TGulpFunctionEncoding
promiseArray.push(returnValue); ): Promise<void> => {
} await functionArg(fileArg, encArg);
}; };
let checkAndRunFunction = function(file, enc) { const checkAndRunFunction = async (
fileArg: TFile | null,
encArg: TGulpFunctionEncoding
): Promise<void> => {
if (typeof functionsToExecuteArg === 'function') { if (typeof functionsToExecuteArg === 'function') {
runFunction(functionsToExecuteArg, file, enc); await runFunction(functionsToExecuteArg, fileArg, encArg);
} else if (Array.isArray(functionsToExecuteArg)) { } else if (Array.isArray(functionsToExecuteArg)) {
for (let anyFunction in functionsToExecuteArg) { await Promise.all(
runFunction(functionsToExecuteArg[anyFunction], file, enc); functionsToExecuteArg.map(async (functionArg) => runFunction(functionArg, fileArg, encArg))
} );
} else { } else {
throw new Error('gulp-callfunction: something is strange with the given arguments'); throw new Error('gulp-callfunction: something is strange with the given arguments');
} }
return Promise.all(promiseArray);
}; };
let hasExecutedOnce = false; let hasExecutedOnce = false;
let forEach = function(file, enc, cb) { const transformFunction = (fileArg: TFile, encArg: BufferEncoding, cbArg: TTransformCallback) => {
// the forEach function is called for every chunk
switch (executionModeArg) { switch (executionModeArg) {
case 'forEach': case 'forEach':
checkAndRunFunction(file, enc).then(function() { checkAndRunFunction(fileArg, encArg).then(
cb(null, file); () => cbArg(null, fileArg),
}); (errorArg) => cbArg(normalizeError(errorArg))
);
break; break;
case 'forFirst': case 'forFirst':
if (hasExecutedOnce) { if (!hasExecutedOnce) {
checkAndRunFunction(file, enc).then(function() {
cb(null, file);
});
} else {
cb(null, file);
}
hasExecutedOnce = true; hasExecutedOnce = true;
checkAndRunFunction(fileArg, encArg).then(
() => cbArg(null, fileArg),
(errorArg) => cbArg(normalizeError(errorArg))
);
} else {
cbArg(null, fileArg);
}
break; break;
case 'atEnd': case 'atEnd':
cb(); cbArg(null, fileArg);
break; break;
default: default:
cbArg(null, fileArg);
break; break;
} }
}; };
let atEnd = function(cb) { const flushFunction = (cbArg: TFlushCallback) => {
if (executionModeArg === 'atEnd') { if (executionModeArg === 'atEnd') {
checkAndRunFunction(null, null).then(function() { checkAndRunFunction(null, null).then(
cb(); () => cbArg(),
}); (errorArg) => cbArg(normalizeError(errorArg))
);
} else { } else {
cb(); cbArg();
} }
}; };
return through2.obj(forEach, atEnd);
return through2.obj(transformFunction, flushFunction) as Transform;
}; };
export let forEach = (funcArg: IPromiseFunction) => { export const forEach = <TFile = unknown>(funcArg: IPromiseFunction<TFile>): Transform => {
return defaultExport(funcArg, 'forEach'); return defaultExport(funcArg, 'forEach');
}; };
export let forFirst = (funcArg: IPromiseFunction) => { export const forFirst = <TFile = unknown>(funcArg: IPromiseFunction<TFile>): Transform => {
return defaultExport(funcArg, 'forFirst'); return defaultExport(funcArg, 'forFirst');
}; };
export let atEnd = (funcArg: IPromiseFunction) => { export const atEnd = <TFile = unknown>(funcArg: IPromiseFunction<TFile>): Transform => {
return defaultExport(funcArg, 'atEnd'); return defaultExport(funcArg, 'atEnd');
}; };
+3 -1
View File
@@ -5,8 +5,10 @@
"target": "ES2022", "target": "ES2022",
"module": "NodeNext", "module": "NodeNext",
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",
"noImplicitAny": true,
"esModuleInterop": true, "esModuleInterop": true,
"verbatimModuleSyntax": true "verbatimModuleSyntax": true,
"types": ["node"]
}, },
"exclude": [ "exclude": [
"dist_*/**/*.d.ts" "dist_*/**/*.d.ts"