Compare commits

..

No commits in common. "master" and "v4.2.8" have entirely different histories.

72 changed files with 2523 additions and 12688 deletions

View File

@ -1,66 +0,0 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -1,124 +0,0 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

21
.gitignore vendored
View File

@ -1,20 +1,7 @@
.nogit/
# artifacts
coverage/
public/
pages/
# installs
node_modules/ node_modules/
coverage/
pages/
public/
# caches test/temp/
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom

71
.gitlab-ci.yml Normal file
View File

@ -0,0 +1,71 @@
# gitzone standard
image: hosttoday/ht-docker-node:npmci
cache:
paths:
- .yarn/
key: "$CI_BUILD_STAGE"
stages:
- test
- release
- trigger
- pages
testLEGACY:
stage: test
script:
- npmci test legacy
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
allow_failure: true
testLTS:
stage: test
script:
- npmci test lts
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testSTABLE:
stage: test
script:
- npmci test stable
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci publish
only:
- tags
tags:
- docker
trigger:
stage: trigger
script:
- npmci trigger
only:
- tags
tags:
- docker
pages:
image: hosttoday/ht-docker-node:npmci
stage: pages
script:
- npmci command yarn global add npmpage
- npmci command npmpage --publish gitlab
tags:
- docker
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public

11
.vscode/launch.json vendored
View File

@ -1,11 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

26
.vscode/settings.json vendored
View File

@ -1,26 +0,0 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 Lossless GmbH Copyright (c) 2015 Push.Rocks
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

38
README.md Normal file
View File

@ -0,0 +1,38 @@
# smartfile
make files easily accessible for processing in javascript.
## Availabililty
[![npm](https://pushrocks.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartfile)
[![git](https://pushrocks.gitlab.io/assets/repo-button-git.svg)](https://gitlab.com/pushrocks/smartfile)
[![git](https://pushrocks.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smartfile)
[![docs](https://pushrocks.gitlab.io/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smartfile/)
## Status for master
[![build status](https://gitlab.com/pushrocks/smartfile/badges/master/build.svg)](https://gitlab.com/pushrocks/smartfile/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartfile/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartfile/commits/master)
[![Dependency Status](https://david-dm.org/pushrocks/smartfile.svg)](https://david-dm.org/pushrocks/smartfile)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartfile/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartfile/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smartfile/badges/code.svg)](https://www.bithound.io/github/pushrocks/smartfile)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
smartfile is an approach of being one tool to handle files in diverse environments.
### Smartfile Sections
smartfile thinks in sections:
section | description
--- | ---
fs | (object) gets data from fs to somewhere
memory | gets data from memory to somewhere
remote | gets data from remote locations to somewhere
interpreter | (object) handles yaml and json
smartfile | (class) a virtual representation of a file, alternative to vinyl file format
For further information read the linked docs at the top of this README.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
[![npm](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://push.rocks)

View File

@ -1,357 +0,0 @@
# Changelog
## 2025-01-29 - 11.2.0 - feat(fs)
Enhanced copy method with optional replaceTargetDir option for directory replacement
- Added optional 'replaceTargetDir' option to 'copy' and 'copySync' methods in 'fs.ts'.
- The 'replaceTargetDir' option allows replacing the target directory if both source and target are directories.
## 2025-01-29 - 11.1.9 - fix(fs)
Fix directory handling in copy and copySync functions
- Ensured existing directories at destination are removed before copying over them in async copy.
- Added a similar check and handling for synchronous copySync when destination is a directory.
## 2025-01-29 - 11.1.8 - fix(fs)
Fixed copy and copySync functions to ensure they always overwrite files.
- Fixed bug in copy function where files were not being overwritten when they already existed at the destination.
- Fixed bug in copySync function to ensure files are overwritten to match the async function's behavior.
## 2025-01-29 - 11.1.7 - fix(fs)
Refactor copy and copySync functions to simplify return type
- Changed the return type of fs.copy and fs.copySync from boolean to void.
- Removed unnecessary promise handling in fs.copy.
## 2025-01-29 - 11.1.6 - fix(fs)
Fix issues with fs file copy functions.
- Updated dependencies in package.json.
- Corrected comments for asynchronous and synchronous file copy functions in fs.ts.
## 2025-01-07 - 11.1.5 - fix(fs)
Improve waitForFileToBeReady function to handle directories and file stabilization
- Enhanced the waitForFileToBeReady to handle directory paths by checking for file existence within directories and waiting for stabilization.
- Modified the watcher logic to cater to changes when monitoring directories for file appearance.
- Introduced a helper function to ensure paths exist and another to resolve the first file in directories.
- Corrected logic for polling and stabilizing files within directories.
## 2025-01-07 - 11.1.4 - fix(fs)
Fix file existence check in waitForFileToBeReady method.
- Ensured that the directory and file exist before setting up the watcher in waitForFileToBeReady.
- Changed ensureDirectoryExists to ensureFileExists for correct file path verification.
- Handled ENOENT errors correctly to retry file existence checks until timeout is reached.
## 2025-01-07 - 11.1.3 - fix(fs)
Fix TypeScript type issue in fs module
- Corrected a TypeScript type in the fs module's checkFileStability function.
## 2025-01-07 - 11.1.2 - fix(fs)
Fix issues in file stability check and directory existence verification in fs module
- Removed unused variable 'isFileAvailable' in 'waitForFileToBeReady'.
- Fixed logic for ensuring the target directory exists before setting up file stability watcher.
- Refactored directory existence logic into 'ensureDirectoryExists' function.
## 2025-01-07 - 11.1.1 - fix(fs)
Improve waitForFileToBeReady function for file stability detection
- Enhanced error handling and file stability checks in waitForFileToBeReady function
- Added timeout feature for file readiness check
- Improved directory access check before file availability check
## 2025-01-07 - 11.1.0 - feat(SmartFile)
Add rename functionality to SmartFile class
- Implemented a new method to rename a file within the SmartFile class.
- The rename method updates the file path and optionally writes the renamed file to the disk.
## 2024-12-15 - 11.0.23 - fix(fs)
Handle errors in toObjectSync method
- Added error handling in toObjectSync function to capture and provide more informative error messages.
## 2024-06-23 - 11.0.22 - fix(core)
Update dependencies and changelog
- Updated @push.rocks/smartstream to ^3.0.44
- Updated glob to ^10.4.2
- Updated @types/node to ^20.14.8
## 2024-06-23 - 11.0.21 - fix(dependencies)
Update dependencies to latest versions
- Updated @push.rocks/smartpromise to ^4.0.4
- Updated @push.rocks/smartstream to ^3.0.44
- Updated glob to ^10.4.2
- Updated @types/node to ^20.14.8
## 2024-06-07 - 11.0.20 - Changelog
11.0.20
## 2024-06-07 - 11.0.19 - fix(core): update
11.0.19
- fix(core): update
## 2024-06-07 - 11.0.18 - fix(core): update
11.0.18
- fix(core): update
## 2024-06-06 - 11.0.17 - fix(core): update
11.0.17
- fix(core): update
## 2024-06-06 - 11.0.16 - fix(core): update
11.0.16
- fix(core): update
## 2024-05-29 - 11.0.16 - update description
11.0.16
- update description
## 2024-05-17 - 11.0.15 - fix(core): update
11.0.15
- fix(core): update
## 2024-04-14 - 11.0.14 - update tsconfig
11.0.14
- update tsconfig
## 2024-04-12 - 11.0.13 - fix(core): update
11.0.13
- fix(core): update
## 2024-04-12 - 11.0.12 - fix(core): update
11.0.12
- fix(core): update
## 2024-04-12 - 11.0.11 - fix(core): update
11.0.11
- fix(core): update
## 2024-04-03 - 11.0.10 - fix(core): update
11.0.10
- fix(core): update
## 2024-04-03 - 11.0.9 - fix(core): update
11.0.9
- fix(core): update
## 2024-04-02 - 11.0.8 - fix(core): update
11.0.8
- fix(core): update
## 2024-04-02 - 11.0.7 - fix(core): update
11.0.7
- fix(core): update
## 2024-04-02 - 11.0.6 - fix(core): update
11.0.6
- fix(core): update
## 2024-04-01 - 11.0.5 - update npmextra.json
11.0.5
- update npmextra.json: githost
## 2024-04-01 - 11.0.4 - fix(core): update
11.0.4
- fix(core): update
## 2023-11-24 - 11.0.3 - fix(core): update
11.0.3
- fix(core): update
## 2023-11-07 - 11.0.2 - fix(core): update
11.0.2
- fix(core): update
## 2023-11-07 - 11.0.1 - fix(core): update
11.0.1
- fix(core): update
## 2023-11-06 - 11.0.0 - fix(core): update
11.0.0
- fix(core): update
## 2023-11-06 - 10.0.40 - BREAKING CHANGE(core): update
10.0.40
- BREAKING CHANGE(core): update
## 2023-11-04 - 10.0.39 - fix(core): update
10.0.39
- fix(core): update
## 2023-11-04 - 10.0.38 - fix(core): update
10.0.38
- fix(core): update
## 2023-11-04 - 10.0.37 - fix(core): update
10.0.37
- fix(core): update
## 2023-11-03 - 10.0.36 - fix(core): update
10.0.36
- fix(core): update
## 2023-11-03 - 10.0.35 - fix(core): update
10.0.35
- fix(core): update
## 2023-11-03 - 10.0.34 - fix(core): update
10.0.34
- fix(core): update
## 2023-11-03 - 10.0.33 - fix(core): update
10.0.33
- fix(core): update
## 2023-10-12 - 10.0.32 - fix(core): update
10.0.32
- fix(core): update
## 2023-09-22 - 10.0.31 - fix(core): update
10.0.31
- fix(core): update
## 2023-08-31 - 10.0.30 - fix(core): update
10.0.30
- fix(core): update
## 2023-08-23 - 10.0.29 - fix(core): update
10.0.29
- fix(core): update
## 2023-07-12 - 10.0.28 - fix(core): update
10.0.28
- fix(core): update
## 2023-07-10 - 10.0.27 - fix(core): update
10.0.27
- fix(core): update
## 2023-07-10 - 10.0.26 - fix(core): update
10.0.26
- fix(core): update
## 2023-07-08 - 10.0.25 - fix(core): update
10.0.25
- fix(core): update
## 2023-06-25 - 10.0.24 to 10.0.14 - Series of Fixes
10.0.24 to 10.0.14
- Series of fixes in the core module
## 2023-01-09 - 10.0.13 to 10.0.6 - Series of Fixes
10.0.13 to 10.0.6
- Series of fixes in the core module
## 2022-09-05 - 10.0.5 to 10.0.3 - Series of Fixes
10.0.5 to 10.0.3
- Series of fixes in the core module
## 2022-06-07 - 10.0.2 to 10.0.1 - Series of Fixes
10.0.2 to 10.0.1
- Series of fixes in the core module
## 2022-06-07 - 9.0.7 - BREAKING CHANGE(core): switch to esm
9.0.7
- BREAKING CHANGE(core): switch to esm
## 2022-03-11 - 9.0.6 to 9.0.2 - Series of Fixes
9.0.6 to 9.0.2
- Series of fixes in the core module
## 2021-12-01 - 9.0.1 - fix(core): update
9.0.1
- fix(core): update
## 2021-12-01 - 9.0.0 - fix(absolute pathing)
9.0.0
- add functions for easily getting absolute paths
## 2021-11-30 - 8.0.11 - BREAKING CHANGE(relative pathing)
8.0.11
- improved relative pathing
## 2020-08-10 - 8.0.10 to 7.0.12 - Series of Fixes and Updates
8.0.10 to 7.0.12
- Series of fixes in the core module
- BREAKING CHANGE(Smartfile class): switch to a Buffer-only approach
## 2019-02-17 - 7.0.0 - fix(core): update dependencies
7.0.0
- fix(core): update dependencies
## 2019-01-27 - 6.0.12 - BREAKING CHANGE(smartfile.fs.fileExists)
6.0.12
- now returns a Promise<boolean>
## 2018-08-19 - 6.0.11 to 6.0.6 - Series of Fixes
6.0.11 to 6.0.6
- Series of fixes in core and dependencies
## 2018-07-03 - 6.0.5 to 5.0.0 - Series of Fixes
6.0.5 to 5.0.0
- Series of fixes in core and dependencies
## 2018-02-16 - 4.2.28 - BREAKING CHANGE(scope)
4.2.28
- switch to pushrocks scope

11
dist/index.d.ts vendored Normal file
View File

@ -0,0 +1,11 @@
import 'typings-global';
import * as SmartfileFs from './smartfile.fs';
import * as SmartfileInterpreter from './smartfile.interpreter';
import * as SmartfileMemory from './smartfile.memory';
import * as SmartfileRemote from './smartfile.remote';
export { Smartfile } from './smartfile.classes.smartfile';
export declare let fs: typeof SmartfileFs;
export declare let interpreter: typeof SmartfileInterpreter;
export declare let memory: typeof SmartfileMemory;
export declare let remote: typeof SmartfileRemote;
export declare let requireReload: (path: string) => any;

15
dist/index.js vendored Normal file
View File

@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("typings-global");
const SmartfileFs = require("./smartfile.fs");
const SmartfileInterpreter = require("./smartfile.interpreter");
const SmartfileMemory = require("./smartfile.memory");
const SmartfileRemote = require("./smartfile.remote");
var smartfile_classes_smartfile_1 = require("./smartfile.classes.smartfile");
exports.Smartfile = smartfile_classes_smartfile_1.Smartfile;
exports.fs = SmartfileFs;
exports.interpreter = SmartfileInterpreter;
exports.memory = SmartfileMemory;
exports.remote = SmartfileRemote;
exports.requireReload = SmartfileFs.requireReload;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLDBCQUF1QjtBQUd2Qiw4Q0FBNkM7QUFDN0MsZ0VBQStEO0FBQy9ELHNEQUFxRDtBQUNyRCxzREFBcUQ7QUFFckQsNkVBQXVEO0FBQS9DLGtEQUFBLFNBQVMsQ0FBQTtBQUVOLFFBQUEsRUFBRSxHQUFHLFdBQVcsQ0FBQTtBQUNoQixRQUFBLFdBQVcsR0FBRyxvQkFBb0IsQ0FBQTtBQUNsQyxRQUFBLE1BQU0sR0FBRyxlQUFlLENBQUE7QUFDeEIsUUFBQSxNQUFNLEdBQUcsZUFBZSxDQUFBO0FBQ3hCLFFBQUEsYUFBYSxHQUFHLFdBQVcsQ0FBQyxhQUFhLENBQUEifQ==

70
dist/smartfile.classes.smartfile.d.ts vendored Normal file
View File

@ -0,0 +1,70 @@
/// <reference types="node" />
export interface ISmartfileConstructorOptions {
path?: string;
contentString?: string;
contentBuffer?: Buffer;
base?: string;
}
/**
* class Smartfile
* -> is vinyl file compatible
*/
export declare class Smartfile {
/**
* the full path of the file on disk
*/
path: string;
/**
* the content of the file as Buffer
*/
contentBuffer: Buffer;
/**
* The current working directory of the file
*/
base: string;
/**
* sync the file with disk
*/
sync: boolean;
/**
* the constructor of Smartfile
* @param optionsArg
*/
constructor(optionsArg: ISmartfileConstructorOptions);
/**
* set contents from string
* @param contentString
*/
setContentsFromString(contentString: string): void;
/**
* write file to disk
*/
write(): Promise<void>;
/**
* read file from disk
*/
read(): Promise<void>;
/**
* vinyl-compatibility: alias of this.contentBuffer
*/
contents: Buffer;
/**
* vinyl-compatibility
*/
readonly cwd: string;
/**
* return relative path of file
*/
readonly relative: string;
/**
* return truw when the file has content
*/
isNull(): boolean;
/**
* return true if contents are Buffer
*/
isBuffer(): boolean;
isDirectory(): boolean;
isStream(): boolean;
isSymbolic(): boolean;
}

108
dist/smartfile.classes.smartfile.js vendored Normal file
View File

@ -0,0 +1,108 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const plugins = require("./smartfile.plugins");
/**
* class Smartfile
* -> is vinyl file compatible
*/
class Smartfile {
/**
* the constructor of Smartfile
* @param optionsArg
*/
constructor(optionsArg) {
if (optionsArg.contentBuffer) {
this.contentBuffer = optionsArg.contentBuffer;
}
else if (optionsArg.contentString) {
this.setContentsFromString(optionsArg.contentString);
}
else {
console.log('created empty Smartfile?');
}
this.path = optionsArg.path;
this.base = optionsArg.base;
}
/**
* set contents from string
* @param contentString
*/
setContentsFromString(contentString) {
this.contents = new Buffer(contentString);
}
/**
* write file to disk
*/
write() {
return __awaiter(this, void 0, void 0, function* () {
});
}
/**
* read file from disk
*/
read() {
return __awaiter(this, void 0, void 0, function* () {
});
}
// -----------------------------------------------
// vinyl compatibility
// -----------------------------------------------
/**
* vinyl-compatibility: alias of this.contentBuffer
*/
get contents() {
return this.contentBuffer;
}
set contents(contentsArg) {
this.contentBuffer = contentsArg;
}
/**
* vinyl-compatibility
*/
get cwd() {
return process.cwd();
}
/**
* return relative path of file
*/
get relative() {
return plugins.path.relative(this.base, this.path);
}
/**
* return truw when the file has content
*/
isNull() {
if (!this.contentBuffer) {
return true;
}
return false;
}
/**
* return true if contents are Buffer
*/
isBuffer() {
if (this.contents instanceof Buffer) {
return true;
}
return false;
}
isDirectory() {
return false;
}
isStream() {
return false;
}
isSymbolic() {
return false;
}
}
exports.Smartfile = Smartfile;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRmaWxlLmNsYXNzZXMuc21hcnRmaWxlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRmaWxlLmNsYXNzZXMuc21hcnRmaWxlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7QUFBQSwrQ0FBOEM7QUFTOUM7OztHQUdHO0FBQ0g7SUFxQkU7OztPQUdHO0lBQ0gsWUFBYSxVQUF3QztRQUNuRCxFQUFFLENBQUMsQ0FBQyxVQUFVLENBQUMsYUFBYSxDQUFDLENBQUMsQ0FBQztZQUM3QixJQUFJLENBQUMsYUFBYSxHQUFHLFVBQVUsQ0FBQyxhQUFhLENBQUE7UUFDL0MsQ0FBQztRQUFDLElBQUksQ0FBQyxFQUFFLENBQUMsQ0FBQyxVQUFVLENBQUMsYUFBYSxDQUFDLENBQUMsQ0FBQztZQUNwQyxJQUFJLENBQUMscUJBQXFCLENBQUMsVUFBVSxDQUFDLGFBQWEsQ0FBQyxDQUFBO1FBQ3RELENBQUM7UUFBQyxJQUFJLENBQUMsQ0FBQztZQUNOLE9BQU8sQ0FBQyxHQUFHLENBQUMsMEJBQTBCLENBQUMsQ0FBQTtRQUN6QyxDQUFDO1FBQ0QsSUFBSSxDQUFDLElBQUksR0FBRyxVQUFVLENBQUMsSUFBSSxDQUFBO1FBQzNCLElBQUksQ0FBQyxJQUFJLEdBQUcsVUFBVSxDQUFDLElBQUksQ0FBQTtJQUM3QixDQUFDO0lBR0Q7OztPQUdHO0lBQ0gscUJBQXFCLENBQUMsYUFBcUI7UUFDekMsSUFBSSxDQUFDLFFBQVEsR0FBRyxJQUFJLE1BQU0sQ0FBQyxhQUFhLENBQUMsQ0FBQTtJQUMzQyxDQUFDO0lBRUQ7O09BRUc7SUFDRyxLQUFLOztRQUVYLENBQUM7S0FBQTtJQUVEOztPQUVHO0lBQ0csSUFBSTs7UUFDVixDQUFDO0tBQUE7SUFFRCxrREFBa0Q7SUFDbEQsc0JBQXNCO0lBQ3RCLGtEQUFrRDtJQUNsRDs7T0FFRztJQUNILElBQUksUUFBUTtRQUNWLE1BQU0sQ0FBQyxJQUFJLENBQUMsYUFBYSxDQUFBO0lBQzNCLENBQUM7SUFDRCxJQUFJLFFBQVEsQ0FBRSxXQUFXO1FBQ3ZCLElBQUksQ0FBQyxhQUFhLEdBQUcsV0FBVyxDQUFBO0lBQ2xDLENBQUM7SUFFRDs7T0FFRztJQUNILElBQUksR0FBRztRQUNMLE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxFQUFFLENBQUE7SUFDdEIsQ0FBQztJQUVEOztPQUVHO0lBQ0gsSUFBSSxRQUFRO1FBQ1YsTUFBTSxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLElBQUksQ0FBQyxJQUFJLEVBQUUsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFBO0lBQ3BELENBQUM7SUFFRDs7T0FFRztJQUNILE1BQU07UUFDSixFQUFFLENBQUMsQ0FBQyxDQUFDLElBQUksQ0FBQyxhQUFhLENBQUMsQ0FBQyxDQUFDO1lBQ3hCLE1BQU0sQ0FBQyxJQUFJLENBQUE7UUFDYixDQUFDO1FBQ0QsTUFBTSxDQUFDLEtBQUssQ0FBQTtJQUNkLENBQUM7SUFFRDs7T0FFRztJQUNILFFBQVE7UUFDTixFQUFFLENBQUMsQ0FBQyxJQUFJLENBQUMsUUFBUSxZQUFZLE1BQU0sQ0FBQyxDQUFDLENBQUM7WUFDcEMsTUFBTSxDQUFDLElBQUksQ0FBQTtRQUNiLENBQUM7UUFDRCxNQUFNLENBQUMsS0FBSyxDQUFBO0lBQ2QsQ0FBQztJQUVELFdBQVc7UUFDVCxNQUFNLENBQUMsS0FBSyxDQUFBO0lBQ2QsQ0FBQztJQUVELFFBQVE7UUFDTixNQUFNLENBQUMsS0FBSyxDQUFBO0lBQ2QsQ0FBQztJQUVELFVBQVU7UUFDUixNQUFNLENBQUMsS0FBSyxDQUFBO0lBQ2QsQ0FBQztDQUNGO0FBckhELDhCQXFIQyJ9

144
dist/smartfile.fs.d.ts vendored Normal file
View File

@ -0,0 +1,144 @@
import 'typings-global';
import { Smartfile } from './smartfile.classes.smartfile';
/**
*
* @param filePath
* @returns {boolean}
*/
export declare let fileExistsSync: (filePath: any) => boolean;
/**
*
* @param filePath
* @returns {any}
*/
export declare let fileExists: (filePath: any) => Promise<{}>;
/**
* Checks if given path points to an existing directory
*/
export declare let isDirectory: (pathArg: any) => boolean;
/**
* Checks if a given path points to an existing file
*/
export declare let isFile: (pathArg: any) => boolean;
/**
* copies a file from A to B on the local disk
*/
export declare let copy: (fromArg: string, toArg: string) => Promise<{}>;
/**
* copies a file SYNCHRONOUSLY from A to B on the local disk
*/
export declare let copySync: (fromArg: string, toArg: string) => boolean;
/**
* ensures that a directory is in place
*/
export declare let ensureDir: (dirPathArg: string) => Promise<{}>;
/**
* ensures that a directory is in place
*/
export declare let ensureDirSync: (dirPathArg: string) => void;
/**
* ensure an empty directory
* @executes ASYNC
*/
export declare let ensureEmptyDir: (dirPathArg: string) => Promise<{}>;
/**
* ensure an empty directory
* @executes SYNC
*/
export declare let ensureEmptyDirSync: (dirPathArg: string) => void;
/**
* ensures that a file is on disk
* @param filePath the filePath to ensureDir
* @param the fileContent to place into a new file in case it doesn't exist yet
* @returns Promise<void>
* @exec ASYNC
*/
export declare let ensureFile: (filePathArg: any, initFileStringArg: any) => Promise<void>;
/**
* ensures that a file is on disk
* @param filePath the filePath to ensureDir
* @param the fileContent to place into a new file in case it doesn't exist yet
* @returns Promise<void>
* @exec SYNC
*/
export declare let ensureFileSync: (filePathArg: string, initFileStringArg: string) => void;
/**
* removes a file or folder from local disk
*/
export declare let remove: (pathArg: string) => Promise<void>;
/**
* removes a file SYNCHRONOUSLY from local disk
*/
export declare let removeSync: (pathArg: string) => boolean;
/**
* removes an array of filePaths from disk
*/
export declare let removeMany: (filePathArrayArg: string[]) => Promise<void[]>;
/**
* like removeFilePathArray but SYNCHRONOUSLY
*/
export declare let removeManySync: (filePathArrayArg: string[]) => void;
/**
*
* @param filePathArg
* @param fileTypeArg
* @returns {any}
*/
export declare let toObjectSync: (filePathArg: any, fileTypeArg?: any) => any;
/**
* reads a file content to a String
* @param filePath
* @returns {string|Buffer|any}
*/
export declare let toStringSync: (filePath: string) => string;
export declare let fileTreeToObject: (dirPathArg: string, miniMatchFilter: string) => Promise<Smartfile[]>;
/**
*
* @param filePathArg
* @param options
* @returns {number}
*/
export declare let toVinylSync: (filePathArg: any, options?: {}) => any;
/**
* lets you reload files hot.
* @param path
* @returns {any}
*/
export declare let requireReload: (path: string) => any;
/**
* lists Folders in a directory on local disk
* @returns Promise
*/
export declare let listFolders: (pathArg: string, regexFilter?: RegExp) => Promise<{}>;
/**
* lists Folders SYNCHRONOUSLY in a directory on local disk
* @returns an array with the folder names as strings
*/
export declare let listFoldersSync: (pathArg: string, regexFilter?: RegExp) => string[];
/**
* lists Files in a directory on local disk
* @returns Promise
*/
export declare let listFiles: (pathArg: string, regexFilter?: RegExp) => Promise<{}>;
/**
* lists Files SYNCHRONOUSLY in a directory on local disk
* @returns an array with the folder names as strings
*/
export declare let listFilesSync: (pathArg: string, regexFilter?: RegExp) => string[];
/**
* lists all items (folders AND files) in a directory on local disk
* @returns Promise<string[]>
*/
export declare let listAllItems: (pathArg: string, regexFilter?: RegExp) => Promise<string[]>;
/**
* lists all items (folders AND files) in a directory on local disk
* @returns an array with the folder names as strings
* @executes SYNC
*/
export declare let listAllItemsSync: (pathArg: string, regexFilter?: RegExp) => string[];
/**
* lists a file tree using a miniMatch filter
* note: if the miniMatch Filter is an absolute path, the cwdArg will be omitted
* @returns Promise<string[]> string array with the absolute paths of all matching files
*/
export declare let listFileTree: (dirPathArg: string, miniMatchFilter: string) => Promise<string[]>;

362
dist/smartfile.fs.js vendored Normal file

File diff suppressed because one or more lines are too long

3
dist/smartfile.interpreter.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
import 'typings-global';
export declare let filetype: (pathArg: string) => string;
export declare let objectFile: (fileStringArg: string, fileTypeArg: any) => any;

22
dist/smartfile.interpreter.js vendored Normal file
View File

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("typings-global");
const plugins = require("./smartfile.plugins");
exports.filetype = (pathArg) => {
let extName = plugins.path.extname(pathArg);
let fileType = extName.replace(/\.([a-z]*)/, '$1'); // remove . form fileType
return fileType;
};
exports.objectFile = (fileStringArg, fileTypeArg) => {
switch (fileTypeArg) {
case 'yml':
case 'yaml':
return plugins.yaml.safeLoad(fileStringArg);
case 'json':
return JSON.parse(fileStringArg);
default:
console.error('file type ' + fileTypeArg.blue + ' not supported');
break;
}
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRmaWxlLmludGVycHJldGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvc21hcnRmaWxlLmludGVycHJldGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsMEJBQXVCO0FBRXZCLCtDQUErQztBQUVwQyxRQUFBLFFBQVEsR0FBRyxDQUFDLE9BQWU7SUFDbEMsSUFBSSxPQUFPLEdBQUcsT0FBTyxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUE7SUFDM0MsSUFBSSxRQUFRLEdBQUcsT0FBTyxDQUFDLE9BQU8sQ0FBQyxZQUFZLEVBQUMsSUFBSSxDQUFDLENBQUEsQ0FBQyx5QkFBeUI7SUFDM0UsTUFBTSxDQUFDLFFBQVEsQ0FBQTtBQUNuQixDQUFDLENBQUE7QUFFVSxRQUFBLFVBQVUsR0FBRyxDQUFDLGFBQXFCLEVBQUUsV0FBVztJQUN2RCxNQUFNLENBQUMsQ0FBQyxXQUFXLENBQUMsQ0FBQyxDQUFDO1FBQ2xCLEtBQUssS0FBSyxDQUFFO1FBQ1osS0FBSyxNQUFNO1lBQ1AsTUFBTSxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLGFBQWEsQ0FBQyxDQUFBO1FBQy9DLEtBQUssTUFBTTtZQUNQLE1BQU0sQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLGFBQWEsQ0FBQyxDQUFBO1FBQ3BDO1lBQ0ksT0FBTyxDQUFDLEtBQUssQ0FBQyxZQUFZLEdBQUcsV0FBVyxDQUFDLElBQUksR0FBRyxnQkFBZ0IsQ0FBQyxDQUFBO1lBQ2pFLEtBQUssQ0FBQTtJQUNiLENBQUM7QUFDTCxDQUFDLENBQUEifQ==

46
dist/smartfile.memory.d.ts vendored Normal file
View File

@ -0,0 +1,46 @@
/// <reference types="node" />
import 'typings-global';
export interface IVinylFile {
contents: Buffer;
base: string;
path: string;
}
/**
* converts file to Object
* @param fileStringArg
* @param fileTypeArg
* @returns {any|any}
*/
export declare let toObject: (fileStringArg: string, fileTypeArg: string) => any;
/**
* takes a string and converts it to vinyl file
* @param fileArg
* @param optionsArg
*/
export declare let toVinylFileSync: (fileArg: string, optionsArg?: {
filename?: string;
base?: string;
relPath?: string;
}) => any;
/**
* takes a string array and some options and returns a vinylfile array
* @param arrayArg
* @param optionsArg
*/
export declare let toVinylArraySync: (arrayArg: string[], optionsArg?: {
filename?: string;
base?: string;
relPath?: string;
}) => any[];
/**
* takes a vinylFile object and converts it to String
*/
export declare let vinylToStringSync: (fileArg: IVinylFile) => string;
/**
* writes string or vinyl file to disk.
* @param fileArg
* @param fileNameArg
* @param fileBaseArg
*/
export declare let toFs: (fileContentArg: string | IVinylFile, filePathArg: any) => Promise<{}>;
export declare let toFsSync: (fileArg: any, filePathArg: string) => void;

93
dist/smartfile.memory.js vendored Normal file
View File

@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("typings-global");
const plugins = require("./smartfile.plugins");
const SmartfileInterpreter = require("./smartfile.interpreter");
let vinyl = require('vinyl');
/**
* converts file to Object
* @param fileStringArg
* @param fileTypeArg
* @returns {any|any}
*/
exports.toObject = function (fileStringArg, fileTypeArg) {
return SmartfileInterpreter.objectFile(fileStringArg, fileTypeArg);
};
/**
* takes a string and converts it to vinyl file
* @param fileArg
* @param optionsArg
*/
exports.toVinylFileSync = function (fileArg, optionsArg) {
optionsArg ? void (0) : optionsArg = { filename: 'vinylfile', base: '/' };
optionsArg.filename ? void (0) : optionsArg.filename = 'vinylfile';
optionsArg.base ? void (0) : optionsArg.base = '/';
optionsArg.relPath ? void ('0') : optionsArg.relPath = '';
let vinylFile = new vinyl({
base: optionsArg.base,
path: plugins.path.join(optionsArg.base, optionsArg.relPath, optionsArg.filename),
contents: new Buffer(fileArg)
});
return vinylFile;
};
/**
* takes a string array and some options and returns a vinylfile array
* @param arrayArg
* @param optionsArg
*/
exports.toVinylArraySync = function (arrayArg, optionsArg) {
let vinylArray = [];
for (let stringIndexArg in arrayArg) {
let myString = arrayArg[stringIndexArg];
vinylArray.push(exports.toVinylFileSync(myString, optionsArg));
}
return vinylArray;
};
/**
* takes a vinylFile object and converts it to String
*/
exports.vinylToStringSync = function (fileArg) {
return fileArg.contents.toString('utf8');
};
/**
* writes string or vinyl file to disk.
* @param fileArg
* @param fileNameArg
* @param fileBaseArg
*/
exports.toFs = function (fileContentArg, filePathArg) {
let done = plugins.q.defer();
// function checks to abort if needed
if (!fileContentArg || !filePathArg) {
throw new Error('expected valid arguments');
}
// prepare actual write action
let fileString;
let filePath = filePathArg;
if (vinyl.isVinyl(fileContentArg)) {
let fileContentArg2 = fileContentArg;
fileString = exports.vinylToStringSync(fileContentArg2);
}
else if (typeof fileContentArg === 'string') {
fileString = fileContentArg;
}
plugins.fsExtra.writeFile(filePath, fileString, 'utf8', done.resolve);
return done.promise;
};
exports.toFsSync = function (fileArg, filePathArg) {
// function checks to abort if needed
if (!fileArg || !filePathArg) {
throw new Error('expected a valid arguments');
}
// prepare actual write action
let fileString;
let filePath = filePathArg;
if (typeof fileArg !== 'string') {
fileString = exports.vinylToStringSync(fileArg);
}
else if (typeof fileArg === 'string') {
fileString = fileArg;
}
plugins.fsExtra.writeFileSync(filePath, fileString, 'utf8');
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRmaWxlLm1lbW9yeS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL3NtYXJ0ZmlsZS5tZW1vcnkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSwwQkFBdUI7QUFFdkIsK0NBQStDO0FBQy9DLGdFQUFnRTtBQUNoRSxJQUFJLEtBQUssR0FBRyxPQUFPLENBQUMsT0FBTyxDQUFDLENBQUE7QUFRNUI7Ozs7O0dBS0c7QUFDUSxRQUFBLFFBQVEsR0FBRyxVQUFVLGFBQXFCLEVBQUUsV0FBbUI7SUFDeEUsTUFBTSxDQUFDLG9CQUFvQixDQUFDLFVBQVUsQ0FBQyxhQUFhLEVBQUUsV0FBVyxDQUFDLENBQUE7QUFDcEUsQ0FBQyxDQUFBO0FBRUQ7Ozs7R0FJRztBQUNRLFFBQUEsZUFBZSxHQUFHLFVBQVUsT0FBZSxFQUFFLFVBQW1FO0lBQ3pILFVBQVUsR0FBRyxLQUFLLENBQUMsQ0FBQyxDQUFDLEdBQUcsVUFBVSxHQUFHLEVBQUUsUUFBUSxFQUFFLFdBQVcsRUFBRSxJQUFJLEVBQUUsR0FBRyxFQUFFLENBQUE7SUFDekUsVUFBVSxDQUFDLFFBQVEsR0FBRyxLQUFLLENBQUMsQ0FBQyxDQUFDLEdBQUcsVUFBVSxDQUFDLFFBQVEsR0FBRyxXQUFXLENBQUE7SUFDbEUsVUFBVSxDQUFDLElBQUksR0FBRyxLQUFLLENBQUMsQ0FBQyxDQUFDLEdBQUcsVUFBVSxDQUFDLElBQUksR0FBRyxHQUFHLENBQUE7SUFDbEQsVUFBVSxDQUFDLE9BQU8sR0FBRyxLQUFLLENBQUMsR0FBRyxDQUFDLEdBQUcsVUFBVSxDQUFDLE9BQU8sR0FBRyxFQUFFLENBQUE7SUFDekQsSUFBSSxTQUFTLEdBQUcsSUFBSSxLQUFLLENBQUM7UUFDeEIsSUFBSSxFQUFFLFVBQVUsQ0FBQyxJQUFJO1FBQ3JCLElBQUksRUFBRSxPQUFPLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxVQUFVLENBQUMsSUFBSSxFQUFFLFVBQVUsQ0FBQyxPQUFPLEVBQUUsVUFBVSxDQUFDLFFBQVEsQ0FBQztRQUNqRixRQUFRLEVBQUUsSUFBSSxNQUFNLENBQUMsT0FBTyxDQUFDO0tBQzlCLENBQUMsQ0FBQTtJQUNGLE1BQU0sQ0FBQyxTQUFTLENBQUE7QUFDbEIsQ0FBQyxDQUFBO0FBRUQ7Ozs7R0FJRztBQUNRLFFBQUEsZ0JBQWdCLEdBQUcsVUFDNUIsUUFBa0IsRUFDbEIsVUFJQztJQUVELElBQUksVUFBVSxHQUFHLEVBQUUsQ0FBQTtJQUNuQixHQUFHLENBQUMsQ0FBQyxJQUFJLGNBQWMsSUFBSSxRQUFRLENBQUMsQ0FBQyxDQUFDO1FBQ3BDLElBQUksUUFBUSxHQUFHLFFBQVEsQ0FBRSxjQUFjLENBQUUsQ0FBQTtRQUN6QyxVQUFVLENBQUMsSUFBSSxDQUFDLHVCQUFlLENBQUMsUUFBUSxFQUFFLFVBQVUsQ0FBQyxDQUFDLENBQUE7SUFDeEQsQ0FBQztJQUNELE1BQU0sQ0FBQyxVQUFVLENBQUE7QUFDbkIsQ0FBQyxDQUFBO0FBRUQ7O0dBRUc7QUFDUSxRQUFBLGlCQUFpQixHQUFHLFVBQVUsT0FBbUI7SUFDMUQsTUFBTSxDQUFDLE9BQU8sQ0FBQyxRQUFRLENBQUMsUUFBUSxDQUFDLE1BQU0sQ0FBQyxDQUFBO0FBQzFDLENBQUMsQ0FBQTtBQUVEOzs7OztHQUtHO0FBQ1EsUUFBQSxJQUFJLEdBQUcsVUFBVSxjQUFtQyxFQUFFLFdBQVc7SUFDMUUsSUFBSSxJQUFJLEdBQUcsT0FBTyxDQUFDLENBQUMsQ0FBQyxLQUFLLEVBQUUsQ0FBQTtJQUU1QixxQ0FBcUM7SUFDckMsRUFBRSxDQUFDLENBQUMsQ0FBQyxjQUFjLElBQUksQ0FBQyxXQUFXLENBQUMsQ0FBQyxDQUFDO1FBQ3BDLE1BQU0sSUFBSSxLQUFLLENBQUMsMEJBQTBCLENBQUMsQ0FBQTtJQUM3QyxDQUFDO0lBRUQsOEJBQThCO0lBQzlCLElBQUksVUFBa0IsQ0FBQTtJQUN0QixJQUFJLFFBQVEsR0FBVyxXQUFXLENBQUE7SUFDbEMsRUFBRSxDQUFDLENBQUMsS0FBSyxDQUFDLE9BQU8sQ0FBQyxjQUFjLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFDbEMsSUFBSSxlQUFlLEdBQVEsY0FBYyxDQUFBO1FBQ3pDLFVBQVUsR0FBRyx5QkFBaUIsQ0FBQyxlQUFlLENBQUMsQ0FBQTtJQUNqRCxDQUFDO0lBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sY0FBYyxLQUFLLFFBQVEsQ0FBQyxDQUFDLENBQUM7UUFDOUMsVUFBVSxHQUFHLGNBQWMsQ0FBQTtJQUM3QixDQUFDO0lBQ0QsT0FBTyxDQUFDLE9BQU8sQ0FBQyxTQUFTLENBQUMsUUFBUSxFQUFFLFVBQVUsRUFBRSxNQUFNLEVBQUUsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFBO0lBQ3JFLE1BQU0sQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFBO0FBQ3JCLENBQUMsQ0FBQTtBQUVVLFFBQUEsUUFBUSxHQUFHLFVBQVUsT0FBTyxFQUFFLFdBQW1CO0lBQzFELHFDQUFxQztJQUNyQyxFQUFFLENBQUMsQ0FBQyxDQUFDLE9BQU8sSUFBSSxDQUFDLFdBQVcsQ0FBQyxDQUFDLENBQUM7UUFDN0IsTUFBTSxJQUFJLEtBQUssQ0FBQyw0QkFBNEIsQ0FBQyxDQUFBO0lBQy9DLENBQUM7SUFFRCw4QkFBOEI7SUFDOUIsSUFBSSxVQUFrQixDQUFBO0lBQ3RCLElBQUksUUFBUSxHQUFXLFdBQVcsQ0FBQTtJQUVsQyxFQUFFLENBQUMsQ0FBQyxPQUFPLE9BQU8sS0FBSyxRQUFRLENBQUMsQ0FBQyxDQUFDO1FBQ2hDLFVBQVUsR0FBRyx5QkFBaUIsQ0FBQyxPQUFPLENBQUMsQ0FBQTtJQUN6QyxDQUFDO0lBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFDLE9BQU8sT0FBTyxLQUFLLFFBQVEsQ0FBQyxDQUFDLENBQUM7UUFDdkMsVUFBVSxHQUFHLE9BQU8sQ0FBQTtJQUN0QixDQUFDO0lBQ0QsT0FBTyxDQUFDLE9BQU8sQ0FBQyxhQUFhLENBQUMsUUFBUSxFQUFFLFVBQVUsRUFBRSxNQUFNLENBQUMsQ0FBQTtBQUM3RCxDQUFDLENBQUEifQ==

11
dist/smartfile.plugins.d.ts vendored Normal file
View File

@ -0,0 +1,11 @@
import 'typings-global';
export import fs = require('fs');
export import fsExtra = require('fs-extra');
export declare let glob: any;
export import path = require('path');
export import q = require('smartq');
export import smartrequest = require('smartrequest');
export declare let requireReload: any;
export import smartpath = require('smartpath');
export declare let vinylFile: any;
export declare let yaml: any;

14
dist/smartfile.plugins.js vendored Normal file
View File

@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("typings-global");
exports.fs = require("fs");
exports.fsExtra = require("fs-extra");
exports.glob = require('glob');
exports.path = require("path");
exports.q = require("smartq");
exports.smartrequest = require("smartrequest");
exports.requireReload = require('require-reload');
exports.smartpath = require("smartpath");
exports.vinylFile = require('vinyl-file');
exports.yaml = require('js-yaml');
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRmaWxlLnBsdWdpbnMuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9zbWFydGZpbGUucGx1Z2lucy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLDBCQUF1QjtBQUN2QiwyQkFBZ0M7QUFDaEMsc0NBQTJDO0FBQ2hDLFFBQUEsSUFBSSxHQUFHLE9BQU8sQ0FBQyxNQUFNLENBQUMsQ0FBQTtBQUNqQywrQkFBb0M7QUFDcEMsOEJBQW1DO0FBQ25DLCtDQUFvRDtBQUN6QyxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsZ0JBQWdCLENBQUMsQ0FBQTtBQUNwRCx5Q0FBOEM7QUFDbkMsUUFBQSxTQUFTLEdBQUcsT0FBTyxDQUFDLFlBQVksQ0FBQyxDQUFBO0FBQ2pDLFFBQUEsSUFBSSxHQUFHLE9BQU8sQ0FBQyxTQUFTLENBQUMsQ0FBQSJ9

13
dist/smartfile.remote.d.ts vendored Normal file
View File

@ -0,0 +1,13 @@
import 'typings-global';
/**
*
* @param fromArg
* @returns {any}
*/
export declare let toObject: (fromArg: string) => Promise<{}>;
/**
*
* @param fromArg
* @returns {any}
*/
export declare let toString: (fromArg: string) => Promise<{}>;

51
dist/smartfile.remote.js vendored Normal file
View File

@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("typings-global");
const plugins = require("./smartfile.plugins");
/* export let toFs = function (from: string, toPath: string) {
let done = plugins.q.defer()
let stream = plugins.smartrequest(from).pipe(plugins.fsExtra.createWriteStream(toPath))
stream.on('finish', function () {
done.resolve(toPath)
})
return done.promise
} */
/**
*
* @param fromArg
* @returns {any}
*/
exports.toObject = function (fromArg) {
let done = plugins.q.defer();
plugins.smartrequest.request(fromArg, {
method: 'get'
}).then((res) => {
if (res.statusCode === 200) {
done.resolve(res.body);
}
else {
console.log('could not get remote file from ' + fromArg);
done.reject(new Error('could not get remote file from ' + fromArg));
}
});
return done.promise;
};
/**
*
* @param fromArg
* @returns {any}
*/
exports.toString = (fromArg) => {
let done = plugins.q.defer();
plugins.smartrequest.get(fromArg).then((res) => {
if (res.statusCode === 200) {
done.resolve(res.body);
}
else {
console.error('could not get remote file from ' + fromArg);
done.reject(new Error('could not get remote file from ' + fromArg));
}
});
return done.promise;
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic21hcnRmaWxlLnJlbW90ZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3RzL3NtYXJ0ZmlsZS5yZW1vdGUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSwwQkFBdUI7QUFDdkIsK0NBQStDO0FBRy9DOzs7Ozs7O0lBT0k7QUFFSjs7OztHQUlHO0FBQ1EsUUFBQSxRQUFRLEdBQUcsVUFBVSxPQUFlO0lBQzdDLElBQUksSUFBSSxHQUFHLE9BQU8sQ0FBQyxDQUFDLENBQUMsS0FBSyxFQUFFLENBQUE7SUFDNUIsT0FBTyxDQUFDLFlBQVksQ0FBQyxPQUFPLENBQUMsT0FBTyxFQUFFO1FBQ3BDLE1BQU0sRUFBRSxLQUFLO0tBQ2QsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLEdBQVE7UUFDZixFQUFFLENBQUMsQ0FBQyxHQUFHLENBQUMsVUFBVSxLQUFLLEdBQUcsQ0FBQyxDQUFDLENBQUM7WUFDM0IsSUFBSSxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLENBQUE7UUFDeEIsQ0FBQztRQUFDLElBQUksQ0FBQyxDQUFDO1lBQ04sT0FBTyxDQUFDLEdBQUcsQ0FBQyxpQ0FBaUMsR0FBRyxPQUFPLENBQUMsQ0FBQTtZQUN4RCxJQUFJLENBQUMsTUFBTSxDQUFDLElBQUksS0FBSyxDQUFDLGlDQUFpQyxHQUFHLE9BQU8sQ0FBQyxDQUFDLENBQUE7UUFDckUsQ0FBQztJQUNILENBQUMsQ0FBQyxDQUFBO0lBQ0YsTUFBTSxDQUFDLElBQUksQ0FBQyxPQUFPLENBQUE7QUFDckIsQ0FBQyxDQUFBO0FBRUQ7Ozs7R0FJRztBQUNRLFFBQUEsUUFBUSxHQUFHLENBQUMsT0FBZTtJQUNwQyxJQUFJLElBQUksR0FBRyxPQUFPLENBQUMsQ0FBQyxDQUFDLEtBQUssRUFBRSxDQUFBO0lBQzVCLE9BQU8sQ0FBQyxZQUFZLENBQUMsR0FBRyxDQUFDLE9BQU8sQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLEdBQVE7UUFDOUMsRUFBRSxDQUFDLENBQUMsR0FBRyxDQUFDLFVBQVUsS0FBSyxHQUFHLENBQUMsQ0FBQyxDQUFDO1lBQzNCLElBQUksQ0FBQyxPQUFPLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxDQUFBO1FBQ3hCLENBQUM7UUFBQyxJQUFJLENBQUMsQ0FBQztZQUNOLE9BQU8sQ0FBQyxLQUFLLENBQUMsaUNBQWlDLEdBQUcsT0FBTyxDQUFDLENBQUE7WUFDMUQsSUFBSSxDQUFDLE1BQU0sQ0FBQyxJQUFJLEtBQUssQ0FBQyxpQ0FBaUMsR0FBRyxPQUFPLENBQUMsQ0FBQyxDQUFBO1FBQ3JFLENBQUM7SUFDSCxDQUFDLENBQUMsQ0FBQTtJQUNGLE1BQU0sQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFBO0FBQ3JCLENBQUMsQ0FBQSJ9

38
docs/index.md Normal file
View File

@ -0,0 +1,38 @@
# smartfile
make files easily accessible for processing in javascript.
## Availabililty
[![npm](https://pushrocks.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartfile)
[![git](https://pushrocks.gitlab.io/assets/repo-button-git.svg)](https://gitlab.com/pushrocks/smartfile)
[![git](https://pushrocks.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/pushrocks/smartfile)
[![docs](https://pushrocks.gitlab.io/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/smartfile/)
## Status for master
[![build status](https://gitlab.com/pushrocks/smartfile/badges/master/build.svg)](https://gitlab.com/pushrocks/smartfile/commits/master)
[![coverage report](https://gitlab.com/pushrocks/smartfile/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartfile/commits/master)
[![Dependency Status](https://david-dm.org/pushrocks/smartfile.svg)](https://david-dm.org/pushrocks/smartfile)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/smartfile/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/smartfile/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/smartfile/badges/code.svg)](https://www.bithound.io/github/pushrocks/smartfile)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
smartfile is an approach of being one tool to handle files in diverse environments.
### Smartfile Sections
smartfile thinks in sections:
section | description
--- | ---
fs | (object) gets data from fs to somewhere
memory | gets data from memory to somewhere
remote | gets data from remote locations to somewhere
interpreter | (object) handles yaml and json
smartfile | (class) a virtual representation of a file, alternative to vinyl file format
For further information read the linked docs at the top of this README.
> MIT licensed | **&copy;** [Lossless GmbH](https://lossless.gmbh)
[![npm](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://push.rocks)

View File

@ -1,48 +1,14 @@
{ {
"npmdocker": {}, "npmts":{
"npmci": { "mode":"default",
"npmGlobalTools": [], "coverageTreshold":70
"npmAccessLevel": "public"
}, },
"gitzone": { "npmdocker":{
"projectType": "npm",
"module": { },
"githost": "code.foss.global", "npmci": {
"gitscope": "push.rocks", "globalNpmTools": [
"gitrepo": "smartfile", "npmts"
"description": "Provides comprehensive tools for efficient file management in Node.js using TypeScript, including handling streams, virtual directories, and various file operations.",
"npmPackagename": "@push.rocks/smartfile",
"license": "MIT",
"keywords": [
"file management",
"TypeScript",
"Node.js",
"file operations",
"file manipulation",
"file streaming",
"virtual directory",
"filesystem utilities",
"memory-efficient file handling",
"custom file operations",
"write files",
"read files",
"copy files",
"delete files",
"list directories",
"handle large files",
"virtual filesystems",
"buffer operations"
] ]
} }
},
"tsdoc": {
"classes": [
"SmartFile",
"StreamFile"
],
"descriptions": [
"the purpose of the StreamFile class is to provide a hybrid interface between streaming files and simple handling when writing and reading those files multiple times."
],
"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"
}
} }

View File

@ -1,84 +1,46 @@
{ {
"name": "@push.rocks/smartfile", "name": "smartfile",
"private": false, "version": "4.2.8",
"version": "11.2.0", "description": "offers smart ways to work with files in nodejs",
"description": "Provides comprehensive tools for efficient file management in Node.js using TypeScript, including handling streams, virtual directories, and various file operations.", "main": "dist/index.js",
"main": "dist_ts/index.js", "typings": "dist/index.d.ts",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(npmts)",
"build": "(tsbuild --web --allowimplicitany)", "reinstall": "(rm -r node_modules && npm install)",
"buildDocs": "tsdoc" "release": "(git pull origin master && npm version patch && git push origin master && git checkout release && git merge master && git push origin release && git checkout master)",
"update": "(git checkout master && git pull origin master && npm install)",
"upgrade": "(npm run update) && (ncu upgradeAll && npm install)"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://code.foss.global/push.rocks/smartfile.git" "url": "https://gitlab.com/pushrocks/smartfile.git"
}, },
"keywords": [ "keywords": [
"file management", "filesystem",
"TypeScript", "json"
"Node.js",
"file operations",
"file manipulation",
"file streaming",
"virtual directory",
"filesystem utilities",
"memory-efficient file handling",
"custom file operations",
"write files",
"read files",
"copy files",
"delete files",
"list directories",
"handle large files",
"virtual filesystems",
"buffer operations"
], ],
"author": "Lossless GmbH <hello@lossless.com> (https://lossless.com)", "author": "Smart Coordination GmbH <office@push.rocks> (https://push.rocks)",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://gitlab.com/push.rocks/smartfile/issues" "url": "https://gitlab.com/pushrocks/smartfile/issues"
}, },
"homepage": "https://code.foss.global/push.rocks/smartfile", "homepage": "https://gitlab.com/pushrocks/smartfile",
"dependencies": { "dependencies": {
"@push.rocks/lik": "^6.1.0", "@types/fs-extra": "2.x.x",
"@push.rocks/smartdelay": "^3.0.5", "@types/vinyl": "^2.0.0",
"@push.rocks/smartfile-interfaces": "^1.0.7", "fs-extra": "^3.0.0",
"@push.rocks/smarthash": "^3.0.4", "glob": "^7.1.1",
"@push.rocks/smartjson": "^5.0.20", "js-yaml": "^3.8.3",
"@push.rocks/smartmime": "^2.0.4", "require-reload": "0.2.2",
"@push.rocks/smartpath": "^5.0.18", "smartpath": "^3.2.8",
"@push.rocks/smartpromise": "^4.2.2", "smartq": "^1.1.1",
"@push.rocks/smartrequest": "^2.0.23", "smartrequest": "^1.0.4",
"@push.rocks/smartstream": "^3.2.5", "typings-global": "^1.0.16",
"@types/fs-extra": "^11.0.4", "vinyl": "^2.0.2",
"@types/glob": "^8.1.0", "vinyl-file": "^3.0.0"
"@types/js-yaml": "^4.0.9",
"fs-extra": "^11.3.0",
"glob": "^11.0.1",
"js-yaml": "^4.1.0"
}, },
"devDependencies": { "devDependencies": {
"@git.zone/tsbuild": "^2.2.1", "gulp-function": "^2.2.9",
"@git.zone/tsrun": "^1.3.3", "tapbundle": "^1.0.10"
"@git.zone/tstest": "^1.0.96", }
"@push.rocks/tapbundle": "^5.5.6",
"@types/node": "^22.12.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
]
} }

9846
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@

241
readme.md
View File

@ -1,241 +0,0 @@
# @push.rocks/smartfile
> Provides a robust suite of tools for managing files in Node.js using TypeScript.
## Install
To integrate `@push.rocks/smartfile` into your project, run:
```bash
npm install @push.rocks/smartfile
```
## Usage
`@push.rocks/smartfile` offers extensive file management utilities, enabling seamless file processing with TypeScript in a Node.js environment. Below are detailed examples showcasing various features of the module.
### Quick Start
First, ensure you're working in an environment that supports ECMAScript modules (ESM) and TypeScript. Heres how youd generally import and use `@push.rocks/smartfile`:
```typescript
import { SmartFile, StreamFile, VirtualDirectory, fs, memory, interpreter } from '@push.rocks/smartfile';
```
### Working with `SmartFile`
#### Reading Files
To read from a file and convert it to a `SmartFile` instance:
```typescript
const myJsonSmartFile: SmartFile = await SmartFile.fromFilePath('./somePath/data.json');
const jsonData = JSON.parse(myJsonSmartFile.contents.toString());
console.log(jsonData); // Assuming the file contains JSON content
```
#### Writing Files
To write data to a file through a `SmartFile`:
```typescript
const filePath: string = './output/outputData.json';
const content: string = JSON.stringify({ key: 'value' });
await memory.toFs(content, filePath);
```
### Streaming Large Files with `StreamFile`
When dealing with large files, you can use `StreamFile` to handle such files efficiently, minimizing memory usage:
```typescript
const largeFile: StreamFile = await StreamFile.fromPath('./largeInput/largeFile.mp4');
await largeFile.writeToDisk('./largeOutput/largeFileCopy.mp4');
```
### Working with Virtual Directories
Handling multiple files as if they were part of a file system:
```typescript
const virtualDir = await VirtualDirectory.fromFsDirPath('./data/inputDir');
await virtualDir.saveToDisk('./data/outputDir');
```
### File System Operations
`@push.rocks/smartfile` provides a suite of utilities for common file system operations such as copying, deleting, and listing files or directories.
#### Copying a File
```typescript
await fs.copy('./sourceFile.txt', './destinationFile.txt');
```
#### Deleting a Directory
```typescript
await fs.remove('./directoryToDelete');
```
#### Listing Files in a Directory
```typescript
const fileList: string[] = await fs.listFiles('./someDirectory');
console.log(fileList);
```
### Advanced File Management
For specialized file operations, such as editing the contents of a file or streaming files from URLs, `@push.rocks/smartfile` includes advanced management features.
#### Editing a Files Contents
```typescript
const smartFileToEdit: SmartFile = await SmartFile.fromFilePath('./editableFile.txt');
await smartFileToEdit.editContentAsString(async (content) => content.replace(/originalText/g, 'newText'));
await smartFileToEdit.write();
```
#### Streaming a File from a URL
```typescript
const streamedFile: StreamFile = await StreamFile.fromUrl('https://example.com/file.pdf');
await streamedFile.writeToDisk('./downloadedFiles/file.pdf');
```
### Working with File Buffers and Streams
`@push.rocks/smartfile` allows you to easily work with files using Buffers and Streams, facilitating operations like file transformations, uploads, and downloads.
#### Creating a SmartFile from a Buffer
```typescript
const buffer: Buffer = Buffer.from('Sample data');
const bufferSmartFile: SmartFile = await SmartFile.fromBuffer('./bufferFile.txt', buffer);
await bufferSmartFile.write();
```
### Using `VirtualDirectory` for Complex File Management
`VirtualDirectory` simplifies the management of multiple files that are otherwise scattered across different directories or created at runtime.
#### Creating a `VirtualDirectory`
To create a `VirtualDirectory` from an existing file directory:
```typescript
const virtualDirectory = await VirtualDirectory.fromFsDirPath('./someDirectory');
```
#### Adding More Files
You can add more `SmartFile` instances to your `VirtualDirectory`:
```typescript
const additionalFiles = [
await SmartFile.fromFilePath('./anotherDirectory/file1.txt'),
await SmartFile.fromFilePath('./anotherDirectory/file2.txt')
];
virtualDirectory.addSmartfiles(additionalFiles);
```
#### Saving `VirtualDirectory` to Disk
Save your entire `VirtualDirectory` to disk:
```typescript
await virtualDirectory.saveToDisk('./outputDirectory');
```
### Utilizing StreamFile for Efficient File Handling
Using `StreamFile` can be especially beneficial for large files or when performing streaming operations.
#### Streaming from a URL
`StreamFile` provides capabilities to stream files directly from URLs, making it easier to work with remote content.
```typescript
const urlStreamFile: StreamFile = await StreamFile.fromUrl('https://example.com/largefile.zip');
await urlStreamFile.writeToDisk('./downloadedFiles/largefile.zip');
```
### Combining Buffer and Stream Approaches
Create `StreamFile` from a buffer for efficient, multi-use streams.
```typescript
const buffer = Buffer.from('Streaming buffer content');
const bufferStreamFile = StreamFile.fromBuffer(buffer, 'bufferBasedStream.txt');
await bufferStreamFile.writeToDisk('./streams/bufferBasedStream.txt');
```
### Read and Write Operations with StreamFile
Perform read and write operations efficiently using `StreamFile`.
```typescript
const fileStream = await StreamFile.fromPath('./inputData/largeFile.data');
await fileStream.writeToDisk('./outputData/largeFileCopy.data');
```
Check for completeness of your read and write operations, ensuring the integrity of file content.
```typescript
const readBuffer = await fileStream.getContentAsBuffer();
console.log(readBuffer.toString());
```
### Ensuring File Readiness for Streaming
Ensure a file is ready for streaming or create a custom readable stream incorporating data transformation.
```typescript
const smartReadStream = new SmartReadStream('./incomingData/sample.data');
smartReadStream.on('data', (chunk) => {
console.log('New Data Chunk:', chunk.toString());
});
```
### File Transformation with SmartReadStream
Perform transformations on the stream of data while reading:
```typescript
smartReadStream.on('data', (chunk) => {
// Perform some transformation
const transformedChunk = chunk.toString().toUpperCase();
console.log('Transformed Data Chunk:', transformedChunk);
});
```
### Streaming with SmartReadStream
Stream data from a `SmartReadStream` to a file efficiently managing large datasets.
```typescript
const transformedWriteStream = fs.createWriteStream('./processedData/transformed.data');
smartReadStream.pipe(transformedWriteStream);
```
`@push.rocks/smartfile` significantly simplifies the handling of complex file operations in Node.js projects, making these tasks straightforward while maintaining efficiency and ease of use. Explore and leverage these features to enhance your project's file management capabilities.
## 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.
**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
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.
### Company Information
Task Venture Capital GmbH
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.
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.

View File

@ -1,67 +0,0 @@
import * as path from 'path';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartfile from '../ts/index.js'; // adjust the import path as needed
// Test assets path
const testAssetsPath = './test/testassets/';
// ---------------------------
// StreamFile tests
// ---------------------------
tap.test('StreamFile.fromPath should create a StreamFile from a file path', async () => {
const streamFile = await smartfile.StreamFile.fromPath(path.join(testAssetsPath, 'mytest.json'));
expect(streamFile).toBeInstanceOf(smartfile.StreamFile);
const contentBuffer = await streamFile.getContentAsBuffer();
expect(contentBuffer).toBeInstanceOf(Buffer);
});
tap.test('StreamFile.fromUrl should create a StreamFile from a URL', async () => {
const streamFile = await smartfile.StreamFile.fromUrl('http://example.com/somefile.json');
expect(streamFile).toBeInstanceOf(smartfile.StreamFile);
});
tap.test('StreamFile.fromBuffer should create a StreamFile from a Buffer', async () => {
const buffer = Buffer.from('Some content');
const streamFile = smartfile.StreamFile.fromBuffer(buffer, 'bufferfile.txt');
expect(streamFile).toBeInstanceOf(smartfile.StreamFile);
});
tap.test('StreamFile should write the stream to disk', async () => {
const streamFile = await smartfile.StreamFile.fromPath(path.join(testAssetsPath, 'mytest.json'));
await streamFile.writeToDisk(path.join(testAssetsPath, 'temp', 'mytest.json'));
// Verify the file was written
expect(
// We'll use the fileExists method from your smartfile library
// Replace with the actual method you use to check file existence
await smartfile.fs.fileExists(path.join(testAssetsPath, 'temp', 'mytest.json'))
).toBeTrue();
});
tap.test('StreamFile should write to a directory', async () => {
const streamFile = await smartfile.StreamFile.fromPath(path.join(testAssetsPath, 'mytest.json'));
await streamFile.writeToDir(path.join(testAssetsPath, 'temp'));
// Verify the file was written
expect(
await smartfile.fs.fileExists(path.join(testAssetsPath, 'temp', 'mytest.json'))
).toBeTrue();
});
tap.test('StreamFile should return content as a buffer', async () => {
const streamFile = await smartfile.StreamFile.fromPath(path.join(testAssetsPath, 'mytest.json'));
const contentBuffer = await streamFile.getContentAsBuffer();
expect(contentBuffer).toBeInstanceOf(Buffer);
// Further checks on the content can be added here if necessary
});
tap.test('StreamFile should return content as a string', async () => {
const streamFile = await smartfile.StreamFile.fromPath(path.join(testAssetsPath, 'mytest.json'));
const contentString = await streamFile.getContentAsString();
expect(typeof contentString).toBeTypeofString();
// Verify the content matches what's expected
// This assumes the file contains a JSON object with a key 'key1' with value 'this works'
expect(JSON.parse(contentString).key1).toEqual('this works');
});
// Start the test sequence
tap.start();

View File

@ -1,224 +1,205 @@
import * as smartfile from '../ts/index.js'; import * as smartfile from '../dist/index'
import * as path from 'path'; import path = require('path')
import { expect, tap } from '@push.rocks/tapbundle'; import { expect, tap } from 'tapbundle'
import * as vinyl from 'vinyl'
// --------------------------- // ---------------------------
// smartfile.fs // smartfile.fs
// --------------------------- // ---------------------------
tap.test('.fs.fileExistsSync -> should return an accurate boolean', async () => { tap.test('.fs.fileExistsSync -> should return an accurate boolean', async () => {
// tslint:disable-next-line: no-unused-expression expect(smartfile.fs.fileExistsSync('./test/mytest.json')).to.be.true
expect(smartfile.fs.fileExistsSync('./test/testassets/mytest.json')).toBeTrue(); expect(smartfile.fs.fileExistsSync('./test/notthere.json')).be.false
// tslint:disable-next-line: no-unused-expression })
expect(smartfile.fs.fileExistsSync('./test/testassets/notthere.json')).toBeFalse();
});
tap.test('.fs.fileExists -> should resolve or reject a promise', async () => { tap.test('.fs.fileExists should resolve or reject a promise', async () => {
expect(smartfile.fs.fileExists('./test/testassets/mytest.json')).toBeInstanceOf(Promise); expect(smartfile.fs.fileExists('./test/mytest.json')).to.be.instanceof(Promise)
await smartfile.fs.fileExists('./test/testassets/mytest.json'); await expect(smartfile.fs.fileExists('./test/mytest.json')).to.eventually.be.fulfilled
await smartfile.fs.fileExists('./test/testassets/notthere.json').catch((err) => { await expect(smartfile.fs.fileExists('./test/notthere.json')).to.eventually.be.rejected
return expect(err.message).toEqual( })
"ENOENT: no such file or directory, access './test/testassets/notthere.json'"
);
});
});
tap.test('.fs.listFoldersSync() -> should get the file type from a string', async () => { tap.test('.fs.listFoldersSync() -> should get the file type from a string', async () => {
expect(smartfile.fs.listFoldersSync('./test/testassets/')).toContain('testfolder'); expect(smartfile.fs.listFoldersSync('./test/')).to.deep.include('testfolder')
expect(smartfile.fs.listFoldersSync('./test/testassets/')).not.toContain('notExistentFolder'); expect(smartfile.fs.listFoldersSync('./test/')).to.not.deep.include('notExistentFolder')
}); })
tap.test('.fs.listFolders() -> should get the file type from a string', async () => { tap.test('.fs.listFolders() -> should get the file type from a string', async () => {
const folderArrayArg = await smartfile.fs.listFolders('./test/testassets/'); let folderArrayArg = await smartfile.fs.listFolders('./test/')
expect(folderArrayArg).toContain('testfolder'); expect(folderArrayArg).to.deep.include('testfolder')
expect(folderArrayArg).not.toContain('notExistentFolder'); expect(folderArrayArg).to.not.deep.include('notExistentFolder')
}); })
tap.test('.fs.listFilesSync() -> should get the file type from a string', async () => { tap.test('.fs.listFilesSync() -> should get the file type from a string', async () => {
expect(smartfile.fs.listFilesSync('./test/testassets/')).toContain('mytest.json'); expect(smartfile.fs.listFilesSync('./test/')).to.deep.include('mytest.json')
expect(smartfile.fs.listFilesSync('./test/testassets/')).not.toContain('notExistentFile'); expect(smartfile.fs.listFilesSync('./test/')).to.not.deep.include('notExistentFile')
expect(smartfile.fs.listFilesSync('./test/testassets/', /mytest\.json/)).toContain('mytest.json'); expect(smartfile.fs.listFilesSync('./test/', /mytest\.json/)).to.deep.include('mytest.json')
expect(smartfile.fs.listFilesSync('./test/testassets/', /mytests.json/)).not.toContain( expect(smartfile.fs.listFilesSync('./test/', /mytests.json/)).to.not.deep.include('mytest.json')
'mytest.json' })
);
});
tap.test('.fs.listFiles() -> should get the file type from a string', async () => { tap.test('.fs.listFiles() -> should get the file type from a string', async () => {
const folderArrayArg = await smartfile.fs.listFiles('./test/testassets/'); let folderArrayArg = await smartfile.fs.listFiles('./test/')
expect(folderArrayArg).toContain('mytest.json'); expect(folderArrayArg).to.deep.include('mytest.json')
expect(folderArrayArg).not.toContain('notExistentFile'); expect(folderArrayArg).to.not.deep.include('notExistentFile')
}); })
tap.test('.fs.listFileTree() -> should get a file tree', async () => { tap.test('.fs.listFileTree() -> should get a file tree', async () => {
const folderArrayArg = await smartfile.fs.listFileTree( let folderArrayArg = await smartfile.fs.listFileTree(path.resolve('./test/'), '**/*.txt')
path.resolve('./test/testassets/'), expect(folderArrayArg).to.deep.include('testfolder/testfile1.txt')
'**/*.txt' expect(folderArrayArg).to.not.deep.include('mytest.json')
); })
expect(folderArrayArg).toContain('testfolder/testfile1.txt');
expect(folderArrayArg).not.toContain('mytest.json');
});
tap.test('.fs.fileTreeToObject -> should read a file tree into an Object', async () => { tap.test('.fs.fileTreeToObject -> should read a file tree into an Object', async () => {
const fileArrayArg = await smartfile.fs.fileTreeToObject( let fileArrayArg = await smartfile.fs.fileTreeToObject(path.resolve('./test/'), '**/*.txt')
path.resolve('./test/testassets/'), expect(fileArrayArg[0]).to.be.instanceof(smartfile.Smartfile)
'**/*.txt' expect(fileArrayArg[0].contents.toString()).to.equal(fileArrayArg[0].contentBuffer.toString())
); })
expect(fileArrayArg[0]).toBeInstanceOf(smartfile.SmartFile);
expect(fileArrayArg[0].contents.toString()).toEqual(fileArrayArg[0].contentBuffer.toString());
});
tap.test('.fs.copy() -> should copy a directory', async () => { tap.test('.fs.copy() -> should copy a directory', async () => {
await smartfile.fs.copy('./test/testassets/testfolder/', './test/testassets/temp/'); smartfile.fs.copy('./test/testfolder/', './test/temp/')
}); })
tap.test('.fs.copy() -> should copy a file', async () => { tap.test('.fs.copy() -> should copy a file', async () => {
await smartfile.fs.copy('./test/testassets/mytest.yaml', './test/testassets/temp/mytest.yaml'); smartfile.fs.copy('./test/mytest.yaml', './test/temp/')
}); })
tap.test('.fs.copy() -> should copy a file and rename it', async () => { tap.test('.fs.copy() -> should copy a file and rename it', async () => {
await smartfile.fs.copy( smartfile.fs.copy('./test/mytest.yaml', './test/temp/mytestRenamed.yaml')
'./test/testassets/mytest.yaml', })
'./test/testassets/temp/mytestRenamed.yaml'
);
});
tap.test('.fs.remove() -> should remove an entire directory', async () => {}); tap.test('.fs.remove() -> should remove an entire directory', async () => {
})
tap.test('.fs.remove -> should remove single files', async () => { tap.test('.fs.remove -> should remove single files', async () => {
await smartfile.fs.remove('./test/testassets/temp/mytestRenamed.yaml'); await expect(smartfile.fs.remove('./test/temp/mytestRenamed.yaml')).to.eventually.be.fulfilled
}); })
tap.test('.fs.removeSync -> should remove single files synchronouly', async () => { tap.test('.fs.removeSync -> should remove single files synchronouly', async () => {
smartfile.fs.removeSync('./test/testassets/temp/testfile1.txt'); smartfile.fs.removeSync('./test/temp/testfile1.txt')
expect(smartfile.fs.fileExistsSync('./test/testassets/temp/testfile1.txt')).toBeFalse(); expect(smartfile.fs.fileExistsSync('./test/temp/testfile1.txt')).to.be.false
}); })
tap.test('.fs.removeMany -> should remove and array of files', async () => { tap.test('.fs.removeMany -> should remove and array of files', async () => {
smartfile.fs smartfile.fs.removeMany([ './test/temp/testfile1.txt', './test/temp/testfile2.txt' ]).then(() => {
.removeMany(['./test/testassets/temp/testfile1.txt', './test/testassets/temp/testfile2.txt']) expect(smartfile.fs.fileExistsSync('./test/temp/testfile1.txt')).to.be.false
.then(() => { expect(smartfile.fs.fileExistsSync('./test/temp/testfile2.txt')).to.be.false
expect(smartfile.fs.fileExistsSync('./test/testassets/temp/testfile1.txt')).toBeFalse(); })
expect(smartfile.fs.fileExistsSync('./test/testassets/temp/testfile2.txt')).toBeFalse(); })
});
});
tap.test('.fs.removeManySync -> should remove and array of single files synchronouly', async () => { tap.test('.fs.removeManySync -> should remove and array of single files synchronouly', async () => {
smartfile.fs.removeManySync([ smartfile.fs.removeManySync([ './test/temp/testfile1.txt', './test/temp/testfile2.txt' ])
'./test/testassets/temp/testfile1.txt', expect(smartfile.fs.fileExistsSync('./test/temp/testfile1.txt')).to.be.false
'./test/testassets/temp/testfile2.txt', expect(smartfile.fs.fileExistsSync('./test/temp/testfile2.txt')).to.be.false
]); })
expect(smartfile.fs.fileExistsSync('./test/testassets/temp/testfile1.txt')).toBeFalse();
expect(smartfile.fs.fileExistsSync('./test/testassets/temp/testfile2.txt')).toBeFalse();
});
tap.test('.fs.toObjectSync() -> should read an .yaml file to an object', async () => { tap.test('.fs.toObjectSync() -> should read an ' + '.yaml' + ' file to an object', async () => {
const testData = smartfile.fs.toObjectSync('./test/testassets/mytest.yaml'); let testData = smartfile.fs.toObjectSync('./test/mytest.yaml')
expect(testData.key1).toEqual('this works'); expect(testData).have.property('key1', 'this works')
expect(testData.key2).toEqual('this works too'); expect(testData).have.property('key2', 'this works too')
});
tap.test( })
'.fs.toObjectSync() -> should state unknown file type for unknown file types', tap.test('.fs.toObjectSync() -> should state unknown file type for unknown file types', async () => {
async () => { let testData = smartfile.fs.toObjectSync('./test/mytest.txt')
const testData = smartfile.fs.toObjectSync('./test/testassets/mytest.txt'); })
}
); tap.test('.fs.toObjectSync() -> should read an ' + '.json' + ' file to an object', async () => {
let testData = smartfile.fs.toObjectSync('./test/mytest.json')
expect(testData).have.property('key1', 'this works')
expect(testData).have.property('key2', 'this works too')
})
tap.test('.fs.toObjectSync() -> should read an .json file to an object', async () => {
const testData = smartfile.fs.toObjectSync('./test/testassets/mytest.json');
expect(testData.key1).toEqual('this works');
expect(testData.key2).toEqual('this works too');
});
tap.test('.fs.toStringSync() -> should read a file to a string', async () => { tap.test('.fs.toStringSync() -> should read a file to a string', async () => {
expect(smartfile.fs.toStringSync('./test/testassets/mytest.txt')).toEqual('Some TestString &&%$'); expect(smartfile.fs.toStringSync('./test/mytest.txt'))
}); .to.equal('Some TestString &&%$')
})
tap.test('.fs.toVinylSync -> should read an ' + '.json OR .yaml' + ' file to an ' + 'vinyl file object', async () => {
let testData = smartfile.fs.toVinylSync('./test/mytest.json')
expect(vinyl.isVinyl(testData)).to.be.true
})
// --------------------------- // ---------------------------
// smartfile.interpreter // smartfile.interpreter
// --------------------------- // ---------------------------
tap.test('.interpreter.filetype() -> should get the file type from a string', async () => { tap.test('.interpreter.filetype() -> should get the file type from a string', async () => {
expect(smartfile.interpreter.filetype('./somefolder/data.json')).toEqual('json'); expect(smartfile.interpreter.filetype('./somefolder/data.json')).equal('json')
}); })
// --------------------------- // ---------------------------
// smartfile.memory // smartfile.memory
// --------------------------- // ---------------------------
tap.test('.memory.toVinylFileSync() -> should produce a vinylFile', async () => {
let localString = 'myString'
let localOptions = { filename: 'vinylfile2', base: '/someDir' }
expect(smartfile.memory.toVinylFileSync(localString, localOptions) instanceof vinyl).to.be.true
})
tap.test('.memory.toVinylArraySync() -> should produce a an array of vinylfiles', async () => {
let localStringArray = [ 'string1', 'string2', 'string3' ]
let localOptions = { filename: 'vinylfile2', base: '/someDir' }
let testResult = smartfile.memory.toVinylArraySync(localStringArray, localOptions)
expect(testResult).to.be.a('array')
expect(testResult.length === 3).to.be.true
for (let myKey in testResult) {
expect(testResult[ myKey ] instanceof vinyl).to.be.true
}
})
tap.test('.memory.vinylToStringSync() -> should produce a String from vinyl file', async () => {
let localString = smartfile.memory.vinylToStringSync(new vinyl({
base: '/',
path: '/test.txt',
contents: new Buffer('myString')
}))
expect(localString).equal('myString')
})
tap.test('.memory.toFs() -> should write a file to disk and return a promise', async () => { tap.test('.memory.toFs() -> should write a file to disk and return a promise', async () => {
const localString = 'myString'; let localString = 'myString'
await smartfile.memory.toFs( await smartfile.memory.toFs(
localString, localString,
path.join(process.cwd(), './test/testassets/temp/testMemToFs.txt') path.join(process.cwd(), './test/temp/testMemToFs.txt')
); )
}); })
tap.test( tap.test('.memory.toFsSync() -> should write a file to disk and return true if successfull', async () => {
'.memory.toFsSync() -> should write a file to disk and return true if successfull', let localString = 'myString'
async () => {
const localString = 'myString';
smartfile.memory.toFsSync( smartfile.memory.toFsSync(
localString, localString,
path.join(process.cwd(), './test/testassets/temp/testMemToFsSync.txt') path.join(process.cwd(), './test/temp/testMemToFsSync.txt')
); )
} })
);
tap.test('.remote.toString() -> should load a remote file to a variable', async () => {
let responseString = await smartfile.remote.toString(
'https://raw.githubusercontent.com/pushrocks/smartfile/master/test/mytest.txt'
)
expect(responseString).to.equal('Some TestString &&%$')
})
tap.test('.remote.toString() -> should reject a Promise when the link is false', async () => {
await expect(smartfile.remote.toString('https://push.rocks/doesnotexist.txt'))
.to.eventually.be.rejected
})
// --------------------------- // ---------------------------
// smartfile.Smartfile // smartfile.Smartfile
// --------------------------- // ---------------------------
tap.test('.Smartfile -> should produce vinyl compatible files', async () => { tap.test('.Smartfile -> should produce vinyl compatible files', async () => {
const smartfileArray = await smartfile.fs.fileTreeToObject( let smartfileArray = await smartfile.fs.fileTreeToObject(process.cwd(), './test/testfolder/**/*')
process.cwd(), let localSmartfile = smartfileArray[0]
'./test/testassets/testfolder/**/*' expect(localSmartfile).to.be.instanceof(smartfile.Smartfile)
); expect(localSmartfile.contents).to.be.instanceof(Buffer)
const localSmartfile = smartfileArray[0]; expect(localSmartfile.isBuffer()).to.be.true
expect(localSmartfile).toBeInstanceOf(smartfile.SmartFile); expect(localSmartfile.isDirectory()).to.be.false
expect(localSmartfile.contents).toBeInstanceOf(Buffer); expect(localSmartfile.isNull()).to.be.false
// tslint:disable-next-line:no-unused-expression })
expect(localSmartfile.isBuffer()).toBeTrue();
// tslint:disable-next-line:no-unused-expression
expect(localSmartfile.isDirectory()).toBeFalse();
// tslint:disable-next-line:no-unused-expression
expect(localSmartfile.isNull()).toBeFalse();
});
tap.test('should output a smartfile array to disk', async () => { tap.start()
const smartfileArray = await smartfile.fs.fileTreeToObject('./test/testassets/testfolder/', '*');
for (const smartfileInstance of smartfileArray) {
console.log(smartfileInstance.relative);
console.log(smartfileInstance.path);
console.log(smartfileInstance.base);
console.log(smartfileInstance.parsedPath);
}
await smartfile.memory.smartfileArrayToFs(
smartfileArray,
path.resolve('./test/testassets/temp/testoutput/')
);
});
tap.test('should create, store and retrieve valid smartfiles', async () => {
const fileString = 'hi there';
const filePath = './test/testassets/utf8.txt';
const smartfileInstance = await smartfile.SmartFile.fromString(filePath, fileString, 'utf8');
smartfileInstance.write();
const smartfileInstance2 = await smartfile.SmartFile.fromFilePath(filePath);
const retrievedString = smartfileInstance.contents.toString();
expect(retrievedString).toEqual(fileString);
});
tap.test('should get a hash', async () => {
const fileString = 'hi there';
const filePath = './test/testassets/utf8.txt';
const smartfileInstance = await smartfile.SmartFile.fromString(filePath, fileString, 'utf8');
const hash = await smartfileInstance.getHash();
console.log(hash);
});
tap.test('should wait for file to be ready', async () => {
await smartfile.fs.waitForFileToBeReady('./test/testassets/mytest.json');
});
tap.start();

View File

@ -1,15 +0,0 @@
import { tap, expect } from '@push.rocks/tapbundle';
import * as smartfile from '../ts/index.js';
tap.test('should create a virtualdirectory', async () => {
const virtualDir = await smartfile.VirtualDirectory.fromFsDirPath('./test/testassets/testfolder');
expect(virtualDir.smartfileArray.length).toEqual(4);
});
tap.test('should write to a directory', async () => {
const virtualDir = await smartfile.VirtualDirectory.fromFsDirPath('./test/testassets/testfolder');
virtualDir.saveToDisk('./test/testassets/test');
});
tap.start();

View File

@ -1,8 +0,0 @@
{
"key1": "this works",
"key2": "this works too",
"key3": {
"nestedkey1": "hello"
}
}

View File

@ -1,4 +0,0 @@
key1: this works
key2: this works too
key3:
nestedkey1: hello

View File

@ -1 +0,0 @@
hi

View File

@ -1,8 +0,0 @@
{
"key1": "this works",
"key2": "this works too",
"key3": {
"nestedkey1": "hello"
}
}

View File

@ -1 +0,0 @@
myString

View File

@ -1 +0,0 @@
myString

View File

@ -1 +0,0 @@
hi

View File

@ -1 +0,0 @@
hi there

View File

@ -1,8 +0,0 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/smartfile',
version: '11.2.0',
description: 'Provides comprehensive tools for efficient file management in Node.js using TypeScript, including handling streams, virtual directories, and various file operations.'
}

View File

@ -1,353 +0,0 @@
import * as plugins from './plugins.js';
import * as fs from './fs.js';
import * as memory from './memory.js';
export interface ISmartfileConstructorOptions {
path: string;
contentBuffer: Buffer;
base: string;
}
/**
* an vinyl file compatible in memory file class
*/
export class SmartFile extends plugins.smartjson.Smartjson {
// ======
// STATIC
// ======
/**
* creates a Smartfile from a filePath
* @param filePath
*/
public static async fromFilePath(filePath: string, baseArg: string = process.cwd()) {
filePath = plugins.path.resolve(filePath);
const fileBuffer = fs.toBufferSync(filePath);
const smartfile = new SmartFile({
contentBuffer: fileBuffer,
base: baseArg,
path: plugins.path.relative(baseArg, filePath),
});
return smartfile;
}
public static async fromBuffer(
filePath: string,
contentBufferArg: Buffer,
baseArg: string = process.cwd()
) {
const smartfile = new SmartFile({
contentBuffer: contentBufferArg,
base: baseArg,
path: plugins.path.relative(baseArg, filePath),
});
return smartfile;
}
public static async fromString(
filePath: string,
contentStringArg: string,
encodingArg: 'utf8' | 'binary',
baseArg = process.cwd()
) {
const smartfile = new SmartFile({
contentBuffer: Buffer.from(contentStringArg, encodingArg),
base: baseArg,
path: plugins.path.relative(baseArg, filePath),
});
return smartfile;
}
public static async fromFoldedJson(foldedJsonArg: string) {
return new SmartFile(plugins.smartjson.parse(foldedJsonArg));
}
/**
* creates a Smartfile from a ReadableStream
* @param stream a readable stream that provides file content
* @param filePath the file path to associate with the content
* @param baseArg the base path to use for the file
*/
public static async fromStream(
stream: plugins.stream.Readable,
filePath: string,
baseArg: string = process.cwd()
): Promise<SmartFile> {
return new Promise<SmartFile>((resolve, reject) => {
const chunks: Buffer[] = [];
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
stream.on('error', (error) => reject(error));
stream.on('end', () => {
const contentBuffer = Buffer.concat(chunks);
const smartfile = new SmartFile({
contentBuffer: contentBuffer,
base: baseArg,
path: plugins.path.relative(baseArg, filePath),
});
resolve(smartfile);
});
});
}
public static async fromUrl(urlArg: string) {
const response = await plugins.smartrequest.getBinary(urlArg);
const smartfile = await SmartFile.fromBuffer(urlArg, response.body);
return smartfile;
}
// ========
// INSTANCE
// ========
/**
* the relative path of the file
*/
@plugins.smartjson.foldDec()
public path: string;
/**
* a parsed path
*/
public get parsedPath(): plugins.path.ParsedPath {
return plugins.path.parse(this.path);
}
public get absolutePath() {
return plugins.path.join(this.base, this.path);
}
public get absoluteParsedPath() {
return plugins.path.parse(this.absolutePath);
}
/**
* the content of the file as Buffer
*/
@plugins.smartjson.foldDec()
public contentBuffer: Buffer;
/**
* The current working directory of the file
* Note:this is similar to gulp and different from native node path base
*/
@plugins.smartjson.foldDec()
public base: string;
/**
* sync the file with disk
*/
@plugins.smartjson.foldDec()
public sync: boolean;
/**
* the constructor of Smartfile
* @param optionsArg
*/
constructor(optionsArg: ISmartfileConstructorOptions) {
super();
if (optionsArg.contentBuffer) {
this.contentBuffer = optionsArg.contentBuffer;
} else {
console.log('created empty Smartfile?');
}
this.path = optionsArg.path;
this.base = optionsArg.base;
}
/**
* set contents from string
* @param contentString
*/
public setContentsFromString(contentString: string, encodingArg: 'utf8' | 'binary' = 'utf8') {
this.contents = Buffer.from(contentString, encodingArg);
}
/**
* write file to disk at its original location
* Behaviours:
* - no argument write to exactly where the file was picked up
*/
public async write() {
let writePath = plugins.smartpath.transform.makeAbsolute(this.path, this.base);
console.log(`writing to ${writePath}`);
await memory.toFs(this.contentBuffer, writePath);
}
/**
* writes the file to path given as argument
* note: if the path is not absolute, takes process.cwd() as base
* @param filePathArg
*/
public async writeToDiskAtPath(filePathArg: string) {
if (!plugins.path.isAbsolute(filePathArg)) {
filePathArg = plugins.path.join(process.cwd(), filePathArg);
}
await memory.toFs(this.contentBuffer, filePathArg);
}
/**
* writes the file to a directory combined with the relative path portion
* @param dirPathArg
* @returns
*/
public async writeToDir(dirPathArg: string) {
dirPathArg = plugins.smartpath.transform.toAbsolute(dirPathArg) as string;
const filePath = plugins.path.join(dirPathArg, this.path);
await memory.toFs(this.contentBuffer, filePath);
return filePath;
}
/**
* read file from disk
*/
public async read() {
this.contentBuffer = await fs.toBuffer(plugins.path.join(this.base, this.path));
}
/**
* deletes the file from disk at its original location
*/
public async delete() {
await fs.remove(plugins.path.join(this.base, this.path));
}
/**
* Renames the file to the specified new name.
* - Updates the `path` property with the new name.
* - Writes the file to the new location if it exists on disk.
* @param newName The new name of the file (including extension if applicable).
* @param writeToDisk (optional) If true, also renames the file on the disk.
* @returns The updated file path after renaming.
*/
public async rename(newName: string, writeToDisk: boolean = false): Promise<string> {
// Validate the new name
if (!newName || typeof newName !== 'string') {
throw new Error('Invalid new name provided.');
}
// Extract the directory path
const oldFilePath = this.path;
const dirPath = plugins.path.dirname(this.path);
// Create the new file path
const newFilePath = plugins.path.join(dirPath, newName);
// Update the `path` property
this.path = newFilePath;
// Optionally write the renamed file to disk
if (writeToDisk) {
const oldAbsolutePath = plugins.smartpath.transform.makeAbsolute(oldFilePath, this.base);
const newAbsolutePath = plugins.smartpath.transform.makeAbsolute(newFilePath, this.base);
// Rename the file on disk
await plugins.fsExtra.rename(oldAbsolutePath, newAbsolutePath);
}
// Return the new path
return this.path;
}
// -----------------------------------------------
// vinyl compatibility
// -----------------------------------------------
/**
* vinyl-compatibility: alias of this.contentBuffer
*/
get contents(): Buffer {
return this.contentBuffer;
}
set contents(contentsArg) {
this.contentBuffer = contentsArg;
}
/**
* vinyl-compatibility
*/
public get cwd() {
return process.cwd();
}
/**
* return relative path of file
*/
public get relative(): string {
return this.path;
}
/**
* return truw when the file has content
*/
public isNull(): boolean {
if (!this.contentBuffer) {
return true;
}
return false;
}
/**
* return true if contents are Buffer
*/
public isBuffer(): boolean {
if (this.contents instanceof Buffer) {
return true;
}
return false;
}
public isDirectory() {
return false;
}
public isStream() {
return false;
}
public isSymbolic() {
return false;
}
public async getHash(typeArg: 'path' | 'content' | 'all' = 'all') {
const pathHash = await plugins.smarthash.sha256FromString(this.path);
const contentHash = await plugins.smarthash.sha256FromBuffer(this.contentBuffer);
const combinedHash = await plugins.smarthash.sha256FromString(pathHash + contentHash);
switch (typeArg) {
case 'path':
return pathHash;
case 'content':
return contentHash;
case 'all':
default:
return combinedHash;
}
}
// update things
public updateFileName(fileNameArg: string) {
const oldFileName = this.parsedPath.base;
this.path = this.path.replace(new RegExp(oldFileName + '$'), fileNameArg);
}
public async editContentAsString(editFuncArg: (fileStringArg: string) => Promise<string>) {
const newFileString = await editFuncArg(this.contentBuffer.toString());
this.contentBuffer = Buffer.from(newFileString);
}
/**
* Returns a ReadableStream from the file's content buffer
*/
public getStream(): plugins.stream.Readable {
const stream = new plugins.stream.Readable();
stream.push(this.contentBuffer); // Push the content buffer to the stream
stream.push(null); // Push null to signify the end of the stream (EOF)
return stream;
}
/**
* Returns the size of the file in bytes
*/
public async getSize(): Promise<number> {
return this.contentBuffer.length;
}
}

View File

@ -1,174 +0,0 @@
import * as plugins from './plugins.js';
import * as smartfileFs from './fs.js';
import * as smartfileFsStream from './fsstream.js';
import { Readable } from 'stream';
type TStreamSource = (streamFile: StreamFile) => Promise<Readable>;
/**
* The StreamFile class represents a file as a stream.
* It allows creating streams from a file path, a URL, or a buffer.
*/
export class StreamFile {
// STATIC
public static async fromPath(filePath: string): Promise<StreamFile> {
const streamSource: TStreamSource = async (streamFileArg) => smartfileFsStream.createReadStream(filePath);
const streamFile = new StreamFile(streamSource, filePath);
streamFile.multiUse = true;
streamFile.byteLengthComputeFunction = async () => {
const stats = await smartfileFs.stat(filePath);
return stats.size;
}
return streamFile;
}
public static async fromUrl(url: string): Promise<StreamFile> {
const streamSource: TStreamSource = async (streamFileArg) => plugins.smartrequest.getStream(url); // Replace with actual plugin method
const streamFile = new StreamFile(streamSource);
streamFile.multiUse = true;
streamFile.byteLengthComputeFunction = async () => {
const response = await plugins.smartrequest.getBinary(url); // TODO: switch to future .getBinaryByteLength()
return response.body.length;
}
return streamFile;
}
public static fromBuffer(buffer: Buffer, relativeFilePath?: string): StreamFile {
const streamSource: TStreamSource = async (streamFileArg) => {
const stream = new Readable();
stream.push(buffer);
stream.push(null); // End of stream
return stream;
};
const streamFile = new StreamFile(streamSource, relativeFilePath);
streamFile.multiUse = true;
streamFile.byteLengthComputeFunction = async () => buffer.length;
return streamFile;
}
/**
* Creates a StreamFile from an existing Readable stream with an option for multiple uses.
* @param stream A Node.js Readable stream.
* @param relativeFilePath Optional file path for the stream.
* @param multiUse If true, the stream can be read multiple times, caching its content.
* @returns A StreamFile instance.
*/
public static fromStream(stream: Readable, relativeFilePath?: string, multiUse: boolean = false): StreamFile {
const streamSource: TStreamSource = (streamFileArg) => {
if (streamFileArg.multiUse) {
// If multi-use is enabled and we have cached content, create a new readable stream from the buffer
const bufferedStream = new Readable();
bufferedStream.push(streamFileArg.cachedStreamBuffer);
bufferedStream.push(null); // No more data to push
return Promise.resolve(bufferedStream);
} else {
return Promise.resolve(stream);
}
};
const streamFile = new StreamFile(streamSource, relativeFilePath);
streamFile.multiUse = multiUse;
// If multi-use is enabled, cache the stream when it's first read
if (multiUse) {
const chunks: Buffer[] = [];
stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
stream.on('end', () => {
streamFile.cachedStreamBuffer = Buffer.concat(chunks);
});
// It's important to handle errors that may occur during streaming
stream.on('error', (err) => {
console.error('Error while caching stream:', err);
});
}
return streamFile;
}
// INSTANCE
relativeFilePath?: string;
private streamSource: TStreamSource;
// enable stream based multi use
private cachedStreamBuffer?: Buffer;
public multiUse: boolean;
public used: boolean = false;
public byteLengthComputeFunction: () => Promise<number>;
private constructor(streamSource: TStreamSource, relativeFilePath?: string) {
this.streamSource = streamSource;
this.relativeFilePath = relativeFilePath;
}
// METHODS
private checkMultiUse() {
if (!this.multiUse && this.used) {
throw new Error('This stream can only be used once.');
}
this.used = true;
}
/**
* Creates a new readable stream from the source.
*/
public async createReadStream(): Promise<Readable> {
return this.streamSource(this);
}
/**
* Writes the stream to the disk at the specified path.
* @param filePathArg The file path where the stream should be written.
*/
public async writeToDisk(filePathArg: string): Promise<void> {
this.checkMultiUse();
const readStream = await this.createReadStream();
const writeStream = smartfileFsStream.createWriteStream(filePathArg);
return new Promise((resolve, reject) => {
readStream.pipe(writeStream);
readStream.on('error', reject);
writeStream.on('error', reject);
writeStream.on('finish', resolve);
});
}
public async writeToDir(dirPathArg: string) {
this.checkMultiUse();
const filePath = plugins.path.join(dirPathArg, this.relativeFilePath);
await smartfileFs.ensureDir(plugins.path.parse(filePath).dir);
return this.writeToDisk(filePath);
}
public async getContentAsBuffer() {
this.checkMultiUse();
const done = plugins.smartpromise.defer<Buffer>();
const readStream = await this.createReadStream();
const chunks: Buffer[] = [];
readStream.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
readStream.on('error', done.reject);
readStream.on('end', () => {
const contentBuffer = Buffer.concat(chunks);
done.resolve(contentBuffer);
});
return done.promise;
}
public async getContentAsString(formatArg: 'utf8' | 'binary' = 'utf8') {
const contentBuffer = await this.getContentAsBuffer();
return contentBuffer.toString(formatArg);
}
/**
* Returns the size of the file content in bytes.
*/
public async getSize(): Promise<number> {
if (this.byteLengthComputeFunction) {
return this.byteLengthComputeFunction();
} else {
return null;
}
}
}

View File

@ -1,87 +0,0 @@
import { SmartFile } from './classes.smartfile.js';
import * as plugins from './plugins.js';
import * as fs from './fs.js';
export interface IVirtualDirectoryConstructorOptions {
mode: ''
}
/**
* a virtual directory exposes a fs api
*/
export class VirtualDirectory {
consstructor(options = {}) {
}
// STATIC
public static async fromFsDirPath(pathArg: string): Promise<VirtualDirectory> {
const newVirtualDir = new VirtualDirectory();
newVirtualDir.addSmartfiles(await fs.fileTreeToObject(pathArg, '**/*'));
return newVirtualDir;
}
public static async fromVirtualDirTransferableObject(
virtualDirTransferableObjectArg: plugins.smartfileInterfaces.VirtualDirTransferableObject
): Promise<VirtualDirectory> {
const newVirtualDir = new VirtualDirectory();
for (const fileArg of virtualDirTransferableObjectArg.files) {
newVirtualDir.addSmartfiles([SmartFile.enfoldFromJson(fileArg) as SmartFile]);
}
return newVirtualDir;
}
// INSTANCE
public smartfileArray: SmartFile[] = [];
constructor() {}
public addSmartfiles(smartfileArrayArg: SmartFile[]) {
this.smartfileArray = this.smartfileArray.concat(smartfileArrayArg);
}
public async getFileByPath(pathArg: string) {
for (const smartfile of this.smartfileArray) {
if (smartfile.path === pathArg) {
return smartfile;
}
}
}
public async toVirtualDirTransferableObject(): Promise<plugins.smartfileInterfaces.VirtualDirTransferableObject> {
return {
files: this.smartfileArray.map((smartfileArg) => smartfileArg.foldToJson()),
};
}
public async saveToDisk(dirArg: string) {
console.log(`writing VirtualDirectory with ${this.smartfileArray.length} files to directory:
--> ${dirArg}`);
for (const smartfileArg of this.smartfileArray) {
const filePath = await smartfileArg.writeToDir(dirArg);
console.log(`wrote ${smartfileArg.relative} to
--> ${filePath}`);
}
}
public async shiftToSubdirectory(subDir: string): Promise<VirtualDirectory> {
const newVirtualDir = new VirtualDirectory();
for (const file of this.smartfileArray) {
if (file.path.startsWith(subDir)) {
const adjustedFilePath = plugins.path.relative(subDir, file.path);
file.path = adjustedFilePath;
newVirtualDir.addSmartfiles([file]);
}
}
return newVirtualDir;
}
public async addVirtualDirectory(virtualDir: VirtualDirectory, newRoot: string): Promise<void> {
for (const file of virtualDir.smartfileArray) {
file.path = plugins.path.join(newRoot, file.path);
}
this.addSmartfiles(virtualDir.smartfileArray);
}
}

615
ts/fs.ts
View File

@ -1,615 +0,0 @@
import * as plugins from './plugins.js';
import * as interpreter from './interpreter.js';
import { SmartFile } from './classes.smartfile.js';
import * as memory from './memory.js';
import type { StreamFile } from './classes.streamfile.js';
/*===============================================================
============================ Checks =============================
===============================================================*/
/**
*
* @param filePath
* @returns {boolean}
*/
export const fileExistsSync = (filePath): boolean => {
let fileExistsBool: boolean = false;
try {
plugins.fsExtra.readFileSync(filePath);
fileExistsBool = true;
} catch (err) {
fileExistsBool = false;
}
return fileExistsBool;
};
/**
*
* @param filePath
* @returns {any}
*/
export const fileExists = async (filePath): Promise<boolean> => {
const done = plugins.smartpromise.defer<boolean>();
plugins.fs.access(filePath, 4, (err) => {
err ? done.resolve(false) : done.resolve(true);
});
return done.promise;
};
/**
* Checks if given path points to an existing directory
*/
export const isDirectory = (pathArg: string): boolean => {
try {
return plugins.fsExtra.statSync(pathArg).isDirectory();
} catch (err) {
return false;
}
};
/**
* Checks if given path points to an existing directory
*/
export const isDirectorySync = (pathArg: string): boolean => {
try {
return plugins.fsExtra.statSync(pathArg).isDirectory();
} catch (err) {
return false;
}
};
/**
* Checks if a given path points to an existing file
*/
export const isFile = (pathArg): boolean => {
return plugins.fsExtra.statSync(pathArg).isFile();
};
/*===============================================================
============================ FS ACTIONS =========================
===============================================================*/
/**
* copies a file or directory from A to B on the local disk
*/
export const copy = async (fromArg: string, toArg: string, optionsArg?: plugins.fsExtra.CopyOptions & { replaceTargetDir?: boolean }): Promise<void> => {
if (optionsArg?.replaceTargetDir && isDirectory(fromArg) && isDirectory(toArg)) {
await remove(toArg);
}
return await plugins.fsExtra.copy(fromArg, toArg, optionsArg as plugins.fsExtra.CopyOptions);
};
/**
* copies a file or directory SYNCHRONOUSLY from A to B on the local disk
*/
export const copySync = (fromArg: string, toArg: string, optionsArg?: plugins.fsExtra.CopyOptionsSync & { replaceTargetDir?: boolean }): void => {
if (optionsArg?.replaceTargetDir && isDirectory(fromArg) && isDirectory(toArg)) {
removeSync(toArg);
}
return plugins.fsExtra.copySync(fromArg, toArg, optionsArg as plugins.fsExtra.CopyOptionsSync);
};
/**
* ensures that a directory is in place
*/
export const ensureDir = async (dirPathArg: string) => {
await plugins.fsExtra.ensureDir(dirPathArg);
};
/**
* ensures that a directory is in place
*/
export const ensureDirSync = (dirPathArg: string) => {
plugins.fsExtra.ensureDirSync(dirPathArg);
};
/**
* ensure an empty directory
* @executes ASYNC
*/
export const ensureEmptyDir = async (dirPathArg: string) => {
await plugins.fsExtra.ensureDir(dirPathArg);
await plugins.fsExtra.emptyDir(dirPathArg);
};
/**
* ensure an empty directory
* @executes SYNC
*/
export const ensureEmptyDirSync = (dirPathArg: string) => {
plugins.fsExtra.ensureDirSync(dirPathArg);
plugins.fsExtra.emptyDirSync(dirPathArg);
};
/**
* ensures that a file is on disk
* @param filePath the filePath to ensureDir
* @param the fileContent to place into a new file in case it doesn't exist yet
* @returns Promise<void>
* @exec ASYNC
*/
export const ensureFile = async (filePathArg, initFileStringArg): Promise<void> => {
ensureFileSync(filePathArg, initFileStringArg);
};
/**
* ensures that a file is on disk
* @param filePath the filePath to ensureDir
* @param the fileContent to place into a new file in case it doesn't exist yet
* @returns Promise<void>
* @exec SYNC
*/
export const ensureFileSync = (filePathArg: string, initFileStringArg: string): void => {
if (fileExistsSync(filePathArg)) {
return null;
} else {
memory.toFsSync(initFileStringArg, filePathArg);
}
};
/**
* removes a file or folder from local disk
*/
export const remove = async (pathArg: string): Promise<void> => {
await plugins.fsExtra.remove(pathArg);
};
/**
* removes a file SYNCHRONOUSLY from local disk
*/
export const removeSync = (pathArg: string): void => {
plugins.fsExtra.removeSync(pathArg);
};
/**
* removes an array of filePaths from disk
*/
export const removeMany = async (filePathArrayArg: string[]) => {
const promiseArray: Array<Promise<void>> = [];
for (const filePath of filePathArrayArg) {
promiseArray.push(remove(filePath));
}
await Promise.all(promiseArray);
};
/**
* like removeFilePathArray but SYNCHRONOUSLY
*/
export const removeManySync = (filePathArrayArg: string[]): void => {
for (const filePath of filePathArrayArg) {
removeSync(filePath);
}
};
/*===============================================================
============================ Write/Read =========================
===============================================================*/
/**
* reads a file content to an object
* good for JSON, YAML, TOML, etc.
* @param filePathArg
* @param fileTypeArg
* @returns {any}
*/
export const toObjectSync = (filePathArg, fileTypeArg?) => {
const fileString = plugins.fsExtra.readFileSync(filePathArg, 'utf8');
let fileType;
fileTypeArg ? (fileType = fileTypeArg) : (fileType = interpreter.filetype(filePathArg));
try {
return interpreter.objectFile(fileString, fileType);
} catch (err) {
err.message = `Failed to read file at ${filePathArg}` + err.message;
throw err;
}
};
/**
* reads a file content to a String
*/
export const toStringSync = (filePath: string): string => {
const encoding = plugins.smartmime.getEncodingForPathSync(filePath);
let fileString: string | Buffer = plugins.fsExtra.readFileSync(filePath, encoding);
if (Buffer.isBuffer(fileString)) {
fileString = fileString.toString('binary');
}
return fileString;
};
export const toBuffer = async (filePath: string): Promise<Buffer> => {
return plugins.fsExtra.readFile(filePath);
};
export const toBufferSync = (filePath: string): Buffer => {
return plugins.fsExtra.readFileSync(filePath);
};
/**
* Creates a Readable Stream from a file path.
* @param filePath The path to the file.
* @returns {fs.ReadStream}
*/
export const toReadStream = (filePath: string): plugins.fs.ReadStream => {
if (!fileExistsSync(filePath)) {
throw new Error(`File does not exist at path: ${filePath}`);
}
return plugins.fsExtra.createReadStream(filePath);
};
export const fileTreeToHash = async (dirPathArg: string, miniMatchFilter: string) => {
const fileTreeObject = await fileTreeToObject(dirPathArg, miniMatchFilter);
let combinedString = '';
for (const smartfile of fileTreeObject) {
combinedString += await smartfile.getHash();
}
const hash = await plugins.smarthash.sha256FromString(combinedString);
return hash;
};
/**
* creates a smartfile array from a directory
* @param dirPathArg the directory to start from
* @param miniMatchFilter a minimatch filter of what files to include
*/
export const fileTreeToObject = async (dirPathArg: string, miniMatchFilter: string) => {
// handle absolute miniMatchFilter
let dirPath: string;
if (plugins.path.isAbsolute(miniMatchFilter)) {
dirPath = '/';
} else {
dirPath = plugins.smartpath.transform.toAbsolute(dirPathArg) as string;
}
const fileTree = await listFileTree(dirPath, miniMatchFilter);
const smartfileArray: SmartFile[] = [];
for (const filePath of fileTree) {
const readPath = ((): string => {
if (!plugins.path.isAbsolute(filePath)) {
return plugins.path.join(dirPath, filePath);
} else {
return filePath;
}
})();
const fileBuffer = plugins.fs.readFileSync(readPath);
// push a read file as Smartfile
smartfileArray.push(
new SmartFile({
contentBuffer: fileBuffer,
base: dirPath,
path: filePath,
})
);
}
return smartfileArray;
};
/**
* lists Folders in a directory on local disk
* @returns Promise with an array that contains the folder names
*/
export const listFolders = async (pathArg: string, regexFilter?: RegExp): Promise<string[]> => {
return listFoldersSync(pathArg, regexFilter);
};
/**
* lists Folders SYNCHRONOUSLY in a directory on local disk
* @returns an array with the folder names as strings
*/
export const listFoldersSync = (pathArg: string, regexFilter?: RegExp): string[] => {
let folderArray = plugins.fsExtra.readdirSync(pathArg).filter((file) => {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isDirectory();
});
if (regexFilter) {
folderArray = folderArray.filter((fileItem) => {
return regexFilter.test(fileItem);
});
}
return folderArray;
};
/**
* lists Files in a directory on local disk
* @returns Promise
*/
export const listFiles = async (pathArg: string, regexFilter?: RegExp): Promise<string[]> => {
return listFilesSync(pathArg, regexFilter);
};
/**
* lists Files SYNCHRONOUSLY in a directory on local disk
* @returns an array with the folder names as strings
*/
export const listFilesSync = (pathArg: string, regexFilter?: RegExp): string[] => {
let fileArray = plugins.fsExtra.readdirSync(pathArg).filter((file) => {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isFile();
});
if (regexFilter) {
fileArray = fileArray.filter((fileItem) => {
return regexFilter.test(fileItem);
});
}
return fileArray;
};
/**
* lists all items (folders AND files) in a directory on local disk
* @returns Promise<string[]>
*/
export const listAllItems = async (pathArg: string, regexFilter?: RegExp): Promise<string[]> => {
return listAllItemsSync(pathArg, regexFilter);
};
/**
* lists all items (folders AND files) in a directory on local disk
* @returns an array with the folder names as strings
* @executes SYNC
*/
export const listAllItemsSync = (pathArg: string, regexFilter?: RegExp): string[] => {
let allItmesArray = plugins.fsExtra.readdirSync(pathArg).filter((file) => {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isFile();
});
if (regexFilter) {
allItmesArray = allItmesArray.filter((fileItem) => {
return regexFilter.test(fileItem);
});
}
return allItmesArray;
};
/**
* lists a file tree using a miniMatch filter
* note: if the miniMatch Filter is an absolute path, the cwdArg will be omitted
* @returns Promise<string[]> string array with the absolute paths of all matching files
*/
export const listFileTree = async (
dirPathArg: string,
miniMatchFilter: string,
absolutePathsBool: boolean = false
): Promise<string[]> => {
// handle absolute miniMatchFilter
let dirPath: string;
if (plugins.path.isAbsolute(miniMatchFilter)) {
dirPath = '/';
} else {
dirPath = dirPathArg;
}
const options = {
cwd: dirPath,
nodir: true,
dot: true,
};
let fileList = await plugins.glob.glob(miniMatchFilter, options);
if (absolutePathsBool) {
fileList = fileList.map((filePath) => {
return plugins.path.resolve(plugins.path.join(dirPath, filePath));
});
}
return fileList;
};
/**
* Watches for file stability before resolving the promise.
* Ensures that the directory/file exists before setting up the watcher.
*
* **New behavior**: If the given path is a directory, this function will:
* 1. Wait for that directory to exist (creating a timeout if needed).
* 2. Watch the directory until at least one file appears.
* 3. Then wait for the first file in the directory to stabilize before resolving.
*
* @param fileOrDirPathArg The path of the file or directory to monitor.
* @param timeoutMs The maximum time to wait for the file to stabilize (in milliseconds). Default is 60 seconds.
* @returns A promise that resolves when the target is stable or rejects on timeout/error.
*/
export const waitForFileToBeReady = async (
fileOrDirPathArg: string,
timeoutMs: number = 60000
): Promise<void> => {
const startTime = Date.now();
/**
* Ensure that a path (file or directory) exists. If it doesn't yet exist,
* wait until it does (or time out).
* @param pathToCheck The file or directory path to check.
*/
const ensurePathExists = async (pathToCheck: string): Promise<void> => {
while (true) {
try {
await plugins.smartpromise.fromCallback((cb) =>
plugins.fs.access(pathToCheck, plugins.fs.constants.F_OK, cb)
);
return;
} catch (err: any) {
if (err.code !== 'ENOENT') {
throw err; // Propagate unexpected errors
}
if (Date.now() - startTime > timeoutMs) {
throw new Error(`Timeout waiting for path to exist: ${pathToCheck}`);
}
await plugins.smartdelay.delayFor(500);
}
}
};
/**
* Checks if a file (not directory) is stable by comparing sizes
* across successive checks.
* @param filePathArg The path of the file to check.
* @returns A promise that resolves once the file stops changing.
*/
const waitForSingleFileToBeStable = async (filePathArg: string): Promise<void> => {
let lastFileSize = -1;
let fileIsStable = false;
// We'll create a helper for repeated stats-checking logic
const checkFileStability = async () => {
try {
const stats = await plugins.smartpromise.fromCallback<plugins.fs.Stats>((cb) =>
plugins.fs.stat(filePathArg, cb)
);
if (stats.isDirectory()) {
// If it unexpectedly turns out to be a directory here, throw
throw new Error(`Expected a file but found a directory: ${filePathArg}`);
}
if (stats.size === lastFileSize) {
fileIsStable = true;
} else {
lastFileSize = stats.size;
fileIsStable = false;
}
} catch (err: any) {
// Ignore only if file not found
if (err.code !== 'ENOENT') {
throw err;
}
}
};
// Ensure file exists first
await ensurePathExists(filePathArg);
// Set up a watcher on the file itself
const fileWatcher = plugins.fs.watch(filePathArg, { persistent: true }, async () => {
if (!fileIsStable) {
await checkFileStability();
}
});
try {
// Poll until stable or timeout
while (!fileIsStable) {
if (Date.now() - startTime > timeoutMs) {
throw new Error(`Timeout waiting for file to stabilize: ${filePathArg}`);
}
await checkFileStability();
if (!fileIsStable) {
await plugins.smartdelay.delayFor(1000);
}
}
} finally {
fileWatcher.close();
}
};
/**
* Main logic: check if we have a directory or file at fileOrDirPathArg.
* If directory, wait for first file in the directory to appear and stabilize.
* If file, do the old single-file wait logic.
*/
const statsForGivenPath = await (async () => {
try {
await ensurePathExists(fileOrDirPathArg);
return await plugins.smartpromise.fromCallback<plugins.fs.Stats>((cb) =>
plugins.fs.stat(fileOrDirPathArg, cb)
);
} catch (err) {
// If there's an error (including timeout), just rethrow
throw err;
}
})();
if (!statsForGivenPath.isDirectory()) {
// It's a file just do the single-file stability wait
await waitForSingleFileToBeStable(fileOrDirPathArg);
return;
}
// Otherwise, it's a directory. Wait for the first file inside to appear and be stable
const dirPath = fileOrDirPathArg;
// Helper to find the first file in the directory if it exists
const getFirstFileInDirectory = async (): Promise<string | null> => {
const entries = await plugins.smartpromise.fromCallback<string[]>((cb) =>
plugins.fs.readdir(dirPath, cb)
);
// We only want actual files, not subdirectories
for (const entry of entries) {
const entryPath = plugins.path.join(dirPath, entry);
const entryStats = await plugins.smartpromise.fromCallback<plugins.fs.Stats>((cb) =>
plugins.fs.stat(entryPath, cb)
);
if (entryStats.isFile()) {
return entryPath;
}
}
return null;
};
// Wait for a file to appear in this directory
let firstFilePath = await getFirstFileInDirectory();
if (!firstFilePath) {
// Set up a watcher on the directory to see if a file appears
const directoryWatcher = plugins.fs.watch(dirPath, { persistent: true });
try {
// We'll poll for the existence of a file in that directory
while (!firstFilePath) {
if (Date.now() - startTime > timeoutMs) {
throw new Error(`Timeout waiting for a file to appear in directory: ${dirPath}`);
}
firstFilePath = await getFirstFileInDirectory();
if (!firstFilePath) {
await plugins.smartdelay.delayFor(1000);
}
}
} finally {
directoryWatcher.close();
}
}
// Now that we have a file path, wait for that file to stabilize
await waitForSingleFileToBeStable(firstFilePath);
};
/**
* writes string or Smartfile to disk.
* @param fileArg
* @param fileNameArg
* @param fileBaseArg
*/
export let toFs = async (
fileContentArg: string | Buffer | SmartFile | StreamFile,
filePathArg: string,
optionsArg: {
respectRelative?: boolean;
} = {}
) => {
const done = plugins.smartpromise.defer();
// check args
if (!fileContentArg || !filePathArg) {
throw new Error('expected valid arguments');
}
// prepare actual write action
let fileContent: string | Buffer;
let fileEncoding: 'utf8' | 'binary' = 'utf8';
let filePath: string = filePathArg;
// handle Smartfile
if (fileContentArg instanceof SmartFile) {
fileContent = fileContentArg.contentBuffer;
// handle options
if (optionsArg.respectRelative) {
filePath = plugins.path.join(filePath, fileContentArg.path);
}
} else if (Buffer.isBuffer(fileContentArg)) {
fileContent = fileContentArg;
fileEncoding = 'binary';
} else if (typeof fileContentArg === 'string') {
fileContent = fileContentArg;
} else {
throw new Error('fileContent is neither string nor Smartfile');
}
await ensureDir(plugins.path.parse(filePath).dir);
plugins.fsExtra.writeFile(filePath, fileContent, { encoding: fileEncoding }, done.resolve);
return await done.promise;
};
export const stat = async (filePathArg: string) => {
return plugins.fsPromises.stat(filePathArg);
};

View File

@ -1,195 +0,0 @@
/*
This file contains logic for streaming things from and to the filesystem
*/
import * as plugins from './plugins.js';
export const createReadStream = (pathArg: string) => {
return plugins.fs.createReadStream(pathArg);
};
export const createWriteStream = (pathArg: string) => {
return plugins.fs.createWriteStream(pathArg);
};
export const processFile = async (
filePath: string,
asyncFunc: (fileStream: plugins.stream.Readable) => Promise<void>
): Promise<void> => {
return new Promise((resolve, reject) => {
const fileStream = createReadStream(filePath);
asyncFunc(fileStream).then(resolve).catch(reject);
});
}
export const processDirectory = async (
directoryPath: string,
asyncFunc: (fileStream: plugins.stream.Readable) => Promise<void>
): Promise<void> => {
const files = plugins.fs.readdirSync(directoryPath, { withFileTypes: true });
for (const file of files) {
const fullPath = plugins.path.join(directoryPath, file.name);
if (file.isDirectory()) {
await processDirectory(fullPath, asyncFunc); // Recursively call processDirectory for directories
} else if (file.isFile()) {
await processFile(fullPath, asyncFunc); // Call async function with the file stream and wait for it
}
}
};
/**
* Checks if a file is ready to be streamed (exists and is not empty).
*/
export const isFileReadyForStreaming = async (filePathArg: string): Promise<boolean> => {
try {
const stats = await plugins.fs.promises.stat(filePathArg);
return stats.size > 0;
} catch (error) {
if (error.code === 'ENOENT') { // File does not exist
return false;
}
throw error; // Rethrow other unexpected errors
}
};
/**
* Waits for a file to be ready for streaming (exists and is not empty).
*/
export const waitForFileToBeReadyForStreaming = (filePathArg: string): Promise<void> => {
return new Promise((resolve, reject) => {
// Normalize and resolve the file path
const filePath = plugins.path.resolve(filePathArg);
// Function to check file stats
const checkFile = (resolve: () => void, reject: (reason: any) => void) => {
plugins.fs.stat(filePath, (err, stats) => {
if (err) {
if (err.code === 'ENOENT') {
// File not found, wait and try again
return;
}
// Some other error occurred
return reject(err);
}
if (stats.size > 0) {
// File exists and is not empty, resolve the promise
resolve();
}
});
};
// Set up file watcher
const watcher = plugins.fs.watch(filePath, { persistent: false }, (eventType) => {
if (eventType === 'change' || eventType === 'rename') {
checkFile(resolve, reject);
}
});
// Check file immediately in case it's already ready
checkFile(resolve, reject);
// Error handling
watcher.on('error', (error) => {
watcher.close();
reject(error);
});
});
};
export class SmartReadStream extends plugins.stream.Readable {
private watcher: plugins.fs.FSWatcher | null = null;
private lastReadSize: number = 0;
private endTimeout: NodeJS.Timeout | null = null;
private filePath: string;
private endDelay: number;
private reading: boolean = false;
constructor(filePath: string, endDelay = 60000, opts?: plugins.stream.ReadableOptions) {
super(opts);
this.filePath = filePath;
this.endDelay = endDelay;
}
private startWatching(): void {
this.watcher = plugins.fs.watch(this.filePath, (eventType) => {
if (eventType === 'change') {
this.resetEndTimeout();
}
});
this.watcher.on('error', (error) => {
this.cleanup();
this.emit('error', error);
});
}
private resetEndTimeout(): void {
if (this.endTimeout) clearTimeout(this.endTimeout);
this.endTimeout = setTimeout(() => this.checkForEnd(), this.endDelay);
}
private checkForEnd(): void {
plugins.fs.stat(this.filePath, (err, stats) => {
if (err) {
this.emit('error', err);
return;
}
if (this.lastReadSize === stats.size) {
this.push(null); // Signal the end of the stream
this.cleanup();
} else {
this.lastReadSize = stats.size;
this.resetEndTimeout();
if (!this.reading) {
// We only want to continue reading if we were previously waiting for more data
this.reading = true;
this._read(10000); // Try to read more data
}
}
});
}
private cleanup(): void {
if (this.endTimeout) clearTimeout(this.endTimeout);
if (this.watcher) this.watcher.close();
}
_read(size: number): void {
this.reading = true;
const chunkSize = Math.min(size, 16384); // Read in chunks of 16KB
const buffer = Buffer.alloc(chunkSize);
plugins.fs.open(this.filePath, 'r', (err, fd) => {
if (err) {
this.emit('error', err);
return;
}
plugins.fs.read(fd, buffer, 0, chunkSize, this.lastReadSize, (err, bytesRead, buffer) => {
if (err) {
this.emit('error', err);
return;
}
if (bytesRead > 0) {
this.lastReadSize += bytesRead;
this.push(buffer.slice(0, bytesRead)); // Push the data onto the stream
} else {
this.reading = false; // No more data to read for now
this.resetEndTimeout();
}
plugins.fs.close(fd, (err) => {
if (err) {
this.emit('error', err);
}
});
});
});
}
_destroy(error: Error | null, callback: (error: Error | null) => void): void {
this.cleanup();
callback(error);
}
}

View File

@ -1,14 +1,15 @@
import * as plugins from './plugins.js'; import 'typings-global'
import * as fsMod from './fs.js';
import * as fsStreamMod from './fsstream.js';
import * as interpreterMod from './interpreter.js';
import * as memoryMod from './memory.js';
export * from './classes.smartfile.js'; import * as plugins from './smartfile.plugins'
export * from './classes.streamfile.js'; import * as SmartfileFs from './smartfile.fs'
export * from './classes.virtualdirectory.js'; import * as SmartfileInterpreter from './smartfile.interpreter'
import * as SmartfileMemory from './smartfile.memory'
import * as SmartfileRemote from './smartfile.remote'
export const fs = fsMod; export {Smartfile} from './smartfile.classes.smartfile'
export const fsStream = fsStreamMod;
export const interpreter = interpreterMod; export let fs = SmartfileFs
export const memory = memoryMod; export let interpreter = SmartfileInterpreter
export let memory = SmartfileMemory
export let remote = SmartfileRemote
export let requireReload = SmartfileFs.requireReload

View File

@ -1,20 +0,0 @@
import * as plugins from './plugins.js';
export let filetype = (pathArg: string): string => {
const extName = plugins.path.extname(pathArg);
const fileType = extName.replace(/\.([a-z]*)/, '$1'); // remove . form fileType
return fileType;
};
export let objectFile = (fileStringArg: string, fileTypeArg) => {
switch (fileTypeArg) {
case 'yml':
case 'yaml':
return plugins.yaml.load(fileStringArg);
case 'json':
return JSON.parse(fileStringArg);
default:
console.error('file type ' + fileTypeArg.blue + ' not supported');
break;
}
};

View File

@ -1,94 +0,0 @@
import * as plugins from './plugins.js';
import { SmartFile } from './classes.smartfile.js';
import * as smartfileFs from './fs.js';
import * as interpreter from './interpreter.js';
import type { StreamFile } from './classes.streamfile.js';
/**
* converts file to Object
* @param fileStringArg
* @param fileTypeArg
* @returns {any|any}
*/
export let toObject = (fileStringArg: string, fileTypeArg: string) => {
return interpreter.objectFile(fileStringArg, fileTypeArg);
};
export interface IToFsOptions {
respectRelative?: boolean;
}
/**
* writes string or Smartfile to disk.
* @param fileArg
* @param fileNameArg
* @param fileBaseArg
*/
export let toFs = async (
fileContentArg: string | Buffer | SmartFile | StreamFile,
filePathArg: string,
optionsArg: IToFsOptions = {}
) => {
const done = plugins.smartpromise.defer();
// check args
if (!fileContentArg || !filePathArg) {
throw new Error('expected valid arguments');
}
// prepare actual write action
let fileContent: string | Buffer;
let fileEncoding: 'utf8' | 'binary' = 'utf8';
let filePath: string = filePathArg;
// handle Smartfile
if (fileContentArg instanceof SmartFile) {
fileContent = fileContentArg.contentBuffer;
// handle options
if (optionsArg.respectRelative) {
filePath = plugins.path.join(filePath, fileContentArg.path);
}
} else if (Buffer.isBuffer(fileContentArg)) {
fileContent = fileContentArg;
fileEncoding = 'binary';
} else if (typeof fileContentArg === 'string') {
fileContent = fileContentArg;
} else {
throw new Error('fileContent is neither string nor Smartfile');
}
await smartfileFs.ensureDir(plugins.path.parse(filePath).dir);
plugins.fsExtra.writeFile(filePath, fileContent, { encoding: fileEncoding }, done.resolve);
return await done.promise;
};
/**
* writes a string or a Smartfile to disk synchronously, only supports string
* @param fileArg
* @param filePathArg
*/
export const toFsSync = (fileArg: string, filePathArg: string) => {
// function checks to abort if needed
if (!fileArg || !filePathArg) {
throw new Error('expected a valid arguments');
}
// prepare actual write action
let fileString: string;
const filePath: string = filePathArg;
if (typeof fileArg !== 'string') {
throw new Error('fileArg is not of type String.');
} else if (typeof fileArg === 'string') {
fileString = fileArg;
}
plugins.fsExtra.writeFileSync(filePath, fileString, { encoding: 'utf8' });
};
export let smartfileArrayToFs = async (smartfileArrayArg: SmartFile[], dirArg: string) => {
await smartfileFs.ensureDir(dirArg);
for (const smartfile of smartfileArrayArg) {
await toFs(smartfile, dirArg, {
respectRelative: true,
});
}
};

View File

@ -1,39 +0,0 @@
// node native scope
import * as fs from 'fs';
import * as fsPromises from 'fs/promises';
import * as path from 'path';
import * as stream from 'stream';
export { fs, fsPromises, path, stream };
// @pushrocks scope
import * as lik from '@push.rocks/lik';
import * as smartfileInterfaces from '@push.rocks/smartfile-interfaces';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smarthash from '@push.rocks/smarthash';
import * as smartjson from '@push.rocks/smartjson';
import * as smartmime from '@push.rocks/smartmime';
import * as smartpath from '@push.rocks/smartpath';
import * as smartpromise from '@push.rocks/smartpromise';
import * as smartrequest from '@push.rocks/smartrequest';
import * as smartstream from '@push.rocks/smartstream';
export {
lik,
smartfileInterfaces,
smartdelay,
smarthash,
smartjson,
smartmime,
smartpath,
smartpromise,
smartrequest,
smartstream,
};
// third party scope
import fsExtra from 'fs-extra';
import * as glob from 'glob';
import yaml from 'js-yaml';
export { fsExtra, glob, yaml };

View File

@ -0,0 +1,131 @@
import * as plugins from './smartfile.plugins'
export interface ISmartfileConstructorOptions {
path?: string
contentString?: string
contentBuffer?: Buffer
base?: string
}
/**
* class Smartfile
* -> is vinyl file compatible
*/
export class Smartfile {
/**
* the full path of the file on disk
*/
path: string
/**
* the content of the file as Buffer
*/
contentBuffer: Buffer
/**
* The current working directory of the file
*/
base: string
/**
* sync the file with disk
*/
sync: boolean
/**
* the constructor of Smartfile
* @param optionsArg
*/
constructor (optionsArg: ISmartfileConstructorOptions) {
if (optionsArg.contentBuffer) {
this.contentBuffer = optionsArg.contentBuffer
} else if (optionsArg.contentString) {
this.setContentsFromString(optionsArg.contentString)
} else {
console.log('created empty Smartfile?')
}
this.path = optionsArg.path
this.base = optionsArg.base
}
/**
* set contents from string
* @param contentString
*/
setContentsFromString(contentString: string) {
this.contents = new Buffer(contentString)
}
/**
* write file to disk
*/
async write () {
}
/**
* read file from disk
*/
async read () {
}
// -----------------------------------------------
// vinyl compatibility
// -----------------------------------------------
/**
* vinyl-compatibility: alias of this.contentBuffer
*/
get contents (): Buffer {
return this.contentBuffer
}
set contents (contentsArg) {
this.contentBuffer = contentsArg
}
/**
* vinyl-compatibility
*/
get cwd () {
return process.cwd()
}
/**
* return relative path of file
*/
get relative (): string {
return plugins.path.relative(this.base, this.path)
}
/**
* return truw when the file has content
*/
isNull (): boolean {
if (!this.contentBuffer) {
return true
}
return false
}
/**
* return true if contents are Buffer
*/
isBuffer (): boolean {
if (this.contents instanceof Buffer) {
return true
}
return false
}
isDirectory () {
return false
}
isStream () {
return false
}
isSymbolic () {
return false
}
}

385
ts/smartfile.fs.ts Normal file
View File

@ -0,0 +1,385 @@
import 'typings-global'
import plugins = require('./smartfile.plugins')
import SmartfileInterpreter = require('./smartfile.interpreter')
import { Smartfile } from './smartfile.classes.smartfile'
import * as memory from './smartfile.memory'
/*===============================================================
============================ Checks =============================
===============================================================*/
/**
*
* @param filePath
* @returns {boolean}
*/
export let fileExistsSync = function (filePath): boolean {
let fileExistsBool: boolean = false
try {
plugins.fsExtra.readFileSync(filePath)
fileExistsBool = true
} catch (err) {
fileExistsBool = false
}
return fileExistsBool
}
/**
*
* @param filePath
* @returns {any}
*/
export let fileExists = function (filePath) {
let done = plugins.q.defer()
plugins.fs.access(filePath, 4, function (err) {
err ? done.reject(err) : done.resolve()
})
return done.promise
}
/**
* Checks if given path points to an existing directory
*/
export let isDirectory = function (pathArg): boolean {
return plugins.fsExtra.statSync(pathArg).isDirectory()
}
/**
* Checks if a given path points to an existing file
*/
export let isFile = function (pathArg): boolean {
return plugins.fsExtra.statSync(pathArg).isFile()
}
/*===============================================================
============================ FS ACTIONS =========================
===============================================================*/
/**
* copies a file from A to B on the local disk
*/
export let copy = function (fromArg: string, toArg: string) {
let done = plugins.q.defer()
plugins.fsExtra.copy(fromArg, toArg, {}, function () {
done.resolve()
})
return done.promise
}
/**
* copies a file SYNCHRONOUSLY from A to B on the local disk
*/
export let copySync = function (fromArg: string, toArg: string): boolean {
plugins.fsExtra.copySync(fromArg, toArg)
return true
}
/**
* ensures that a directory is in place
*/
export let ensureDir = (dirPathArg: string) => {
let done = plugins.q.defer()
plugins.fsExtra.ensureDir(dirPathArg, done.resolve)
return done.promise
}
/**
* ensures that a directory is in place
*/
export let ensureDirSync = (dirPathArg: string) => {
plugins.fsExtra.ensureDirSync(dirPathArg)
}
/**
* ensure an empty directory
* @executes ASYNC
*/
export let ensureEmptyDir = (dirPathArg: string) => {
let done = plugins.q.defer()
plugins.fsExtra.ensureDir(dirPathArg, () => {
plugins.fsExtra.emptyDir(dirPathArg, done.resolve)
})
return done.promise
}
/**
* ensure an empty directory
* @executes SYNC
*/
export let ensureEmptyDirSync = (dirPathArg: string) => {
plugins.fsExtra.ensureDirSync(dirPathArg)
plugins.fsExtra.emptyDirSync(dirPathArg)
}
/**
* ensures that a file is on disk
* @param filePath the filePath to ensureDir
* @param the fileContent to place into a new file in case it doesn't exist yet
* @returns Promise<void>
* @exec ASYNC
*/
export let ensureFile = (filePathArg, initFileStringArg): Promise<void> => {
let done = plugins.q.defer<void>()
ensureFileSync(filePathArg, initFileStringArg)
done.resolve()
return done.promise
}
/**
* ensures that a file is on disk
* @param filePath the filePath to ensureDir
* @param the fileContent to place into a new file in case it doesn't exist yet
* @returns Promise<void>
* @exec SYNC
*/
export let ensureFileSync = (filePathArg: string, initFileStringArg: string): void => {
if (fileExistsSync(filePathArg)) {
return null
} else {
memory.toFsSync(initFileStringArg, filePathArg)
}
}
/**
* removes a file or folder from local disk
*/
export let remove = function (pathArg: string): Promise<void> {
let done = plugins.q.defer<void>()
plugins.fsExtra.remove(pathArg, function () {
done.resolve()
})
return done.promise
}
/**
* removes a file SYNCHRONOUSLY from local disk
*/
export let removeSync = function (pathArg: string): boolean {
plugins.fsExtra.removeSync(pathArg)
return true
}
/**
* removes an array of filePaths from disk
*/
export let removeMany = function (filePathArrayArg: string[]) {
let promiseArray: Promise<void>[] = []
for (let filePath of filePathArrayArg) {
promiseArray.push(remove(filePath))
}
return Promise.all(promiseArray)
}
/**
* like removeFilePathArray but SYNCHRONOUSLY
*/
export let removeManySync = function (filePathArrayArg: string[]): void {
for (let filePath of filePathArrayArg) {
removeSync(filePath)
}
}
/*===============================================================
============================ Write/Read =========================
===============================================================*/
/**
*
* @param filePathArg
* @param fileTypeArg
* @returns {any}
*/
export let toObjectSync = function (filePathArg, fileTypeArg?) {
let fileString = plugins.fsExtra.readFileSync(filePathArg, 'utf8')
let fileType
fileTypeArg ? fileType = fileTypeArg : fileType = SmartfileInterpreter.filetype(filePathArg)
return SmartfileInterpreter.objectFile(fileString, fileType)
}
/**
* reads a file content to a String
* @param filePath
* @returns {string|Buffer|any}
*/
export let toStringSync = function (filePath: string): string {
let fileString: any = plugins.fsExtra.readFileSync(filePath, 'utf8')
fileString = `${fileString}`
return fileString
}
export let fileTreeToObject = async (dirPathArg: string, miniMatchFilter: string) => {
// handle absolute miniMatchFilter
let dirPath: string
if (plugins.path.isAbsolute(miniMatchFilter)) {
dirPath = '/'
} else {
dirPath = dirPathArg
}
let fileTree = await listFileTree(dirPath, miniMatchFilter)
let smartfileArray: Smartfile[] = []
for (let filePath of fileTree) {
let fileContentString = toStringSync(
plugins.path.join(dirPath, filePath)
)
// push a read file as Smartfile
smartfileArray.push(new Smartfile({
contentBuffer: new Buffer(fileContentString),
base: dirPath,
path: filePath
}))
}
return smartfileArray
}
/**
*
* @param filePathArg
* @param options
* @returns {number}
*/
export let toVinylSync = function (filePathArg, options = {}) {
return plugins.vinylFile.readSync(filePathArg, options)
}
/**
* lets you reload files hot.
* @param path
* @returns {any}
*/
export let requireReload = function (path: string) {
return plugins.requireReload(path)
}
/**
* lists Folders in a directory on local disk
* @returns Promise
*/
export let listFolders = function (pathArg: string, regexFilter?: RegExp) {
let done = plugins.q.defer()
let folderArray = plugins.fsExtra.readdirSync(pathArg).filter(function (file) {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isDirectory()
})
if (regexFilter) {
folderArray = folderArray.filter((fileItem) => {
return regexFilter.test(fileItem)
})
}
done.resolve(folderArray)
return done.promise
}
/**
* lists Folders SYNCHRONOUSLY in a directory on local disk
* @returns an array with the folder names as strings
*/
export let listFoldersSync = function (pathArg: string, regexFilter?: RegExp): string[] {
let folderArray = plugins.fsExtra.readdirSync(pathArg).filter(function (file) {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isDirectory()
})
if (regexFilter) {
folderArray = folderArray.filter((fileItem) => {
return regexFilter.test(fileItem)
})
}
return folderArray
}
/**
* lists Files in a directory on local disk
* @returns Promise
*/
export let listFiles = function (pathArg: string, regexFilter?: RegExp) {
let done = plugins.q.defer()
let fileArray = plugins.fsExtra.readdirSync(pathArg).filter(function (file) {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isFile()
})
if (regexFilter) {
fileArray = fileArray.filter((fileItem) => {
return regexFilter.test(fileItem)
})
}
done.resolve(fileArray)
return done.promise
}
/**
* lists Files SYNCHRONOUSLY in a directory on local disk
* @returns an array with the folder names as strings
*/
export let listFilesSync = function (pathArg: string, regexFilter?: RegExp): string[] {
let fileArray = plugins.fsExtra.readdirSync(pathArg).filter(function (file) {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isFile()
})
if (regexFilter) {
fileArray = fileArray.filter((fileItem) => {
return regexFilter.test(fileItem)
})
}
return fileArray
}
/**
* lists all items (folders AND files) in a directory on local disk
* @returns Promise<string[]>
*/
export let listAllItems = function (pathArg: string, regexFilter?: RegExp): Promise<string[]> {
let done = plugins.q.defer<string[]>()
let allItmesArray = plugins.fsExtra.readdirSync(pathArg)
if (regexFilter) {
allItmesArray = allItmesArray.filter((fileItem) => {
return regexFilter.test(fileItem)
})
};
done.resolve(allItmesArray)
return done.promise
}
/**
* lists all items (folders AND files) in a directory on local disk
* @returns an array with the folder names as strings
* @executes SYNC
*/
export let listAllItemsSync = function (pathArg: string, regexFilter?: RegExp): string[] {
let allItmesArray = plugins.fsExtra.readdirSync(pathArg).filter(function (file) {
return plugins.fsExtra.statSync(plugins.path.join(pathArg, file)).isFile()
})
if (regexFilter) {
allItmesArray = allItmesArray.filter((fileItem) => {
return regexFilter.test(fileItem)
})
}
return allItmesArray
}
/**
* lists a file tree using a miniMatch filter
* note: if the miniMatch Filter is an absolute path, the cwdArg will be omitted
* @returns Promise<string[]> string array with the absolute paths of all matching files
*/
export let listFileTree = (dirPathArg: string, miniMatchFilter: string): Promise<string[]> => {
let done = plugins.q.defer<string[]>()
// handle absolute miniMatchFilter
let dirPath: string
if (plugins.path.isAbsolute(miniMatchFilter)) {
dirPath = '/'
} else {
dirPath = dirPathArg
}
let options = {
cwd: dirPath
}
plugins.glob(miniMatchFilter, options, (err, files: string[]) => {
if (err) {
console.log(err)
done.reject(err)
}
done.resolve(files)
})
return done.promise
}

View File

@ -0,0 +1,22 @@
import 'typings-global'
import plugins = require('./smartfile.plugins')
export let filetype = (pathArg: string): string => {
let extName = plugins.path.extname(pathArg)
let fileType = extName.replace(/\.([a-z]*)/,'$1') // remove . form fileType
return fileType
}
export let objectFile = (fileStringArg: string, fileTypeArg) => {
switch (fileTypeArg) {
case 'yml' :
case 'yaml':
return plugins.yaml.safeLoad(fileStringArg)
case 'json':
return JSON.parse(fileStringArg)
default:
console.error('file type ' + fileTypeArg.blue + ' not supported')
break
}
}

112
ts/smartfile.memory.ts Normal file
View File

@ -0,0 +1,112 @@
import 'typings-global'
import plugins = require('./smartfile.plugins')
import SmartfileInterpreter = require('./smartfile.interpreter')
let vinyl = require('vinyl')
export interface IVinylFile {
contents: Buffer
base: string
path: string,
}
/**
* converts file to Object
* @param fileStringArg
* @param fileTypeArg
* @returns {any|any}
*/
export let toObject = function (fileStringArg: string, fileTypeArg: string) {
return SmartfileInterpreter.objectFile(fileStringArg, fileTypeArg)
}
/**
* takes a string and converts it to vinyl file
* @param fileArg
* @param optionsArg
*/
export let toVinylFileSync = function (fileArg: string, optionsArg?: { filename?: string, base?: string, relPath?: string }) {
optionsArg ? void (0) : optionsArg = { filename: 'vinylfile', base: '/' }
optionsArg.filename ? void (0) : optionsArg.filename = 'vinylfile'
optionsArg.base ? void (0) : optionsArg.base = '/'
optionsArg.relPath ? void ('0') : optionsArg.relPath = ''
let vinylFile = new vinyl({
base: optionsArg.base,
path: plugins.path.join(optionsArg.base, optionsArg.relPath, optionsArg.filename),
contents: new Buffer(fileArg)
})
return vinylFile
}
/**
* takes a string array and some options and returns a vinylfile array
* @param arrayArg
* @param optionsArg
*/
export let toVinylArraySync = function (
arrayArg: string[],
optionsArg?: {
filename?: string,
base?: string,
relPath?: string
}
) {
let vinylArray = []
for (let stringIndexArg in arrayArg) {
let myString = arrayArg[ stringIndexArg ]
vinylArray.push(toVinylFileSync(myString, optionsArg))
}
return vinylArray
}
/**
* takes a vinylFile object and converts it to String
*/
export let vinylToStringSync = function (fileArg: IVinylFile): string {
return fileArg.contents.toString('utf8')
}
/**
* writes string or vinyl file to disk.
* @param fileArg
* @param fileNameArg
* @param fileBaseArg
*/
export let toFs = function (fileContentArg: string | IVinylFile, filePathArg) {
let done = plugins.q.defer()
// function checks to abort if needed
if (!fileContentArg || !filePathArg) {
throw new Error('expected valid arguments')
}
// prepare actual write action
let fileString: string
let filePath: string = filePathArg
if (vinyl.isVinyl(fileContentArg)) {
let fileContentArg2: any = fileContentArg
fileString = vinylToStringSync(fileContentArg2)
} else if (typeof fileContentArg === 'string') {
fileString = fileContentArg
}
plugins.fsExtra.writeFile(filePath, fileString, 'utf8', done.resolve)
return done.promise
}
export let toFsSync = function (fileArg, filePathArg: string) {
// function checks to abort if needed
if (!fileArg || !filePathArg) {
throw new Error('expected a valid arguments')
}
// prepare actual write action
let fileString: string
let filePath: string = filePathArg
if (typeof fileArg !== 'string') {
fileString = vinylToStringSync(fileArg)
} else if (typeof fileArg === 'string') {
fileString = fileArg
}
plugins.fsExtra.writeFileSync(filePath, fileString, 'utf8')
}

11
ts/smartfile.plugins.ts Normal file
View File

@ -0,0 +1,11 @@
import 'typings-global'
export import fs = require('fs')
export import fsExtra = require('fs-extra')
export let glob = require('glob')
export import path = require('path')
export import q = require('smartq')
export import smartrequest = require('smartrequest')
export let requireReload = require('require-reload')
export import smartpath = require('smartpath')
export let vinylFile = require('vinyl-file')
export let yaml = require('js-yaml')

50
ts/smartfile.remote.ts Normal file
View File

@ -0,0 +1,50 @@
import 'typings-global'
import plugins = require('./smartfile.plugins')
import SmartfileInterpreter = require('./smartfile.interpreter')
/* export let toFs = function (from: string, toPath: string) {
let done = plugins.q.defer()
let stream = plugins.smartrequest(from).pipe(plugins.fsExtra.createWriteStream(toPath))
stream.on('finish', function () {
done.resolve(toPath)
})
return done.promise
} */
/**
*
* @param fromArg
* @returns {any}
*/
export let toObject = function (fromArg: string) {
let done = plugins.q.defer()
plugins.smartrequest.request(fromArg, {
method: 'get'
}).then((res: any) => {
if (res.statusCode === 200) {
done.resolve(res.body)
} else {
console.log('could not get remote file from ' + fromArg)
done.reject(new Error('could not get remote file from ' + fromArg))
}
})
return done.promise
}
/**
*
* @param fromArg
* @returns {any}
*/
export let toString = (fromArg: string) => {
let done = plugins.q.defer()
plugins.smartrequest.get(fromArg).then((res: any) => {
if (res.statusCode === 200) {
done.resolve(res.body)
} else {
console.error('could not get remote file from ' + fromArg)
done.reject(new Error('could not get remote file from ' + fromArg))
}
})
return done.promise
}

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

3
tslint.json Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "tslint-config-standard"
}

496
yarn.lock Normal file
View File

@ -0,0 +1,496 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@types/chai-as-promised@0.0.29":
version "0.0.29"
resolved "https://registry.yarnpkg.com/@types/chai-as-promised/-/chai-as-promised-0.0.29.tgz#43d52892aa998e185a3de3e2477edb8573be1d77"
dependencies:
"@types/chai" "*"
"@types/promises-a-plus" "*"
"@types/chai-string@^1.1.30":
version "1.1.30"
resolved "https://registry.yarnpkg.com/@types/chai-string/-/chai-string-1.1.30.tgz#4d8744b31a5a2295fc01c981ed1e2d4c8a070f0a"
dependencies:
"@types/chai" "*"
"@types/chai@*", "@types/chai@^3.4.35":
version "3.5.2"
resolved "https://registry.yarnpkg.com/@types/chai/-/chai-3.5.2.tgz#c11cd2817d3a401b7ba0f5a420f35c56139b1c1e"
"@types/fs-extra@2.x.x":
version "2.1.0"
resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-2.1.0.tgz#8b350239c0455d92b8d3c626edac193860ff395f"
dependencies:
"@types/node" "*"
"@types/node@*":
version "7.0.14"
resolved "https://registry.yarnpkg.com/@types/node/-/node-7.0.14.tgz#1470fa002a113316ac9d9ad163fc738c7a0de2a4"
"@types/promises-a-plus@*":
version "0.0.27"
resolved "https://registry.yarnpkg.com/@types/promises-a-plus/-/promises-a-plus-0.0.27.tgz#c64651134614c84b8f5d7114ce8901d36a609780"
"@types/through2@^2.0.32":
version "2.0.32"
resolved "https://registry.yarnpkg.com/@types/through2/-/through2-2.0.32.tgz#470024450f1ab7640f19f9ebf42d3da574c26129"
dependencies:
"@types/node" "*"
"@types/vinyl@^2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@types/vinyl/-/vinyl-2.0.0.tgz#fd213bf7f4136dde21fe1895500b12c186f8c268"
dependencies:
"@types/node" "*"
ansi-256-colors@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/ansi-256-colors/-/ansi-256-colors-1.1.0.tgz#910de50efcc7c09e3d82f2f87abd6b700c18818a"
argparse@^1.0.7:
version "1.0.9"
resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.9.tgz#73d83bc263f86e97f8cc4f6bae1b0e90a7d22c86"
dependencies:
sprintf-js "~1.0.2"
assertion-error@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.0.2.tgz#13ca515d86206da0bac66e834dd397d87581094c"
balanced-match@^0.4.1:
version "0.4.2"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-0.4.2.tgz#cb3f3e3c732dc0f01ee70b403f302e61d7709838"
beautycolor@^1.0.7:
version "1.0.7"
resolved "https://registry.yarnpkg.com/beautycolor/-/beautycolor-1.0.7.tgz#a4715738ac4c8221371e9cbeb5a6cc6d11ecbf7c"
dependencies:
ansi-256-colors "^1.1.0"
typings-global "^1.0.14"
bindings@^1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.2.1.tgz#14ad6113812d2d37d72e67b4cacb4bb726505f11"
brace-expansion@^1.0.0:
version "1.1.7"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.7.tgz#3effc3c50e000531fb720eaff80f0ae8ef23cf59"
dependencies:
balanced-match "^0.4.1"
concat-map "0.0.1"
buffer-shims@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/buffer-shims/-/buffer-shims-1.0.0.tgz#9978ce317388c649ad8793028c3477ef044a8b51"
chai-as-promised@^6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/chai-as-promised/-/chai-as-promised-6.0.0.tgz#1a02a433a6f24dafac63b9c96fa1684db1aa8da6"
dependencies:
check-error "^1.0.2"
chai-string@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/chai-string/-/chai-string-1.3.0.tgz#df6139f294391b1035be5606f60a843b3a5041e7"
chai@^3.5.0:
version "3.5.0"
resolved "https://registry.yarnpkg.com/chai/-/chai-3.5.0.tgz#4d02637b067fe958bdbfdd3a40ec56fef7373247"
dependencies:
assertion-error "^1.0.1"
deep-eql "^0.1.3"
type-detect "^1.0.0"
check-error@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82"
clone-buffer@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/clone-buffer/-/clone-buffer-1.0.0.tgz#e3e25b207ac4e701af721e2cb5a16792cac3dc58"
clone-stats@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-1.0.0.tgz#b3782dff8bb5474e18b9b6bf0fdfe782f8777680"
clone@^1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.2.tgz#260b7a99ebb1edfe247538175f783243cb19d149"
cloneable-readable@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/cloneable-readable/-/cloneable-readable-1.0.0.tgz#a6290d413f217a61232f95e458ff38418cfb0117"
dependencies:
inherits "^2.0.1"
process-nextick-args "^1.0.6"
through2 "^2.0.1"
concat-map@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
core-util-is@~1.0.0:
version "1.0.2"
resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7"
deep-eql@^0.1.3:
version "0.1.3"
resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-0.1.3.tgz#ef558acab8de25206cd713906d74e56930eb69f2"
dependencies:
type-detect "0.1.1"
early@^2.1.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/early/-/early-2.1.1.tgz#841e23254ea5dc54d8afaeee82f5ab65c00ee23c"
dependencies:
beautycolor "^1.0.7"
smartq "^1.1.1"
typings-global "^1.0.16"
esprima@^3.1.1:
version "3.1.3"
resolved "https://registry.yarnpkg.com/esprima/-/esprima-3.1.3.tgz#fdca51cee6133895e3c88d535ce49dbff62a4633"
first-chunk-stream@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/first-chunk-stream/-/first-chunk-stream-2.0.0.tgz#1bdecdb8e083c0664b91945581577a43a9f31d70"
dependencies:
readable-stream "^2.0.2"
fs-extra@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-3.0.0.tgz#244e0c4b0b8818f54040ec049d8a2bddc1202861"
dependencies:
graceful-fs "^4.1.2"
jsonfile "^3.0.0"
universalify "^0.1.0"
fs.realpath@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"
glob@^7.0.0, glob@^7.1.1:
version "7.1.1"
resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.1.tgz#805211df04faaf1c63a3600306cdf5ade50b2ec8"
dependencies:
fs.realpath "^1.0.0"
inflight "^1.0.4"
inherits "2"
minimatch "^3.0.2"
once "^1.3.0"
path-is-absolute "^1.0.0"
graceful-fs@^4.1.2, graceful-fs@^4.1.6:
version "4.1.11"
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658"
gulp-function@^2.2.9:
version "2.2.9"
resolved "https://registry.yarnpkg.com/gulp-function/-/gulp-function-2.2.9.tgz#de513103db9d817e94bb8aab45f30bf286f19ae5"
dependencies:
"@types/through2" "^2.0.32"
smartq "^1.1.1"
through2 "^2.0.3"
typings-global "^1.0.16"
home@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/home/-/home-1.0.1.tgz#96a423ceb49b98378ff5ef3ceae059a557f9dd35"
dependencies:
os-homedir "^1.0.1"
inflight@^1.0.4:
version "1.0.6"
resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9"
dependencies:
once "^1.3.0"
wrappy "1"
inherits@2, inherits@^2.0.1, inherits@~2.0.1:
version "2.0.3"
resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de"
interpret@^1.0.0:
version "1.0.3"
resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.0.3.tgz#cbc35c62eeee73f19ab7b10a801511401afc0f90"
is-stream@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44"
is-utf8@^0.2.0, is-utf8@^0.2.1:
version "0.2.1"
resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72"
isarray@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11"
js-yaml@^3.8.3:
version "3.8.3"
resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.8.3.tgz#33a05ec481c850c8875929166fe1beb61c728766"
dependencies:
argparse "^1.0.7"
esprima "^3.1.1"
jsonfile@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-3.0.0.tgz#92e7c7444e5ffd5fa32e6a9ae8b85034df8347d0"
optionalDependencies:
graceful-fs "^4.1.6"
leakage@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/leakage/-/leakage-0.2.0.tgz#9e7a8cc1d241d8c8427e348769e192e172fd8733"
dependencies:
left-pad "^1.1.3"
memwatch-next "^0.3.0"
minimist "^1.2.0"
pretty-bytes "^4.0.2"
left-pad@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/left-pad/-/left-pad-1.1.3.tgz#612f61c033f3a9e08e939f1caebeea41b6f3199a"
memwatch-next@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/memwatch-next/-/memwatch-next-0.3.0.tgz#2111050f9a906e0aa2d72a4ec0f0089c78726f8f"
dependencies:
bindings "^1.2.1"
nan "^2.3.2"
minimatch@^3.0.2:
version "3.0.3"
resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.3.tgz#2a4e4090b96b2db06a9d7df01055a62a77c9b774"
dependencies:
brace-expansion "^1.0.0"
minimist@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
nan@^2.3.2:
version "2.6.2"
resolved "https://registry.yarnpkg.com/nan/-/nan-2.6.2.tgz#e4ff34e6c95fdfb5aecc08de6596f43605a7db45"
once@^1.3.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
dependencies:
wrappy "1"
os-homedir@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3"
path-is-absolute@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f"
path-parse@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.5.tgz#3c1adf871ea9cd6c9431b6ea2bd74a0ff055c4c1"
pify@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c"
pretty-bytes@^4.0.2:
version "4.0.2"
resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-4.0.2.tgz#b2bf82e7350d65c6c33aa95aaa5a4f6327f61cd9"
process-nextick-args@^1.0.6, process-nextick-args@~1.0.6:
version "1.0.7"
resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3"
readable-stream@^2.0.2, readable-stream@^2.1.5:
version "2.2.9"
resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.2.9.tgz#cf78ec6f4a6d1eb43d26488cac97f042e74b7fc8"
dependencies:
buffer-shims "~1.0.0"
core-util-is "~1.0.0"
inherits "~2.0.1"
isarray "~1.0.0"
process-nextick-args "~1.0.6"
string_decoder "~1.0.0"
util-deprecate "~1.0.1"
rechoir@^0.6.2:
version "0.6.2"
resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384"
dependencies:
resolve "^1.1.6"
remove-trailing-separator@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.0.1.tgz#615ebb96af559552d4bf4057c8436d486ab63cc4"
replace-ext@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.0.tgz#de63128373fcbf7c3ccfa4de5a480c45a67958eb"
require-reload@0.2.2:
version "0.2.2"
resolved "https://registry.yarnpkg.com/require-reload/-/require-reload-0.2.2.tgz#29a7591846caf91b6e8a3cda991683f95f8d7d42"
resolve@^1.1.6:
version "1.3.3"
resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.3.3.tgz#655907c3469a8680dc2de3a275a8fdd69691f0e5"
dependencies:
path-parse "^1.0.5"
semver@^5.3.0:
version "5.3.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f"
shelljs@^0.7.7:
version "0.7.7"
resolved "https://registry.yarnpkg.com/shelljs/-/shelljs-0.7.7.tgz#b2f5c77ef97148f4b4f6e22682e10bba8667cff1"
dependencies:
glob "^7.0.0"
interpret "^1.0.0"
rechoir "^0.6.2"
smartchai@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/smartchai/-/smartchai-1.0.3.tgz#de6d010bb8b5aef24cb70b31a5f5334e8c41b72f"
dependencies:
"@types/chai" "^3.4.35"
"@types/chai-as-promised" "0.0.29"
"@types/chai-string" "^1.1.30"
chai "^3.5.0"
chai-as-promised "^6.0.0"
chai-string "^1.3.0"
smartdelay@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/smartdelay/-/smartdelay-1.0.1.tgz#687f8bcc09d7c62c9c5a8a1771c1aba3aff54156"
dependencies:
typings-global "^1.0.14"
smartpath@^3.2.8:
version "3.2.8"
resolved "https://registry.yarnpkg.com/smartpath/-/smartpath-3.2.8.tgz#4834bd3a8bae2295baacadba23c87a501952f940"
dependencies:
home "^1.0.1"
typings-global "^1.0.14"
smartq@^1.1.0, smartq@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/smartq/-/smartq-1.1.1.tgz#efb358705260d41ae18aef7ffd815f7b6fe17dd3"
dependencies:
typed-promisify "^0.3.0"
typings-global "^1.0.14"
smartrequest@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/smartrequest/-/smartrequest-1.0.4.tgz#86af2163ae28f1031b01c2d8ad8c429733920611"
dependencies:
smartq "^1.1.0"
typings-global "^1.0.14"
sprintf-js@~1.0.2:
version "1.0.3"
resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c"
string_decoder@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.0.tgz#f06f41157b664d86069f84bdbdc9b0d8ab281667"
dependencies:
buffer-shims "~1.0.0"
strip-bom-buf@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/strip-bom-buf/-/strip-bom-buf-1.0.0.tgz#1cb45aaf57530f4caf86c7f75179d2c9a51dd572"
dependencies:
is-utf8 "^0.2.1"
strip-bom-stream@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/strip-bom-stream/-/strip-bom-stream-2.0.0.tgz#f87db5ef2613f6968aa545abfe1ec728b6a829ca"
dependencies:
first-chunk-stream "^2.0.0"
strip-bom "^2.0.0"
strip-bom@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e"
dependencies:
is-utf8 "^0.2.0"
tapbundle@^1.0.10:
version "1.0.10"
resolved "https://registry.yarnpkg.com/tapbundle/-/tapbundle-1.0.10.tgz#36fd40036f6b5b738cbb9b5fc400df4c4031bc26"
dependencies:
early "^2.1.1"
leakage "^0.2.0"
smartchai "^1.0.3"
smartdelay "^1.0.1"
smartq "^1.1.1"
typings-global "^1.0.16"
through2@^2.0.1, through2@^2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.3.tgz#0004569b37c7c74ba39c43f3ced78d1ad94140be"
dependencies:
readable-stream "^2.1.5"
xtend "~4.0.1"
type-detect@0.1.1:
version "0.1.1"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-0.1.1.tgz#0ba5ec2a885640e470ea4e8505971900dac58822"
type-detect@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-1.0.0.tgz#762217cc06db258ec48908a1298e8b95121e8ea2"
typed-promisify@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/typed-promisify/-/typed-promisify-0.3.0.tgz#1ba0af5e444c87d8047406f18ce49092a1191853"
typings-global@^1.0.14, typings-global@^1.0.16:
version "1.0.16"
resolved "https://registry.yarnpkg.com/typings-global/-/typings-global-1.0.16.tgz#489b71781af24268750c2899316400a5e482961f"
dependencies:
semver "^5.3.0"
shelljs "^0.7.7"
universalify@^0.1.0:
version "0.1.0"
resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.0.tgz#9eb1c4651debcc670cc94f1a75762332bb967778"
util-deprecate@~1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"
vinyl-file@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/vinyl-file/-/vinyl-file-3.0.0.tgz#b104d9e4409ffa325faadd520642d0a3b488b365"
dependencies:
graceful-fs "^4.1.2"
pify "^2.3.0"
strip-bom-buf "^1.0.0"
strip-bom-stream "^2.0.0"
vinyl "^2.0.1"
vinyl@^2.0.1, vinyl@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.0.2.tgz#0a3713d8d4e9221c58f10ca16c0116c9e25eda7c"
dependencies:
clone "^1.0.0"
clone-buffer "^1.0.0"
clone-stats "^1.0.0"
cloneable-readable "^1.0.0"
is-stream "^1.1.0"
remove-trailing-separator "^1.0.1"
replace-ext "^1.0.0"
wrappy@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
xtend@~4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af"