diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index ba5a48d7..00000000 --- a/.appveyor.yml +++ /dev/null @@ -1,17 +0,0 @@ -platform: x64 - -install: - - ps: Install-Product node $env:nodejs_version $env:platform - -build: off - -build_script: - - node --version - - npm --version - - - npm i now nupdate -g - - nupdate -a gritty - - now rm cloudcmd -y -t %NOW_TOKEN% || true - - now --public -t %NOW_TOKEN% - - now alias -t %NOW_TOKEN% - diff --git a/.babelrc b/.babelrc deleted file mode 100644 index b5a9ba48..00000000 --- a/.babelrc +++ /dev/null @@ -1,21 +0,0 @@ -{ - "presets": [ - ["@babel/preset-env", { - "exclude": [ - "transform-regenerator" - ] - }], - ], - "plugins": [ - "@babel/plugin-transform-object-assign", - "@babel/plugin-proposal-object-rest-spread", - "@babel/plugin-syntax-dynamic-import", - ["module:fast-async", { - "compiler": { - "generators": false, - "runtimePatter": ".js" - } - }], - "module:babel-plugin-macros", - ] -} diff --git a/.babelrc.json b/.babelrc.json new file mode 100644 index 00000000..33d70c39 --- /dev/null +++ b/.babelrc.json @@ -0,0 +1,9 @@ +{ + "presets": [ + "@babel/preset-env" + ], + "plugins": [ + "module:babel-plugin-macros", + "@babel/plugin-transform-optional-chaining" + ] +} diff --git a/.browserslistrc b/.browserslistrc new file mode 100644 index 00000000..bde9f522 --- /dev/null +++ b/.browserslistrc @@ -0,0 +1,4 @@ +last 2 Chrome versions +last 2 Safari versions +Firefox ESR +not dead diff --git a/.cloudcmd.menu.js b/.cloudcmd.menu.js new file mode 100644 index 00000000..0e0126b6 --- /dev/null +++ b/.cloudcmd.menu.js @@ -0,0 +1,31 @@ +export default { + 'F2 - Rename File': renameCurrent, + 'L - Lint': run('npm run lint'), + 'F - Fix Lint': run('npm run fix:lint'), + 'T - Test': run('npm run test'), + 'C - Coverage': run('npm run coverage'), + 'D - Build Dev': run('npm run build:client:dev'), + 'P - Build Prod': run('npm run build:client'), +}; + +async function renameCurrent(DOM) { + await DOM.renameCurrent(); +} + +function run(command) { + return async ({CloudCmd, DOM}) => { + const {TerminalRun, config} = CloudCmd; + + const {CurrentInfo} = DOM; + const {dirPath} = CurrentInfo; + + const cwd = config('root') + dirPath; + + return await TerminalRun.show({ + cwd, + command, + closeMessage: 'Press any key to close Terminal', + autoClose: false, + }); + }; +} diff --git a/.dockerignore b/.dockerignore index 627bba19..1c9d9d9a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -11,8 +11,7 @@ yarn-error.log yarn.lock now.json -Dockerfile -Dockerfile.alpine +docker webpack.config.js cssnano.config.js @@ -20,6 +19,5 @@ cssnano.config.js bin/release.js client -legacy server_ diff --git a/.editorconfig b/.editorconfig index 09fa9422..439abfd0 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,7 +9,7 @@ root = true charset = utf-8 end_of_line = lf insert_final_newline = true -trim_trailing_whitespace = true +trim_trailing_whitespace = false indent_style = space indent_size = 4 diff --git a/.eslintrc b/.eslintrc deleted file mode 100644 index fc514e99..00000000 --- a/.eslintrc +++ /dev/null @@ -1,19 +0,0 @@ -{ - "env": { - "es6": true, - "node": true, - }, - "parserOptions": { - "ecmaVersion": 2018, - "sourceType": "module", - }, - "rules": { - "indent": ["error", 4], - "semi": "error", - "no-console": 0, - "no-use-before-define": 0, - }, - "extends": [ - "eslint:recommended" - ] -} diff --git a/.eslintrc.server b/.eslintrc.server deleted file mode 100644 index 2e2555ea..00000000 --- a/.eslintrc.server +++ /dev/null @@ -1,15 +0,0 @@ -{ - "env": { - "node": true - }, - "rules": { - "no-process-exit": 0 - }, - "extends": [ - ".eslintrc", - "plugin:node/recommended" - ], - "plugins": [ - "node" - ] -} diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..9fdb6d3c --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +github: coderaiser +open_collective: cloudcmd +ko_fi: coderaiser diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 6cc34cc8..00000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,12 +0,0 @@ - - -* **Version** (`cloudcmd -v`): -* **Node Version** `node -v`: -* **OS** (`uname -a` on Linux): -* **Browser name/version**: -* **Used Command Line Parameters**: -* **Changed Config**: - diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..5c1e7460 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,45 @@ +--- + +name: Bug report +about: Create a report to help us improve +title: '' +labels: needs clarification +assignees: coderaiser + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + +- **Version** (`cloudcmd -v`): +- **Node Version** `node -v`: +- **OS** (`uname -a` on Linux): +- **Browser name/version**: +- **Used Command Line Parameters**: +- **Changed Config**: + +```json +{} +``` +- [ ] 🎁 **I'm ready to donate on https://opencollective.com/cloudcmd** +- [ ] 🎁 **I'm ready to donate on https://ko-fi.com/coderaiser** +- [ ] 💪 **I'm willing to work on this issue** + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..5f41e73a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Stack Overflow + url: https://stackoverflow.com/search?q=cloudcmd + about: Please ask and answer questions here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..549a8874 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,21 @@ +--- + +name: Feature request +about: Suggest an idea for this project +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/issue_template.md b/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 00000000..17bf5831 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,24 @@ +*** + +name: Tracking issue +about: Create an issue with bug report or feature request. +title: "" +labels: needs triage +assignees: coderaiser + +*** + +- **Version** (`cloudcmd -v`): +- **Node Version** `node -v`: +- **OS** (`uname -a` on Linux): +- **Browser name/version**: +- **Used Command Line Parameters**: +- **Changed Config**: + +```json +{} +``` + +- [ ] 🎁 **I'm ready to donate on https://opencollective.com/cloudcmd** +- [ ] 🎁 **I'm ready to donate on https://ko-fi.com/coderaiser** +- [ ] 💪 **I'm willing to work on this issue** diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 98b1f1ad..fb62bd82 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -4,6 +4,5 @@ about something, just do as best as you're able. --> - [ ] commit message named according to [Contributing Guide](https://github.com/coderaiser/cloudcmd/blob/master/CONTRIBUTING.md "Contributting Guide") -- [ ] `npm run codestyle` is OK +- [ ] `npm run fix:lint` is OK - [ ] `npm test` is OK - diff --git a/.github/workflows/docker-io.yml b/.github/workflows/docker-io.yml new file mode 100644 index 00000000..8cbeb042 --- /dev/null +++ b/.github/workflows/docker-io.yml @@ -0,0 +1,60 @@ +name: Docker IO +permissions: + contents: write +on: + - push +jobs: + buildx: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - name: Checkout + uses: actions/checkout@v5 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + - name: Use Node.js 24.x + uses: actions/setup-node@v6 + with: + node-version: 24.x + - name: Install Redrun + run: bun i redrun -g --no-save + - name: NPM Install + run: bun i --no-save + - name: Lint + run: redrun lint + - name: Build + id: build + run: | + redrun build + VERSION=$(grep '"version":' package.json -m1 | cut -d\" -f4) + echo "version=$VERSION" >> $GITHUB_OUTPUT + - name: Set up QEMU + uses: docker/setup-qemu-action@v4 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + - name: Login to DockerHub + uses: docker/login-action@v4 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN }} + - name: Login to GitHub Container Registry + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Build and push io-image + uses: docker/build-push-action@v7 + with: + context: . + file: docker/Dockerfile.io + platforms: linux/amd64,linux/arm64 + push: true + tags: | + coderaiser/cloudcmd:io + coderaiser/cloudcmd:${{ steps.build.outputs.version }}-io + ghcr.io/${{ github.repository }}-io + ghcr.io/${{ github.repository }}:${{ steps.build.outputs.version }}-io diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 00000000..5c81d368 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,88 @@ +name: Docker CI +permissions: + contents: write +on: + push: + tags: + - "*" +jobs: + buildx: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - name: Checkout + uses: actions/checkout@v5 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + - name: Use Node.js 22.x + uses: actions/setup-node@v6 + with: + node-version: 22.x + - name: Install Redrun + run: bun i redrun -g --no-save + - name: NPM Install + run: bun i --no-save + - name: Lint + run: redrun lint + - name: Build + id: build + run: | + redrun build + VERSION=$(grep '"version":' package.json -m1 | cut -d\" -f4) + echo "version=$VERSION" >> $GITHUB_OUTPUT + - name: Set up QEMU + uses: docker/setup-qemu-action@v4 + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + - name: Login to DockerHub + uses: docker/login-action@v4 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_TOKEN }} + - name: Login to GitHub Container Registry + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Build and push base-image + uses: docker/build-push-action@v7 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: | + coderaiser/cloudcmd:latest + coderaiser/cloudcmd:${{ steps.build.outputs.version }} + ghcr.io/${{ github.repository }}:latest + ghcr.io/${{ github.repository }}:${{ steps.build.outputs.version }} + - name: Build and push alpine-image + uses: docker/build-push-action@v7 + with: + context: . + file: docker/Dockerfile.alpine + platforms: linux/amd64,linux/arm64 + push: true + tags: | + coderaiser/cloudcmd:alpine + coderaiser/cloudcmd:latest-alpine + coderaiser/cloudcmd:${{ steps.build.outputs.version }}-alpine + ghcr.io/${{ github.repository }}:latest-alpine + ghcr.io/${{ github.repository }}:${{ steps.build.outputs.version }}-alpine + - name: Build and push slim-image + uses: docker/build-push-action@v7 + with: + context: . + file: docker/Dockerfile.slim + platforms: linux/amd64,linux/arm64 + push: true + tags: | + coderaiser/cloudcmd:slim + coderaiser/cloudcmd:latest-slim + coderaiser/cloudcmd:${{ steps.build.outputs.version }}-slim + ghcr.io/${{ github.repository }}-slim + ghcr.io/${{ github.repository }}:${{ steps.build.outputs.version }}-slim diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml new file mode 100644 index 00000000..429e5568 --- /dev/null +++ b/.github/workflows/nodejs.yml @@ -0,0 +1,53 @@ +name: Node CI +on: + - push +permissions: + contents: write +jobs: + build: + runs-on: ubuntu-latest + env: + NAME: cloudcmd + strategy: + matrix: + node-version: + - 22.x + - 24.x + - 26.x + steps: + - uses: actions/checkout@v5 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: latest + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v6 + with: + node-version: ${{ matrix.node-version }} + - name: Install Redrun + run: bun i redrun madrun -g --no-save + - name: Install + run: bun i --no-save + - name: Init Madrun + run: madrun --init + - name: Lint + run: redrun fix:lint + - name: Typos + uses: coderaiser/typos.ai@v1.1.8 + with: + key: ${{ secrets.TYPOS_AI_KEY }} + - name: Commit fixes + uses: EndBug/add-and-commit@v10 + continue-on-error: true + with: + message: "chore: ${{ env.NAME }}: actions: lint ☘️" + - name: Build + run: redrun build + - name: Test + run: redrun test + - name: Coverage + run: redrun coverage coverage:report + - name: Coveralls + uses: coverallsapp/github-action@v2 + continue-on-error: true + with: + github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index c629c5b4..6aa86aa9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,17 @@ -package-lock.json -yarn.lock -yarn-error.log -node_modules -npm-debug.log* -coverage - -modules/execon -modules/emitify +*.swp +*.log +*.lock .nyc_output +.DS_Store +.idea -*.swp +package-lock.json +npm-debug.log* +node_modules +coverage +modules/execon +modules/emitify dist dist-dev - diff --git a/.madrun.js b/.madrun.js new file mode 100644 index 00000000..efa8ce98 --- /dev/null +++ b/.madrun.js @@ -0,0 +1,62 @@ +import {run, cutEnv} from 'madrun'; +import {defineEnv} from 'supertape/env'; + +const testEnv = defineEnv({ + timeout: 7000, + css: true, +}); + +const buildEnv = { + NODE_ENV: 'production', +}; + +export default { + 'start': () => 'node bin/cloudcmd.js', + 'start:dev': async () => await run('start', null, { + NODE_ENV: 'development', + }), + 'build:start': () => run(['build:client', 'start']), + 'build:start:dev': () => run([ + 'build:client:dev', + 'start:dev', + ]), + 'lint:all': () => run('lint:progress'), + 'lint': () => 'redlint fix; putout .', + 'lint:progress': () => run('lint', '-f progress'), + 'watch:lint': () => 'nodemon -w client -w server -w test -w common -w .webpack -x "putout -s"', + 'fresh:lint': () => run('lint', '--fresh'), + 'lint:fresh': () => run('lint', '--fresh'), + 'fix:lint': async () => `putout --fix . && redlint fix`, + 'lint:stream': () => run('lint', '-f stream'), + 'test': () => [testEnv, `tape '{test}/**/*.js' '{bin,client,static,common,server}/**/*.spec.js' -f fail`], + 'test:e2e': () => `tape 'test-e2e/**/*.js'`, + 'test:client': () => `tape 'test/client/**/*.js'`, + 'test:server': () => `tape 'test/**/*.js' 'server/**/*.spec.js' 'common/**/*.spec.js'`, + 'wisdom': async () => await run(['lint:all', 'build', 'test'], null, { + CI: 1, + }), + 'wisdom:type': () => 'bin/release.js', + 'coverage': async () => [testEnv, `c8 ${await cutEnv('test')}`], + 'coverage:report': () => 'c8 report --reporter=lcov', + 'report': () => 'c8 report --reporter=lcov', + '6to5': () => [buildEnv, 'rspack build --config rspack.config.js'], + '6to5:client': () => run('6to5', '--mode production'), + '6to5:client:dev': async () => await run('6to5', '--mode development', { + NODE_ENV: 'development', + }), + 'pre6to5:client': () => 'rimraf dist', + 'pre6to5:client:dev': () => 'rimraf dist-dev', + 'watch:client': () => run('6to5:client', '--watch'), + 'watch:client:dev': () => run('6to5:client:dev', '--watch'), + 'watch:server': () => 'nodemon bin/cloudcmd.js', + 'watch:test': async () => [testEnv, `nodemon -w client -w server -w test -w common -x ${await cutEnv('test')}`], + 'watch:test:client': async () => `nodemon -w client -w test/client -x ${await run('test:client')}`, + 'watch:test:server': async () => `nodemon -w client -w test/client -x ${await run('test:server')}`, + 'watch:coverage': async () => [testEnv, `nodemon -w server -w test -w common -x ${await cutEnv('coverage')}`], + 'watch:fix:lint': async () => `nodemon -w client -w server -w test -w common -x '${await run('fix:lint')}'`, + 'build': async () => run('6to5:*'), + 'build:dev': async () => run('build:client:dev'), + 'build:client': () => run('6to5:client'), + 'build:client:dev': () => run('6to5:client:dev'), + 'heroku-postbuild': () => run('6to5:client'), +}; diff --git a/.npmignore b/.npmignore index e9b75839..b83b5923 100644 --- a/.npmignore +++ b/.npmignore @@ -1,30 +1,29 @@ -.* -*.spec.js -*.fixture.js -manifest.yml -Dockerfile* -docker-compose.yml -test -fixture -coverage -css -html -yarn-error.log -yarn.lock -now.json -cssnano.config.js - -app.json -bower.json -manifest.yml - -bin/release.js - -client - -webpack.config.js - +*.spec.* +*.config.* +*.fixture.js* *.ai *.cdr *.eps +*.log +*.lock +.* + +manifest.yml +docker-compose.yml +now.json +app.json +bower.json +deno.json +bin/release.* +img/logo/cloudcmd-hq.png +webpack.config.js + +docker +test* +fixture +fixture-* +coverage +css +html +client diff --git a/.nycrc.json b/.nycrc.json new file mode 100644 index 00000000..1fe174f3 --- /dev/null +++ b/.nycrc.json @@ -0,0 +1,15 @@ +{ + "checkCoverage": false, + "all": false, + "exclude": [ + "**/*.spec.js", + "**/*.*.js", + "**/*.config.*", + "**/fixture", + "**/test/**" + ], + "branches": 100, + "lines": 100, + "functions": 100, + "statements": 100 +} diff --git a/.putout.json b/.putout.json new file mode 100644 index 00000000..7154775a --- /dev/null +++ b/.putout.json @@ -0,0 +1,60 @@ +{ + "plugins": ["cloudcmd"], + "ignore": [ + "*.md", + "app.json", + "fontello.json", + "html", + "fixture*" + ], + "rules": { + "package-json/add-type": "off" + }, + "match": { + ".filesystem.json": { + "nodejs/rename-file-cjs-to-js": "off" + }, + "base64": { + "types/convert-typeof-to-is-type": "off" + }, + "*.md": { + "nodejs/convert-commonjs-to-esm": "on" + }, + ".webpack": { + "webpack": "on" + }, + "server": { + "nodejs/remove-process-exit": "on" + }, + "server/{server,exit}.js": { + "nodejs/remove-process-exit": "off" + }, + "server/{server,exit,terminal,distribute/log}.{js,mjs}": { + "remove-console": "off" + }, + "client/{client,cloudcmd,load-module}.{js,mjs}": { + "remove-console": "off" + }, + "client": { + "nodejs": "off" + }, + "client/sw": { + "remove-console": "off" + }, + "test/common/cloudfunc.js": { + "remove-console": "off" + }, + "storage.js": { + "promises/remove-useless-async": "off" + }, + "docker.yml": { + "github/set-node-versions": "off" + }, + "vim.js": { + "merge-duplicate-functions": "off" + }, + "common": { + "nodejs/declare": "off" + } + } +} diff --git a/.rspack/css.js b/.rspack/css.js new file mode 100644 index 00000000..10d28250 --- /dev/null +++ b/.rspack/css.js @@ -0,0 +1,38 @@ +import {env} from 'node:process'; +import {rspack} from '@rspack/core'; + +const {CssExtractRspackPlugin} = rspack; +const isDev = env.NODE_ENV === 'development'; + +const plugins = [ + new CssExtractRspackPlugin({ + filename: '[name].css', + }), +]; + +const rules = [{ + test: /\.css$/i, + use: [CssExtractRspackPlugin.loader, { + loader: 'css-loader', + options: { + url: true, + }, + }], +}, { + test: /\.(png|gif|svg|woff|woff2|eot|ttf)$/, + type: 'asset/inline', +}]; + +export default { + mode: isDev ? 'development' : 'production', + plugins, + module: { + rules, + }, + optimization: { + minimize: !isDev, + minimizer: [ + new rspack.LightningCssMinimizerRspackPlugin(), + ], + }, +}; diff --git a/.rspack/html.js b/.rspack/html.js new file mode 100644 index 00000000..e90038ac --- /dev/null +++ b/.rspack/html.js @@ -0,0 +1,36 @@ +import {env} from 'node:process'; +import HtmlWebpackPlugin from 'html-webpack-plugin'; + +const isDev = env.NODE_ENV === 'development'; + +export const plugins = [ + new HtmlWebpackPlugin({ + inject: false, + template: 'html/index.html', + minify: !isDev && getMinifyHtmlOptions(), + }), +]; + +function getMinifyHtmlOptions() { + return { + removeComments: true, + removeCommentsFromCDATA: true, + removeCDATASectionsFromCDATA: true, + collapseWhitespace: true, + collapseBooleanAttributes: true, + removeAttributeQuotes: true, + removeRedundantAttributes: true, + useShortDoctype: true, + removeEmptyAttributes: true, + /* оставляем, поскольку у нас + * в элемент fm генерируеться + * таблица файлов + */ + removeEmptyElements: false, + removeOptionalTags: true, + removeScriptTypeAttributes: true, + removeStyleLinkTypeAttributes: true, + + minifyJS: true, + }; +} diff --git a/.rspack/js.js b/.rspack/js.js new file mode 100644 index 00000000..251d85f6 --- /dev/null +++ b/.rspack/js.js @@ -0,0 +1,173 @@ +import {resolve, sep} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {env} from 'node:process'; +import {rspack} from '@rspack/core'; + +const resolveModule = (a) => fileURLToPath(import.meta.resolve(a)); + +const { + EnvironmentPlugin, + NormalModuleReplacementPlugin, + ProvidePlugin, +} = rspack; + +const modules = './modules'; +const dirModules = './client/modules'; +const dirCss = './css'; +const dirThemes = `${dirCss}/themes`; +const dirColumns = `${dirCss}/columns`; +const dir = './client'; +const {NODE_ENV} = env; +const isDev = NODE_ENV === 'development'; + +const rootDir = new URL('..', import.meta.url).pathname; +const dist = resolve(rootDir, 'dist'); +const distDev = resolve(rootDir, 'dist-dev'); +const devtool = isDev ? 'eval' : 'source-map'; + +const noParse = (a) => a.endsWith('.spec.js'); + +// codegen.macro is a babel-macro (build-time codegen), not supported by +// Rspack's native SWC transform, so client/sw/sw.js (the only file that +// uses it) keeps going through babel-loader. Everything else uses +// Rspack's built-in SWC loader, which is the main source of the speedup. +const rules = [{ + test: /sw\/sw\.js$/, + exclude: /node_modules/, + loader: 'babel-loader', +}, { + test: /\.[mc]?js$/, + exclude: [/node_modules/, /sw\/sw\.js$/], + loader: 'builtin:swc-loader', + options: { + jsc: { + parser: { + syntax: 'ecmascript', + }, + }, + env: { + targets: 'defaults', + }, + }, +}]; + +const plugins = [ + new NormalModuleReplacementPlugin(/^node:/, (resource) => { + resource.request = resource.request.replace(/^node:/, ''); + }), + new NormalModuleReplacementPlugin(/^putout$/, '@putout/bundle'), + new EnvironmentPlugin({ + NODE_ENV, + }), + new ProvidePlugin({ + process: 'process/browser', + }), +]; + +const splitChunks = { + chunks: 'all', + cacheGroups: { + abcCommon: { + name: 'cloudcmd.common', + chunks: (chunk) => { + const lazyChunks = [ + 'sw', + 'nojs', + 'view', + 'edit', + 'terminal', + 'config', + 'user-menu', + 'help', + 'themes/dark', + 'themes/light', + 'columns/name-size', + 'columns/name-size-date', + 'columns/name-size-time', + 'columns/name-size-date-time', + ]; + + return !lazyChunks.includes(chunk.name); + }, + minChunks: 1, + enforce: true, + priority: -1, + reuseExistingChunk: true, + }, + }, +}; + +export default { + resolve: { + symlinks: false, + alias: { + 'node:process': 'process', + 'node:path': 'path', + }, + fallback: { + path: resolveModule('path-browserify'), + process: resolveModule('process/browser'), + util: resolveModule('util'), + }, + }, + devtool, + optimization: { + splitChunks, + }, + entry: { + 'themes/dark': `${dirThemes}/dark.css`, + 'themes/light': `${dirThemes}/light.css`, + 'columns/name-size': `${dirColumns}/name-size.css`, + 'columns/name-size-date': `${dirColumns}/name-size-date.css`, + 'columns/name-size-date-time': `${dirColumns}/name-size-date-time.css`, + 'nojs': `${dirCss}/nojs.css`, + 'help': `${dirCss}/help.css`, + 'view': `${dirCss}/view.css`, + 'config': `${dirCss}/config.css`, + 'terminal': `${dirCss}/terminal.css`, + 'user-menu': `${dirCss}/user-menu.css`, + 'sw': `${dir}/sw/sw.js`, + 'cloudcmd': `${dir}/cloudcmd.js`, + [`${modules}/edit`]: `${dirModules}/edit.js`, + [`${modules}/edit-file`]: `${dirModules}/edit-file.js`, + [`${modules}/edit-file-vim`]: `${dirModules}/edit-file-vim.js`, + [`${modules}/edit-names`]: `${dirModules}/edit-names.js`, + [`${modules}/edit-names-vim`]: `${dirModules}/edit-names-vim.js`, + [`${modules}/menu`]: `${dirModules}/menu/index.js`, + [`${modules}/view`]: `${dirModules}/view/index.js`, + [`${modules}/help`]: `${dirModules}/help.js`, + [`${modules}/markdown`]: `${dirModules}/markdown.js`, + [`${modules}/config`]: `${dirModules}/config/index.js`, + [`${modules}/contact`]: `${dirModules}/contact.js`, + [`${modules}/upload`]: `${dirModules}/upload.js`, + [`${modules}/operation`]: `${dirModules}/operation/index.js`, + [`${modules}/konsole`]: `${dirModules}/konsole.js`, + [`${modules}/terminal`]: `${dirModules}/terminal.js`, + [`${modules}/terminal-run`]: `${dirModules}/terminal-run.js`, + [`${modules}/cloud`]: `${dirModules}/cloud.js`, + [`${modules}/user-menu`]: `${dirModules}/user-menu/index.js`, + [`${modules}/polyfill`]: `${dirModules}/polyfill.js`, + [`${modules}/command-line`]: `${dirModules}/command-line.js`, + }, + output: { + filename: '[name].js', + path: isDev ? distDev : dist, + pathinfo: isDev, + devtoolModuleFilenameTemplate, + publicPath: '/dist/', + }, + module: { + rules, + noParse, + }, + plugins, + performance: { + maxEntrypointSize: 800_000, + maxAssetSize: 600_000, + }, +}; + +function devtoolModuleFilenameTemplate(info) { + const resource = info.absoluteResourcePath.replace(rootDir + sep, ''); + return `file://cloudcmd/${resource}`; +} diff --git a/.stylelintrc.yml b/.stylelintrc.yml deleted file mode 100644 index a94abc6b..00000000 --- a/.stylelintrc.yml +++ /dev/null @@ -1,17 +0,0 @@ -extends: stylelint-config-standard -rules: - indentation: 4 - declaration-block-trailing-semicolon: always - declaration-colon-space-before: null - selector-list-comma-newline-after: null - comment-empty-line-before: null - number-leading-zero: null - number-no-trailing-zeros: null - string-quotes: single - function-url-quotes: never - no-eol-whitespace: null - font-family-name-quotes: always-unless-keyword - font-family-no-missing-generic-family-keyword: null - rule-empty-line-before: null - max-empty-lines: 2 - diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index bd8ec269..00000000 --- a/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -language: node_js -node_js: - - 11 - - 10 - - 8 - -matrix: - allow_failures: - - os: windows - -os: - - linux - - osx - - windows - -script: - - npm run lint && npm run build && npm run coverage && npm run report - -notifications: - email: - on_success: never - on_failure: change - -sudo: required - -services: - - docker - -deploy: - provider: script - script: npm run docker-ci - skip_cleanup: true - on: - node: '8' - condition: $TRAVIS_OS_NAME = linux - tags: true - all_branches: false - diff --git a/.typos.toml b/.typos.toml new file mode 100644 index 00000000..dc8af253 --- /dev/null +++ b/.typos.toml @@ -0,0 +1,2 @@ +[files] +extend-exclude = ["ChangeLog"] diff --git a/.webpack/css.js b/.webpack/css.js deleted file mode 100644 index 398116b1..00000000 --- a/.webpack/css.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const { - basename, - extname, - join, -} = require('path'); - -const {env} = process; -const isDev = env.NODE_ENV === 'development'; - -const ExtractTextPlugin = require('extract-text-webpack-plugin'); -const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'); - -const extractCSS = (a) => new ExtractTextPlugin(`${a}.css`); -const extractMain = extractCSS('[name]'); - -const cssNames = [ - 'nojs', - 'view', - 'config', - 'terminal', - ...getCSSList('columns'), -]; - -const cssPlugins = cssNames.map(extractCSS); -const clean = (a) => a.filter(Boolean); - -const plugins = clean([ - ...cssPlugins, - extractMain, - !isDev && new OptimizeCssAssetsPlugin(), -]); - -const rules = [{ - test: /\.css$/, - exclude: /css\/(nojs|view|config|terminal|columns.*)\.css/, - use: extractMain.extract([ - 'css-loader', - ]), -}, -...cssPlugins.map(extract), { - test: /\.(png|gif|svg|woff|woff2|eot|ttf)$/, - loader: 'url-loader?limit=100000', -}]; - -module.exports = { - plugins, - module: { - rules, - }, -}; - -function getCSSList(dir) { - const base = (a) => basename(a, extname(a)); - const addDir = (name) => `${dir}/${name}`; - const rootDir = join(__dirname, '..'); - - return fs.readdirSync(`${rootDir}/css/${dir}`) - .map(base) - .map(addDir); -} - -function extract(extractPlugin) { - const {filename} = extractPlugin; - - return { - test: RegExp(`css/${filename}`), - use: extractPlugin.extract([ - 'css-loader', - ]) - }; -} - diff --git a/.webpack/html.js b/.webpack/html.js deleted file mode 100644 index 28e40c65..00000000 --- a/.webpack/html.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -const {env} = process; -const isDev = env.NODE_ENV === 'development'; - -const HtmlWebpackPlugin = require('html-webpack-plugin'); - -const plugins = [ - new HtmlWebpackPlugin({ - inject: false, - template: 'html/index.html', - minify: !isDev && getMinifyHtmlOptions(), - }), -]; - -module.exports = { - plugins, -}; - -function getMinifyHtmlOptions() { - return { - removeComments: true, - removeCommentsFromCDATA: true, - removeCDATASectionsFromCDATA: true, - collapseWhitespace: true, - collapseBooleanAttributes: true, - removeAttributeQuotes: true, - removeRedundantAttributes: true, - useShortDoctype: true, - removeEmptyAttributes: true, - /* оставляем, поскольку у нас - * в элемент fm генерируеться - * таблица файлов - */ - removeEmptyElements: false, - removeOptionalTags: true, - removeScriptTypeAttributes: true, - removeStyleLinkTypeAttributes: true, - - minifyJS: true, - }; -} - diff --git a/.webpack/js.js b/.webpack/js.js deleted file mode 100644 index c93f428a..00000000 --- a/.webpack/js.js +++ /dev/null @@ -1,129 +0,0 @@ -'use strict'; - -const { - resolve, - sep, - join, -} = require('path'); - -const { - EnvironmentPlugin, -} = require('webpack'); - -const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin'); - -const dir = './client'; -const dirModules = './client/modules'; -const modules = './modules'; - -const {env} = process; -const isDev = env.NODE_ENV === 'development'; - -const rootDir = join(__dirname, '..'); -const dist = resolve(rootDir, 'dist'); -const distDev = resolve(rootDir, 'dist-dev'); -const devtool = isDev ? 'eval' : 'source-map'; - -const notEmpty = (a) => a; -const clean = (array) => array.filter(notEmpty); - -const noParse = (a) => /\.spec\.js$/.test(a); - -const babelDev = { - babelrc: false, - plugins: [ - 'module:babel-plugin-macros', - '@babel/plugin-proposal-object-rest-spread', - ] -}; - -const rules = clean([ - !isDev && { - test: /\.js$/, - exclude: /node_modules/, - loader: 'babel-loader', - }, - isDev && { - test: /sw\.js$/, - exclude: /node_modules/, - loader: 'babel-loader', - options: babelDev - }]); - -const plugins = [ - new EnvironmentPlugin(['NODE_ENV']), - new ServiceWorkerWebpackPlugin({ - entry: join(__dirname, '..', 'client', 'sw', 'sw.js'), - excludes: ['*'], - }), -]; - -const splitChunks = { - name: 'cloudcmd.common', - chunks: 'all', -}; - -module.exports = { - resolve: { - symlinks: false - }, - devtool, - optimization: { - splitChunks, - }, - entry: { - cloudcmd: `${dir}/cloudcmd.js`, - [modules + '/edit']: `${dirModules}/edit.js`, - [modules + '/edit-file']: `${dirModules}/edit-file.js`, - [modules + '/edit-file-vim']: `${dirModules}/edit-file-vim.js`, - [modules + '/edit-names']: `${dirModules}/edit-names.js`, - [modules + '/edit-names-vim']: `${dirModules}/edit-names-vim.js`, - [modules + '/menu']: `${dirModules}/menu.js`, - [modules + '/view']: `${dirModules}/view.js`, - [modules + '/help']: `${dirModules}/help.js`, - [modules + '/markdown']: `${dirModules}/markdown.js`, - [modules + '/config']: `${dirModules}/config.js`, - [modules + '/contact']: `${dirModules}/contact.js`, - [modules + '/upload']: `${dirModules}/upload.js`, - [modules + '/operation']: `${dirModules}/operation/index.js`, - [modules + '/konsole']: `${dirModules}/konsole.js`, - [modules + '/terminal']: `${dirModules}/terminal.js`, - [modules + '/cloud']: `${dirModules}/cloud.js`, - [modules + '/polyfill']: `${dirModules}/polyfill.js`, - }, - output: { - filename: '[name].js', - path: isDev ? distDev : dist, - pathinfo: isDev, - devtoolModuleFilenameTemplate, - publicPath: '/dist/', - }, - externals: [ - externals - ], - module: { - rules, - noParse, - }, - plugins, -}; - -function externals(context, request, fn) { - if (!isDev) - return fn(); - - const list = [ - 'es6-promise', - ]; - - if (list.includes(request)) - return fn(null, request); - - fn(); -} - -function devtoolModuleFilenameTemplate(info) { - const resource = info.absoluteResourcePath.replace(rootDir + sep, ''); - return `file://cloudcmd/${resource}`; -} - diff --git a/.yaspellerrc b/.yaspellerrc index 582fabab..7e29119e 100644 --- a/.yaspellerrc +++ b/.yaspellerrc @@ -10,6 +10,7 @@ ".md" ], "dictionary":[ + "CloudCmd", "Dev", "Dropbox", "Deepword", @@ -21,18 +22,23 @@ "Iptables", "JitSu", "Node", + "IO", "Olena", "TarZak", "Termux", "Zalitok", "WebSocket", "auth", + "autostart", + "binded", "cd", "cloudcmd", "coderaiser", "com", - "dev", "deepword", + "dev", + "destructuring", + "dropbox", "dword", "edward", "favicon", @@ -40,13 +46,18 @@ "gz", "io", "js", + "linux", "maintainers", + "markdown", "microservice", "minification", "mouseup", "named", "nginx", + "npm", "or io", + "patreon", + "rc", "refactor", "sexualized", "sslPort", @@ -55,6 +66,7 @@ "v0", "v1", "v2", - "yml" + "yml", + "systemd" ] } diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 7e77a3a2..0e2522dd 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -8,19 +8,19 @@ In the interest of fostering an open and welcoming environment, we as contributo Examples of behavior that contributes to creating a positive environment include: -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members Examples of unacceptable behavior by participants include: -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c7c9b914..b6b6b4ef 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,27 +1,30 @@ -Commit ---------------- +## Commit + Format of the commit message: **type(scope) subject** **Type**: -- feature(scope) subject -- fix(scope) subject -- docs(scope) subject -- refactor(scope) subject -- test(scope) subject -- chore(scope) subject + +- feature: scope: subject +- fix: scope: subject +- docs: scope: subject +- refactor: scope: subject +- test: scope: subject +- chore: scope: subject **Scope**: Scope could be anything specifying place of the commit change. For example util, console, view, edit, style etc... **Subject text**: + - use imperative, present tense: “change” not “changed” nor “changes” - don't capitalize first letter - no dot (.) at the end -**Message body**: + **Message body**: - just as in use imperative, present tense: “change” not “changed” nor “changes” - includes motivation for the change and contrasts with previous behavior **Examples**: -- [fix(style) .name{width}: 37% -> 35%](https://github.com/coderaiser/cloudcmd/commit/94b0642e3990c17b3a0ee3efeb75f343e1e7c050) -- [fix(console) dispatch: focus -> mouseup](https://github.com/coderaiser/cloudcmd/commit/f41ec5058d1411e86a881f8e8077e0572e0409ec) + +- [fix: style: .name{width}: 37% -> 35%](https://github.com/coderaiser/cloudcmd/commit/94b0642e3990c17b3a0ee3efeb75f343e1e7c050) +- [fix: console: dispatch: focus -> mouseup](https://github.com/coderaiser/cloudcmd/commit/f41ec5058d1411e86a881f8e8077e0572e0409ec) diff --git a/ChangeLog b/ChangeLog index 435cad4a..c5e0fbca 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,2524 @@ +2026.06.15, v19.19.1 + +feature: +- 78b206e0 client: key: Ctrl + L -> Ctrl + Shift + L: Log out (#466) +- b1492885 docker: io: NPM_CONFIG_PACKAGE_LOCK=false +- 76d7bf4d docker: typos, shellcheck: add + +2026.05.26, v19.19.0 + +feature: +- 4ee38db6 client: view: flac: add support + +2026.05.26, v19.18.1 + +feature: +- 40ecef5e cloudcmd: ratelimit: X-Forwarded-For (#437) + +2026.05.26, v19.18.0 + +fix: +- 161bede8 client: menu: @putout/bundle@5.5. +- 447d990f cloudcmd: server: rest: sendError + +feature: +- 5d9628ce cloudcmd: rate limit: add support (#437) +- 2be395e6 cloudcmd: get rid of manifest: 401 basic auth + +2026.05.17, v19.17.0 + +fix: +- d96f6c46 css: query: hide time on mobile +- e7c55e05 docker: io: XDG_CONFIG_HOME + +feature: +- ae1ca0f8 cloudcmd: cssnano-preset-default v8.0.1 +- 94d5096a style: owner, mode: improve +- 807f8346 cloudcmd: superc8 v12.6.0 +- 67a95722 docker: io: cline: add +- 68eacb91 qword: add +- 4acd294b docker: io: tmux +- 05c80043 cloudcmd: @supertape/loader-css v1.0.0 +- 800a6545 cloudcmd: eslint-plugin-n v18.0.1 +- a985bb36 cloudcmd: supertape v13.0.0 +- 4315ec61 docker: io XDG_CONFIG_HOME: /etc -> /usr/local/etc + +2026.05.03, v19.16.0 + +feature: +- d82d0335 client: vim: rr for rename file +- acfa27cf docker: io: nvchad: add +- 14f009f8 docker: io: bash-completion: add +- c6c60146 docker: io: f4 +- 9a6b8935 docker: io: GOPATH +- a9bc22ce cloudcmd: operation: rm useless checks +- 36bacfe9 cloudcmd: client: key: vim: cc, mm +- 591da25c cloudcmd: ponse v8.0.0 +- 1e1b073c docker: io: /usr/src/cloudcmd -> /usr/local/share/cloudcmd + +2026.04.28, v19.15.0 + +feature: +- 9d97343b cloudcmd: operation: rm useless checks +- 46a88cfa cloudcmd: client: key: vim: cc, mm + +2026.04.28, v19.14.0 + +feature: +- 36a8b641 cloudcmd: ponse v8.0.0 +- 1c263c18 docker: io: /usr/src/cloudcmd -> /usr/local/share/cloudcmd +- ea7b828c docker: io: ubuntu: resolute +- cd6c11ac docker: io: far2l +- c4beeec6 docker: io: gdu: add + +2026.04.21, v19.13.1 + +feature: +- d5cd11e8 cloudcmd: montag v2.0.1 +- dc94d2db docker: io: add latest git version +- 1637beee docker: io: /usr/local/src -> /usr/local/share +- b1bc4e73 Docker: io: pv +- 7c0dca60 docker: io: git: master + +2026.04.15, v19.13.0 + +fix: +- 48693d9e docker: io: XDG_CACHE_HOME + +feature: +- 4b2395c5 cloudcmd: Ctrl + L: logout +- 977a8aaa docker: io: strace: add +- 7d0098fd docker: io: XDG_CACHE_HOME=/tmp/cache +- a89e901b actions: docker: io: add + +2026.04.12, v19.12.5 + +feature: +- 1cfc1a6f docker: io: only amd64 + +2026.04.12, v19.12.4 + +feature: +- 3c2b5658 docker: io: haskell +- d37f8cd3 docker: io: palabra: node + +2026.04.12, v19.12.3 + +feature: +- cb6cabd4 docker: io: PALABRA_DIR + +2026.04.11, v19.12.2 + +feature: +- 2ce11fa2 docker: io: get rid of haskell: to slow install +- aa741232 docker: io: rizin, yara + +2026.04.09, v19.12.1 + +feature: +- 5bd03215 docker: io: add PREFIX + +2026.04.09, v19.12.0 + +feature: +- 13b15b7b docker: io: palabra + +2026.04.07, v19.11.14 + +feature: +- a31beab0 docker: io: rustup env + +2026.04.07, v19.11.13 + +feature: +- 6a08479a docker: io: BUN_INSTALL + +2026.04.06, v19.11.12 + +feature: +- 46c65554 docker: io: npm_config_cache + +2026.04.06, v19.11.11 + +feature: +- ae2ce388 docker: io: $DENO_DIR + +2026.04.06, v19.11.10 + +feature: +- 12ea14ac docker: io: nvm: node + +2026.04.06, v19.11.9 + +feature: +- ea96d13f docker: io: net-tools + +2026.04.06, v19.11.8 + +feature: +- 5c08565f docker: io: debian -> ubuntu + +2026.04.05, v19.11.7 + +feature: +- 36cdef37 docker: io: bookworm + +2026.04.05, v19.11.6 + +feature: +- 845f9bd1 cloudcmd: gritty v10.2.0 + +2026.04.05, v19.11.5 + +feature: +- f9c513cc docker: io: hexyl: add + +2026.04.04, v19.11.4 + +feature: +- e7347d25 docker: io: neovim: apt -> github + +2026.04.04, v19.11.3 + +feature: +- 9970ff76 docker: io: btop +- 4395a471 docker: io: $PATH: add $HOME/.local/bin + +2026.04.04, v19.11.2 + +feature: +- c40ae8e4 docker: io: htop +- f463c5c5 docker: io: aptitude: add +- d1032f09 docker: io: remove unused + +2026.04.04, v19.11.1 + +feature: +- 7787bfc2 cloudcmd: user-menu: runFromCDN + +2026.04.04, v19.11.0 + +feature: +- 32f89d38 cloudcmd: user-menu: root + +2026.04.04, v19.10.2 + +feature: +- df4fb517 cloudcmd: aleman v2.0.1 + +2026.04.03, v19.10.1 + +feature: +- ceb7ef4f docker: io: keep /var/lib/apt/lists + +2026.04.02, v19.10.0 + +fix: +- d12e7bd0 distribute: fix event listener leak on socket disconnect (#462) + +2026.04.02, v19.9.24 + +feature: +- c4d26c6a docker: io: apt-get upgrade +- 9ddb8c29 docker: io: get rid of nix +- e4d7d441 docker: io: nix + +2026.04.01, v19.9.23 + +feature: +- 5a3413ce docker: io: nix + +2026.03.31, v19.9.22 + +feature: +- b4345ed4 docker: io: DENO_DIR + +2026.03.31, v19.9.21 + +fix: +- 5c6a9a95 css: columns: name: 40% -> 35% + +2026.03.30, v19.9.20 + +feature: +- cd0b5554 iocmd: io: nvm + +2026.03.30, v19.9.19 + +feature: +- 6a52b11e docker: io: go, rust + +2026.03.30, v19.9.18 + +feature: +- 738059f2 docker: io: fzf +- 3fc8932f docker: io: less, el_GR + +2026.03.30, v19.9.17 + +feature: +- cf424d6c docker: io: command-not-found update + +2026.03.29, v19.9.16 + +feature: +- 19347a2b docker: io: add command-not-found + +2026.03.29, v19.9.15 + +feature: +- ee170552 docker: io: ubuntu +- e04c4594 docker: io: net-tools: add + +2026.03.29, v19.9.14 + +fix: +- 6c7709be docker: io: PS1 + +2026.03.29, v19.9.13 + +fix: +- 439b3710 bin: currify +- e4182841 docker: io: xterm-256color + +2026.03.29, v19.9.12 + +feature: +- 811a47fd cloudcmd: bin: get rid of require + +2026.03.29, v19.9.11 + +feature: +- 1f95f188 cloudcmd: get rid of simport + +2026.03.29, v19.9.10 + +feature: +- f0deb323 docker: io: add ja_JP.UTF-8 + +2026.03.29, v19.9.9 + +fix: +- f671f798 docker: io: PS1 environment variable in Dockerfile + +feature: +- cc7f9dc7 docker: io: use ubuntu + +2026.03.28, v19.9.8 + +feature: +- 4d1cd8cd docker: io: ffmpeg +- 54b56fdc cloudcmd: vim: ESC: use only to enable, do not use to disable + +2026.03.27, v19.9.7 + +feature: +- 110908e2 docker: io: apt-get + +2026.03.26, v19.9.6 + +feature: +- 6450a2f8 docker: io: add UTF-8 + +2026.03.26, v19.9.5 + +fix: +- e761cacb columns: name-size-date-time: 20% -> 19% + +2026.03.26, v19.9.4 + +feature: +- 69498ed6 docker: io: pull.rebase by default + +2026.03.24, v19.9.3 + +feature: +- 8763788b docker: io: healthcheck + +2026.03.23, v19.9.2 + +feature: +- 09a02074 docker: io: git config: add +- c448eaa4 docker: io: buni + +2026.03.23, v19.9.1 + +fix: +- 6e5318fa client: modules: config: input: quote + +2026.03.23, v19.9.0 + +feature: +- a1216cdd cloudcmd: add ability to hide port configuration + +2026.03.23, v19.8.15 + +feature: +- 68b2aa78 docker: io: cloudcmd_vim + +2026.03.23, v19.8.14 + +fix: +- 665ed9c2 docker: io: get back port + +2026.03.23, v19.8.13 + +feature: +- 618a5615 docker: io: PS1 + +2026.03.23, v19.8.12 + +feature: +- 556b0150 docker: io: PS1 + +2026.03.23, v19.8.11 + +fix: +- 97672ef5 docker: io: apt-get install -> apt-get + +feature: +- 67f27d84 docker: io: bun, deno + +2026.03.23, v19.8.10 + +feature: +- 025b005e docker: io: add PS1 + +2026.03.23, v19.8.9 + +fix: +- b052cf22 cloudcmd: no time available: --.--.---- -> --:--:-- (#461) + +2026.03.23, v19.8.8 + +feature: +- 02dbe56d server: user-menu: when error send it + +2026.03.23, v19.8.7 + +feature: +- ecc76e8b docker: io: renamify-cli, runny, redfork + +2026.03.23, v19.8.6 + +fix: +- 53c072ab @putout/plugin-cloudcmd: devDependencies -> dependnecies + +feature: +- 4b9922bf docker: /usr/src: app -> cloudcmd + +2026.03.23, v19.8.5 + +fix: +- 56fc8b83 docker: gritty + +2026.03.22, v19.8.4 + +feature: +- 5000227e docker: vim nvim + +2026.03.22, v19.8.3 + +fix: +- 01677e6a docker: io: slim -> io + +feature: +- 7e35c606 docker: io: curl wget + +2026.03.22, v19.8.2 + +feature: +- e5b221f7 docker: io: add + +2026.03.22, v19.8.1 + +feature: +- 708a4c6b docker: slim: add +- 80613f46 docker: slim: add + +2026.03.20, v19.8.0 + +fix: +- 59037f2c cloudcmd: bin: --show-config + +feature: +- 10934b3a cloudcmd: add ability to show modification time (#230) + +2026.03.18, v19.7.1 + +feature: +- b0c1d36c cloudcmd: @cloudcmd/fileop v9.0.7 (#460) + +2026.03.17, v19.7.0 + +feature: +- daf83875 cloudfunc: override date format (#459) + +2026.03.17, v19.6.9 + +feature: +- b28a070a cloudcmd: redzip v4.6.1 +- 43c5a011 cloudcmd: css-minimizer-webpack-plugin v8.0.0 +- 15dcae5c cloudcmd: webpack-cli v7.0.2 +- 5976da81 cloudcmd: @cloudcmd/fileop v9.0.5 +- 37cb83f2 cloudcmd: redzip v4.6.0 + +2026.02.27, v19.6.8 + +feature: +- 15fab514 cloudcmd: copymitter v10.3.0 (#458) + +2026.02.26, v19.6.7 + +feature: +- 68c7d0be cloudcmd: onezip v7.0.0 + +2026.02.26, v19.6.6 + +feature: +- 3987cc82 cloudcmd: redzip v4.5.1 (#457) + +2026.02.26, v19.6.5 + +feature: +- 964ae989 cloudcmd: redzip v4.5.0 (#457) + +2026.02.25, v19.6.4 + +feature: +- a66eeda3 cloudcmd: copymitter v10.2.0 (coderaiser/cloudcmd#457) +- 4340533a cloudcmd: c8 v11.0.0 +- 0857711f cloudcmd: redzip v4.2.0 (#457) + +2026.02.24, v19.6.3 + +feature: +- 2234f1b4 cloudcmd: redzip v4.2.0 (#475) + +2026.02.24, v19.6.2 + +feature: +- 321a54dd cloudcmd: @cloudcmd/fileop v9.0.2 (#457) + +2026.02.24, v19.6.1 + +feature: +- 7c5ac408 cloudcmd: @cloudcmd/fileop v9.0.1 (#457) + +2026.02.21, v19.6.0 + +feature: +- 6d19bf2e common: object.omit -> omit + +2026.02.18, v19.5.1 + +feature: +- 6e1cf4ef cloudcmd: supermenu v5.0.0 + +2026.02.18, v19.5.0 + +feature: +- b20539ef common: entity: encode {,} +- 7ef134f4 cloudcmd: rendy v5.0.0 + +2026.02.18, v19.4.1 + +feature: +- 1e18d513 cloudcmd: @cloudcmd/fileop v9.0.0 + +2026.02.18, v19.4.0 + +fix: +- 45cf9baf menu: prefix (#456) + +feature: +- 3e647290 cloudcmd: redlint v6.0.0 +- 800ed012 cloudcmd: putout v42.0.5 +- 525c17d4 cloudcmd: madrun v13.0.0 +- 44247499 cloudcmd: eslint-plugin-putout v31.0.0 + +2026.02.15, v19.3.9 + +feature: +- 9ffe3ef1 cloudcmd: copymitter v10.0.0 (#457) + +2026.02.15, v19.3.8 + +fix: +- d274a2b3 spinner (#456) + +2026.02.13, v19.3.7 + +feature: +- 8fd79a27 cloudcmd: win32 v8.0.0 + +2026.02.12, v19.3.6 + +feature: +- ac94eccd cloudcmd: konsole: named +- 144e4a34 cloudcmd: gritty v10.0.0 +- 938f9e76 cloudcmd: console-io v15.0.1 + +2026.02.08, v19.3.5 + +feature: +- fb40bd9c rm cssnano: has no sense for spinner, option disabled by default (https://svgo.dev/docs/plugins/convertPathData/) +- 76125be9 cloudcmd: eslint v10.0.0 + +2026.02.06, v19.3.4 + +feature: +- 66a08c7f cloudcmd: deepword v11.0.0 + +2026.02.05, v19.3.3 + +feature: +- 4a5a56f4 cloudcmd: dword v16.0.0 + +2026.02.04, v19.3.2 + +fix: +- 99d8435e cloudcmd: exports +- a266c145 cloudcmd: default -> named +- 6e3ba271 Closing X in editor disappeared (#455) + +feature: +- 30f42e94 cloudcmd: restafary v13.0.1 +- f84ce853 cloudcmd: edward v16.0.0 + +2026.02.03, v19.3.1 + +fix: +- 5661bc4f Closing X in editor disappeared (#455) + +2026.02.03, v19.3.0 + +feature: +- 4533a25c cloudcmd: migrate to ESM +- e8a81c49 client: dom: events: migrate to ESM +- 071141bc client: terminal-run: migrate to ESM + +2026.02.03, v19.2.0 + +feature: +- bb32f7c4 client: dom: migrate to ESM +- 457c83db client: migrate to ESM +- f8a941bd client: modules: markdown: migrate to ESM +- 9d6cffaf client: polifyll: migrate to ESM +- 5b704d06 client: edit-names: migrate to ESM +- 2c2ca8eb client: edit-file: migrate to ESM +- c9f57c5f client: modules: edit-file-vim: migrate to ESM +- 327ac9de client: modules: help: migrate to ESM +- dc34ee87 cloudcmd: @putout/plugin-cloudcmd v5.0.0 +- 3cd3695b client: modules: edit-names-vim: migrate to ESM +- dfcbfd63 client: modules: terminal: migrate to ESM + +2026.02.02, v19.1.21 + +feature: +- e3ad330e client: konsole: migrate to ESM +- 983fd9af client: edit: migrate to ESM +- ebabad94 common: entity: migrate to ESM +- c3b71653 client: dom: images -> #images +- 8cad7514 common: cloudfunc -> #common/cloudfunc +- 1f174870 client: view: migrate to ESM +- 7173f6cb cloudcmd: smalltalk v5.0.0 + +2026.01.31, v19.1.20 + +feature: +- c1014c9c client: dom: operations: rename-current: migrate to ESM +- 2e486f8b cloudcmd: restafary v13.0.0 +- 6addb29f cloudcmd: redzip v4.0.0 + +2026.01.30, v19.1.19 + +feature: +- 2a0feac7 cloudcmd: @cloudcmd/modal v4.0.0 + +2026.01.30, v19.1.18 + +feature: +- 73fa4961 client: modules: user-menu: migrate to ESM +- ebfdf8c0 client: modules: operation: migrate to ESM +- ad683171 client: modules: menu: migrate to ESM +- 0054cfa3 client: dom: load-remote: migrate to ESM +- e4d0ece0 client: dom: rest: migrate to ESM +- c704ffe4 client: dom: storage: migrate to ESM +- 5182cb81 client: modules: upload: migrate to ESM +- 9543f1ad client: dom: upload-files: migrate to ESM + +2026.01.29, v19.1.17 + +feature: +- f9c28319 client: dom: migrate to ESM +- 9d2c4e4a client: dom: cmd: move out +- 5a2aa70f client: dom: simplify require +- dee50a85 client: dom: files: migrate to ESM +- 23c0d770 client: dom: dom-tree: migrate to ESM +- cf2c6415 client: directory: migrate to ESM +- 0eb802e7 client: dom: dialog: migrate to ESM + +2026.01.28, v19.1.16 + +fix: +- 4c242631 css: spinner: do not minify svg + +2026.01.28, v19.1.15 + +feature: +- 265c0b49 client: key: vim: migrate to ESM +- 3bc49f02 client: set-current-by-char: migrate to ESM + +2026.01.28, v19.1.14 + +feature: +- f8a63b5a client: key: binder: migrate to ESM +- 2cc97f33 client: cloud: migrate to ESM + +2026.01.27, v19.1.13 + +feature: +- 41b5a96f client: load: migrate to ESM + +2026.01.27, v19.1.12 + +feature: +- 27a52d33 client: sw: migrate to ESM +- 6b049d95 client: sw: register: migrate to ESM + +2026.01.25, v19.1.11 + +feature: +- f849b842 client: listeners: migrate to ESM +- 091f9017 client: listeners: simplify +- 3c1a82e7 client: key: view: get rid of mock-require + +2026.01.25, v19.1.10 + +feature: +- dc5867b0 client: key: vim: get rid of mock-require +- 77b70b21 cloudcmd: aleman v2.0.0 + +2026.01.21, v19.1.9 + +feature: +- 75ad4415 cloudcmd: @putout/eslint-flat v4.0.0 +- c5d9bd7c client: key: vim: get rid of mock-require +- f437a52f client: images: migrate to EMS +- 7192a56e client: dom: current-file: migrate to ESM + +2026.01.20, v19.1.8 + +fix: +- 8a769fd5 client: modules: operation: no update after copy + +feature: +- d574a93d client: key: migrate to ESM +- 3b409074 client: modules: operation: migrate to ESM +- 3b6b0b5a client: buffer: migrate to ESM +- 8876f050 cloudcmd: eslint-plugin-putout v30.0.0 + +2026.01.17, v19.1.7 + +feature: +- 23a6a698 client: dom/events -> #dom/events +- 9cebb241 client: dom: events: migrate to ESM +- a94fa0d4 client: cloudcmd: migrate to ESM +- 3bdf47a5 client: migrate to ESM + +2026.01.16, v19.1.6 + +fix: +- a523ef65 tests + +feature: +- 64654e8d common: cloudfunc: migrate to ESM +- add31607 common: cloudfunc: get rid of bas64 +- e36de00c modulas: migrate to ESM + +2026.01.16, v19.1.5 + +feature: +- 450f1461 client: improve testability +- d979e949 server: env: migrate to ESM + +2026.01.15, v19.1.4 + +feature: +- 6e778a35 client: sort: migrate to ESM +- e27ef51d client: sort: migrate to ESM +- 917f5851 client: load-module: migrate to ESM +- 9950caca client: get-json-from-file-table: migrate to ESM + +2026.01.15, v19.1.3 + +feature: +- f903c5c9 cloudcmd: multi-rename v3.0.0 + +2026.01.14, v19.1.2 + +fix: +- 9e2c5ac6 client: edit-names: group rename not renaming (#453) +- f0dcbe94 client: key: config + +feature: +- 6856207d server: env -> env.parse +- dc99417c client: key: get rid of mock-require +- 4bb7d704 client: modules: view: get rid of mock-require + +2026.01.12, v19.1.1 + +feature: +- 5cc6f79d cloudcmd: @cloudcmd/stub v5.0.0 +- 024bc413 cloudcmd: fullstore v4.0.0 +- 53f6f9e7 cloudcmd: globals v17.0.0 +- 6d21c539 cloudcmd: madrun v12.1.0 +- 253389ea cloudcmd: supertape v12.0.0 + +2025.12.31, v19.1.0 + +feature: +- 0ff16314 cloudcmd: redlint v5.0.0 +- 43edba8c cloudcmd: try-to-catch v4.0.0 +- 06f3b782 cloudcmd: try-catch v4.0.4 +- dfcd6557 deno config: add +- ab20a462 server: bun support (oven-sh/bun#25674) + +2025.12.24, v19.0.17 + +feature: +- 0222d177 cloudcmd: gritty v9.0.0 + +2025.12.05, v19.0.16 + +feature: +- 14ec19e8 cloudcmd: find-up v8.0.0 +- e6a00979 cloudcmd: eslint-plugin-putout v29.0.2 +- 5b5352c7 cloudcmd: putout v41.0.0 + +2025.11.28, v19.0.15 + +feature: +- 00676531 cloudcmd: aleman v1.16.5 + +2025.11.27, v19.0.14 + +fix: +- 2a525e9b aleman: copy paste in text editor (#449) + +feature: +- 3ceb9a8c cloudcmd: open v11.0.0 + +2025.09.26, v19.0.13 + +feature: +- 8477f3e4 cloudcmd: aleman v1.16.3 (#446) + +2025.09.25, v19.0.12 + +feature: +- 836e908e cloudcmd: aleman v1.16.2 + +2025.09.24, v19.0.11 + +feature: +- f4386a6f cloudcmd: aleman v1.16.1 + +2025.09.23, v19.0.10 + +feature: +- 2e667ba6 cloudcmd: aleman v1.15.0 + +2025.09.22, v19.0.9 + +feature: +- 60c56164 cloudcmd: aleman v1.14.4 + +2025.09.20, v19.0.8 + +feature: +- efe81320 cloudcmd: aleman v1.14.3 + +2025.09.18, v19.0.7 + +feature: +- 5b972e2e cloudcmd: aleman v1.14.0 + +2025.09.17, v19.0.6 + +feature: +- 39a24028 cloudcmd: aleman v1.13.0 + +2025.09.16, v19.0.5 + +fix: +- 64df81bc cloudcmd: client: listeners: f9: stopPropagation + +feature: +- 38dd5101 cloudcmd: aleman v1.12.4 + +2025.09.15, v19.0.4 + +feature: +- 66db798c cloudcmd: aleman v1.12.3 + +2025.09.15, v19.0.3 + +feature: +- c5aed16f cloudcmd: aleman v1.12.2 + +2025.09.14, v19.0.2 + +feature: +- 511347d3 cloudcmd: aleman v1.11.0 + +2025.09.14, v19.0.1 + +fix: +- fc6304a1 tmpl: config: aleman, supermenu + +feature: +- a05ecdb4 cloudcmd: aleman v1.10.0 + +2025.09.14, v19.0.0 + +feature: +- 50b19dcc cloudcmd: menu: default: supermenu -> aleman +- 5970f10a cloudcmd: drop support of node < 22 + +2025.09.14, v18.8.11 + +feature: +- b0360d8e cloudcmd: aleman v1.9.1 +- 00a20129 cloudcmd: html: importsmap: add + +2025.09.14, v18.8.10 + +feature: +- ddf9e455 cloudcmd: aleman v1.9.0 + +2025.09.14, v18.8.9 + +feature: +- 2e7bdb8a cloudcmd: aleman v1.8.0 + +2025.09.13, v18.8.8 + +feature: +- 03631d95 cloudcmd: aleman v1.7.0 + +2025.09.12, v18.8.7 + +feature: +- 09408af5 cloudcmd: aleman v1.6.1 + +2025.09.12, v18.8.6 + +feature: +- 4fcaf288 cloudcmd: aleman v1.6.0 + +2025.09.10, v18.8.5 + +feature: +- c69ec16e cloudcmd: aleman v1.5.0 + +2025.09.09, v18.8.4 + +feature: +- 08d13c6d cloudcmd: aleman v1.4.9 + +2025.09.04, v18.8.3 + +feature: +- b4792fc3 cloudcmd: aleman v1.4.0 + +2025.09.04, v18.8.2 + +feature: +- a0b3285b cloudcmd: aleman v1.3.0 + +2025.09.04, v18.8.1 + +feature: +- 15b71c14 cloudcmd: aleman v1.2.5 +- d252fe5f robots.txt: add + +2025.09.02, v18.8.0 + +feature: +- 08b5c6b2 client: menu: aleman: add + +2025.08.30, v18.7.4 + +fix: +- a6d18ddb select file: name -> line +- 2077468a client: listeners: click: avoid select on conext menu +- 64e4aba4 client: menu: before show: unsetBind + +2025.07.26, v18.7.3 + +fix: +- 884c83eb client: polyfill (#442) + +2025.07.24, v18.7.2 + +feature: +- 2e775908 cloudcmd: html-looks-like: remove +- bb6a7a28 docker: npm -> bun + +2025.07.06, v18.7.1 + +fix: +- 784bb2eb build: sw + +feature: +- 8f52376d cloudcmd: revert: optimize-css-assets-webpack-plugin -> css-minimizer-webpack-plugin: broken spinner +- 82008749 cloudcmd: optimize-css-assets-webpack-plugin -> css-minimizer-webpack-plugin + +2025.07.05, v18.7.0 + +fix: +- b1e231a5 client: menu: close: ESC + +feature: +- 546d0610 cloudcmd: process v0.11.10 +- 121b114e cloudcmd: path-browserify v1.0.1 +- 8592cedc cloudcmd: mini-css-extract-plugin v2.9.2 +- a53ab67b cloudcmd: webpack-cli v6.0.1 +- de2cedd9 cloudcmd: webpack v5.99.9 +- da545ea4 cloudcmd: style-loader v4.0.0 +- db6e8334 cloudcmd: optimize-css-assets-webpack-plugin v6.0.1 +- 2f0c1a61 cloudcmd: html-webpack-plugin v5.6.3 +- e100dcf6 cloudcmd: extract-text-webpack-plugin v3.0.2 +- 76c40008 cloudcmd: css-loader v7.1.2 +- fb5e5a32 cloudcmd: clean-css-loader v4.2.1 +- 8551cd54 cloudcmd: babel-loader v10.0.0 +- c9380319 webpack 5 +- ddc94adb cloudcmd: eslint-plugin-putout v28.0.0 + +2025.07.04, v18.6.1 + +feature: +- 9eafa189 cloudcmd: http-auth v4.2.1 +- e99d0847 cloudcmd: montag v1.2.1 +- b77e9c91 cloudcmd: pipe-io v4.0.1 +- 4b476a6d cloudcmd: globals v16.3.0 +- 2057065d cloudcmd: @putout/eslint-flat v3.0.1 + +2025.07.02, v18.6.0 + +feature: +- 2eb3dc66 cloudcmd: @iocmd/wait v2.1.0 +- 1679b788 cloudcmd: webpackbar v7.0.0 +- 9a4cf388 cloudcmd: eslint-plugin-putout v27.2.1 +- f4b0f92f cloudcmd: express v5.1.0 +- 4ab4be12 thread-it: get rid (#438) +- 99ad0c21 cloudcmd: rm @putout/babel +- 8ccec23d cloudcmd: help: require -> import +- 2a97ac66 cloudcmd: yargs-parser v22.0.0 +- b26c8bba cloudcmd: thread-it v3.0.0 + +2025.04.10, v18.5.2 + +feature: +- 8450bfa6 cloudcmd: putout v40.0.3 +- 51f51b54 cloudcmd: @putout/plugin-cloudcmd v4.0.0 +- 08ab63d7 cloudcmd: supertape v11.0.4 +- e7cc9b92 cloudcmd: redlint v4.1.1 +- 368c9bb8 cloudcmd: eslint v9.23.0 +- 43fd5ed6 cloudcmd: madrun v11.0.0 +- f774d5b2 cloudcmd: eslint-plugin-putout v26.1.0 +- b0a7fc16 cloudcmd: putout v39.3.0 + +2025.02.03, v18.5.1 + +feature: +- 467f0a79 cloudcmd: webpack-merge v6.0.1 +- 353a1fb6 cloudcmd: putout v38.0.5 +- 8e98b778 cloudcmd: eslint-plugin-putout v24.0.0 + +2025.01.20, v18.5.0 + +fix: +- ad8e55d8 client: themes -> columns (#434) + +feature: +- 2fc503f7 cloudcmd: @putout/babel v3.0.0 + +2024.12.13, v18.4.1 + +feature: +- 100e940e cloudcmd: putout v37.0.1 + +2024.11.22, v18.4.0 + +fix: +- dff02672 cloudcmd: make manifest.json accessible when authentication is enabled (#428) + +2024.11.14, v18.3.0 + +feature: +- 71dc8dd6 cloudcmd: Add support for Progressive Web App (#426) + +2024.11.06, v18.2.1 + +feature: +- a733d814 css: --is-mobile: add +- f22120dc cloudcmd: prevent unselect being fired on panel click when in mobile view (#422) +- 1a0af863 docker: add image source label to dockerfiles (#421) +- 0446a74d docker: add image source label to dockerfiles (#419) + +2024.10.27, v18.2.0 + +feature: +- ac9abbd3 cloudcmd: eslint-plugin-putout v23.1.0 +- 4bc5a783 cloudcmd: add context menu option to toggle file selection (#420) + +2024.08.17, v18.1.0 + +feature: +- ddf4542b cloudcmd: add ability to hide dot files (#307) + +2024.08.16, v18.0.2 + +feature: +- 3d03efbe css: show links in one small screens + +2024.08.16, v18.0.1 + +fix: +- 62ed8411 bin: validateArgs is not a function (#147) + +feature: +- 9ec94dee cloudcmd: chalk v5.3.0 + +2024.08.16, v18.0.0 + +feature: +- 5e93bcca cloudcmd: rimraf v6.0.1 +- 74d1eb7e drop support of node < 20 + +2024.08.16, v17.4.4 + +fix: +- a6aa9bbc revert rimraf v6.0.1 + +feature: +- 282b3d5c cloudcmd: @putout/cli-validate-args v2.0.0 + +2024.07.27, v17.4.3 + +feature: +- 6e8348b8 cloudcmd: rimraf v6.0.1 +- 61ca7f36 cloudcmd: putout v36.0.2 + +2024.07.03, v17.4.2 + +feature: +- ba2d0b36 cloudcmd: just-snake-case v3.2.0 +- 4cc47e30 cloudcmd: just-capitalize v3.2.0 +- d8451e56 cloudcmd: just-pascal-case v3.2.0 +- 6abf327d cloudcmd: package-json v10.0.0 +- 2ae6ad34 docker: Dockerimage update Debian12 (#414) +- 05ef0ae4 cloudcmd: c8 v10.1.2 + +2024.05.06, v17.4.1 + +feature: +- 154b4bd6 cloudcmd: @cloudcmd/move-files v8.0.0 +- c409a2db cloudcmd: copymitter v9.0.0 + +2024.04.17, v17.4.0 + +fix: +- 6fb21020 server: route: path traversal + +feature: +- 37ab7068 publish container image to GHCR (#409) + +2024.04.03, v17.3.3 + +feature: +- b088b84e cloudcmd: deepword v10.0.0 + +2024.03.29, v17.3.2 + +fix: +- f7a6a366 typo: Wraped -> Wrapped + +2024.03.29, v17.3.1 + +feature: +- d7581829 distribute: convert to ESM + +2024.03.29, v17.3.0 + +feature: +- 6bc4f3ec dark theme: add (#332) +- 35622082 route: convert to ESM + +2024.03.29, v17.2.1 + +fix: +- cc134464 client: vim: space + +feature: +- e3f89e88 dark mode: add +- c45b23fe css: vars: add +- b1f74c00 css: add vars + +2024.03.22, v17.2.0 + +feature: +- 3e565109 convert to ESM +- 770a0812 pack: get rid of mock-require +- 25d8faea rest: get rid of mock-require +- 401a669a user-menu: get rid of mock-require +- 4e32241d terminal: get rid of mock-require + +2024.03.21, v17.1.6 + +feature: +- e01ee457 server: route: get rid of mock-require +- c7f90901 root: get rid of mock-require +- fcce26d4 cloudfunc: get rid of mock-require + +2024.03.20, v17.1.5 + +feature: +- bf90bf22 server: validate: get rid of mock-require + +2024.03.20, v17.1.4 + +feature: +- 98d3a4cc server: columns: get rid of mock-require + +2024.03.18, v17.1.3 + +feature: +- e080a540 server: cloudcmd: get rid of mock-require + +2024.03.18, v17.1.2 + +fix: +- 857c9700 docker: alpine + +feature: +- bf614e1d cloudcmd: redlint v3.13.1 + +2024.03.16, v17.1.1 + +feature: +- a92a5a0d cloudcmd: restbox v4.0.0 +- c51ba1d8 docker: drop arm v7 + +2024.03.16, v17.1.0 + +feature: +- 10d6d2e2 cloudcmd: @types/node-fetch v2.6.11 +- 2047cb7a cloudcmd: @cloudcmd/dropbox v5.0.1 +- 6b793cca cloudcmd: docker: alpine +- 5fa9fcc5 cloudcmd: pullout v5.0.0 +- bc617c17 cloudcmd: serve-once v3.0.1 + +2024.03.12, v17.0.7 + +feature: +- 97627dc2 cloudcmd: auto-globals v4.0.0 +- 683c865e cloudcmd: gritty v8.0.0 + +2024.03.11, v17.0.6 + +fix: +- d928c0b8 cloudcmd: ocker: revert alpine (#406) + +2024.03.11, v17.0.5 + +fix: +- 33201dad cloudcmd: docker: alpine (#406) + +2024.02.02, v17.0.4 + +feature: +- 7ce95450 cloudcmd: deepword v9.0.0 +- 1c73e525 cloudcmd: edward v15.0.0 +- da967f08 cloudcmd: dword v15.0.0 +- f0a6109a cloudcmd: restafary v12.0.0 + +2024.02.01, v17.0.3 + +feature: +- aca4119f cloudcmd: inly v5.0.0 + +2024.02.01, v17.0.2 + +feature: +- 5324a41a cloudcmd: supertape v10.0.0 +- d453a1b2 cloudcmd: onezip v6.0.1 +- 71b915be cloudcmd: @cloudcmd/fileop v8.0.0 + +2024.01.25, v17.0.1 + +feature: +- d79a5776 cloudcmd: putout v35.0.0 +- 8d92aa91 cloudcmd: package-json v9.0.0 +- 5ab5576e cloudcmd: open v10.0.3 +- c5cfe68c cloudcmd: c8 v9.1.0 + +2023.12.12, v17.0.0 + +feature: +- 154e3b07 cloudcmd: find-up v7.0.0 +- a02d288d cloudcmd: @putout/babel v2.0.0 +- 3314f9b9 drop support of node < 18 +- a6afa205 cloudcmd: supertape v9.0.0 +- e600c05d cloudcmd: eslint-plugin-putout v22.0.0 +- 99c00954 cloudcmd: madrun v10.0.0 +- afdf7434 cloudcmd: putout v34.0.7 + +2023.12.08, v16.18.0 + +feature: +- 4462f269 cloudcmd: markdown-it v14.0.0 +- 0cc76bd4 cloudcmd: philip v3.0.0: decrease bundle size +- 656ebd87 client: move out set-current + +2023.12.04, v16.17.9 + +fix: +- fb2d0814 github actions + +2023.12.04, v16.17.8 + +feature: +- 93aa7278 yaspeller: rm +- af9c916e cloudcmd: eslint-plugin-putout v21.0.2 +- 01dccbfd cloudcmd: putout v33.13.3 + +2023.10.12, v16.17.7 + +feature: +- 7857fb72 package: rendy v4.1.3 + +2023.09.22, v16.17.6 + +feature: +- 570cb8c0 package: nodemon v3.0.1 +- 828d10a8 package: rimraf v5.0.1 +- 88908b35 package: eslint-plugin-putout v20.0.0 +- 93f4a07e package: putout v32.0.6 +- a5f93523 github actions: use bun + +2023.09.06, v16.17.5 + +feature: +- 3b0941bc actions: docker/login-action@v2 (#396) + +2023.09.05, v16.17.4 + +feature: +- 35dedfdf github: update docker actions (#396) + +2023.09.05, v16.17.3 + +feature: +- 3c93b29b github: docker/build-push-action v4 (#396) + +2023.09.04, v16.17.2 + +fix: +- 621f52da docker + +2023.09.04, v16.17.1 + +fix: +- eb3f037a docker: bun -> node + +2023.09.04, v16.17.0 + +feature: +- 224e5397 docker: use bun instead of node +- 4b9267f3 package: edward v14.2.0 + +2023.08.10, v16.16.3 + +feature: +- 354c137d package: console-io v14.0.0 + +2023.08.09, v16.16.2 + +feature: +- e353fff7 package: redzip v3.0.0 + +2023.08.07, v16.16.1 + +feature: +- d63169cc package: @putout/babel v1.0.5 +- bb9276be package: eslint-plugin-putout v19.0.3 +- 9aed5f75 package: putout v31.0.3 + +2023.07.09, v16.16.0 + +feature: +- c4f56c59 package: memfs v4.2.0 +- 0e663e1d package: @putout/plugin-cloudcmd v3.1.1 +- ff9265b7 package: c8 v8.0.0 +- 22aa337a package: eslint-plugin-n v16.0.1 +- 13350b55 package: eslint-plugin-putout v18.0.0 +- ce196abf package: putout v30.1.1 + +2023.05.17, v16.15.0 + +feature: +- a1bf40bd package: open v9.1.0 +- ef608853 client: self signed certs on Chrome (#393) + +2023.03.21, v16.14.1 + +feature: +- b336a472 package: eslint-plugin-putout v17.1.0 +- 019e15b8 package: @cloudcmd/fileop v7.0.0 +- 64354300 package: copymitter v8.0.1 +- 27437880 package: @cloudcmd/move-files v7.0.0 + +2023.03.08, v16.14.0 + +feature: +- 6b22b241 package: putout v29.0.3 + +2023.01.30, v16.13.1 + +feature: +- client: add DIR_DIST +- client: DIRCLIENT -> DIR_CLIENT + +2023.01.29, v16.13.0 + +feature: +- client: key: vim: open editor with 'e' +- client: vim: add ability to show terminal with 'tt' + +2023.01.29, v16.12.0 + +feature: +- client: vim: add ability to create directory with 'md', and create file with 'mf' + +2023.01.22, v16.11.0 + +fix: +- lint: eslint-plugin-node -> eslint-plugin-n + +feature: +- user-menu: add support of mov +- client: user-menu: navigate: add support of \D + [JK] to speed up vim navigation + +2023.01.19, v16.10.0 + +fix: +- lint: eslint-plugin-node -> eslint-plugin-n + +feature: +- client: user-menu: navigate: add support of \D + [JK] to speed up vim navigation + +2023.01.18, v16.9.1 + +fix: +- static: user-menu: convert flac to mp3 + +2023.01.17, v16.9.0 + +feature: +- package: scroll-into-view-if-needed v3.0.4 +- package: tar-stream v3.0.0 +- static: user-menu: add recipes from Cookbook + +2023.01.16, v16.8.0 + +feature: +- package: @putout/plugin-cloudcmd v2.0.0: CloudCmd.loadDir() -> CloudCmd.changeDir()' + +2023.01.15, v16.7.0 + +feature: +- package: @cloudcmd/modal v3.0.0: add ability to not set cursor when close the modal +- package: auto-globals v3.0.0 +- package: rimraf v4.0.5 +- user-menu: rm border + +2022.10.20, v16.6.1 + +feature: +- package: package-json v8.1.0 +- package: supertape v8.1.0 +- package: putout v28.0.0 + +2022.10.09, v16.6.0 + +feature: +- package: @cloudcmd/fileop v6.0.0 +- package: @cloudcmd/move-files v6.0.0 +- package: copymitter v7.0.0 + +2022.08.06, v16.5.0 + +feature: +- client: add Command Line +- package: add funding +- (package) gritty v7.0.0 + +2022.07.20, v16.4.1 + +feature: +- (package) eslint-plugin-n v15.2.4 +- (package) putout v27.0.1 +- (package) eslint-plugin-putout v16.0.0 + + +2022.07.11, v16.4.0 + +feature: +- (cloudcmd) env: add ability to pass 0 and 1 + + +2022.07.02, v16.3.1 + +fix: +- (client) cloudcmd: rm window.Emitify + + +2022.07.01, v16.3.0 + +feature: +- (cloudcmd) terminal-run: return -1, when not load + + +2022.06.17, v16.2.0 + +feature: +- (package) markdown-it v13.0.1 +- (cloudcmd) server: convert to ESM +- (package) thread-it v2.0.0 + + +2022.05.12, v16.1.1 + +feature: +- (package) edward v14.0.0 +- (package) putout v26.0.1 + + +2022.04.23, v16.1.0 + +feature: +- (cloudcmd) improve support of NBSP + + +2022.04.22, v16.0.1 + +feature: +- (package) dword v14.0.0 +- (package) restafary v11.0.0 +- (package) @cloudcmd/stub v4.0.1 +- (package) win32 v7.0.0 +- (package) eslint-plugin-putout v14.4.0 + + +2022.02.19, v16.0.0 + +feature: +- (cloudcmd) drop support of node < 16 +- (package) supertape v7.1.0 +- (package) eslint-plugin-putout v13.11.0 +- (package) madrun v9.0.0 +- (package) putout v25.0.1 + +2022.01.20, v15.9.15 + +fix: +- (css) icons (#368) + +2022.01.13, v15.9.14 + +fix: +- (cloudcmd) client: edit-names in vim mode +- (docker) images: make dockerfiles use node:lts-buster and node:lts-buster-slim for alpine (#363) +- (docker) images: make dockerfiles use node:lts-buster-slim as base image (#357) +feature: +- (package) eslint-plugin-putout v13.0.1 +- (package) putout v24.0.2 + +2021.12.23, v15.9.13 + +feature: +- (package) putout v23.0.0 + +2021.12.16, v15.9.12 + +fix: +- (client) loadDir: history enabled by default + +2021.12.09, v15.9.11 + +fix: +- (client) load: Upload stuck for zero byte files (#359) + +2021.12.04, v15.9.10 + +fix: +- (client) operation: move and copy not working (#358) +feature: +- (package) eslint-plugin-putout v12.2.0 + +2021.11.22, v15.9.9 + +feature: +- (package) putout v22.0.2 +- (package) yargs-parser v21.0.0 +- (package) yaspeller v8.0.0 +- (package) eslint-plugin-putout v11.1.0 +- (package) putout v21.1.2 +- (package) eslint v8.0.1 +- (package) eslint-plugin-putout v10.3.0 +- (package) find-up v6.1.0 +- (package) putout v20.5.1 +- (package) supertape v6.9.1 +- (package) eslint-plugin-putout v9.0.1 + +2021.08.09, v15.9.8 + +fix: +- (cloudcmd) args: snake case -> camelCase: yargs strip dashed + + +2021.06.27, v15.9.7 + +fix: +- (config) rm broadcast: cannot change config +- (view) close modals using ESC + +feature: +- (package) package-json v7.0.0 +- (config) add more descriptive titles + + +2021.06.13, v15.9.6 + +feature: +- (package) @cloudcmd/move-files v5.0.0 + + +2021.06.08, v15.9.5 + +fix: +- (load) put: replace #: single -> multiple +- (server) user-menu: e.message -> errorFind.message + +feature: +- (package) eslint-plugin-putout v8.0.1 +- (package) es6-promisify v7.0.0 +- (package) putout v18.0.1 +- (package) putout v17.0.0 + + +2021.04.05, v15.9.4 +feature: +- (package) socket.io-client v4.0.1 +- (package) open v8.0.5 +- (package) putout v16.4.0 + +2021.03.17, v15.9.3 + +fix: +- (cloudcmd) Docker latest-alpine (15.9.2) stopped with errors (#337) + + +2021.03.16, v15.9.2 + +fix: +- (route) unable to navigate between folders (#333) + +feature: +- (package) open v8.0.2 +- (package) socket.io-client v4.0.0 +- (package) socket.io v4.0.0 + + +2021.03.01, v15.9.1 + +feature: +- (cloudcmd) icons: add archive icon for small screens +- (cloudcmd) add archive-link image + + +2021.03.01, v15.9.0 + +feature: +- feature(cloudcmd) add archive icon +- feature(client) rm unused loadCurrentTime +- feature(package) win32 v6.0.0 +- feature(package) redzip v2.0.0 + + + +2021.02.27, v15.8.1 + +feature: +- (package) restafary v9.7.0 (#330) + + +2021.02.23, v15.8.0 + +feature: +- (cloudcmd) add ability to suggest option, when wrong provided +- (package) supertape v5.0.0 + + +2021.02.21, v15.7.1 + +fix: +- (cloudcmd) prefix env has no effect (#328) + + +2021.02.19, v15.7.0 + +fix: +- chore(github-actions) add ability to autofix lint + +feature: +- (package) @cloudcmd/move-files v4.0.0 +- (package) putout v15.0.0 +- (package) copymitter v6.0.0 +- (package) @cloudcmd/olark v3.0.2 +- (client) view: unknown file type: method: GET -> HEAD: speed up + + +2021.02.03, v15.6.0 + +feature: +- (client) view: add ability to detect file type when extension is missing (coderaiser/cloudcmd#287) + + +2021.02.02, v15.5.2 + +fix: +- (client) view: isAudio (#322) + + +2021.01.31, v15.5.1 + +fix: +- (cloudcmd) cannot create a directory (#319) + + +2021.01.30, v15.5.0 + +feature: +- (package) style-loader v2.0.0 +- (cloudcmd) improve error handling when viewing or editing a file +- (package) putout v14.0.0 +- (package) eslint-plugin-putout v7.0.0 + + +2021.01.26, v15.4.4 + +feature: +- (package) win32 v5.1.11 + + +2021.01.25, v15.4.3 + +feature: +- (package) restbox v3.0.0 +- (package) ponse v6.0.0 +- (package) files-io v4.0.0 + + +2021.01.21, v15.4.2 + +feature: +- (package) mellow v3.0.0 +- (route) tokenize -> wraptile + + +2021.01.20, v15.4.1 + +feature: +- (route) redzip -> win32 (#317) + + +2021.01.19, v15.4.0 + +feature: +- (cloudcmd) add abilit to parse markdown inside zip archives + + +2021.01.19, v15.3.4 + +fix: +- (docker) images: change alpine images to be part of master image (#316) +- (dom) bug in Firefox with Imagus extension enabled: change getCurrentName to read from `data-name` instead of `title` (#313) + +feature: +- (package) deepword v8.0.0 +- (package) console-io v13.0.0 +- (package) edward v13.0.0 +- (docker) add support of multi-arch builds (#291) + + +2021.01.18, v15.3.3 + +fix: +- (dom) bug in Firefox with Imagus extension enabled: change getCurrentName to read from `data-name` instead of `title` (#313) +- (client) dom: goToDirectory + + +2021.01.18, v15.3.2 + +fix: +- (client) dom: goToDirectory + + +2021.01.17, v15.3.1 + +fix: +- (view) view html, pdf + +feature: +- (package) dword v13.0.0 +- (modules) socket.io v3.1.0 + + +2021.01.17, v15.3.0 + +feature: +- (client) improve vim support: Esc - toggle vim support in editors +- (client) view: add ability to view raw files using Shift + F3 +- (client) view: show markdown without shift +- (key) add ability to toggle global vim config on the time of session + + +2021.01.16, v15.2.0 + +fix: +- (server) distribute: simplify colors + +feature: +- (cloudcmd) add ability to open html files using F3 +- (cloudcmd) add ability to toggle vim hotkes using Esc +- (package) @cloudcmd/fileop v5.0.0 + + +2021.01.07, v15.1.0 + +feature: +- (cloudcmd) add ability to read zip files like directories (#309) + + +2021.01.05, v15.0.4 + +feature: +- (package) flop v9.0.0 +- (package) restafary v9.0.1 + + +2021.01.05, v15.0.3 + +fix: +- (cloudcmd) validateRoot: import -> simport: forEachKey is not a function (#311) + +feature: +- (package) onezip v5.0.0 +- (package) socket.io v3.0.5 (socketio/socket.io#3720) + + +2020.12.31, v15.0.2 + +fix: +- (cloudcmd) criton: crash when password set (#310) + + +2020.12.30, v15.0.1 + +fix: +- (cloudcmd) css: media query for screen size with width more then 1600 (cloudcmd/console-io#6) +- (cloudcmd) client: build: optional chaining +- (cloudcmd) drop support of node < 14 + +feature: +- (package) putout v13.0.0 + + +2020.12.28, v15.0.0 + +fix: +- (cloudcmd) app, help: remove duplicate keys +- chore(cloudcmd) menu: add lint, :lint, test, coverage +- (cloudcmd) importListen prevent server from start (#295) + +feature: +- (package) auto-globals v2.0.0 +- (cloudcmd) convert to EcmaScriptModules +- (package) supertape v4.1.0 +- (package) supertape v3.10.0 +- (package) babel-plugin-macros v3.0.0 +- (package) putout v12.0.0 +- (package) supertape v3.1.3 +- (package) madrun v8.0.0 +- (package) gritty v6.0.0 +- (package) console-io v12.0.0 +- (package) socket.io-client v3.0.1 +- (package) socket.io v3.0.1 +- (package) putout v11.0.2 +- (package) eslint-plugin-putout v6.0.0 +- (package) markdown-it v12.0.0 +- (package) putout v10.0.0 +- (package) gritty v5.0.0 +- (distribute) import: do not import if env variable set +- (package) drop support of node < 12 +- (package) table v6.0.1 + + +2020.08.21, v14.9.3 + +fix: +- (client) dom: buffer: get, set -> getJson, setJson (#295) + +feature: +- (storage) rm unused removeMatch + + +2020.08.19, v14.9.2 + +fix: +- (cloudcmd) client: edit: json files (#294) + + +2020.08.16, v14.9.1 + +feature: +- (cloudcmd) add IO.createDirectory (https://github.com/coderaiser/putout/commit/b54b5486f438804120df261dafa8e6985201a4eb) + + +2020.08.14, v14.9.0 + +feature: +- (key) vim: add ability to navigate to next and previous using w and b +- (key) vim: add ability to navigate using to first and last file using ^ and $ + + +2020.08.14, v14.8.0 + +feature: +- (cloudcmd) IO.cp -> IO.copy +- (cloudcmd) IO.mv -> IO.move +- (package) find-up v5.0.0 + + +2020.08.11, v14.7.2 + +fix: +- (client) key: F3: search appears + + +2020.08.11, v14.7.1 + +fix: +- (view) init config: copy + + +2020.08.10, v14.7.0 + +fix: +- (client) user menu: click on user menu title +- test(cloudcmd) test/server/prefixer -> server/prefixer + +feature: +- (cloudcmd) rest: add rename +- (rest) mv: improved user errors +- (client) io: promisify -> async +- (package) webpack-merge v5.0.8 +- (package) eslint-plugin-putout v5.0.0 +- (package) putout v9.0.0 +- (package) madrun v7.0.0 + + +2020.05.20, v14.6.0 + +feature: +- (package) markdown-it v11.0.0 +- (cloudcmd) client: add ability to handle existing file while rename (#289) +- (package) supertape v2.0.0 +- (package) @cloudcmd/stub v3.0.0 + + +2020.05.06, v14.5.1 + +fix: +- (docker) alpine + + +2020.05.04, v14.5.0 + +fix: +- (user-menu) choose using Enter + +feature: +- (package) eslint v7.0.0 +- (package) eslint-plugin-putout v4.0.0 +- (package) putout v8.0.0 +- (package) madrun v6.0.0 +- (client) directory: add abily to show progress dialog on upload + + +2020.04.27, v14.4.0 + +feature: +- (user-menu) add ability to run selected items without showing dialog + + +2020.04.13, v14.3.10 + +fix: +- (util) getRegExp: multiple dots +- (cloudcmd) crash on check for update (#286) + +feature: +- (package) yaspeller v7.0.0 + + +2020.04.10, v14.3.9 + +fix: +- (docker) node -> node:lts (#280) +- (env) UPPER_CASE first, and then lower_case (#283) + +feature: +- (cloudcmd) promise -> async + + +2020.04.04, v14.3.8 + +feature: +- (client) ajaxLoad: callback -> promise +- (get-json-from-file-table) mv out from client + + +2020.04.03, v14.3.7 + +fix: +- (client) dom: getCurrentType + +feature: +- (package) chalk v4.0.0 + + +2020.03.31, v14.3.6 + +fix: +- (cloudcmd) directoryStorage + + +2020.03.25, v14.3.5 + +feature: +- (package) fullstore v3.0.0 +- (package) html-webpack-plugin v4.0.1 +- (package) codegen.macro v4.0.0 +- (package) url-loader v4.0.0 + + +2020.03.03, v14.3.4 + +feature: +- (package) readjson v2.0.1 +- (package) tryrequire v3.0.0 +- (package) flop v8.0.0 +- (package) writejson v3.0.0 +- (package) try-to-catch v3.0.0 +- (package) try-catch v3.0.0 + + +2020.02.23, v14.3.3 + +feature: +- (key) vim: split DOM and vim + + +2020.02.21, v14.3.2 + +feature: +- (package) serve-once v2.0.0 +- (package) edward v12.0.0 +- (package) dword v12.0.0 +- (package) ponse v5.0.0 + + +2020.02.21, v14.3.1 + +feature: +- (package) supermenu v4.0.1 +- (package) stylelint-config-standard v20.0.0 +- (package) http-auth v4.1.2 + + +2020.01.29, v14.3.0 + +feature: +- (listeners) improve file select with ctrl + click (#269) +- (docker) add Dockerfile for arm based clients such as rpi (#268) +- (package) @cloudcmd/clipboard v2.0.0 +- (package) stylelint v13.0.0 +- (package) emitify v4.0.1 +- (package) nyc v15.0.0 +- (package) eslint-plugin-node v11.0.0 + + +2019.12.21, v14.2.1 + +feature: +- (package) for-each-key v2.0.0 +- (package) jonny v3.0.0 +- (package) jaguar v6.0.0 +- (package) ponse v4.0.0 +- (package) ponse v3.5.1 +- (package) memfs v3.0.1 +- (package) url-loader v3.0.0 +- (package) nodemon v2.0.1 +- (package) stylelint v12.0.0 + + +2019.11.15, v14.2.0 + +feature: +- (cloudcmd) add CLOUDCMD_PREFIX +- (package) chalk v3.0.0 +- (package) eslint-plugin-putout v3.0.0 +- (package) madrun v5.0.0 +- (package) putout v7.0.0 +- (package) madrun v4.0.0 +- (package) try-to-catch v2.0.0 + + +2019.10.16, v14.1.2 + +fix: +- (madrun) client test command: test:client command (#260) + +feature: +- (package) @cloudcmd/fileop v4.0.0 +- (package) inly v4.0.0 +- (package) onezip v4.0.0 +- (package) open v7.0.0 +- (package) multi-rename v2.0.0 +- (package) shortdate v2.0.0 + + +2019.10.09, v14.1.1 + +feature: +- (package) @cloudcmd/fileop v3.0.0 +- (package) @cloudcmd/move-files v3.0.0 +- (package) copymitter v5.0.0 + + +2019.10.02, v14.1.0 + +feature: +- (view) add support of webm (#256) + + +2019.09.25, v14.0.2 + +fix: +- (client) change directory with enabled dirStorage (#255) + + +2019.09.25, v14.0.1 + +fix: +- (cloudcmd) wrong editor root on multi instance + +feature: +- (package) deepword v7.0.0 +- (cloudcmd) rm now (zeit/micro/issues/377) + + +2019.09.22, v14.0.0 + +feature: +- (operation) show progress bar on first operation (#253) +- (package) pullout v4.0.0 +- (package) console-io v11.0.0 +- (package) flop v7.0.0 +- (package) restbox v2.0.0 +- (package) restafary v8.0.0 +- (package) nomine v4.0.0 +- (cloudcmd) drop support of node < 10 +- (cloudcmd) remove --progress option, make always enabled + + +2019.09.21, v13.4.2 + +fix: +- (terminal) on -> onKey + + +2019.09.20, v13.4.1 + +feature: +- (package) @cloudcmd/olark v3.0.0 +- (package) format-io v2.0.0 +- (package) limier v3.0.0 +- (package) currify v4.0.0 +- (package) limier v2.0.1 +- (package) load.js v3.0.0 +- (package) @cloudcmd/create-element v2.0.0 +- (package) supermenu v3.0.0 +- (package) smalltalk v4.0.0 +- (package) @cloudcmd/modal v2.0.0 +- (package) putout v6.0.0 +- (package) stylelint-config-standard v19.0.0 +- (package) stylelint v11.0.0 +- (package) markdown-it v10.0.0 +- (package) rm version-io +- (package) fullstore v2.0.2 +- (package) wraptile v3.0.0 +- (package) rendy v3.0.0 +- (package) eslint-plugin-node v10.0.0 +- (package) restafary v7.0.0 + + +2019.09.03, v13.4.0 + +feature: +- (view) add support of pdf +- (package) madrun v3.0.1 + + +2019.08.28, v13.3.0 + +fix: +- feature(client) remove legacy suffix, use modules as is +- (client) rm additional dialog +- (user-menu) putout path +- (edit-names) hide +- (vim) find + +feature: +- (cloudcmd) decrease bundle size: disable convertion to es5 +- (client) remove legacy suffix, use modules as is +- (package) es6-promisify v6.0.2 +- (menu) rm mute: has no sense with new ponse headers +- (markdown) move out parse to worker + + +2019.08.22, v13.2.1 + +fix: +- (buffer) copy, cut +- (key) chrome event double pass +- (user-menu) processing menu item run error + +feature: +- (user-menu) rm path + + +2019.08.20, v13.2.0 + +fix: +- (menu) autoplay on download in firefox +- (dom) getCurrentData + +feature: +- (user-menu) improve error handling +- (package) eslint-plugin-putout v2.0.0 + + +2019.08.16, v13.1.0 + +fix: +- (user-menu) hide load on error +- (key) keys block + +feature: +- (cloudcmd) add ability to remember position of current file on reload +- (madrun) disable web workers, while testing +- (user-menu) speed up user menu parsing with help of worker threads +- (user-menu) add ability to used EcmaScript Modules, improve error handling +- (server) add compress: speed up client side load + + +2019.08.14, v13.0.1 + +fix: +- (cloudcmd) rm --user-menu: always enabled + +feature: +- (package) rimraf v3.0.0 + + +2019.08.14, v13.0.0 + +fix: +- (set-listeners) can not continue first error operation error +- (view) getMediaElement: play video/audio + +feature: +- (cloudcmd) only user menu on f2 +- (cloudcmd) remove plugins +- (package) putout v5.2.1 +- (package) style-loader v1.0.0 + + +2019.08.02, v12.6.3 + +fix: +- (operation) first copy after startup fails (close #251) +- (key) chrome keydown event double pass +- (client) load +- (cloudcmd) server start when importListen enabled + +feature: +- (cloudcmd) simplify lint +- (package) markdown-it v9.0.0 +- (package) deepmerge v4.0.0 +- (package) yaspeller v6.0.0 +- (package) css-loader v3.0.0 +- (babel) remove unused @babel/plugin-syntax-dynamic-import +- (cloudcmd) rm Promise polyfill +- (package) rm Object.assign polyfill + + +2019.06.06, v12.6.2 + +fix: +- (cloudcmd) config: save -> write (#247) + +feature: +- (package) remove file-loader +- (package) url-loader v2.0.0 + + +2019.06.04, v12.6.1 + +fix: +- (config) configManager: totally move away from singletone + + +2019.05.31, v12.6.0 + +feature: +- (config-manager) add (#208) +- (package) add support of cwd in TerminalRun with help of gritty v4.7.0 +- (user-menu) add ability to ignore private methods + + +2019.05.28, v12.5.0 + +feature: +- (user-menu) add Compare Directories (#220) + + +2019.05.27, v12.4.0 + +fix: +- (terminal-run) resolve before close + +feature: +- (terminal-run) add ability to resolve exit code + + +2019.05.24, v12.3.2 + +fix: +- (user-menu) F1 and F keys overlapping +- (select-by-pattern) crash + + +2019.05.24, v12.3.1 + +fix: +- (cloudcmd) copy + + +2019.05.24, v12.3.0 + +fix: +- (user-menu) prefix (#244) +- (dom) renameCurrent: try-to-promise RESTful.mv + +feature: +- (user-menu) hide scroll when small amount of items +- (user-menu) add ability to run in mobile devices +- (upload) improve style +- (user-menu) imrove error output +- (user-menu) add default user menu +- (dialog) cancel -> tryToCatch +- (user-menu) add default option: create user menu +- (user-menu) add error handling +- (user-menu) add ability to navigate with j, k +- (cloudcmd) deprecate plugins + + +2019.05.13, v12.2.0 + +fix: +- feature(npmignore) add fixture.json +- (operation) set-listeners: alert: noCancel -> cancel +- (cloudcmd) different title + +feature: +- (key) add ability to rename file with Shift + F6 +- (user-menu) add (#221) +- (package) clean-css-loader v2.0.0 +- (package) edward v11.0.0 +- (npmignore) add fixture.json +- (package) dword v11.0.0 +- (package) smalltalk v3.4.0 +- (package) eslint v6.0.0-alpha +- (package) eslint-plugin-node v9.0.1 +- (config) speed up load: series -> parallel +- (cloudcmd) avoid service worker reoload scripts in dev mode +- (package) putout v4.23.0 +- (package) nyc v14.0.0 + + +2019.04.15, v12.1.0 + +fix: +- (heroku) app: add "}" (#236) + +feature: +- (edit-names) add bulk rename (#231) +- (package) stylelint v10.0.0 + + +2019.04.04, v12.0.2 + +fix: +- (listeners) any touch open file (#235) + + +2019.04.04, v12.0.1 + +fix: +- (listeners) unable to navigate into folders (#235) + + +2019.04.01, v12.0.0 + +fix: +- feature(cloudcmd) split prefix and prefixSocket finally + +feature: +- (cloudcmd) drop support of beautify, minify +- (cloudcmd) improved progress of file operations +- (cloudcmd) split prefix and prefixSocket finally +- (cloudcmd) view file on double click or enter +- (cloudcmd) add ability to change directory using F3 + + +2019.03.27, v11.8.6 + +fix: +- (operation) progress +- (terminal) rm IntersectionObserver handling (xtermjs/xterm.js#1929) + +feature: +- (package) opn -> open v6.0.0 +- (package) remove @babel/plugin-proposal-object-rest-spread + + +2019.02.20, v11.8.5 + +fix: +- (plugins) set content-type (#230) + +feature: +- (package) putout v4.0.0 +- (package) madrun v2.0.0 + + +2019.02.15, v11.8.4 + +fix: +- (terminal) chrome does not display anything on first open (#214) +- (rest) can not read ###files (#223) +- (help) add --terminal-auto-restart +- (cloudcmd) read root from custom config (#224) +- refactor(view) viewImage: href, prefixURL -> prefixURL +- docs(help) improve English translation of HELP.md (#211) + +feature: +- (package) tar-stream v2.0.0 +- (package) redrun -> madrun +- (package) unionfs v4.0.0 +- (package) package-json v6.0.0 +- (package) add @putout/eslint-config +- (package) tape -> supertape +- (package) add putout +- (package) add eslint-plugin-tape +- (package) file-loader v3.0.1 +- (package) css-loader v2.0.1 +- (package) kebabToCamelCase -> just-pascal-case +- (package) deepmerge v3.0.0 + + +2018.12.04, v11.8.3 + +fix: +- test(export) defaultConfig: prefix +- (edit) prefix (#207) +- feature(package) :lint: add eslint-remove-line + +feature: +- (modules) socket.io v2.2.0 +- (package) clear-module -> mock-require +- (package) auto-globals v1.7.0 +- (package) fix:lint: add eslint-remove-line +- (cloudcmd) sinon, sinon-called-with-diff -> @cloudcmd/stub + + +2018.11.22, v11.8.2 + +fix: +- (Dockerfile) WORKDIR (#182) + + +2018.11.14, v11.8.1 + +fix: +- (validate) corruption of config when root not found + +feature: +- (package) pullout v3.0.0 +- (validate) root: do not validate dropbox root + + +2018.11.09, v11.8.0 + +fix: +- (dialog) noFiles: reject on close + +feature: +- (package) add dropbox support +- (server) add graceful shutdown +- (package) sinon-called-with-diff v3.0.0 + + +2018.11.01, v11.7.1 + +fix: +- (cloudcmd) register service worker on http connection (#203) +- refactor(cloudcmd) PREFIX -> prefix +- docs(help) example: prefix -> express mount point + +feature: +- (package) criton v2.0.0 +- (package) eslint-plugin-node v8.0.0 + + 2018.10.25, v11.7.0 fix: @@ -4245,7 +6766,7 @@ fix: - (rest) onDelete: func(null, body) -> func - (rest) onStat: add var - (cloudcmd) change index path -- (server) start: url -> URL +- (server) start: url -> PREFIX - (server) start: SSLPort -> sslPort - (server) start: Port -> port - (dom) getCurrentDirPath: "," -> ";" @@ -5257,7 +7778,7 @@ with clicks on files. - Removed allowed from cache property in config. - Added ability to hide "Upload To" menu item if -no storage modules setted up in modules.json. +no storage modules set up in modules.json. - From now any file minifying only if last modified time was changed. @@ -5463,7 +7984,7 @@ in any position in anyLoadOnLoad function. - Added chainable to Cache object in DOM. - Changed default ip to null so IP would be geted from -config.json only if it setted up. +config.json only if it set up. - Fixed bug with starting node from other then projects dir. @@ -5772,7 +8293,7 @@ time was possible. - Fixed bug with undefined size on root directory of Cloud Commander. Now Cloud Commander writes size 0, if can't get size, and besides will -setted b char: "0b". +set b char: "0b". - Added supporting of Russian language in directory names. diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index fded2cdf..00000000 --- a/Dockerfile +++ /dev/null @@ -1,25 +0,0 @@ -FROM node:10 -MAINTAINER Coderaiser - -RUN mkdir -p /usr/src/app -WORKDIR /usr/src/app - -COPY package.json /usr/src/app/ - -RUN npm config set package-lock false && \ - npm install --production && \ - npm i gritty && \ - npm cache clean --force - -COPY . /usr/src/app - -WORKDIR /root - -ENV cloudcmd_terminal true -ENV cloudcmd_terminal_path gritty -ENV cloudcmd_open false - -EXPOSE 8000 - -ENTRYPOINT ["/usr/src/app/bin/cloudcmd.js"] - diff --git a/Dockerfile.alpine b/Dockerfile.alpine deleted file mode 100644 index c77b9e1e..00000000 --- a/Dockerfile.alpine +++ /dev/null @@ -1,29 +0,0 @@ -FROM node:alpine -MAINTAINER Coderaiser - -RUN mkdir -p /usr/src/app -WORKDIR /usr/src/app - -COPY package.json /usr/src/app/ - -RUN npm config set package-lock false && \ - npm install --production && \ - apk update && \ - apk add --no-cache bash make g++ python && \ - npm i gritty && \ - npm cache clean --force && \ - apk del make g++ python && \ - rm -rf /usr/include /tmp/* /var/cache/apk/* - -COPY . /usr/src/app - -WORKDIR /root - -ENV cloudcmd_terminal true -ENV cloudcmd_terminal_path gritty -ENV cloudcmd_open false - -EXPOSE 8000 - -ENTRYPOINT ["/usr/src/app/bin/cloudcmd.js"] - diff --git a/HELP.md b/HELP.md index dd07c75b..2967f0d0 100644 --- a/HELP.md +++ b/HELP.md @@ -1,267 +1,282 @@ -# Cloud Commander v11.7.0 +# Cloud Commander v19.19.1 -### [Main][MainURL] [Blog][BlogURL] Live(![Heroku][Heroku_LIVE_IMG] [Heroku][HerokuURL], ![Now][NOW_LIVE_IMG] [Now][NowURL]) +### [Main][MainURL] [Blog][BlogURL] [Demo][DemoURL] [Deploy](#deploy) -[MainURL]: http://cloudcmd.io "Main" -[BlogURL]: http://blog.cloudcmd.io "Blog" -[HerokuURL]: https://cloudcmd.herokuapp.com/ "Heroku" -[NowURL]: https://cloudcmd.now.sh/ "Now" -[HEROKU_LIVE_IMG]: https://status.cloudcmd.io/host/cloudcmd.herokuapp.com/img/txt.png "Heroku" -[NOW_LIVE_IMG]: https://status.cloudcmd.io/host/cloudcmd.now.sh/img/txt.png "Now" +[MainURL]: https://cloudcmd.io "Main" +[BlogURL]: https://blog.cloudcmd.io "Blog" +[SupportURL]: https://patreon.com/coderaiser "Patreon" +[DemoURL]: https://cloudcmd-zdp6.onrender.com/ +[DWORD]: https://github.com/cloudcmd/dword "Editor based on CodeMirror" +[EDWARD]: https://github.com/cloudcmd/edward "Editor based on Ace" +[DEEPWORD]: https://github.com/cloudcmd/deepword "Editor based on Monaco" +[QWORD]: https://github.com/cloudcmd/qword "Editor based on CodeMirror 6" +[EDWARD_KEYS]: https://github.com/cloudcmd/edward/#hot-keys "Edward Hot keys" +[TERMUX]: https://termux.com "Termux" +[INLY]: https://github.com/coderaiser/node-inly "Extract archive" -[DWORD]: https://github.com/cloudcmd/dword "Editor based on CodeMirror" -[EDWARD]: https://github.com/cloudcmd/edward "Editor based on Ace" -[DEEPWORD]: https://github.com/cloudcmd/deepword "Editor based on Monaco" -[EDWARD_KEYS]: https://github.com/cloudcmd/edward/#hot-keys "Edward Hot keys" -[TERMUX]: https://termux.com "Termux" -[INLY]: https://github.com/coderaiser/node-inly "Extract archive" +[DeployInstaPodsIMG]: https://img.shields.io/badge/deploy%20on-InstaPods-blue +[DeployInstaPodsURL]: https://app.instapods.com/dashboard/pods/create?app=cloudcmd&ref=cloudcmd -**Cloud Commander** a file manager for the web with console and editor. - Will help you manage the server and work with files, directories and programs in browser from any computer, mobile or tablet. +**Cloud Commander** is a file manager for the web. It includes a command-line console and a text editor. Cloud Commander helps you manage your server and work with files, directories and programs in a web browser from any computer, mobile or tablet. -![Cloud Commander](/img/logo/cloudcmd.png "Cloud Commander") +![Cloud Commander](https://cloudcmd.io/img/logo/cloudcmd.png "Cloud Commander") -Benefits ---------------- +## Benefits -- Open Source (**MIT License**). +- Open source (**MIT License**). - Has 2 classic panels. - Optional **authorization**. -- Client works in web browser. +- Client works in a web browser. - Server works on **Windows**, **Linux**, **Mac OS** and **Android** (with help of [Termux][TERMUX]). -- Could be used local or remotely. -- Adapting to screen size. -- **3 built-in editors** with support of **syntax highlighting**: [Dword][DWORD], [Edward][EDWARD] and [Deepword][DEEPWORD]. -- [Console](https://github.com/cloudcmd/console "Console") with support of default OS command line. +- Can be used local or remotely. +- Adapts to screen size. +- **3 built-in editors** with support of **syntax highlighting**: [Dword][DWORD], [Edward][EDWARD] [Deepword][DEEPWORD] and [Qword][QWORD]. +- [Console](https://github.com/cloudcmd/console "Console") with support of the default OS command line. - Written in **JavaScript/Node.js**. - Built-in archives pack: **zip** and **tar.gz**. - Built-in archives extract: **zip**, **tar**, **gz**, **bz2**, **.tar.gz** and **.tar.bz2** (with help of [inly][INLY]). -Install ---------------- +## Installation -The installation of file manager is very simple. +Installation is very simple: -- install latest version of [node.js](https://nodejs.org/ "node.js"). -- install `cloudcmd` via `npm` with: +- Install the latest version of [node.js](https://nodejs.org/ "node.js"). +- Install `cloudcmd` via `npm` with: ```sh npm i cloudcmd -g ``` -When in trouble use: +When in trouble, use: ```sh npm i cloudcmd -g --force ``` -Start ---------------- -For starting just type in console: +## Usage + +To start the server, just run the global *npm* binary from your terminal: ```sh cloudcmd ``` -Cloud Commander supports command line parameters: +Cloud Commander supports the following command-line parameters: -|Parameter |Operation -|:------------------------------|:------------------------------ -| `-h, --help` | display help and exit -| `-v, --version` | display version and exit -| `-s, --save` | save configuration -| `-o, --online` | load scripts from remote servers -| `-a, --auth` | enable authorization -| `-u, --username` | set username -| `-p, --password` | set password -| `-c, --config` | configuration file path -| `--show-config` | show config values -| `--show-file-name` | show file name in view and edit -| `--editor` | set editor: "dword", "edward" or "deepword" -| `--packer` | set packer: "tar" or "zip" -| `--root` | set root directory -| `--prefix` | set url prefix -| `--prefix-socket` | set prefix for url connection -| `--port` | set port number -| `--progress` | show progress of file operations -| `--confirm-copy` | confirm copy -| `--confirm-move` | confirm move -| `--open` | open web browser when server started -| `--name` | set tab name in web browser -| `--one-file-panel` | show one file panel -| `--keys-panel` | show keys panel -| `--contact` | enable contact -| `--config-dialog` | enable config dialog -| `--config-auth` | enable auth change in config dialog -| `--console` | enable console -| `--sync-console-path` | sync console path -| `--terminal` | enable terminal -| `--terminal-path` | set terminal path -| `--terminal-command` | set command to run in terminal (shell by default) -| `--terminal-auto-restart` | restart command on exit -| `--vim` | enable vim hot keys -| `--columns` | set visible columns -| `--export` | enable export of config through a server -| `--export-token` | authorization token used by export server -| `--import` | enable import of config -| `--import-token` | authorization token used to connect to export server -| `--import-url` | url of an import server -| `--import-listen` | enable listen on config updates from import server -| `--log` | enable logging -| `--no-show-config` | do not show config values -| `--no-server` | do not start server -| `--no-auth` | disable authorization -| `--no-online` | load scripts from local server -| `--no-open` | do not open web browser when server started -| `--no-name` | set default tab name in web browser -| `--no-keys-panel` | hide keys panel -| `--no-one-file-panel` | show two file panels -| `--no-progress` | do not show progress of file operations -| `--no-confirm-copy` | do not confirm copy -| `--no-confirm-move` | do not confirm move -| `--no-config-dialog` | disable config dialog -| `--no-config-auth` | disable auth change in config dialog -| `--no-console` | disable console -| `--no-sync-console-path` | do not sync console path -| `--no-contact` | disable contact -| `--no-terminal` | disable terminal -| `--no-terminal-command` | set default shell to run in terminal -| `--no-terminal-auto-restart` | do not restart command on exit -| `--no-vim` | disable vim hot keys -| `--no-columns` | set default visible columns -| `--no-export` | disable export config through a server -| `--no-import` | disable import of config -| `--no-import-listen` | disable listen on config updates from import server -| `--no-log` | disable logging -| `--no-show-file-name` | do not show file name in view and edit +| Parameter |Operation +|:-----------------------------|:------------------------------ +| `-h, --help` | display help and exit +| `-v, --version` | display version and exit +| `-s, --save` | save configuration +| `-o, --online` | load scripts from remote servers +| `-a, --auth` | enable authorization +| `-u, --username` | set username +| `-p, --password` | set password +| `-c, --config` | configuration file path +| `--show-config` | show config values +| `--show-dot-files` | show dot files +| `--show-file-name` | show file name in view and edit +| `--editor` | set editor: "dword", "edward" or "deepword" +| `--packer` | set packer: "tar" or "zip" +| `--root` | set root directory +| `--prefix` | set url prefix +| `--prefix-socket` | set prefix for url connection +| `--port` | set port number +| `--confirm-copy` | confirm copy +| `--confirm-move` | confirm move +| `--open` | open web browser when server starts +| `--name` | set tab name in web browser +| `--menu` | set menu: "supermenu" or "aleman" +| `--one-file-panel` | show one file panel +| `--keys-panel` | show keys panel +| `--contact` | enable contact +| `--config-dialog` | enable config dialog +| `--config-auth` | enable auth change in config dialog +| `--config-port` | enable port change in config dialog +| `--console` | enable console +| `--sync-console-path` | sync console path +| `--terminal` | enable terminal +| `--terminal-path` | set terminal path +| `--terminal-command` | set command to run in terminal (shell by default) +| `--terminal-auto-restart` | restart command on exit +| `--vim` | enable vim hot keys +| `--columns` | set visible columns +| `--theme` | set theme 'light' or 'dark'" +| `--export` | enable export of config through a server +| `--export-token` | authorization token used by export server +| `--import` | enable import of config +| `--import-token` | authorization token used to connect to export server +| `--import-url` | url of an import server +| `--import-listen` | enable listen on config updates from import server +| `--dropbox` | enable dropbox integration +| `--dropbox-token` | set dropbox token +| `--log` | enable logging +| `--no-show-config` | do not show config values +| `--no-server` | do not start server +| `--no-auth` | disable authorization +| `--no-online` | load scripts from local server +| `--no-open` | do not open web browser when server started +| `--no-name` | set default tab name in web browser +| `--no-keys-panel` | hide keys panel +| `--no-one-file-panel` | show two file panels +| `--no-confirm-copy` | do not confirm copy +| `--no-confirm-move` | do not confirm move +| `--no-config-dialog` | disable config dialog +| `--no-config-auth` | disable auth change in config dialog +| `--no-config-port` | disable port change in config dialog +| `--no-console` | disable console +| `--no-sync-console-path` | do not sync console path +| `--no-contact` | disable contact +| `--no-terminal` | disable terminal +| `--no-terminal-command` | set default shell to run in terminal +| `--no-terminal-auto-restart` | do not restart command on exit +| `--no-vim` | disable vim hot keys +| `--no-themes` | set default visible themes +| `--no-export` | disable export config through a server +| `--no-import` | disable import of config +| `--no-import-listen` | disable listen on config updates from import server +| `--no-show-file-name` | do not show file name in view and edit +| `--no-dropbox` | disable dropbox integration +| `--no-dropbox-token` | unset dropbox token +| `--no-log` | disable logging -If no parameters given Cloud Commander reads information from `~/.cloudcmd.json` and use -port from it (`8000` default). if port variables `PORT` isn't exist. +For options not specified by command-line parameters, Cloud Commander then reads configuration data from `~/.cloudcmd.json`. It uses port `8000` by default. -To begin use, type in address bar of your browser: +To begin using the web client, go to this PREFIX in your browser: ``` http://localhost:8000 ``` -Update ---------------- -If you installed Cloud Commander with `npm`, stop application and -re-install it: +## Updating the app + +If you installed Cloud Commander with `npm`, stop the server. Then, reinstall it with: ```sh npm install cloudcmd -g ``` -Then start it again and reload the page. +Then, start the server again with `cloudcmd` and reload the page. -Hot keys ---------------- +## Hot keys -|Key |Operation -|:----------------------|:-------------------------------------------- -| `F1` | help -| `F2` | rename -| `F3` | view -| `Shift + F3` | view as `markdown` -| `F4` | edit -| `Shift + F4` | edit in `vim` mode -| `F5` | copy -| `Alt` + `F5` | pack -| `F6` | rename/move -| `F7` | new directory -| `Shift + F7` | new file -| `F8`, `Delete` | remove -| `Shift + Delete` | remove without prompt -| `F9` | menu -| `Alt` + `F9` | extract -| `F10` | config -| `*` | select/unselect all -| `+` | expand selection -| `-` | shrink selection -| `Ctrl + x` | cut to buffer -| `Ctrl + с` | copy to buffer -| `Ctrl + v` | paste from buffer -| `Ctrl + z` | clear buffer -| `Ctrl + p` | copy path -| `Ctrl + r` | refresh -| `Ctrl + d` | clear local storage -| `Ctrl + a` | select all files in a panel -| `Ctrl + m` | rename selected files in editor -| `Shift + Ctrl + m` | rename selected files in vim mode of editor -| `Ctrl + u` | swap panels -| `Ctrl + F3` | sort by name -| `Ctrl + F5` | sort by date -| `Ctrl + F6` | sort by size -| `Up`, `Down`, `Enter` | file system navigation -| `Alt + Left/Right` | show content of directory under cursor in target panel -| `Alt + g` | go to directory -| `Ctrl + \` | go to the root directory -| `Tab` | move via panels -| `Page Up` | up on one page -| `Page Down` | down on one page -| `Home` | to begin of list -| `End` | to end of list -| `Space` | select current file (and get size of directory) -| `Insert` | select current file (and move to next) -| `F9` | context menu -| `~` | console -| `Ctrl + Click` | open file on new tab +| Key |Operation +|:---------------------|:-------------------------------------------- +| `F1` | help +| `F2` | show `user menu` +| `F3` | view, change directory +| `Shift + F3` | view raw file, change directory +| `F4` | edit +| `F5` | copy +| `Alt` + `F5` | pack +| `F6` | rename/move +| `Shift` + `F6` | rename current file +| `F7` | new directory +| `Shift + F7` | new file +| `F8`, `Delete` | remove +| `Shift + Delete` | remove without prompt +| `F9` | menu +| `Alt` + `F9` | extract +| `F10` | config +| `*` | select/unselect all +| `+` | expand selection +| `-` | shrink selection +| `:` | open Command Line +| `Ctrl + X` | cut to buffer +| `Ctrl + C` | copy to buffer +| `Ctrl + V` | paste from buffer +| `Ctrl + Z` | clear buffer +| `Ctrl + P` | copy path +| `Ctrl + R` | refresh +| `Ctrl + D` | clear local storage +| `Ctrl + A` | select all files in a panel +| `Ctrl + M` | [rename selected files](https://github.com/coderaiser/cloudcmd/releases/tag/v12.1.0) in editor +| `Ctrl + U` | swap panels +| `Ctrl + F3` | sort by name +| `Ctrl + F5` | sort by date +| `Ctrl + F6` | sort by size +| `Ctrl + Shift + L` | logout +| `Ctrl + Command + .` | show/hide dot files +| `Up` | move cursor up +| `Down` | move cursor down +| `Enter` | change directory/view file +| `Alt + Left/Right` | show content of directory under cursor in target panel +| `Alt + G` | go to directory +| `Ctrl + \` | go to the root directory +| `Tab` | move via panels +| `Page Up` | up on one page +| `Page Down` | down on one page +| `Home` | to begin of list +| `End` | to end of list +| `Space` | select current file (and get size of directory) +| `Insert` | select current file (and move to next) +| `F9` | context menu +| `~` | console +| `Esc` | toggle vim hotkeys (`file manager`, `editor`) ### Vim -When `--vim` option provided, or configuration parameter `vim` set, next hot keys become available: +When the `--vim` option is provided, or the configuration parameter `vim` is set, the following hotkeys become available: -|Key |Operation -|:----------------------|:-------------------------------------------- -| `j` | navigate to next file -| `k` | navigate to previous file -| `dd` | remove current file -| `G` | navigate to bottom file -| `gg` | navigate to top file -| `v` | visual mode -| `y` | copy (selected in visual mode files) -| `p` | paste files -| `Esc` | unselect all -| `/` | find file in current directory -| `n` | navigate to next found file -| `N` | navigate to previous found file +| Key |Operation +|:------------|:-------------------------------------------- +| `j` | navigate to next file +| `k` | navigate to previous file +| `dd` | remove current file +| `G` or `$` | navigate to bottom file +| `gg` or `^` | navigate to top file +| `v` | visual mode +| `y` | copy (selected in visual mode files) +| `p` | paste files +| `Esc` | unselect all +| `/` | find file in current directory +| `n` | navigate to next found file +| `N` | navigate to previous found file +| `md` | make directory +| `mf` | make file +| `tt` | show terminal +| `e` | edit file +| `cc` | copy +| `mm` | move +| `rr` | rename file Commands can be joined, for example: -- `5j` will navigate `5` files below current; -- `d5j` will remove next `5` files; + +- `5j` will navigate **5** files below current; +- `d5j` will remove next **5** files; - `dG` will remove all files from current to bottom; -Drag and Drop ---------------- -Next file operations are accessible through `Drag and Drop`. +## Drag and drop + +These file operations are accessible with "drag and drop". | Drag Mouse Button | Key | Origin | Destination |Operation |:------------------|:----------|:----------|:--------------|:------------------ -| `Left` | | `Panel` | `Panel` | copy files -| `Left` | `Shift` | `Panel` | `Panel` | rename/move files -| `Left` | | `Panel` | `Desktop` | download files -| `Left` | | `Desktop` | `Panel` | upload files +| Left | | Panel | Panel | copy files +| Left | `Shift` | Panel | Panel | rename/move files +| Left | | Panel | Desktop | download files +| Left | | Desktop | Panel | upload files + +## View -View ---------------- ![View](/img/screen/view.png "View") ### Features + - View images. - View text files. -- Playing audio. -- Playing video. +- Play audio. +- Play video. -### Hot keys +### Hotkeys |Key |Operation |:----------------------|:-------------------------------------------- | `F3` | open | `Esc` | close -Edit ---------------- +## Edit + ![Edit](/img/screen/edit.png "Edit") ### Hot keys @@ -269,13 +284,13 @@ Edit |Key |Operation |:----------------------|:-------------------------------------------- | `F4` | open -| `Shift + F4` | open in `vim` mode +| `Shift + F4` | open in "vim" mode | `Esc` | close -For more details see [Edward hot keys][EDWARD_KEYS]. +For more details see [Edward hotkeys][EDWARD_KEYS]. + +## Console -Console ---------------- ![Console](/img/screen/console.png "Console") ### Hot keys @@ -283,24 +298,24 @@ Console |Key |Operation |:----------------------|:-------------------------------------------- | `~` | open -| `Ctrl + p` | paste path of current directory +| `Ctrl + P` | paste path of current directory | `Esc` | close For more details see [console hot keys](https://github.com/cloudcmd/console#hot-keys "Console Hot Keys"). -Terminal ---------------- +## Terminal + ![Terminal](/img/screen/terminal.png "Terminal") ### Install -`Terminal` disabled and not installed by default. To use it you should install [gritty](https://github.com/cloudcmd/gritty "Gritty") with: +The terminal is disabled and not installed by default. To use it, you should install [gritty](https://github.com/cloudcmd/gritty "Gritty") with: ```sh npm i gritty -g ``` -And then set the path of a terminal with: +and then set the path for the terminal with: ```sh cloudcmd --terminal --terminal-path `gritty --path` --save @@ -308,17 +323,18 @@ cloudcmd --terminal --terminal-path `gritty --path` --save ### Windows -If you can't install `gritty` on Windows try to install `windows-build-tools` first: +If you can't install `gritty` on Windows, try to install `windows-build-tools` first: ```sh npm install windows-build-tools -g ``` -Then get path of a `gritty` with: +Then get the path of `gritty` with: ```sh gritty --path ``` + It will returns something like: ```sh @@ -331,34 +347,33 @@ Set this path as `--terminal-path` with: cloudcmd --save --terminal --terminal-path "C:\Users\coderaiser\AppData\Roaming\npm\node_modules\gritty" ``` -After that you can use `terminal` in the same way as a `console`. +After that, you can use Cloud Commander's terminal in the same way as a normal shell console. -### Hot keys +### Hotkeys |Key |Operation |:----------------------|:-------------------------------------------- | `Shift` + `~` | open | `Shift` + `Esc` | close -Environment Variables ---------------- +## Environment Variables -Every program executed in `console` or `terminal` has these `environment` variables: +Every program executed in Cloud Commander's terminal has these environment variables: - `ACTIVE_DIR` - directory that contains cursor - `PASSIVE_DIR` - directory with no cursor - `CURRENT_NAME` - name of a file under cursor - `CURRENT_PATH` - path to file under cursor -On `Unix` you can use it this way: +On Unix, you can use it this way: ```sh ~> echo $CURRENT_PATH /home/coderaiser/cloudcmd/bin/cloudcmd.js ``` -Config ---------------- +## Configuration + ![Config](/img/screen/config.png "Config") ### Hot keys @@ -368,69 +383,74 @@ Config | `F10` | open | `Esc` | close -When you change one of options file `~/.cloudcmd.json` would be saved. -It could be edited manually with any text editor. -Here is description of options: +When you change any options, the `~/.cloudcmd.json` file is automatically updated. +It can also be edited manually with any text editor. +Here's a description of all options: -```js +```json { - "name" : "", /* set tab name in web browser */ - "auth" : false, /* enable http authentication */ - "username" : "root", /* username for authentication */ -    "password"         : "toor",   /* password hash for authentication */ - "algo" : "sha512WithRSAEncryption", /* cryptographic algorithm */ - "editor" : "edward", /* default, could be "dword" or "edward" */ - "packer" : "tar", /* default, could be "tar" or "zip" */ - "diff" : true, /* when save - send patch, not whole file */ - "zip" : true, /* zip text before send / unzip before save */ - "buffer" : true, /* buffer for copying files */ - "dirStorage" : true, /* store directory listing */ - "online" : false, /* do not load js files from cdn */ - "open" : true, /* open web browser when server started */ - "oneFilePanel" : false, /* show one file panel */ - "keysPanel" : true, /* show classic panel with buttons of keys */ - "port" : 8000, /* http port */ - "ip" : null, /* ip or null(default) */ - "root" : "/", /* root directory */ - "prefix" : "", /* url prefix */ - "prefixSocket" : "", /* prefix for socket connection */ - "progress" : true, /* show progress of file operations */ - "confirmCopy" : true, /* confirm copy */ - "confirmMove" : true, /* confirm move */ - "showConfig" : false, /* show config at startap */ - "showFileName" : false /* do not show file name in view and edit */ - "contact" : true, /* enable contact */ - "configDialog" : true, /* enable config dialog */ - "configAuth" : true, /* enable auth change in config dialog */ - "console" : true, /* enable console */ - "syncConsolePath" : false /* do not sync console path */ - "terminal" : false, /* disable terminal */ - "terminalPath" : '', /* path of a terminal */ - "terminalCommand" : '', /* set command to run in terminal */ - "terminalAutoRestart" : true, /* restart command on exit */ - "vim" : false, /* disable vim hot keys */ - "columns" : "name-size-date-owner-mode", /* set visible columns */ - "export" : false, /* enable export of config through a server */ - "exportToken" : "root", /* token used by export server */ - "import" : false, /* enable import of config */ - "import-url" : "http://localhost:8000", /* url of an export server */ - "importToken" : "root", /* token used to connect to export server */ - "importListen" : false, /* listen on config updates */ - "log" : true /* logging */ + "name": "", // set tab name in web browser + "auth": false, // enable http authentication + "username": "root", // username for authentication + "password": "toor", // password hash for authentication + "algo": "sha512WithRSAEncryption", // cryptographic algorithm + "editor": "edward", // default, could be "dword" or "edward" + "packer": "tar", // default, could be "tar" or "zip" + "diff": true, // when save - send patch, not whole file + "zip": true, // zip text before send / unzip before save + "buffer": true, // buffer for copying files + "dirStorage": true, // store directory listing + "online": false, // do not load js files from cdn + "open": true, // open web browser when server started + "oneFilePanel": false, // show one file panel + "keysPanel": true, // show classic panel with buttons of keys + "port": 8000, // http port + "ip": null, // ip or null(default) + "root": "/", // root directory + "prefix": "", // url prefix + "prefixSocket": "", // prefix for socket connection + "confirmCopy": true, // confirm copy + "confirmMove": true, // confirm move + "showConfig": false, // show config at startup + "showDotFiles": true, // show dot files + "showFileName": false, // do not show file name in view and edit + "contact": true, // enable contact + "configDialog": true, // enable config dialog + "configAuth": true, // enable auth change in config dialog + "console": true, // enable console + "syncConsolePath": false, // do not sync console path + "terminal": false, // disable terminal + "terminalPath": "", // path of a terminal + "terminalCommand": "", // set command to run in terminal + "terminalAutoRestart": true, // restart command on exit + "vim": false, // disable vim hot keys + "themes": "name-size-date-owner-mode", // set visible themes + "export": false, // enable export of config through a server + "exportToken": "root", // token used by export server + "import": false, // enable import of config + "import-url": "http://localhost:8000", // url of an export server + "importToken": "root", // token used to connect to export server + "importListen": false, // listen on config updates + "dropbox": false, // disable dropbox integration + "dropboxToken": "", // unset dropbox token + "log": true // logging } ``` ### Environment Variables -Some config options can be overridden with `environment variables` such: +Some config options can be overridden with environment variables, such as: - `CLOUDCMD_NAME` - set tab name in web browser - `CLOUDCMD_OPEN` - open web browser when server started - `CLOUDCMD_EDITOR` - set editor -- `CLOUDCMD_COLUMNS` - set visible columns +- `CLOUDCMD_COLUMNS` - set visible themes +- `CLOUDCMD_THEME` - set themes "light" or "dark" +- `CLOUDCMD_MENU` - set menu "supermenu" or "aleman" - `CLOUDCMD_CONTACT` - enable contact - `CLOUDCMD_CONFIG_DIALOG` - enable config dialog - `CLOUDCMD_CONFIG_AUTH` - enable auth change in config dialog +- `CLOUDCMD_CONFIG_PORT` - enable port change in config dialog - `CLOUDCMD_CONSOLE` - enable console - `CLOUDCMD_SYNC_CONSOLE_PATH` - sync console path - `CLOUDCMD_TERMINAL` - enable terminal @@ -442,6 +462,7 @@ Some config options can be overridden with `environment variables` such: - `CLOUDCMD_AUTH` - enable authentication - `CLOUDCMD_USERNAME` - set username - `CLOUDCMD_PASSWORD` - set password +- `CLOUDCMD_PREFIX` - set url prefix - `CLOUDCMD_ROOT` - set root directory - `CLOUDCMD_VIM` - enable vim hot keys - `CLOUDCMD_CONFIRM_COPY` - confirm copy @@ -452,41 +473,138 @@ Some config options can be overridden with `environment variables` such: - `CLOUDCMD_IMPORT` - enable import of config - `CLOUDCMD_IMPORT_TOKEN` - authorization token used to connect to export server - `CLOUDCMD_IMPORT_URL` - url of an import server -- `CLOUDCMD_IMPORT_LISTEN`- enable listen on config updates from import server +- `CLOUDCMD_IMPORT_LISTEN` - enable listen on config updates from import server + +### User Menu + +When you press `F2` Cloud Commander will read a file `.cloudcmd.menu.js` by walking up parent directories, if can't read it will try to read `~/.cloudcmd.menu.js`. + +Let's consider example `user menu` works file: + +```js +const RENAME_FILE = 'Rename file'; + +export default { + '__settings': { + select: [RENAME_FILE], + run: false, + }, + [`F2 - ${RENAME_FILE}`]: async ({DOM}) => { + await DOM.renameCurrent(); + }, + 'D - Build Dev': async ({CloudCmd}) => { + await CloudCmd.TerminalRun.show({ + command: 'npm run build:client:dev', + autoClose: false, // optional + closeMessage: 'Press any button to close Terminal', // optional + }); + + await CloudCmd.refresh(); + }, + 'P - Build Prod': async ({CloudCmd}) => { + await CloudCmd.TerminalRun.show({ + command: 'npm run build:client', + autoClose: true, // optional + }); + + await CloudCmd.refresh(); + }, + 'C - Create User Menu File': async ({DOM, CloudCmd}) => { + const {CurrentInfo} = DOM; + + const {dirPath} = CurrentInfo; + const path = `${dirPath}.cloudcmd.menu.js`; + const {prefix} = CloudCmd; + + const data = await readDefaultMenu({ + prefix, + }); + + await createDefaultMenu({ + path, + data, + DOM, + CloudCmd, + }); + }, +}; + +async function createDefaultMenu({path, data, DOM, CloudCmd}) { + const {IO} = DOM; + + await IO.write(path, data); + await CloudCmd.refresh(); + + DOM.setCurrentByName('.cloudcmd.menu.js'); + + await CloudCmd.EditFile.show(); +} + +async function readDefaultMenu({prefix}) { + const res = await fetch(`${prefix}/api/v1/user-menu/default`); + const data = await res.text(); + + return data; +} +``` + +You will have ability to run one of this 3 commands with help of double click, enter, or binded key (`F2`, `D` or `P` in this example). Also you can run commands in terminal, or execute any built-in function of `Cloud Commander` extended it's interface. You can find more examples in [User Menu Cookbook](https://github.com/coderaiser/cloudcmd/wiki/User-Menu-Cookbook). + +#### User Menu API + +Here you can find `API` that can be used in **User Menu**. **DOM** and **CloudCmd** two main objects you receive in arguments list using destructuring. + +**DOM** contains all base functions of `Cloud Commander` (rename, remove, download etc); + +- `renameCurrent` - shows renames current file dialog, and does renaming. + +**CloudCmd** contains all modules (`Terminal`, `View`, `Edit`, `Config`, `Console` etc); + +- `TerminalRun` - module that shows `Terminal` with a `command` from options and closes terminal when everything is done. + +**IO** Files API + +- `rename(from, to)` - rename `from` into `to` +- `move(from, to, names)` - rename files with a `names` `from` into `to`; +- `copy(from, to, names)` - copy files with a `names` `from` into `to`; +- `createDirectory(path)` - create directory with a `path`; ### Distribute -Being able to configure `Cloud Commander` remotely opens the doors to using it as microservice and that's what distribute options set out to do. -There is an `export server` and `import client` and they enabled with `--export` and `--import` accordingly. There is a `token` it should be the same -in `--import-token` and `--export-token`. To use `import` you should provide `--import-url` to `import client` so it can connect to an `export server`. -There is 2 ways `import client` can receive config from an `export server`: +Being able to configure Cloud Commander remotely opens the doors to using it as microservice, and that's what the "distribute" options set out to do. + +There is an **export server** and an **import client**, which are enabled with `--export` and `--import` respectively. There is a "token", which should be the same in `--import-token` and `--export-token`. To use the *import client*, you should provide `--import-url` to the client so it can connect to an *export server*. + +There are two ways that the *import client* can receive configuration from an *export server*: - full config at startup (default) -- get every updated option (with help of `--import-listen` flag) +- get every updated option (with help of the `--import-listen` flag) -There is an example of using distribute options in `Cloud Commander` to get config from remote instance. -Here is an `export server`: +#### An example - using the "distribute" options to get configuration from a remote instance: + +Here's an *export server*: ``` coderaiser@cloudcmd:~$ cloudcmd --port 1234 --export --export-token=cloudcmd ``` -And `import client`: +...and an *import client*: + ``` coderaiser@cloudcmd:~$ cloudcmd --name importer --port 4321 --import-url http://127.0.0.1:1234 --import-token=cloudcmd --no-server --save ``` -Here is the log of `export server`: +Here's the log output from the *export server*: ``` url: http://localhost:1234/ 2018.08.23 13:41:45 -> export: try to auth from importer [127.0.0.1:4321] 2018.08.23 13:41:45 -> export: connected to importer [127.0.0.1:4321] -2018.08.23 13:41:45 -> export: config send to importer[127.0.0.1:4321] +2018.08.23 13:41:45 -> export: config send to importer [127.0.0.1:4321] 2018.08.23 13:41:45 -> export: disconnected importer [127.0.0.1:4321] ``` -And log of `import client`: +...and the log output from the *import client*: ``` 2018.08.23 13:47:36 -> import: try to auth to http://127.0.0.1:1234 @@ -495,9 +613,9 @@ And log of `import client`: 2018.08.23 13:47:36 -> import: disconnected from http://127.0.0.1:1234 ``` -When `import client` uses `--import-listen` persistent connection used and client receives live updates from the `import server`. +When the *import client* uses `--import-listen`, a persistent connection is used, and the *client* receives live updates from the *import server*. -`Export server` omit next configuration fields: +The *export server* omits the following configuration fields: - `auth` - `username` @@ -515,11 +633,11 @@ When `import client` uses `--import-listen` persistent connection used and clien - `log` - `configDialog` -Menu ---------------- +## Menu + ![Menu](/img/screen/menu.png "Menu") -Right mouse click button shows context menu with items: +Right-mouse click to show a context menu with these items: - View - Edit @@ -540,22 +658,30 @@ Right mouse click button shows context menu with items: ### Hot keys -|Key |Operation -|:----------------------|:-------------------------------------------- -| `F9` | open -| `Esc` | close +| Key | Operation | +|:-------------|:------------------------| +| `F9` | open | +| `Esc` | close | +| `Up`, `j` | move cursor up | +| `Down`, `k` | move cursor down | +| `Left`, `h` | close submenu | +| `Right`, `l` | open submenu | +| `G` or `$` | navigate to bottom | +| `gg` or `^` | navigate to top | -One file panel ---------------- -Cloud Commander can work in one panel mode when screen size can not accommodate second panel or via `--one-file-panel` options flag. -It could happen when mobile device, tablet or small window size used to work with file manager. +Commands can be joined, for example: + +- `5j` will navigate **5** items below current; + +## One file panel + +Cloud Commander can work in one panel mode when your screen size can't accommodate a second panel (such as on mobile or tablet), or via the `--one-file-panel` options flag. ![One file panel](/img/screen/one-file-panel.png "One file panel") -Using as Middleware ---------------- +## Using as middleware -Cloud Commander could be used as middleware for `node.js` applications based on [socket.io](http://socket.io "Socket.IO") and [express](http://expressjs.com "Express"): +Cloud Commander can be used as middleware for `node.js` applications based on [socket.io](http://socket.io "Socket.IO") and [express](http://expressjs.com "Express"): Init `package.json`: @@ -572,35 +698,30 @@ npm i cloudcmd express socket.io -S And create `index.js`: ```js -const http = require('http'); -const cloudcmd = require('cloudcmd'); -const io = require('socket.io'); -const app = require('express')(); +import http from 'node:http'; +import {cloudcmd} from 'cloudcmd'; +import {Server} from 'socket.io'; +import express from 'express'; +const app = express(); const port = 1337; -const prefix = '/cloudcmd'; -const socketPrefix = '/cloudcmd-sockets'; +const prefix = '/'; const server = http.createServer(app); -const socket = io.listen(server, { - path: `${prefix}/socket.io` +const socket = new Server(server, { + path: `${prefix}socket.io`, }); const config = { - prefix, // base URL or function which returns base URL (optional) - socketPrefix, // prefix for socket connection + name: 'cloudcmd :)', }; -const plugins = [ - __dirname + '/plugin.js' -]; - const filePicker = { data: { FilePicker: { - key: 'key' - } - } + key: 'key', + }, + }, }; // override option from json/modules.json @@ -608,32 +729,81 @@ const modules = { filePicker, }; -app.use(cloudcmd({ - socket, // used by Config, Edit (optional) and Console (required) - config, // config data (optional) - plugins, // optional +const { + createConfigManager, + configPath, +} = cloudcmd; + +const configManager = createConfigManager({ + configPath, +}); + +app.use(prefix, cloudcmd({ + socket, // used by Config, Edit (optional) and Console (required) + config, // config data (optional) modules, // optional + configManager, // optional })); server.listen(port); ``` -And you are ready to go. - -### Authorization - -If you want to enable `authorization` you can pass credentials in a `config`. -To generate password you can install `criton` with `npm i criton --save` and use it -or any other way to generate a `hash` of a `password`. +Here is example with two `Config Managers`: ```js -const criton = require('criton'); -const algo = 'sha512WithRSAEncryption'; // default +import http from 'node:http'; +import cloudcmd from 'cloudcmd'; +import {Server} from 'socket.io'; +import express from 'express'; -// you can generate hash dynamically +const app = express(); +const port = 8000; +const prefix1 = '/1'; +const prefix2 = '/2'; + +const {createConfigManager} = cloudcmd; + +const server = http.createServer(app); +const socket1 = new Server(server, { + path: `${prefix1}/socket.io`, +}); + +const socket2 = new Server(server, { + path: `${prefix2}/socket.io`, +}); + +const configManager1 = createConfigManager(); + +configManager1('name', '1'); + +const configManager2 = createConfigManager(); +configManager2('name', '2'); + +app.use(prefix1, cloudcmd({ + socket: socket1, + configManager: configManager1, +})); + +app.use(prefix2, cloudcmd({ + socket: socket2, + configManager: configManager2, +})); + +server.listen(port); +``` + +If you want to enable authorization, you can pass credentials to Cloud Commander with a config. To generate a password, you can install `criton` with `npm i criton --save`, and use it (or any other way) to generate a hash of a password. + +```js +import criton from 'criton'; + +const algo = 'sha512WithRSAEncryption'; + +// default +// you can generate a hash dynamically const password = criton('root', algo); -// or use pregenerated hash as well +// or use a pregenerated hash as well '2b64f2e..ca5d9a9'; const auth = true; @@ -643,16 +813,27 @@ const config = { algo, // optional auth, username, - pasword, -} + password, +}; ``` -Server ---------------- -Standard practices say no non-root process gets to talk to -the Internet on a port less than 1024. Anyway I suggest you -to start Cloud Commander as non-root. How it could be solved? -There is a couple easy and fast ways. One of them is port forwarding. +Now you're ready to go! + +## Authorization + +`~/.cloudcmd.json` contains [password hash](https://github.com/coderaiser/cloudcmd/blob/v11.8.3/json/config.json#L5) because of security reason, if someone steal your config, he wouldn't know your password, because hash is [very strong](https://github.com/coderaiser/cloudcmd/blob/v11.8.3/json/config.json#L6) and can be customized. + +You should never write your password as plain text to `~/.cloudcmd.json`, you can generate password using `cloudcmd` itself: + +``` +cloudcmd --username name --password password --auth --save --no-server +``` + +This command will create hash of your password and write it to `~/.cloudcmd.json`. + +## Server + +Standard practices dictate that no non-root process get to talk to the internet on a port less than 1024. Despite this, **I suggest you start Cloud Commander as a non-root process**. How can we get around this limitation? There's a couple of fast & easy ways. One of them is port forwarding: ### Iptables @@ -665,15 +846,15 @@ iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 4430 iptables -t nat -L # look rules after ``` -You should see something like this ( **8000** and **4430** should be in config as **port** and **sslPort** ) +You should see something like this (**8000** and **4430** should be in config as **port** and **sslPort**) ```sh target prot opt source destination REDIRECT tcp -- anywhere anywhere tcp dpt:http redir ports 8000 REDIRECT tcp -- anywhere anywhere tcp dpt:https redir ports 4430 ``` -If you would want to get things back just clear rules ( **1** and **2** it's rule numbers, -in your list they could differ). + +If you would want to get things back just clear rules (rule numbers **1** and **2**; in your list they could differ). ```sh iptables -t nat -D PREROUTING 2 @@ -681,14 +862,15 @@ iptables -t nat -D PREROUTING 1 ``` ### nginx -Get [nginx](http://nginx.org/ "nginx"). On Linux it could be done this way: + +Get [nginx](http://nginx.org/ "nginx"). On Linux, you can run: ```sh sudo apt-get install nginx #for ubuntu and debian ``` -Then make host file **/etc/nginx/sites-available/io.cloudcmd.io** -( *io.cloudcmd.io* is your domain name) with content: +Then, make a host file **/etc/nginx/sites-available/io.cloudcmd.io** +(where, for example, *io.cloudcmd.io* is your domain name) with these contents: ```sh server { @@ -702,7 +884,7 @@ server { } ``` -If you want add **SSL**, add a couple lines to server block: +**If you want add SSL**, add a couple lines to the `server` block: ```sh server { @@ -719,7 +901,7 @@ server { } ``` -For WebSocket support (nginx >= v1.3.13) modify server block: +For WebSocket support, (nginx >= v1.3.13) modify the `server` block like so: ```sh location / { @@ -731,8 +913,7 @@ For WebSocket support (nginx >= v1.3.13) modify server block: } ``` - -If you need redirection from **http** to **https**, it's simple: +If you need redirection from **http** to **https**, simply use: ```sh server { @@ -744,30 +925,29 @@ server { ``` ```sh -# create symlink of this file +# create a symlink of this file ln -s ./sites-available/io.cloudcmd.io ./sites-enabled # restart nginx /etc/init.d/nginx restart ``` -Deploy ---------------- -`Cloud Commander` could be easily deployed to [Heroku](https://heroku.com/deploy?template=https://github.com/coderaiser/cloudcmd "Deploy to Heroku"). +## Deploy -[![Deploy to Heroku](https://www.herokucdn.com/deploy/button.png "Deploy to Heroku")]( https://heroku.com/deploy?template=https://github.com/coderaiser/cloudcmd) +`Cloud Commander` can be easily deployed to [InstaPods][DeployInstaPodsURL]. After deploy you receive email with credentials. -Docker ---------------- -`Cloud Commander` could be used as [docker container](https://hub.docker.com/r/coderaiser/cloudcmd/ "Docker container") this way: +[![Deploy on InstaPods](https://instapods.com/deploy-button.svg)](https://app.instapods.com/dashboard/pods/create?app=cloudcmd&ref=cloudcmd) + +## Docker + +`Cloud Commander` can be used as [docker container](https://hub.docker.com/r/coderaiser/cloudcmd/ "Docker container") like so: ```sh -docker run -t --rm -v ~:/root -v /:/mnt/fs -p 8000:8000 coderaiser/cloudcmd +docker run -t --rm -v ~:/root -v /:/mnt/fs -w=/root -p 8000:8000 coderaiser/cloudcmd ``` -Config would be read from home directory, hosts root file system would be mount to `/mnt/fs`, -`8000` port would be exposed to hosts port. +Configuration will be read from the home directory, the host's root file system will be mounted to `/mnt/fs`, and port `8000` port will exposed to the host's port. -Also you could use [docker compose](https://docs.docker.com/compose/ "Docker Compose") with `docker-compose.yml`: +Also, you can use [docker compose](https://docs.docker.com/compose/ "Docker Compose") with `docker-compose.yml`: ```yml version: '2' @@ -781,23 +961,493 @@ services: image: coderaiser/cloudcmd ``` -When you create this file run: +When you create this file, run: ```sh docker-compose up ``` -Get involved ---------------- +# Dropbox -There is a lot ways to be involved in `Cloud Commander` development: +Dropbox support is integrated into Cloud Commander, and you can switch from your local file system to a Dropbox account. +All you need to do is set `--dropbox` option and [generate a dropbox token](https://blogs.dropbox.com/developers/2014/05/generate-an-access-token-for-your-own-account/) for your account. -- if you find a bug or got idea to share [create issue](https://github.com/coderaiser/cloudcmd/issues/new "Create issue"); -- if you fixed a bug, typo or implemented new feature [create pull request](https://github.com/coderaiser/cloudcmd/compare "Create pull request"); -- if you know languages you can help with [site translations](https://github.com/coderaiser/cloudcmd/wiki "Cloud Commander community wiki"); +This could look like this: -Version history ---------------- +```sh +cloudcmd --dropbox --dropbox-token your-dropbox-token +``` + +While using Dropbox remember that there is no remote support for the console/terminal. Seeing the progress of file operations is also not supported. There's only basic support, but you can do the following things with files and directories: + +- create +- remove +- rename/move +- view +- edit + +## Automatically start cloudcmd on boot for `systemd` + +First, locate the command to run cloudcmd + +```sh +which cloudcmd +``` + +take note of the result and create a systemd entry by executing + +```sh +sudo nano /etc/systemd/system/cloudcmd.service +``` + +and use this template + +``` +[Unit] +Description = Cloud Commander + +[Service] +TimeoutStartSec = 0 +Restart = always +ExecStart = THE RESULT OF which cloudcmd WE'VE EXECUTED EARLIER +User = YOUR_USER + +[Install] +WantedBy = multi-user.target +``` + +Don't forget to change the line for `ExecStart` and `User` + +Save the changes and exit editor. + +You may now enable cloudcmd and set it to autostart on boot by running: + +```sh +sudo systemctl enable --now cloudcmd +``` + +## Automatically start cloudcmd on boot for `FreeBSD` + +First, locate the command to run cloudcmd + +``` +which cloudcmd +``` + +take note of the result and create a rc script + +``` +vi /usr/local/etc/rc.d/cloudcmd +``` + +and use this template + +``` +!/bin/sh +# +# PROVIDE: cloudcmd +# REQUIRE: LOGIN +# KEYWORD: shutdown + +# Author: IhatemyISP (ihatemyisp.net) +# Version: 1.0.0 + +# Description: +# This script runs Cloud Commander as a service under the supplied user on boot + +# 1) Place file in /usr/local/etc/rc.d/ +# 2) Add cloudcmd_enable="YES" to /etc/rc.conf +# 3) (Optional) To run as non-root, add cloudcmd_runAs="user" to /etc/rc.conf +# 4) (Optional) To pass Cloud Commander args, add cloudcmd_args="" to /etc/rc.conf + +# Freebsd rc library +. /etc/rc.subr + +# General Info +name="cloudcmd" # Safe name of program +program_name="cloudcmd" # Name of exec +title="CloudCommander" # Title to display in top/htop + +# RC.config vars +load_rc_config $name # Loading rc config vars +: ${cloudcmd_enable="NO"} # Default: Do not enable Cloud Commander +: ${cloudcmd_runAs="root"} # Default: Run Cloud Commander as root + +# Freebsd Setup +rcvar=cloudcmd_enable # Enables the rc.conf YES/NO flag +pidfile="/var/run/${program_name}.pid" # PID file location + +# Env Setup +export HOME=$( getent passwd "$cloudcmd_runAs" | cut -d: -f6 ) # Gets the home directory of the runAs user + +# Command Setup +exec_path="/usr/local/bin/${program_name}" # Path to the cloudcmd exec, /usr/local/bin/ when installed globally +output_file="/var/log/${program_name}.log" # Path to Cloud Commander output file + +# Command +command="/usr/sbin/daemon" +command_args="-r -t ${title} -u ${cloudcmd_runAs} -o ${output_file} -P ${pidfile} ${exec_path} ${cloudcmd_args}" + +# Loading Config +load_rc_config ${name} +run_rc_command "$1" +``` + +Enable autostart + +``` +echo cloudcmd_enable="YES" >> /etc/rc.conf +``` + +(Optional) Set user to run Cloud Commander as (default is root) + +``` +echo cloudcmd_runAs="user" >> /etc/rc.conf +``` + +Start the service (or just reboot) + +``` +service cloudcmd start +``` + +## Get involved + +There are a lot of ways to be involved in `Cloud Commander` development: + +- support project on patreon: https://patreon.com/coderaiser; +- if you find a bug or have an idea to share, [create an issue](https://github.com/coderaiser/cloudcmd/issues/new "Create issue"); +- if you fixed a bug, typo or implemented a new feature, [create a pull request](https://github.com/coderaiser/cloudcmd/compare "Create pull request"); +- if you know a language not currently translated, or would like to improve an existing translation, you can help with [site translations](https://github.com/coderaiser/cloudcmd/wiki "Cloud Commander community wiki"); + +## Version history + +- *2026.06.15*, **[v19.19.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.19.1)** +- *2026.05.26*, **[v19.19.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.19.0)** +- *2026.05.26*, **[v19.18.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.18.1)** +- *2026.05.26*, **[v19.18.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.18.0)** +- *2026.05.17*, **[v19.17.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.17.0)** +- *2026.05.03*, **[v19.16.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.16.0)** +- *2026.04.28*, **[v19.15.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.15.0)** +- *2026.04.28*, **[v19.14.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.14.0)** +- *2026.04.21*, **[v19.13.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.13.1)** +- *2026.04.15*, **[v19.13.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.13.0)** +- *2026.04.12*, **[v19.12.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.12.5)** +- *2026.04.12*, **[v19.12.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.12.4)** +- *2026.04.12*, **[v19.12.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.12.3)** +- *2026.04.11*, **[v19.12.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.12.2)** +- *2026.04.09*, **[v19.12.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.12.1)** +- *2026.04.09*, **[v19.12.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.12.0)** +- *2026.04.07*, **[v19.11.14](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.14)** +- *2026.04.07*, **[v19.11.13](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.13)** +- *2026.04.06*, **[v19.11.12](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.12)** +- *2026.04.06*, **[v19.11.11](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.11)** +- *2026.04.06*, **[v19.11.10](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.10)** +- *2026.04.06*, **[v19.11.9](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.9)** +- *2026.04.06*, **[v19.11.8](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.8)** +- *2026.04.05*, **[v19.11.7](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.7)** +- *2026.04.05*, **[v19.11.6](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.6)** +- *2026.04.05*, **[v19.11.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.5)** +- *2026.04.04*, **[v19.11.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.4)** +- *2026.04.04*, **[v19.11.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.3)** +- *2026.04.04*, **[v19.11.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.2)** +- *2026.04.04*, **[v19.11.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.1)** +- *2026.04.04*, **[v19.11.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.11.0)** +- *2026.04.04*, **[v19.10.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.10.2)** +- *2026.04.03*, **[v19.10.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.10.1)** +- *2026.04.02*, **[v19.10.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.10.0)** +- *2026.04.02*, **[v19.9.24](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.24)** +- *2026.04.01*, **[v19.9.23](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.23)** +- *2026.03.31*, **[v19.9.22](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.22)** +- *2026.03.31*, **[v19.9.21](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.21)** +- *2026.03.30*, **[v19.9.20](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.20)** +- *2026.03.30*, **[v19.9.19](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.19)** +- *2026.03.30*, **[v19.9.18](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.18)** +- *2026.03.30*, **[v19.9.17](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.17)** +- *2026.03.29*, **[v19.9.16](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.16)** +- *2026.03.29*, **[v19.9.15](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.15)** +- *2026.03.29*, **[v19.9.14](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.14)** +- *2026.03.29*, **[v19.9.13](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.13)** +- *2026.03.29*, **[v19.9.12](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.12)** +- *2026.03.29*, **[v19.9.11](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.11)** +- *2026.03.29*, **[v19.9.10](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.10)** +- *2026.03.29*, **[v19.9.9](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.9)** +- *2026.03.28*, **[v19.9.8](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.8)** +- *2026.03.27*, **[v19.9.7](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.7)** +- *2026.03.26*, **[v19.9.6](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.6)** +- *2026.03.26*, **[v19.9.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.5)** +- *2026.03.26*, **[v19.9.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.4)** +- *2026.03.24*, **[v19.9.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.3)** +- *2026.03.23*, **[v19.9.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.2)** +- *2026.03.23*, **[v19.9.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.1)** +- *2026.03.23*, **[v19.9.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.9.0)** +- *2026.03.23*, **[v19.8.15](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.15)** +- *2026.03.23*, **[v19.8.14](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.14)** +- *2026.03.23*, **[v19.8.13](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.13)** +- *2026.03.23*, **[v19.8.12](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.12)** +- *2026.03.23*, **[v19.8.11](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.11)** +- *2026.03.23*, **[v19.8.10](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.10)** +- *2026.03.23*, **[v19.8.9](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.9)** +- *2026.03.23*, **[v19.8.8](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.8)** +- *2026.03.23*, **[v19.8.7](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.7)** +- *2026.03.23*, **[v19.8.6](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.6)** +- *2026.03.23*, **[v19.8.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.5)** +- *2026.03.22*, **[v19.8.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.4)** +- *2026.03.22*, **[v19.8.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.3)** +- *2026.03.22*, **[v19.8.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.2)** +- *2026.03.22*, **[v19.8.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.1)** +- *2026.03.20*, **[v19.8.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.8.0)** +- *2026.03.18*, **[v19.7.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.7.1)** +- *2026.03.17*, **[v19.7.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.7.0)** +- *2026.03.17*, **[v19.6.9](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.9)** +- *2026.02.27*, **[v19.6.8](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.8)** +- *2026.02.26*, **[v19.6.7](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.7)** +- *2026.02.26*, **[v19.6.6](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.6)** +- *2026.02.26*, **[v19.6.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.5)** +- *2026.02.25*, **[v19.6.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.4)** +- *2026.02.24*, **[v19.6.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.3)** +- *2026.02.24*, **[v19.6.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.2)** +- *2026.02.24*, **[v19.6.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.1)** +- *2026.02.21*, **[v19.6.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.6.0)** +- *2026.02.18*, **[v19.5.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.5.1)** +- *2026.02.18*, **[v19.5.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.5.0)** +- *2026.02.18*, **[v19.4.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.4.1)** +- *2026.02.18*, **[v19.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.4.0)** +- *2026.02.15*, **[v19.3.9](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.9)** +- *2026.02.15*, **[v19.3.8](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.8)** +- *2026.02.13*, **[v19.3.7](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.7)** +- *2026.02.12*, **[v19.3.6](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.6)** +- *2026.02.08*, **[v19.3.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.5)** +- *2026.02.06*, **[v19.3.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.4)** +- *2026.02.05*, **[v19.3.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.3)** +- *2026.02.04*, **[v19.3.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.2)** +- *2026.02.03*, **[v19.3.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.1)** +- *2026.02.03*, **[v19.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.3.0)** +- *2026.02.03*, **[v19.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.2.0)** +- *2026.02.02*, **[v19.1.21](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.21)** +- *2026.01.31*, **[v19.1.20](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.20)** +- *2026.01.30*, **[v19.1.19](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.19)** +- *2026.01.30*, **[v19.1.18](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.18)** +- *2026.01.29*, **[v19.1.17](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.17)** +- *2026.01.28*, **[v19.1.16](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.16)** +- *2026.01.28*, **[v19.1.15](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.15)** +- *2026.01.28*, **[v19.1.14](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.14)** +- *2026.01.27*, **[v19.1.13](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.13)** +- *2026.01.27*, **[v19.1.12](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.12)** +- *2026.01.25*, **[v19.1.11](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.11)** +- *2026.01.25*, **[v19.1.10](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.10)** +- *2026.01.21*, **[v19.1.9](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.9)** +- *2026.01.20*, **[v19.1.8](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.8)** +- *2026.01.17*, **[v19.1.7](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.7)** +- *2026.01.16*, **[v19.1.6](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.6)** +- *2026.01.16*, **[v19.1.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.5)** +- *2026.01.15*, **[v19.1.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.4)** +- *2026.01.15*, **[v19.1.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.3)** +- *2026.01.14*, **[v19.1.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.2)** +- *2026.01.12*, **[v19.1.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.1)** +- *2025.12.31*, **[v19.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.1.0)** +- *2025.12.24*, **[v19.0.17](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.17)** +- *2025.12.05*, **[v19.0.16](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.16)** +- *2025.11.28*, **[v19.0.15](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.15)** +- *2025.11.27*, **[v19.0.14](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.14)** +- *2025.09.26*, **[v19.0.13](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.13)** +- *2025.09.25*, **[v19.0.12](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.12)** +- *2025.09.24*, **[v19.0.11](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.11)** +- *2025.09.23*, **[v19.0.10](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.10)** +- *2025.09.22*, **[v19.0.9](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.9)** +- *2025.09.20*, **[v19.0.8](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.8)** +- *2025.09.18*, **[v19.0.7](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.7)** +- *2025.09.17*, **[v19.0.6](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.6)** +- *2025.09.16*, **[v19.0.5](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.5)** +- *2025.09.15*, **[v19.0.4](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.4)** +- *2025.09.15*, **[v19.0.3](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.3)** +- *2025.09.14*, **[v19.0.2](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.2)** +- *2025.09.14*, **[v19.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.1)** +- *2025.09.14*, **[v19.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v19.0.0)** +- *2025.09.14*, **[v18.8.11](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.11)** +- *2025.09.14*, **[v18.8.10](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.10)** +- *2025.09.14*, **[v18.8.9](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.9)** +- *2025.09.13*, **[v18.8.8](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.8)** +- *2025.09.12*, **[v18.8.7](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.7)** +- *2025.09.12*, **[v18.8.6](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.6)** +- *2025.09.10*, **[v18.8.5](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.5)** +- *2025.09.09*, **[v18.8.4](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.4)** +- *2025.09.04*, **[v18.8.3](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.3)** +- *2025.09.04*, **[v18.8.2](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.2)** +- *2025.09.04*, **[v18.8.1](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.1)** +- *2025.09.02*, **[v18.8.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.8.0)** +- *2025.08.30*, **[v18.7.4](//github.com/coderaiser/cloudcmd/releases/tag/v18.7.4)** +- *2025.07.26*, **[v18.7.3](//github.com/coderaiser/cloudcmd/releases/tag/v18.7.3)** +- *2025.07.24*, **[v18.7.2](//github.com/coderaiser/cloudcmd/releases/tag/v18.7.2)** +- *2025.07.06*, **[v18.7.1](//github.com/coderaiser/cloudcmd/releases/tag/v18.7.1)** +- *2025.07.05*, **[v18.7.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.7.0)** +- *2025.07.04*, **[v18.6.1](//github.com/coderaiser/cloudcmd/releases/tag/v18.6.1)** +- *2025.07.02*, **[v18.6.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.6.0)** +- *2025.04.10*, **[v18.5.2](//github.com/coderaiser/cloudcmd/releases/tag/v18.5.2)** +- *2025.02.03*, **[v18.5.1](//github.com/coderaiser/cloudcmd/releases/tag/v18.5.1)** +- *2025.01.20*, **[v18.5.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.5.0)** +- *2024.12.13*, **[v18.4.1](//github.com/coderaiser/cloudcmd/releases/tag/v18.4.1)** +- *2024.11.22*, **[v18.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.4.0)** +- *2024.11.14*, **[v18.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.3.0)** +- *2024.11.06*, **[v18.2.1](//github.com/coderaiser/cloudcmd/releases/tag/v18.2.1)** +- *2024.10.27*, **[v18.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.2.0)** +- *2024.08.17*, **[v18.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.1.0)** +- *2024.08.16*, **[v18.0.2](//github.com/coderaiser/cloudcmd/releases/tag/v18.0.2)** +- *2024.08.16*, **[v18.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v18.0.1)** +- *2024.08.16*, **[v18.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v18.0.0)** +- *2024.08.16*, **[v17.4.4](//github.com/coderaiser/cloudcmd/releases/tag/v17.4.4)** +- *2024.07.27*, **[v17.4.3](//github.com/coderaiser/cloudcmd/releases/tag/v17.4.3)** +- *2024.07.03*, **[v17.4.2](//github.com/coderaiser/cloudcmd/releases/tag/v17.4.2)** +- *2024.05.06*, **[v17.4.1](//github.com/coderaiser/cloudcmd/releases/tag/v17.4.1)** +- *2024.04.17*, **[v17.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v17.4.0)** +- *2024.04.03*, **[v17.3.3](//github.com/coderaiser/cloudcmd/releases/tag/v17.3.3)** +- *2024.03.29*, **[v17.3.2](//github.com/coderaiser/cloudcmd/releases/tag/v17.3.2)** +- *2024.03.29*, **[v17.3.1](//github.com/coderaiser/cloudcmd/releases/tag/v17.3.1)** +- *2024.03.29*, **[v17.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v17.3.0)** +- *2024.03.29*, **[v17.2.1](//github.com/coderaiser/cloudcmd/releases/tag/v17.2.1)** +- *2024.03.22*, **[v17.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v17.2.0)** +- *2024.03.21*, **[v17.1.6](//github.com/coderaiser/cloudcmd/releases/tag/v17.1.6)** +- *2024.03.20*, **[v17.1.5](//github.com/coderaiser/cloudcmd/releases/tag/v17.1.5)** +- *2024.03.20*, **[v17.1.4](//github.com/coderaiser/cloudcmd/releases/tag/v17.1.4)** +- *2024.03.18*, **[v17.1.3](//github.com/coderaiser/cloudcmd/releases/tag/v17.1.3)** +- *2024.03.18*, **[v17.1.2](//github.com/coderaiser/cloudcmd/releases/tag/v17.1.2)** +- *2024.03.16*, **[v17.1.1](//github.com/coderaiser/cloudcmd/releases/tag/v17.1.1)** +- *2024.03.16*, **[v17.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v17.1.0)** +- *2024.03.12*, **[v17.0.7](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.7)** +- *2024.03.11*, **[v17.0.6](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.6)** +- *2024.03.11*, **[v17.0.5](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.5)** +- *2024.02.02*, **[v17.0.4](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.4)** +- *2024.02.01*, **[v17.0.3](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.3)** +- *2024.02.01*, **[v17.0.2](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.2)** +- *2024.01.25*, **[v17.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.1)** +- *2023.12.12*, **[v17.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v17.0.0)** +- *2023.12.08*, **[v16.18.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.18.0)** +- *2023.12.04*, **[v16.17.9](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.9)** +- *2023.12.04*, **[v16.17.8](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.8)** +- *2023.10.12*, **[v16.17.7](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.7)** +- *2023.09.22*, **[v16.17.6](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.6)** +- *2023.09.06*, **[v16.17.5](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.5)** +- *2023.09.05*, **[v16.17.4](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.4)** +- *2023.09.05*, **[v16.17.3](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.3)** +- *2023.09.04*, **[v16.17.2](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.2)** +- *2023.09.04*, **[v16.17.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.1)** +- *2023.09.04*, **[v16.17.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.17.0)** +- *2023.08.10*, **[v16.16.3](//github.com/coderaiser/cloudcmd/releases/tag/v16.16.3)** +- *2023.08.09*, **[v16.16.2](//github.com/coderaiser/cloudcmd/releases/tag/v16.16.2)** +- *2023.08.07*, **[v16.16.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.16.1)** +- *2023.07.09*, **[v16.16.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.16.0)** +- *2023.05.17*, **[v16.15.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.15.0)** +- *2023.03.21*, **[v16.14.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.14.1)** +- *2023.03.08*, **[v16.14.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.14.0)** +- *2023.01.30*, **[v16.13.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.13.1)** +- *2023.01.29*, **[v16.13.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.13.0)** +- *2023.01.29*, **[v16.12.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.12.0)** +- *2023.01.22*, **[v16.11.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.11.0)** +- *2023.01.19*, **[v16.10.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.10.0)** +- *2023.01.18*, **[v16.9.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.9.1)** +- *2023.01.17*, **[v16.9.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.9.0)** +- *2023.01.16*, **[v16.8.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.8.0)** +- *2023.01.15*, **[v16.7.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.7.0)** +- *2022.10.20*, **[v16.6.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.6.1)** +- *2022.10.09*, **[v16.6.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.6.0)** +- *2022.08.06*, **[v16.5.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.5.0)** +- *2022.07.20*, **[v16.4.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.4.1)** +- *2022.07.11*, **[v16.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.4.0)** +- *2022.07.02*, **[v16.3.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.3.1)** +- *2022.07.01*, **[v16.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.3.0)** +- *2022.06.17*, **[v16.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.2.0)** +- *2022.05.12*, **[v16.1.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.1.1)** +- *2022.04.23*, **[v16.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.1.0)** +- *2022.04.22*, **[v16.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v16.0.1)** +- *2022.02.19*, **[v16.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v16.0.0)** +- *2022.01.20*, **[v15.9.15](//github.com/coderaiser/cloudcmd/releases/tag/v15.9.15)** +- *2022.01.13*, **[v15.9.14](//github.com/coderaiser/cloudcmd/releases/tag/v15.9.14)** +- *2021.12.23*, **[v15.9.13](//github.com/coderaiser/cloudcmd/releases/tag/v15.9.13)** +- *2021.12.16*, **[v15.9.12](//github.com/coderaiser/cloudcmd/releases/tag/v15.9.12)** +- *2021.12.09*, **[v15.9.11](//github.com/coderaiser/cloudcmd/releases/tag/v15.9.11)** +- *2021.12.04*, **[v15.9.10](//github.com/coderaiser/cloudcmd/releases/tag/v15.9.10)** +- *2021.11.22*, **[v15.9.9](//github.com/coderaiser/cloudcmd/releases/tag/v15.9.9)** +- *2021.02.03*, **[v15.6.0](//github.com/coderaiser/cloudcmd/releases/tag/v15.6.0)** +- *2021.02.02*, **[v15.5.2](//github.com/coderaiser/cloudcmd/releases/tag/v15.5.2)** +- *2021.01.31*, **[v15.5.1](//github.com/coderaiser/cloudcmd/releases/tag/v15.5.1)** +- *2021.01.30*, **[v15.5.0](//github.com/coderaiser/cloudcmd/releases/tag/v15.5.0)** +- *2021.01.26*, **[v15.4.4](//github.com/coderaiser/cloudcmd/releases/tag/v15.4.4)** +- *2021.01.25*, **[v15.4.3](//github.com/coderaiser/cloudcmd/releases/tag/v15.4.3)** +- *2021.01.21*, **[v15.4.2](//github.com/coderaiser/cloudcmd/releases/tag/v15.4.2)** +- *2021.01.20*, **[v15.4.1](//github.com/coderaiser/cloudcmd/releases/tag/v15.4.1)** +- *2021.01.19*, **[v15.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v15.4.0)** +- *2021.01.19*, **[v15.3.4](//github.com/coderaiser/cloudcmd/releases/tag/v15.3.4)** +- *2021.01.17*, **[v15.3.1](//github.com/coderaiser/cloudcmd/releases/tag/v15.3.1)** +- *2021.01.17*, **[v15.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v15.3.0)** +- *2021.01.16*, **[v15.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v15.2.0)** +- *2021.01.07*, **[v15.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v15.1.0)** +- *2021.01.05*, **[v15.0.4](//github.com/coderaiser/cloudcmd/releases/tag/v15.0.4)** +- *2020.01.05*, **[v15.0.3](//github.com/coderaiser/cloudcmd/releases/tag/v15.0.3)** +- *2020.12.31*, **[v15.0.2](//github.com/coderaiser/cloudcmd/releases/tag/v15.0.2)** +- *2020.12.30*, **[v15.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v15.0.1)** +- *2020.12.28*, **[v15.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v15.0.0)** +- *2020.08.21*, **[v14.9.3](//github.com/coderaiser/cloudcmd/releases/tag/v14.9.3)** +- *2020.08.19*, **[v14.9.2](//github.com/coderaiser/cloudcmd/releases/tag/v14.9.2)** +- *2020.08.16*, **[v14.9.1](//github.com/coderaiser/cloudcmd/releases/tag/v14.9.1)** +- *2020.08.14*, **[v14.9.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.9.0)** +- *2020.08.14*, **[v14.8.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.8.0)** +- *2020.08.11*, **[v14.7.2](//github.com/coderaiser/cloudcmd/releases/tag/v14.7.2)** +- *2020.08.11*, **[v14.7.1](//github.com/coderaiser/cloudcmd/releases/tag/v14.7.1)** +- *2020.08.10*, **[v14.7.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.7.0)** +- *2020.05.20*, **[v14.6.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.6.0)** +- *2020.05.06*, **[v14.5.1](//github.com/coderaiser/cloudcmd/releases/tag/v14.5.1)** +- *2020.05.04*, **[v14.5.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.5.0)** +- *2020.04.27*, **[v14.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.4.0)** +- *2020.04.13*, **[v14.3.10](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.10)** +- *2020.04.10*, **[v14.3.9](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.9)** +- *2020.04.04*, **[v14.3.8](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.8)** +- *2020.04.03*, **[v14.3.7](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.7)** +- *2020.03.31*, **[v14.3.6](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.6)** +- *2020.03.25*, **[v14.3.5](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.5)** +- *2020.03.03*, **[v14.3.4](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.4)** +- *2020.02.23*, **[v14.3.3](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.3)** +- *2020.02.21*, **[v14.3.2](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.2)** +- *2020.02.21*, **[v14.3.1](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.1)** +- *2020.01.29*, **[v14.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.3.0)** +- *2019.12.21*, **[v14.2.1](//github.com/coderaiser/cloudcmd/releases/tag/v14.2.1)** +- *2019.11.15*, **[v14.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.2.0)** +- *2019.10.16*, **[v14.1.2](//github.com/coderaiser/cloudcmd/releases/tag/v14.1.2)** +- *2019.10.09*, **[v14.1.1](//github.com/coderaiser/cloudcmd/releases/tag/v14.1.1)** +- *2019.10.02*, **[v14.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.1.0)** +- *2019.09.25*, **[v14.0.2](//github.com/coderaiser/cloudcmd/releases/tag/v14.0.2)** +- *2019.09.25*, **[v14.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v14.0.1)** +- *2019.09.22*, **[v14.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v14.0.0)** +- *2019.09.21*, **[v13.4.2](//github.com/coderaiser/cloudcmd/releases/tag/v13.4.2)** +- *2019.09.20*, **[v13.4.1](//github.com/coderaiser/cloudcmd/releases/tag/v13.4.1)** +- *2019.09.03*, **[v13.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v13.4.0)** +- *2019.08.28*, **[v13.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v13.3.0)** +- *2019.08.22*, **[v13.2.1](//github.com/coderaiser/cloudcmd/releases/tag/v13.2.1)** +- *2019.08.20*, **[v13.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v13.2.0)** +- *2019.08.16*, **[v13.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v13.1.0)** +- *2019.08.14*, **[v13.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v13.0.1)** +- *2019.08.14*, **[v13.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v13.0.0)** +- *2019.08.02*, **[v12.6.3](//github.com/coderaiser/cloudcmd/releases/tag/v12.6.3)** +- *2019.06.06*, **[v12.6.2](//github.com/coderaiser/cloudcmd/releases/tag/v12.6.2)** +- *2019.06.04*, **[v12.6.1](//github.com/coderaiser/cloudcmd/releases/tag/v12.6.1)** +- *2019.05.31*, **[v12.6.0](//github.com/coderaiser/cloudcmd/releases/tag/v12.6.0)** +- *2019.05.28*, **[v12.5.0](//github.com/coderaiser/cloudcmd/releases/tag/v12.5.0)** +- *2019.05.27*, **[v12.4.0](//github.com/coderaiser/cloudcmd/releases/tag/v12.4.0)** +- *2019.05.24*, **[v12.3.2](//github.com/coderaiser/cloudcmd/releases/tag/v12.3.2)** +- *2019.05.24*, **[v12.3.1](//github.com/coderaiser/cloudcmd/releases/tag/v12.3.1)** +- *2019.05.24*, **[v12.3.0](//github.com/coderaiser/cloudcmd/releases/tag/v12.3.0)** +- *2019.05.13*, **[v12.2.0](//github.com/coderaiser/cloudcmd/releases/tag/v12.2.0)** +- *2019.04.15*, **[v12.1.0](//github.com/coderaiser/cloudcmd/releases/tag/v12.1.0)** +- *2019.04.04*, **[v12.0.2](//github.com/coderaiser/cloudcmd/releases/tag/v12.0.2)** +- *2019.04.04*, **[v12.0.1](//github.com/coderaiser/cloudcmd/releases/tag/v12.0.1)** +- *2019.04.01*, **[v12.0.0](//github.com/coderaiser/cloudcmd/releases/tag/v12.0.0)** +- *2019.03.27*, **[v11.8.6](//github.com/coderaiser/cloudcmd/releases/tag/v11.8.6)** +- *2019.02.20*, **[v11.8.5](//github.com/coderaiser/cloudcmd/releases/tag/v11.8.5)** +- *2019.02.15*, **[v11.8.4](//github.com/coderaiser/cloudcmd/releases/tag/v11.8.4)** +- *2018.12.04*, **[v11.8.3](//github.com/coderaiser/cloudcmd/releases/tag/v11.8.3)** +- *2018.11.22*, **[v11.8.2](//github.com/coderaiser/cloudcmd/releases/tag/v11.8.2)** +- *2018.11.14*, **[v11.8.1](//github.com/coderaiser/cloudcmd/releases/tag/v11.8.1)** +- *2018.11.09*, **[v11.8.0](//github.com/coderaiser/cloudcmd/releases/tag/v11.8.0)** +- *2018.11.01*, **[v11.7.1](//github.com/coderaiser/cloudcmd/releases/tag/v11.7.1)** - *2018.10.25*, **[v11.7.0](//github.com/coderaiser/cloudcmd/releases/tag/v11.7.0)** - *2018.10.23*, **[v11.6.0](//github.com/coderaiser/cloudcmd/releases/tag/v11.6.0)** - *2018.10.23*, **[v11.5.4](//github.com/coderaiser/cloudcmd/releases/tag/v11.5.4)** @@ -1104,12 +1754,11 @@ Version history - *2012.07.11*, **[v0.1.1](//github.com/cloudcmd/archive/raw/master/cloudcmd-v0.1.1.zip)** - *2012.07.09*, **[v0.1.0](//github.com/cloudcmd/archive/raw/master/cloudcmd-v0.1.0.zip)** -Special Thanks ---------------- -- [Olena Zalitok](https://zalitok.github.io/ "Olena Zalitok") for **logo** and **favicon**. -- [TarZak](https://github.com/tarzak "TarZak") - - Russian and Ukrainian translations; - - config template and style; - - change order of directories and files; - - add ability do not hide path and header when files are scrolling; +## Special Thanks +- [Olena Zalitok](https://www.linkedin.com/in/ozalitok-ux-ui/ "Olena Zalitok") for **logo** and **favicon**. +- [TarZak](https://github.com/tarzak "TarZak") + - Russian and Ukrainian translations; + - config template and style; + - change order of directories and files; + - add ability to keep path and header when files are scrolling; diff --git a/LICENSE b/LICENSE index 37f32f80..a0d7436b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ (The MIT License) -Copyright (c) 2012-2018 Coderaiser +Copyright (c) 2012-2025 Coderaiser Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/README.md b/README.md index 255bf6be..dfe8d8c6 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,22 @@ -# Cloud Commander v11.7.0 [![Build Status][BuildStatusIMGURL]][BuildStatusURL] [![Now status][BuildAppveyorIMGURL]][BuildAppveyorURL] [![Codacy][CodacyIMG]][CodacyURL] [![Gitter][GitterIMGURL]][GitterURL] [![OpenCollective](https://opencollective.com/cloudcmd/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/cloudcmd/sponsors/badge.svg)](#sponsors) +# Cloud Commander v19.19.1 [![Build Status][BuildStatusIMGURL]][BuildStatusURL] [![Codacy][CodacyIMG]][CodacyURL] [![Gitter][GitterIMGURL]][GitterURL] [![Deploy on InstaPods][DeployInstaPodsIMG]][DeployInstaPodsURL] -### [Main][MainURL] [Blog][BlogURL] Live([Heroku][HerokuURL], [Now][NowURL]) +### [Main][MainURL] [Blog][BlogURL] [Support][SupportURL] [Demo][DemoURL] -[NPM_INFO_IMG]: https://nodei.co/npm/cloudcmd.png -[MainURL]: http://cloudcmd.io "Main" -[BlogURL]: http://blog.cloudcmd.io "Blog" -[HerokuURL]: https://cloudcmd.herokuapp.com/ "Heroku" -[NowURL]: https://cloudcmd.now.sh/ "Now" -[BuildStatusURL]: https://travis-ci.org/coderaiser/cloudcmd "Build Status" -[BuildStatusIMGURL]: https://img.shields.io/travis/coderaiser/cloudcmd.svg?style=flat-squere&longCache=true - -[BuildAppveyorURL]: https://ci.appveyor.com/project/coderaiser/cloudcmd -[BuildAppveyorIMGURL]: https://ci.appveyor.com/api/projects/status/tse6sc8dxrqxqehi?svg=true - -[CodacyURL]: https://www.codacy.com/app/coderaiser/cloudcmd -[CodacyIMG]: https://api.codacy.com/project/badge/Grade/ddda78be780549ce8754f8d47a8c0e36 - -[GitterURL]: https://gitter.im/cloudcmd/hello -[GitterIMGURL]: https://img.shields.io/gitter/room/coderaiser/cloudcmd.js.svg - -[DeployURL]: https://heroku.com/deploy?template=https://github.com/coderaiser/cloudcmd "Deploy" -[DeployIMG]: https://www.herokucdn.com/deploy/button.png +[MainURL]: https://cloudcmd.io "Main" +[BlogURL]: https://blog.cloudcmd.io "Blog" +[SupportURL]: https://patreon.com/coderaiser "Patreon" +[DemoURL]: https://cloudcmd-zdp6.onrender.com +[NPM_INFO_IMG]: https://nodei.co/npm/cloudcmd.png +[BuildStatusURL]: https://github.com/coderaiser/cloudcmd/actions/workflows/nodejs.yml "Build Status" +[BuildStatusIMGURL]: https://github.com/coderaiser/cloudcmd/actions/workflows/nodejs.yml/badge.svg +[CodacyURL]: https://www.codacy.com/app/coderaiser/cloudcmd +[CodacyIMG]: https://api.codacy.com/project/badge/Grade/ddda78be780549ce8754f8d47a8c0e36 +[GitterURL]: https://gitter.im/cloudcmd/hello +[GitterIMGURL]: https://img.shields.io/gitter/room/coderaiser/cloudcmd.js.svg +[DeployURL]: https://heroku.com/deploy?template=https://github.com/coderaiser/cloudcmd "Deploy" +[DeployIMG]: https://www.herokucdn.com/deploy/button.png +[DeployInstaPodsIMG]: https://img.shields.io/badge/deploy%20on-InstaPods-blue +[DeployInstaPodsURL]: https://app.instapods.com/dashboard/pods/create?app=cloudcmd&ref=cloudcmd **Cloud Commander** a file manager for the web with console and editor. @@ -31,6 +27,7 @@ ``` npm i cloudcmd -g ``` + ## Start For starting just type in console: @@ -48,8 +45,8 @@ Open url `http://localhost:8000` in browser. You will see something similar to this. ![View](https://cloudcmd.io/img/screen/view.png "View") - ## Deploy + `Cloud Commander` could be easily deployed to [Heroku][DeployURL]. [![Deploy][DeployIMG]][DeployURL] @@ -73,33 +70,31 @@ npm i cloudcmd express socket.io -S And create `index.js`: ```js -const http = require('http'); -const cloudcmd = require('cloudcmd'); -const io = require('socket.io'); -const app = require('express')(); +import http from 'node:http'; +import {cloudcmd} from 'cloudcmd'; +import {Server} from 'socket.io'; +import express from 'express'; + +const app = express(); const port = 1337; -const prefix = '/cloudcmd'; +const prefix = '/'; const server = http.createServer(app); -const socket = io.listen(server, { - path: `${prefix}/socket.io` +const socket = new Server(server, { + path: `${prefix}socket.io`, }); const config = { - prefix // base URL or function which returns base URL (optional) + name: 'cloudcmd :)', }; -const plugins = [ - __dirname + '/plugin.js' -]; - const filePicker = { data: { FilePicker: { key: 'key', - } - } + }, + }, }; // override option from json/modules.json @@ -107,22 +102,40 @@ const modules = { filePicker, }; -app.use(cloudcmd({ - socket, // used by Config, Edit (optional) and Console (required) - config, // config data (optional) - plugins, // optional +const { + createConfigManager, + configPath, +} = cloudcmd; + +const configManager = createConfigManager({ + configPath, +}); + +app.use(prefix, cloudcmd({ + socket, // used by Config, Edit (optional) and Console (required) + config, // config data (optional) modules, // optional + configManager, // optional })); server.listen(port); ``` -Docker ---------------- +## Docker + +The docker images are provided for multiple architectures and types. The following list shows all existing images: + +| Architecture | Type | +|----------------|--------------| +| amd64 | linux | +| arm64 (arm/v8) | linux | +| amd64 | linux-alpine | +| arm64 (arm/v8) | linux-alpine | + `Cloud Commander` could be used as a [docker container](https://hub.docker.com/r/coderaiser/cloudcmd/ "Docker container") this way: ```sh -docker run -t --rm -v ~:/root -v /:/mnt/fs -p 8000:8000 coderaiser/cloudcmd +docker run -it --rm -v ~:/root -v /:/mnt/fs -w=/root -p 8000:8000 coderaiser/cloudcmd ``` Config would be read from home directory, hosts root file system would be mount to `/mnt/fs`, @@ -148,84 +161,19 @@ When you create this file run: docker-compose up ``` -Get involved ---------------- +## Documentation + +More documentation you can find on https://cloudcmd.io/. + +## Get involved There is a lot ways to be involved in `Cloud Commander` development: +- support project on patreon: https://patreon.com/coderaiser; - if you find a bug or got idea to share [create an issue](https://github.com/coderaiser/cloudcmd/issues/new "Create issue"); - if you fixed a bug, typo or implemented new feature [create pull request](https://github.com/coderaiser/cloudcmd/compare "Create pull request"); - if you know languages you can help with [site translations](https://github.com/coderaiser/cloudcmd/wiki "Cloud Commander community wiki"); -## Backers -Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/cloudcmd#backer)] - -[![](https://opencollective.com/cloudcmd/backer/0/avatar.svg)](https://opencollective.com/cloudcmd/backer/0/website) -[![](https://opencollective.com/cloudcmd/backer/1/avatar.svg)](https://opencollective.com/cloudcmd/backer/1/website) -[![](https://opencollective.com/cloudcmd/backer/2/avatar.svg)](https://opencollective.com/cloudcmd/backer/2/website) -[![](https://opencollective.com/cloudcmd/backer/3/avatar.svg)](https://opencollective.com/cloudcmd/backer/3/website) -[![](https://opencollective.com/cloudcmd/backer/4/avatar.svg)](https://opencollective.com/cloudcmd/backer/4/website) -[![](https://opencollective.com/cloudcmd/backer/5/avatar.svg)](https://opencollective.com/cloudcmd/backer/5/website) -[![](https://opencollective.com/cloudcmd/backer/6/avatar.svg)](https://opencollective.com/cloudcmd/backer/6/website) -[![](https://opencollective.com/cloudcmd/backer/7/avatar.svg)](https://opencollective.com/cloudcmd/backer/7/website) -[![](https://opencollective.com/cloudcmd/backer/8/avatar.svg)](https://opencollective.com/cloudcmd/backer/8/website) -[![](https://opencollective.com/cloudcmd/backer/9/avatar.svg)](https://opencollective.com/cloudcmd/backer/9/website) -[![](https://opencollective.com/cloudcmd/backer/10/avatar.svg)](https://opencollective.com/cloudcmd/backer/10/website) -[![](https://opencollective.com/cloudcmd/backer/11/avatar.svg)](https://opencollective.com/cloudcmd/backer/11/website) -[![](https://opencollective.com/cloudcmd/backer/12/avatar.svg)](https://opencollective.com/cloudcmd/backer/12/website) -[![](https://opencollective.com/cloudcmd/backer/13/avatar.svg)](https://opencollective.com/cloudcmd/backer/13/website) -[![](https://opencollective.com/cloudcmd/backer/14/avatar.svg)](https://opencollective.com/cloudcmd/backer/14/website) -[![](https://opencollective.com/cloudcmd/backer/15/avatar.svg)](https://opencollective.com/cloudcmd/backer/15/website) -[![](https://opencollective.com/cloudcmd/backer/16/avatar.svg)](https://opencollective.com/cloudcmd/backer/16/website) -[![](https://opencollective.com/cloudcmd/backer/17/avatar.svg)](https://opencollective.com/cloudcmd/backer/17/website) -[![](https://opencollective.com/cloudcmd/backer/18/avatar.svg)](https://opencollective.com/cloudcmd/backer/18/website) -[![](https://opencollective.com/cloudcmd/backer/19/avatar.svg)](https://opencollective.com/cloudcmd/backer/19/website) -[![](https://opencollective.com/cloudcmd/backer/20/avatar.svg)](https://opencollective.com/cloudcmd/backer/20/website) -[![](https://opencollective.com/cloudcmd/backer/21/avatar.svg)](https://opencollective.com/cloudcmd/backer/21/website) -[![](https://opencollective.com/cloudcmd/backer/22/avatar.svg)](https://opencollective.com/cloudcmd/backer/22/website) -[![](https://opencollective.com/cloudcmd/backer/23/avatar.svg)](https://opencollective.com/cloudcmd/backer/23/website) -[![](https://opencollective.com/cloudcmd/backer/24/avatar.svg)](https://opencollective.com/cloudcmd/backer/24/website) -[![](https://opencollective.com/cloudcmd/backer/25/avatar.svg)](https://opencollective.com/cloudcmd/backer/25/website) -[![](https://opencollective.com/cloudcmd/backer/26/avatar.svg)](https://opencollective.com/cloudcmd/backer/26/website) -[![](https://opencollective.com/cloudcmd/backer/27/avatar.svg)](https://opencollective.com/cloudcmd/backer/27/website) -[![](https://opencollective.com/cloudcmd/backer/28/avatar.svg)](https://opencollective.com/cloudcmd/backer/28/website) -[![](https://opencollective.com/cloudcmd/backer/29/avatar.svg)](https://opencollective.com/cloudcmd/backer/29/website) - -## Sponsors -Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/cloudcmd#sponsor)] - -[![](https://opencollective.com/cloudcmd/sponsor/0/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/0/website) -[![](https://opencollective.com/cloudcmd/sponsor/1/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/1/website) -[![](https://opencollective.com/cloudcmd/sponsor/2/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/2/website) -[![](https://opencollective.com/cloudcmd/sponsor/3/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/3/website) -[![](https://opencollective.com/cloudcmd/sponsor/4/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/4/website) -[![](https://opencollective.com/cloudcmd/sponsor/5/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/5/website) -[![](https://opencollective.com/cloudcmd/sponsor/6/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/6/website) -[![](https://opencollective.com/cloudcmd/sponsor/7/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/7/website) -[![](https://opencollective.com/cloudcmd/sponsor/8/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/8/website) -[![](https://opencollective.com/cloudcmd/sponsor/9/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/9/website) -[![](https://opencollective.com/cloudcmd/sponsor/10/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/10/website) -[![](https://opencollective.com/cloudcmd/sponsor/11/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/11/website) -[![](https://opencollective.com/cloudcmd/sponsor/12/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/12/website) -[![](https://opencollective.com/cloudcmd/sponsor/13/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/13/website) -[![](https://opencollective.com/cloudcmd/sponsor/14/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/14/website) -[![](https://opencollective.com/cloudcmd/sponsor/15/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/15/website) -[![](https://opencollective.com/cloudcmd/sponsor/16/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/16/website) -[![](https://opencollective.com/cloudcmd/sponsor/17/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/17/website) -[![](https://opencollective.com/cloudcmd/sponsor/18/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/18/website) -[![](https://opencollective.com/cloudcmd/sponsor/19/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/19/website) -[![](https://opencollective.com/cloudcmd/sponsor/20/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/20/website) -[![](https://opencollective.com/cloudcmd/sponsor/21/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/21/website) -[![](https://opencollective.com/cloudcmd/sponsor/22/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/22/website) -[![](https://opencollective.com/cloudcmd/sponsor/23/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/23/website) -[![](https://opencollective.com/cloudcmd/sponsor/24/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/24/website) -[![](https://opencollective.com/cloudcmd/sponsor/25/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/25/website) -[![](https://opencollective.com/cloudcmd/sponsor/26/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/26/website) -[![](https://opencollective.com/cloudcmd/sponsor/27/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/27/website) -[![](https://opencollective.com/cloudcmd/sponsor/28/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/28/website) -[![](https://opencollective.com/cloudcmd/sponsor/29/avatar.svg)](https://opencollective.com/cloudcmd/sponsor/29/website) - ## License MIT - diff --git a/app.json b/app.json index 9072f44d..3dbe05a0 100644 --- a/app.json +++ b/app.json @@ -11,6 +11,7 @@ "folder", "orthodox" ], + "stack": "heroku-18", "env": { "NPM_CONFIG_PRODUCTION": { "description": "Keep false to install devDependencies and build frontend", @@ -62,11 +63,6 @@ "value": "", "required": false }, - "CLOUDCMD_CONFIG_DIALOG": { - "description": "show config dialog", - "value": "false", - "required": false - }, "CLOUDCMD_ONE_FILE_PANEL": { "description": "show one file panel", "value": "false", @@ -163,3 +159,4 @@ "required": false } } +} diff --git a/bin/cloudcmd.js b/bin/cloudcmd.js index e331e0d1..6ca6716c 100755 --- a/bin/cloudcmd.js +++ b/bin/cloudcmd.js @@ -1,31 +1,48 @@ #!/usr/bin/env node -'use strict'; +import process from 'node:process'; +import {promisify} from 'node:util'; +import {tryToCatch} from 'try-to-catch'; +import parse from 'yargs-parser'; +import exit from '../server/exit.js'; +import {createConfig, configPath} from '../server/config.js'; +import * as env from '../server/env.js'; +import prefixer from '../server/prefixer.js'; +import * as validate from '../server/validate.js'; +import Info from '../package.json' with { + type: 'json', +}; -const Info = require('../package'); -const DIR_SERVER = '../server/'; +process.on('unhandledRejection', exit); -const {promisify} = require('util'); -const wraptile = require('wraptile'); - -const exit = require(DIR_SERVER + 'exit'); -const config = require(DIR_SERVER + 'config'); -const env = require(DIR_SERVER + 'env'); -const prefixer = require(DIR_SERVER + '/prefixer'); - -const noop = () => {}; +const isUndefined = (a) => typeof a === 'undefined'; const choose = (a, b) => { - if (a === undefined) + if (isUndefined(a)) return b; return a; }; -process.on('unhandledRejection', exit); +const config = createConfig({ + configPath, +}); -const argv = process.argv; -const args = require('minimist')(argv.slice(2), { +const maybeRoot = (a) => { + if (a === '.') + return process.cwd(); + + return a; +}; + +const yargsOptions = { + configuration: { + 'strip-aliased': true, + 'strip-dashed': true, + }, + coerce: { + root: maybeRoot, + }, string: [ 'name', 'port', @@ -40,9 +57,12 @@ const args = require('minimist')(argv.slice(2), { 'terminal-path', 'terminal-command', 'columns', + 'menu', + 'theme', 'import-url', 'import-token', 'export-token', + 'dropbox-token', ], boolean: [ 'auth', @@ -51,9 +71,9 @@ const args = require('minimist')(argv.slice(2), { 'server', 'online', 'open', - 'progress', 'config-dialog', 'config-auth', + 'config-port', 'console', 'sync-console-path', 'contact', @@ -63,6 +83,7 @@ const args = require('minimist')(argv.slice(2), { 'confirm-copy', 'confirm-move', 'show-config', + 'show-dot-files', 'show-file-name', 'vim', 'keys-panel', @@ -71,62 +92,70 @@ const args = require('minimist')(argv.slice(2), { 'import', 'import-listen', 'log', + 'zip', + 'dropbox', ], default: { - server : true, - name : choose(env('name'), config('name')), - auth : choose(env.bool('auth'), config('auth')), - port : config('port'), - online : config('online'), - open : choose(env.bool('open'), config('open')), - editor : env('editor') || config('editor'), - packer : config('packer') || 'tar', - zip : config('zip'), - username : env('username') || config('username'), - root : choose(env('root'), config('root')), - prefix : config('prefix'), - progress : config('progress'), - console : choose(env.bool('console'), config('console')), - contact : choose(env.bool('contact'), config('contact')), - terminal : choose(env.bool('terminal'), config('terminal')), - columns : env('columns') || config('columns') || '', - vim : choose(env.bool('vim'), config('vim')), - log : config('log'), + 'server': true, + 'name': choose(env.parse('name'), config('name')), + 'auth': choose(env.bool('auth'), config('auth')), + 'port': config('port'), + 'online': config('online'), + 'open': choose(env.bool('open'), config('open')), + 'editor': env.parse('editor') || config('editor'), + 'menu': env.parse('menu') || config('menu'), + 'packer': config('packer') || 'tar', + 'zip': config('zip'), + 'username': env.parse('username') || config('username'), + 'root': choose(env.parse('root'), config('root')), + 'prefix': choose(env.parse('prefix'), config('prefix')), + 'console': choose(env.bool('console'), config('console')), + 'contact': choose(env.bool('contact'), config('contact')), + 'terminal': choose(env.bool('terminal'), config('terminal')), + 'columns': env.parse('columns') || config('columns') || '', + 'theme': env.parse('theme') || config('theme') || '', + 'vim': choose(env.bool('vim'), config('vim')), + 'log': choose(env.bool('log'), config('log')), - 'import-url': env('import_url') || config('importUrl'), + 'import-url': env.parse('import_url') || config('importUrl'), 'import-listen': choose(env.bool('import_listen'), config('importListen')), - import : choose(env.bool('import'), config('import')), - export : choose(env.bool('export'), config('export')), + 'import': choose(env.bool('import'), config('import')), + 'export': choose(env.bool('export'), config('export')), 'prefix-socket': config('prefixSocket'), + 'show-dot-files': choose(env.bool('show_dot_files'), config('showDotFiles')), 'show-file-name': choose(env.bool('show_file_name'), config('showFileName')), 'sync-console-path': choose(env.bool('sync_console_path'), config('syncConsolePath')), 'config-dialog': choose(env.bool('config_dialog'), config('configDialog')), 'config-auth': choose(env.bool('config_auth'), config('configAuth')), - 'terminal-path': env('terminal_path') || config('terminalPath'), - 'terminal-command': env('terminal_command') || config('terminalCommand'), + 'config-port': choose(env.bool('config_port'), config('configPort')), + 'terminal-path': env.parse('terminal_path') || config('terminalPath'), + 'terminal-command': env.parse('terminal_command') || config('terminalCommand'), 'terminal-auto-restart': choose(env.bool('terminal_auto_restart'), config('terminalAutoRestart')), 'one-file-panel': choose(env.bool('one_file_panel'), config('oneFilePanel')), 'confirm-copy': choose(env.bool('confirm_copy'), config('confirmCopy')), 'confirm-move': choose(env.bool('confirm_move'), config('confirmMove')), 'keys-panel': env.bool('keys_panel') || config('keysPanel'), - 'import-token': env('import_token') || config('importToken'), - 'export-token': env('export_token') || config('exportToken'), + 'import-token': env.parse('import_token') || config('importToken'), + 'export-token': env.parse('export_token') || config('exportToken'), + + 'dropbox': config('dropbox'), + 'dropbox-token': config('dropboxToken') || '', }, alias: { - v: 'version', - h: 'help', - p: 'password', - o: 'online', - u: 'username', - s: 'save', - a: 'auth', - c: 'config' + version: 'v', + help: 'h', + password: 'p', + online: 'o', + username: 'u', + save: 's', + auth: 'a', + config: 'c', }, - unknown: (cmd) => { - exit('\'%s\' is not a cloudcmd option. See \'cloudcmd --help\'.', cmd); - } -}); +}; + +const {argv} = process; +const args = parse(argv.slice(2), yargsOptions); if (args.version) version(); @@ -135,11 +164,23 @@ else if (args.help) else main(); -function main() { - if (args.repl) - repl(); +async function main() { + const {validateArgs} = await import('@putout/cli-validate-args'); + + const error = await validateArgs(args, [ + ...yargsOptions.boolean, + ...yargsOptions.string, + ]); + + if (error) + return exit(error); + + if (args.repl) + await repl(); + + validate.columns(args.columns); + validate.theme(args.theme); - checkUpdate(); port(args.port); config('name', args.name); @@ -147,74 +188,88 @@ function main() { config('online', args.online); config('open', args.open); config('username', args.username); - config('progress', args.progress); config('console', args.console); - config('syncConsolePath', args['sync-console-path']); - config('showFileName', args['show-file-name']); + config('syncConsolePath', args.syncConsolePath); + config('showDotFiles', args.showDotFiles); + config('showFileName', args.showFileName); config('contact', args.contact); config('terminal', args.terminal); - config('terminalPath', args['terminal-path']); - config('terminalCommand', args['terminal-command']); - config('terminalAutoRestart', args['terminal-auto-restart']); + config('terminalPath', args.terminalPath); + config('terminalCommand', args.terminalCommand); + config('terminalAutoRestart', args.terminalAutoRestart); config('editor', args.editor); + config('menu', args.menu); config('prefix', prefixer(args.prefix)); - // MAJOR: remove condition on v12 - config('prefixSocket', prefixer(args['prefix-socket']) || config('prefix')); - config('root', args.root); + config('prefixSocket', prefixer(args.prefixSocket)); + config('root', args.root || '/'); config('vim', args.vim); + config('theme', args.theme); config('columns', args.columns); config('log', args.log); - config('confirmCopy', args['confirm-copy']); - config('confirmMove', args['confirm-move']); - config('oneFilePanel', args['one-file-panel']); - config('configDialog', args['config-dialog']); - config('configAuth', args['config-auth']); - config('keysPanel', args['keys-panel']); + config('confirmCopy', args.confirmCopy); + config('confirmMove', args.confirmMove); + config('oneFilePanel', args.oneFilePanel); + config('configDialog', args.configDialog); + config('configAuth', args.configAuth); + config('configPort', args.configPort); + config('keysPanel', args.keysPanel); config('export', args.export); - config('exportToken', args['export-token']); + config('exportToken', args.exportToken); config('import', args.import); - config('importToken', args['import-token']); - config('importListen', args['import-listen']); - config('importUrl', args['import-url']); + config('importToken', args.importToken); + config('importListen', args.importListen); + config('importUrl', args.importUrl); - readConfig(args.config); + config('dropbox', args.dropbox); + config('dropboxToken', args.dropboxToken); + + await readConfig(args.config); const options = { - root: args.root || '/', // --no-root - editor: args.editor, - packer: args.packer, - prefix: args.prefix, - prefixSocket: args['prefix-socket'] || args.prefix, // MAJOR: remove condition on v12 - columns: args.columns, + root: config('root'), + editor: config('editor'), + packer: config('packer'), + prefix: config('prefix'), + prefixSocket: config('prefixSocket'), + columns: config('columns'), + theme: config('theme'), + menu: config('menu'), }; - const password = env('password') || args.password; + const password = env.parse('password') || args.password; if (password) - config('password', getPassword(password)); + config('password', await getPassword(password)); - validateRoot(options.root); + validateRoot(options.root, config); - if (args['show-config']) - showConfig(); + if (args.showConfig) + await showConfig(); - const startWraped = wraptile(start, options); - const distribute = require('../server/distribute'); - const importConfig = promisify(distribute.import); - const caller = (fn) => fn(); + const {distributeImport} = await import('../server/distribute/import.js'); + const importConfig = promisify(distributeImport); - importConfig() - .then(args.save ? caller(config.save) : noop) - .then(startWraped(options)); + await start(options, config); + + if (args.save) + config.write(); + + await tryToCatch(checkUpdate); + await importConfig(config); } -function validateRoot(root) { - const validate = require(DIR_SERVER + 'validate'); - validate.root(root, console.log); +function validateRoot(root, config) { + validate.root(root, config); + + if (root === '/') + return; + + if (config('log')) + console.log(`root: ${root}`); } -function getPassword(password) { - const criton = require('criton'); +async function getPassword(password) { + const {default: criton} = await import('criton'); return criton(password, config('algo')); } @@ -222,14 +277,12 @@ function version() { console.log('v' + Info.version); } -function start(config) { - const SERVER = DIR_SERVER + 'server'; - +async function start(options, config) { if (!args.server) return; - const server = require(SERVER); - server(config); + const {default: server} = await import('../server/server.js'); + server(options, config); } function port(arg) { @@ -241,38 +294,38 @@ function port(arg) { exit('cloudcmd --port: should be a number'); } -function showConfig() { - const show = require('../server/show-config'); - const data = show(config('*')); +async function showConfig() { + const {showConfig} = await import('../server/show-config.js'); + const data = showConfig(config('*')); console.log(data); } -function readConfig(name) { +async function readConfig(name) { if (!name) return; - const fs = require('fs'); - const tryCatch = require('try-catch'); - const jju = require('jju'); - const forEachKey = require('for-each-key'); + const {default: forEachKey} = await import('for-each-key'); - const readjsonSync = (name) => jju.parse(fs.readFileSync(name, 'utf8'), { - mode: 'json' + const data = await import(name, { + with: { + type: 'json', + }, }); - const [error, data] = tryCatch(readjsonSync, name); - - if (error) - return exit(error.message); - forEachKey(config, data); } -function help() { - const bin = require('../json/help'); - const forEachKey = require('for-each-key'); - const currify = require('currify'); +async function help() { + const {default: bin} = await import('../json/help.json', { + with: { + type: 'json', + }, + }); + + const {default: forEachKey} = await import('for-each-key'); + const {default: currify} = await import('currify'); + const usage = 'Usage: cloudcmd [options]'; const url = Info.homepage; const log = currify((a, b, c) => console.log(a, b, c)); @@ -283,31 +336,27 @@ function help() { console.log('\nGeneral help using Cloud Commander: <%s>', url); } -function repl() { +async function repl() { console.log('REPL mode enabled (telnet localhost 1337)'); - require(DIR_SERVER + 'repl'); + await import('../server/repl.js'); } -function checkUpdate() { - const load = require('package-json'); +async function checkUpdate() { + const {default: load} = await import('package-json'); + const {version} = await load(Info.name, 'latest'); - load(Info.name, 'latest') - .then(showUpdateInfo) - .catch(noop); + await showUpdateInfo(version); } -function showUpdateInfo(data) { - const version = data.version; - +async function showUpdateInfo(version) { if (version === Info.version) return; - const chalk = require('chalk'); + const {default: chalk} = await import('chalk'); - const latestVersion = chalk.green.bold('v' + version); + const latestVersion = chalk.green.bold(`v${version}`); const latest = `update available: ${latestVersion}`; const current = chalk.dim(`(current: v${Info.version})`); console.log('%s %s', latest, current); } - diff --git a/bin/cloudcmd.spec.js b/bin/cloudcmd.spec.js new file mode 100644 index 00000000..d09541b9 --- /dev/null +++ b/bin/cloudcmd.spec.js @@ -0,0 +1,26 @@ +import {spawnSync} from 'node:child_process'; +import {test} from 'supertape'; +import info from '../package.json' with { + type: 'json', +}; + +const cliPath = new URL('cloudcmd.js', import.meta.url).pathname; + +test('cloudcmd: bin: cli: -h', (t) => { + const {stdout} = spawnSync(cliPath, ['-h'], { + encoding: 'utf8', + }); + + t.match(stdout, `Options`); + t.end(); +}); + +test('cloudcmd: bin: cli: -v', (t) => { + const {version} = info; + const {stdout} = spawnSync(cliPath, ['-v'], { + encoding: 'utf8', + }); + + t.match(stdout, `v${version}`); + t.end(); +}); diff --git a/bin/release.js b/bin/release.js index 60a2b4ec..86e1d714 100755 --- a/bin/release.js +++ b/bin/release.js @@ -1,67 +1,72 @@ #!/usr/bin/env node -'use strict'; +import {promisify} from 'node:util'; +import process from 'node:process'; +import {tryToCatch} from 'try-to-catch'; +import minor from 'minor'; +import _place from 'place'; +import {rendy} from 'rendy'; +import shortdate from 'shortdate'; +import Info from '../package.json' with { + type: 'json', +}; -const DIR = '../'; -const Info = require(DIR + 'package'); +const place = promisify(_place); -const minor = require('minor'); -const place = require('place'); -const rendy = require('rendy'); -const shortdate = require('shortdate'); +await main(); -const ERROR = Error('ERROR: version is missing. release --patch|--minor|--major'); - -main((error) => { +async function main() { + const history = '## Version history\n\n'; + const link = '//github.com/coderaiser/cloudcmd/releases/tag/'; + + const template = '- ' + + '*{{ date }}*, ' + + '**[v{{ version }}]' + + '(' + + link + + 'v{{ version }})**\n'; + + const {version} = Info; + + const [error, versionNew] = await tryToCatch(cl); + if (error) - console.error(error.message); -}); - -function main(callback) { - const history = 'Version history\n---------------\n'; - const link = '//github.com/coderaiser/cloudcmd/releases/tag/'; - const template = '- *{{ date }}*, ' + - '**[v{{ version }}]' + - '(' + link + 'v{{ version }})**\n'; + return console.error(error); - const version = Info.version; + await replaceVersion('README.md', version, versionNew); + await replaceVersion('HELP.md', version, versionNew); - cl((error, versionNew) => { - if (error) - return callback(error); - - replaceVersion('README.md', version, versionNew, callback); - replaceVersion('HELP.md', version, versionNew, function() { - const historyNew = history + rendy(template, { - date : shortdate(), - version : versionNew - }); - - replaceVersion('HELP.md', history, historyNew, callback); + const historyNew = history + + rendy(template, { + date: shortdate(), + version: versionNew, }); - }); + + await replaceVersion('HELP.md', history, historyNew); } -function replaceVersion(name, version, versionNew, callback) { - place(name, version, versionNew, (error) => { - if (error) - return callback(error); - - callback(null, 'done: ' + name); - }); +async function replaceVersion(name, version, versionNew) { + const [error] = await tryToCatch(place, name, version, versionNew); + + if (error) + return console.error(error); + + console.log(`done: ${name}`); } -function cl(callback) { - const argv = process.argv; +async function cl() { + const {argv} = process; const length = argv.length - 1; const last = process.argv[length]; const regExp = /^--(major|minor|patch)$/; const [, match] = last.match(regExp) || []; - if (!regExp.test(last)) - return callback(ERROR); + console.log(last); - callback(null, getVersionNew(last, match)); + if (!regExp.test(last)) + throw Error('ERROR: version is missing. release --patch|--minor|--major'); + + return getVersionNew(last, match); } function getVersionNew(last, match) { @@ -70,4 +75,3 @@ function getVersionNew(last, match) { return last.substr(3); } - diff --git a/client/client.js b/client/client.js index 4d5966e2..a0e3cb07 100644 --- a/client/client.js +++ b/client/client.js @@ -1,76 +1,59 @@ -'use strict'; - -/* global DOM */ - -const Emitify = require('emitify/legacy'); -const inherits = require('inherits'); -const rendy = require('rendy/legacy'); -const exec = require('execon'); -const load = require('load.js'); - -const {kebabToCamelCase} = require('../common/util'); -const isDev = process.env.NODE_ENV === 'development'; - -const Images = require('./dom/images'); -const { - unregisterSW, -} = require('./sw/register'); - -const jonny = require('jonny/legacy'); -const currify = require('currify/legacy'); - -const bind = (f, ...a) => () => f(...a); -const noop = () => {}; - -const { +import process from 'node:process'; +import Emitify from 'emitify'; +import inherits from 'inherits'; +import {rendy} from 'rendy'; +import load from 'load.js'; +import {tryToCatch} from 'try-to-catch'; +import {addSlashToEnd} from 'format-io'; +import pascalCase from 'just-pascal-case'; +import currify from 'currify'; +import { apiURL, formatMsg, buildFromJSON, -} = require('../common/cloudfunc'); +} from '#common/cloudfunc'; +import * as Images from '#dom/images'; +import {unregisterSW} from './sw/register.js'; +import {getJsonFromFileTable} from './get-json-from-file-table.js'; +import {Key} from './key/index.js'; +import {loadModule} from './load-module.js'; -const loadModule = require('./load-module'); +const noJS = (a) => a.replace(/.js$/, ''); + +const isDev = process.env.NODE_ENV === 'development'; inherits(CloudCmdProto, Emitify); -module.exports = new CloudCmdProto(DOM); +export const createCloudCmd = ({DOM, Listeners}) => { + return new CloudCmdProto({ + DOM, + Listeners, + }); +}; load.addErrorListener((e, src) => { const msg = `file ${src} could not be loaded`; Images.show.error(msg); }); -function CloudCmdProto(DOM) { - let Key; - let Listeners; - - const log = (...a) => { - if (!isDev ) - return; - - console.log(...a); - }; - +function CloudCmdProto({DOM, Listeners}) { Emitify.call(this); const CloudCmd = this; const Info = DOM.CurrentInfo; - const Storage = DOM.Storage; - const Files = DOM.Files; - this.log = log; - this.PREFIX = ''; + const {Storage, Files} = DOM; + + this.log = () => { + if (!isDev) + return; + }; + this.prefix = ''; this.prefixSocket = ''; - this.PREFIX_URL = ''; - this.DIRCLIENT = '/dist/'; - this.DIRCLIENT_MODULES = this.DIRCLIENT + 'modules/'; - - this.MIN_ONE_PANEL_WIDTH = 1155; - this.HOST = location.origin || - location.protocol + '//' + location.host; - - const TITLE = 'Cloud Commander'; - this.TITLE = TITLE; + this.prefixURL = ''; + this.MIN_ONE_PANEL_WIDTH = DOM.getCSSVar('min-one-panel-width'); + this.HOST = location.origin || location.protocol + '//' + location.host; this.sort = { left: 'name', right: 'name', @@ -81,46 +64,38 @@ function CloudCmdProto(DOM) { right: 'asc', }; - /** - * Функция привязываеться ко всем ссылкам и - * загружает содержимое каталогов - * - * @param params - { - * paramLink - ссылка - * needRefresh - необходимость обязательной загрузки данных с сервера - * panel - * } - * @param callback - */ - this.loadDir = (params, callback) => { - const p = params; - - const refresh = p.isRefresh; - const panel = p.panel; - const history = p.history; - const noCurrent = p.noCurrent; - const currentName = p.currentName; + this.changeDir = async (path, overrides = {}) => { + const { + isRefresh, + panel, + history = true, + noCurrent, + currentName, + } = overrides; + const refresh = isRefresh; let panelChanged; - if (!noCurrent) - if (panel && panel !== Info.panel) { - DOM.changePanel(); - panelChanged = true; - } + + if (!noCurrent && panel && panel !== Info.panel) { + DOM.changePanel(); + panelChanged = true; + } let imgPosition; + if (panelChanged || refresh || !history) imgPosition = 'top'; Images.show.load(imgPosition, panel); /* загружаем содержимое каталога */ - ajaxLoad(p.path, { + await ajaxLoad(addSlashToEnd(path), { refresh, history, noCurrent, currentName, - }, panel, callback); + showDotFiles: CloudCmd.config('showDotFiles'), + }, panel); }; /** @@ -128,23 +103,12 @@ function CloudCmdProto(DOM) { * выполняет весь функционал по * инициализации */ - this.init = (prefix, config) => { - const func = bind(exec.series, [ - initModules, - baseInit, - loadPlugins, - loadStyle, - exec.with(CloudCmd.route, location.hash), - ], noop); - - const funcBefore = (callback) => { - const src = prefix + CloudCmd.DIRCLIENT_MODULES + 'polyfill.js'; - load.js(src, callback); - }; - - CloudCmd.PREFIX = prefix; - CloudCmd.PREFIX_URL = prefix + apiURL; + this.init = async (prefix, config) => { + CloudCmd.prefix = prefix; + CloudCmd.prefixURL = `${prefix}${apiURL}`; CloudCmd.prefixSocket = config.prefixSocket; + CloudCmd.DIR_DIST = `${prefix}/dist`; + CloudCmd.DIR_MODULES = `${this.DIR_DIST}/modules`; CloudCmd.config = (key) => config[key]; CloudCmd.config.if = currify((key, fn, a) => config[key] && fn(a)); @@ -153,7 +117,6 @@ function CloudCmdProto(DOM) { * should be called from config.js only * after successful update on server */ - if (key === 'password') return; @@ -163,23 +126,15 @@ function CloudCmdProto(DOM) { if (config.oneFilePanel) CloudCmd.MIN_ONE_PANEL_WIDTH = Infinity; - exec.if(document.body.scrollIntoViewIfNeeded, func, funcBefore); + if (!document.body.scrollIntoViewIfNeeded) + await load.js(`${CloudCmd.DIR_MODULES}/polyfill.js`); + + await initModules(); + await baseInit(); + + CloudCmd.route(location.hash); }; - function loadStyle(callback) { - const prefix = CloudCmd.PREFIX; - const name = prefix + '/dist/cloudcmd.common.css'; - - load.css(name, callback); - } - - function loadPlugins(callback) { - const prefix = CloudCmd.PREFIX; - const plugins = prefix + '/plugins.js'; - - load.js(plugins, callback); - } - this.route = (path) => { const query = path.split('/'); @@ -187,14 +142,15 @@ function CloudCmdProto(DOM) { return; const [kebabModule] = query; - const module = kebabToCamelCase(kebabModule.slice(1)); + const module = noJS(pascalCase(kebabModule.slice(1))); - const file = query[1]; + const [, file] = query; const current = DOM.getCurrentByName(file); if (file && !current) { const msg = formatMsg('set current file', file, 'error'); CloudCmd.log(msg); + return; } @@ -202,76 +158,71 @@ function CloudCmdProto(DOM) { CloudCmd.execFromModule(module, 'show'); }; - this.logOut = () => { - const url = CloudCmd.PREFIX + '/logout'; + this.logOut = async () => { + const url = CloudCmd.prefix + '/logout'; const error = () => document.location.reload(); + const {prefix} = CloudCmd; - DOM.Storage.clear(); - unregisterSW(); + await DOM.Storage.clear(); + unregisterSW(prefix); DOM.load.ajax({ url, error, }); }; - function initModules(callback) { - exec.if(CloudCmd.Key, () => { - Key = new CloudCmd.Key(); - CloudCmd.Key = Key; - Key.bind(); - }, (func) => { - /* привязываем клавиши к функциям */ - const path = 'key.js'; - - loadModule({ - path, - func - }); - }); + const initModules = async () => { + CloudCmd.Key = Key; + CloudCmd.Key.bind(); - Files.get('modules', (error, modules) => { - const showLoad = Images.show.load; - - const doBefore = { - 'edit': showLoad, - 'menu': showLoad, - }; - - const load = (name, path, dobefore) => { - loadModule({ - name, - path, - dobefore, - }); - }; - - if (!modules) - modules = []; - - modules.local.forEach((module) => { - load(null, module, doBefore[module]); + const [, modules] = await tryToCatch(Files.get, 'modules'); + const showLoad = Images.show.load; + + const doBefore = { + edit: showLoad, + menu: showLoad, + }; + + const load = (name, path, dobefore) => { + loadModule({ + name, + path, + dobefore, }); - - callback(); - }); + }; + + if (!modules) + return; + + for (const module of modules.local) { + load(null, module, doBefore[module]); + } + }; + + async function saveCurrentName(currentName) { + await Storage.set('current-name', currentName); } - function baseInit(callback) { + async function baseInit() { const files = DOM.getFiles(); CloudCmd.on('current-file', DOM.updateCurrentInfo); + CloudCmd.on('current-name', saveCurrentName); + + const name = await Storage.get('current-name'); + const currentFile = name && DOM.getCurrentByName(name) || files[0]; /* выделяем строку с первым файлом */ if (files) - DOM.setCurrentFile(files[0], { + DOM.setCurrentFile(currentFile, { // when hash is present // it should be handled with this.route // overwre otherwise - history: !location.hash + history: !location.hash, }); const dirPath = DOM.getCurrentDirPath(); - Listeners = CloudCmd.Listeners; + Listeners.init(); const panels = getPanels(); @@ -280,15 +231,12 @@ function CloudCmdProto(DOM) { Listeners.initKeysPanel(); if (!CloudCmd.config('dirStorage')) - return callback(); + return; - Storage.get(dirPath, (error, data) => { - if (!data) { - data = getJSONfromFileTable(); - Storage.set(dirPath, data); - } - callback(); - }); + const data = await Storage.get(dirPath); + + if (!data) + await Storage.setJson(dirPath, getJsonFromFileTable()); } function getPanels() { @@ -310,28 +258,22 @@ function CloudCmdProto(DOM) { func(...args); }; - this.refresh = (options = {}, callback) => { - if (!callback && typeof options === 'function') { - callback = options; - options = {}; - } - - const panel = options.panel || Info.panel; + this.refresh = async (options = {}) => { + const {panel = Info.panel, currentName} = options; + const path = DOM.getCurrentDirPath(panel); const isRefresh = true; const history = false; - const noCurrent = options ? options.noCurrent : false; - const currentName = options.currentName; + const noCurrent = options?.noCurrent; - CloudCmd.loadDir({ - path, + await CloudCmd.changeDir(path, { isRefresh, history, panel, noCurrent, currentName, - }, callback); + }); }; /** @@ -341,176 +283,132 @@ function CloudCmdProto(DOM) { * @param options * { refresh, history } - необходимость обновить данные о каталоге * @param panel - * @param callback * */ - function ajaxLoad(path, options, panel, callback) { - const create = (error, json) => { - const RESTful = DOM.RESTful; - const name = options.currentName || Info.name; - const obj = jonny.parse(json); - const isRefresh = options.refresh; - const noCurrent = options.noCurrent; - - if (!isRefresh && json) - return createFileTable(obj, panel, options, callback); - - const position = DOM.getPanelPosition(panel); - const sort = CloudCmd.sort[position]; - const order = CloudCmd.order[position]; - - const query = rendy('?sort={{ sort }}&order={{ order }}', { - sort, - order, - }); - - RESTful.read(path + query, 'json', (error, obj) => { - if (error) - return; - - options.sort = sort; - options.order = order; - - createFileTable(obj, panel, options, () => { - if (isRefresh && !noCurrent) - DOM.setCurrentByName(name); - - exec(callback); - }); - - if (!CloudCmd.config('dirStorage')) - return; - - Storage.set(path, obj); - }); - }; + async function ajaxLoad(path, options = {}, panel) { + const {RESTful} = DOM; - if (!options) - options = {}; + CloudCmd.log(`reading dir: "${path}";`); - CloudCmd.log('reading dir: "' + path + '";'); + const dirStorage = CloudCmd.config('dirStorage'); + const json = dirStorage && await Storage.getJson(path); + + const name = options.currentName || Info.name; + const {noCurrent, refresh} = options; + + if (!refresh && json) + return await createFileTable(json, panel, options); + + const position = DOM.getPanelPosition(panel); + const sort = CloudCmd.sort[position]; + const order = CloudCmd.order[position]; + + const query = rendy('?sort={{ sort }}&order={{ order }}', { + sort, + order, + }); + + const [, newObj] = await RESTful.read(path + query, 'json'); + + if (!newObj) + // that's OK, error handled by RESTful + return; + + options.sort = sort; + options.order = order; + + await createFileTable(newObj, panel, options); + + if (refresh && !noCurrent) + DOM.setCurrentByName(name); if (!CloudCmd.config('dirStorage')) - return create(); + return; - Storage.get(path, create); + Storage.setJson(path, newObj); } /** * Функция строит файловую таблицу - * @param json - данные о файлах + * @param data - данные о файлах * @param panelParam - * @param history - * @param callback + * @param options - history, noCurrent, showDotFiles */ - function createFileTable(json, panelParam, options, callback) { + async function createFileTable(data, panelParam, options) { const { history, noCurrent, + showDotFiles, } = options; - const names = ['file', 'path', 'link', 'pathLink']; + const names = [ + 'file', + 'path', + 'link', + 'pathLink', + ]; - Files.get(names, (error, templFile, templPath, templLink, templPathLink) => { - const Dialog = DOM.Dialog; - const panel = panelParam || DOM.getPanel(); + const [error, [ + file, + path, + link, + pathLink, + ]] = await tryToCatch(Files.get, names); + + if (error) + return DOM.Dialog.alert(error.responseText); + + const panel = panelParam || DOM.getPanel(); + const {prefix} = CloudCmd; + + const {dir, name} = Info; + + const {childNodes} = panel; + let i = childNodes.length; + + while (i--) + panel.removeChild(panel.lastChild); + + panel.innerHTML = buildFromJSON({ + sort: options.sort, + order: options.order, + data, + id: panel.id, + prefix, + showDotFiles, + template: { + file, + path, + pathLink, + link, + }, + }); + + Listeners.setOnPanel(panel); + + if (!noCurrent) { + let current; - const { - dir, - name, - } = Info; + if (name === '..' && dir !== '/') + current = DOM.getCurrentByName(dir); - if (error) - return Dialog.alert(TITLE, error.responseText); + if (!current) + [current] = DOM.getFiles(panel); - const childNodes = panel.childNodes; - let i = childNodes.length; - - while (i--) - panel.removeChild(panel.lastChild); - - panel.innerHTML = buildFromJSON({ - sort : options.sort, - order : options.order, - data : json, - id : panel.id, - prefix : CloudCmd.PREFIX, - template : { - file : templFile, - path : templPath, - pathLink : templPathLink, - link : templLink - } + DOM.setCurrentFile(current, { + history, }); - Listeners.setOnPanel(panel); - - if (!noCurrent) { - let current; - - if (name === '..' && dir !== '/') - current = DOM.getCurrentByName(dir); - - if (!current) - current = DOM.getFiles(panel)[0]; - - DOM.setCurrentFile(current, { - history, - }); - - CloudCmd.emit('active-dir', Info.dirPath); - } - - exec(callback); - }); + CloudCmd.emit('active-dir', Info.dirPath); + } } - /** - * Функция генерирует JSON из html-таблицы файлов и - * используеться при первом заходе в корень - */ - function getJSONfromFileTable() { - const path = DOM.getCurrentDirPath(); - const infoFiles = Info.files || []; - - const notParent = (current) => { - const name = DOM.getCurrentName(current); - return name !== '..'; - }; - - const parse = (current) => { - const name = DOM.getCurrentName(current); - const size = DOM.getCurrentSize(current); - const owner = DOM.getCurrentOwner(current); - const mode = DOM.getCurrentMode(current); - const date = DOM.getCurrentDate(current); - - return { - name, - size, - mode, - owner, - date, - }; - }; - - const files = infoFiles - .filter(notParent) - .map(parse); - - const fileTable = { - path, - files, - }; - - return fileTable; - } - - this.goToParentDir = () => { - const dir = Info.dir; + this.goToParentDir = async () => { const { + dir, dirPath, parentDirPath, + panel, } = Info; if (dirPath === parentDirPath) @@ -518,15 +416,13 @@ function CloudCmdProto(DOM) { const path = parentDirPath; - CloudCmd.loadDir({path}, () => { - const {panel} = Info; - const current = DOM.getCurrentByName(dir); - const first = DOM.getFiles(panel)[0]; - - DOM.setCurrentFile(current || first, { - history - }); + await CloudCmd.changeDir(path); + + const current = DOM.getCurrentByName(dir); + const [first] = DOM.getFiles(panel); + + DOM.setCurrentFile(current || first, { + history, }); }; } - diff --git a/client/cloudcmd.js b/client/cloudcmd.js index be53ed08..f2416fd4 100644 --- a/client/cloudcmd.js +++ b/client/cloudcmd.js @@ -1,46 +1,49 @@ -'use strict'; +import '../css/main.css'; +import process from 'node:process'; +import wraptile from 'wraptile'; +import load from 'load.js'; +import * as Util from '#common/util'; +import * as CloudFunc from '#common/cloudfunc'; +import DOM from '#dom'; +import {registerSW, listenSW} from './sw/register.js'; +import {initSortPanel, sortPanel} from './sort.js'; +import {createCloudCmd} from './client.js'; +import * as Listeners from './listeners/index.js'; -require('../css/main.css'); -require('../css/nojs.css'); -require('../css/columns/name-size-date.css'); -require('../css/columns/name-size.css'); +const isDev = process.env.NODE_ENV === 'development'; -const {promisify} = require('es6-promisify'); -const wraptile = require('wraptile/legacy'); -const load = require('load.js'); +export default init; -const { - registerSW, -} = require('./sw/register'); +globalThis.CloudCmd = init; -// prevent additional loading of emitify -window.Emitify = require('emitify/legacy'); - -module.exports = window.CloudCmd = (config) => { - window.Promise = window.Promise || require('es6-promise'); - window.Util = require('../common/util'); - window.CloudFunc = require('../common/cloudfunc'); +async function init(config) { + globalThis.CloudCmd = createCloudCmd({ + DOM, + Listeners, + }); + globalThis.DOM = DOM; + globalThis.Util = Util; + globalThis.CloudFunc = CloudFunc; - const DOM = require('./dom'); - - window.DOM = DOM; - window.CloudCmd = require('./client'); - - register(config); - - require('./listeners'); - require('./key'); - require('./sort'); + await register(config); + initSortPanel(); + globalThis.CloudCmd.sortPanel = sortPanel; const prefix = getPrefix(config.prefix); - window.CloudCmd.init(prefix, config); -}; + globalThis.CloudCmd.init(prefix, config); + + if (globalThis.CloudCmd.config('menu') === 'aleman') + setTimeout(() => { + import('https://esm.sh/@putout/processor-html'); + import('https://esm.sh/@putout/bundle@5.5'); + }, 100); +} function getPrefix(prefix) { if (!prefix) return ''; - + if (!prefix.indexOf('/')) return prefix; @@ -48,22 +51,24 @@ function getPrefix(prefix) { } const onUpdateFound = wraptile(async (config) => { - const {DOM} = window; - const prefix = getPrefix(config.prefix); - const js = promisify(load.js); + if (isDev) + return; - await js(`${prefix}/dist/cloudcmd.common.js`); - await js(`${prefix}/dist/cloudcmd.js`); + const {DOM} = globalThis; + const prefix = getPrefix(config.prefix); + + await load.js(`${prefix}/dist/cloudcmd.common.js`); + await load.js(`${prefix}/dist/cloudcmd.js`); console.log('cloudcmd: sw: updated'); DOM.Events.removeAll(); - window.CloudCmd(config); + globalThis.CloudCmd(config); }); async function register(config) { const {prefix} = config; const sw = await registerSW(prefix); - sw.addEventListener('updatefound', onUpdateFound(config)); + listenSW(sw, 'updatefound', onUpdateFound(config)); } diff --git a/client/dom/buffer.js b/client/dom/buffer.js index 39ce58ae..c6d20ccd 100644 --- a/client/dom/buffer.js +++ b/client/dom/buffer.js @@ -1,133 +1,124 @@ -'use strict'; +/* global CloudCmd*/ +import * as Storage from '#dom/storage'; +import tryToPromiseAll from '../../common/try-to-promise-all.js'; -/* global CloudCmd */ +const CLASS = 'cut-file'; +const COPY = 'copy'; +const CUT = 'cut'; -const jonny = require('jonny/legacy'); -const exec = require('execon'); - -const Storage = require('./storage'); -const DOM = require('./'); - -module.exports = new BufferProto(); - -function BufferProto() { - const Info = DOM.CurrentInfo; - const CLASS = 'cut-file'; - const COPY = 'copy'; - const CUT = 'cut'; - const TITLE = 'Buffer'; - - const Buffer = { - cut : callIfEnabled.bind(null, cut), - copy : callIfEnabled.bind(null, copy), - clear : callIfEnabled.bind(null, clear), - paste : callIfEnabled.bind(null, paste) - }; - - function showMessage(msg) { - DOM.Dialog.alert(TITLE, msg); - } - - function getNames() { - const files = DOM.getActiveFiles(); - const names = DOM.getFilenames(files); - - return names; - } - - function addCutClass() { - const files = DOM.getActiveFiles(); - - files.forEach((element) => { - element.classList.add(CLASS); - }); - } - - function rmCutClass() { - const files = DOM.getByClassAll(CLASS); - - [...files].forEach((element) => { - element.classList.remove(CLASS); - }); - } - - function callIfEnabled(callback) { - const is = CloudCmd.config('buffer'); - - if (is) - return callback(); - - showMessage('Buffer disabled in config!'); - } - - function copy() { - const names = getNames(); - const from = Info.dirPath; - - clear(); - - if (!names.length) - return; - - Storage.remove(CUT) - .set(COPY, { - from, - names, - }); - } - - function cut() { - const names = getNames(); - const from = Info.dirPath; - - clear(); - - if (!names.length) - return; - - addCutClass(); - - Storage - .set(CUT, { - from, - names, - }); - } - - function clear() { - Storage.remove(COPY) - .remove(CUT); - - rmCutClass(); - } - - function paste() { - const copy = Storage.get.bind(Storage, COPY); - const cut = Storage.get.bind(Storage, CUT); - - exec.parallel([copy, cut], (error, cp, ct) => { - const opStr = cp ? 'copy' : 'move'; - const opData = cp || ct; - const Operation = CloudCmd.Operation; - const msg = 'Path is same!'; - const path = Info.dirPath; - - if (!error && !cp && !ct) - error = 'Buffer is empty!'; - - if (error) - return showMessage(error); - - const data = jonny.parse(opData); - data.to = path; - - if (data.from === path) - return showMessage(msg); - - Operation.show(opStr, data); - clear(); - }); - } - - return Buffer; +function showMessage(msg) { + globalThis.DOM.Dialog.alert(msg); } + +function getNames() { + const {DOM} = globalThis; + const files = DOM.getActiveFiles(); + + return DOM.getFilenames(files); +} + +function addCutClass() { + const {DOM} = globalThis; + const files = DOM.getActiveFiles(); + + for (const element of files) { + element.classList.add(CLASS); + } +} + +function rmCutClass() { + const {DOM} = globalThis; + const files = DOM.getByClassAll(CLASS); + + for (const element of files) { + element.classList.remove(CLASS); + } +} + +const checkEnabled = (fn) => () => { + const is = CloudCmd.config('buffer'); + + if (is) + return fn(); + + showMessage('Buffer disabled in config!'); +}; + +async function readBuffer() { + const [e, cp, ct] = await tryToPromiseAll([ + Storage.getJson(COPY), + Storage.getJson(CUT), + ]); + + return [ + e, + cp, + ct, + ]; +} + +export const copy = checkEnabled(async () => { + const Info = globalThis.DOM.CurrentInfo; + const names = getNames(); + const from = Info.dirPath; + + await clear(); + + if (!names.length) + return; + + await Storage.remove(CUT); + await Storage.setJson(COPY, { + from, + names, + }); +}); + +export const cut = checkEnabled(async () => { + const Info = globalThis.DOM.CurrentInfo; + const names = getNames(); + const from = Info.dirPath; + + await clear(); + + if (!names.length) + return; + + addCutClass(); + + await Storage.setJson(CUT, { + from, + names, + }); +}); + +export const clear = checkEnabled(async () => { + await Storage.remove(COPY); + await Storage.remove(CUT); + + rmCutClass(); +}); + +export const paste = checkEnabled(async () => { + const Info = globalThis.DOM.CurrentInfo; + const [error, cp, ct] = await readBuffer(); + + if (error || !cp && !ct) + return showMessage(error || 'Buffer is empty!'); + + const opStr = cp ? 'copy' : 'move'; + const data = cp || ct; + const {Operation} = CloudCmd; + const msg = 'Path is same!'; + const to = Info.dirPath; + + if (data.from === to) + return showMessage(msg); + + Operation.show(opStr, { + ...data, + to, + }); + + await clear(); +}); diff --git a/client/dom/cmd.js b/client/dom/cmd.js new file mode 100644 index 00000000..d228b315 --- /dev/null +++ b/client/dom/cmd.js @@ -0,0 +1,83 @@ +/* global DOM */ +const SELECTED_FILE = 'selected-file'; +const Cmd = { + getSelectedFiles, + isSelected, + unselectFile, + selectFile, + selectAllFiles, + toggleSelectedFile, + toggleAllSelectedFiles, +}; + +/** + * selected file check + * + * @param currentFile + */ +export function isSelected(currentFile) { + if (!currentFile) + return false; + + return DOM.isContainClass(currentFile, SELECTED_FILE); +} + +/** + * select current file + * @param currentFile + */ +export function selectFile(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + + current.classList.add(SELECTED_FILE); + + return Cmd; +} + +export function unselectFile(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + + current.classList.remove(SELECTED_FILE); + + return Cmd; +} + +export function toggleSelectedFile(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + const name = DOM.getCurrentName(current); + + if (name === '..') + return Cmd; + + current.classList.toggle(SELECTED_FILE); + + return Cmd; +} + +export function toggleAllSelectedFiles() { + DOM + .getAllFiles() + .map(DOM.toggleSelectedFile); + + return Cmd; +} + +export function selectAllFiles() { + DOM + .getAllFiles() + .map(DOM.selectFile); + + return Cmd; +} + +/** + * unified way to get selected files + * + * @currentFile + */ +export function getSelectedFiles() { + const panel = DOM.getPanel(); + const selected = DOM.getByClassAll(SELECTED_FILE, panel); + + return Array.from(selected); +} diff --git a/client/dom/current-file.js b/client/dom/current-file.js index 56084eda..b8113054 100644 --- a/client/dom/current-file.js +++ b/client/dom/current-file.js @@ -1,28 +1,16 @@ -'use strict'; - /* global DOM */ /* global CloudCmd */ - -const btoa = require('../../common/btoa'); -const createElement = require('@cloudcmd/create-element'); - -const { - encode, - decode, -} = require('../../common/entity'); - -const { - getTitle, - FS, -} = require('../../common/cloudfunc'); +import createElement from '@cloudcmd/create-element'; +import {getTitle, FS} from '#common/cloudfunc'; +import {encode, decode} from '#common/entity'; let Title; const CURRENT_FILE = 'current-file'; -const NBSP_REG = RegExp(String.fromCharCode(160), 'g'); -const SPACE = ' '; +const encodeNBSP = (a) => a?.replace('\xa0', ' '); +const decodeNBSP = (a) => a?.replace(' ', '\xa0'); -module.exports._CURRENT_FILE = CURRENT_FILE; +export const _CURRENT_FILE = CURRENT_FILE; /** * set name from current (or param) file @@ -30,18 +18,18 @@ module.exports._CURRENT_FILE = CURRENT_FILE; * @param name * @param current */ -module.exports.setCurrentName = (name, current) => { +export const setCurrentName = (name, current) => { const Info = DOM.CurrentInfo; const {link} = Info; - const {PREFIX} = CloudCmd; - const dir = PREFIX + FS + Info.dirPath; + const {prefix} = CloudCmd; + const dir = prefix + FS + Info.dirPath; const encoded = encode(name); link.title = encoded; link.href = dir + encoded; link.innerHTML = encoded; - current.setAttribute('data-name', 'js-file-' + btoa(encodeURI(name))); + current.setAttribute('data-name', createNameAttribute(name)); CloudCmd.emit('current-file', current); return link; @@ -52,28 +40,48 @@ module.exports.setCurrentName = (name, current) => { * * @param currentFile */ -module.exports.getCurrentName = (currentFile) => { +export const getCurrentName = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); if (!current) return ''; - - const link = DOM.getCurrentLink(current); - if (!link) - return ''; - - return decode(link.title) - .replace(NBSP_REG, SPACE); + return parseNameAttribute(current.getAttribute('data-name')); }; /** - * get current direcotory path + * Generate a `data-name` attribute for the given filename + * @param name The string name to encode */ -module.exports.getCurrentDirPath = (panel = DOM.getPanel()) => { +const createNameAttribute = (name) => { + const encoded = btoa(encodeURI(name)); + return `js-file-${encoded}`; +}; + +/** + * Parse a `data-name` attribute string back into the original filename + * @param attribute The string we wish to decode + */ +const parseNameAttribute = (attribute) => { + attribute = attribute.replace('js-file-', ''); + return decodeNBSP(decodeURI(atob(attribute))); +}; + +export const _parseNameAttribute = parseNameAttribute; + +const parseHrefAttribute = (prefix, attribute) => { + attribute = attribute.replace(RegExp('^' + prefix + FS), ''); + return decode(decodeNBSP(attribute)); +}; + +export const _parseHrefAttribute = parseHrefAttribute; + +/** + * get current directory path + */ +export const getCurrentDirPath = (panel = DOM.getPanel()) => { const path = DOM.getByDataName('js-path', panel); - return path.textContent - .replace(NBSP_REG, SPACE); + return path.textContent; }; /** @@ -81,36 +89,31 @@ module.exports.getCurrentDirPath = (panel = DOM.getPanel()) => { * * @param currentFile - current file by default */ -module.exports.getCurrentPath = (currentFile) => { +export const getCurrentPath = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); - const element = DOM.getByTag('a', current)[0]; - const prefix = CloudCmd.PREFIX; + const [element] = DOM.getByTag('a', current); + const {prefix} = CloudCmd; - const path = element - .getAttribute('href') - .replace(RegExp('^' + prefix + FS), '') - .replace(NBSP_REG, SPACE); - - return decode(path); + return parseHrefAttribute(prefix, element.getAttribute('href')); }; /** - * get current direcotory name + * get current directory name */ -module.exports.getCurrentDirName = () => { - const href = DOM.getCurrentDirPath() +export const getCurrentDirName = () => { + const href = DOM + .getCurrentDirPath() .replace(/\/$/, ''); - const substr = href.substr(href, href.lastIndexOf('/')); - const ret = href.replace(substr + '/', '') || '/'; + const substr = href.substr(href, href.lastIndexOf('/')); - return ret; + return href.replace(`${substr}/`, '') || '/'; }; /** - * get current direcotory path + * get current directory path */ -module.exports.getParentDirPath = (panel) => { +export const getParentDirPath = (panel) => { const path = DOM.getCurrentDirPath(panel); const dirName = DOM.getCurrentDirName() + '/'; const index = path.lastIndexOf(dirName); @@ -122,11 +125,11 @@ module.exports.getParentDirPath = (panel) => { }; /** - * get not current direcotory path + * get not current directory path */ -module.exports.getNotCurrentDirPath = () => { +export const getNotCurrentDirPath = () => { const panel = DOM.getPanel({ - active: false + active: false, }); return DOM.getCurrentDirPath(panel); @@ -137,20 +140,20 @@ module.exports.getNotCurrentDirPath = () => { * * @currentFile */ -module.exports.getCurrentFile = () => { +export const getCurrentFile = () => { return DOM.getByClass(CURRENT_FILE); }; /** * get current file by name */ -module.exports.getCurrentByName = (name, panel = DOM.CurrentInfo.panel) => { - const dataName = 'js-file-' + btoa(encodeURI(name)); +export const getCurrentByName = (name, panel = DOM.CurrentInfo.panel) => { + const dataName = 'js-file-' + btoa(encodeURI(encodeNBSP(name))); return DOM.getByDataName(dataName, panel); }; /** - * private function thet unset currentfile + * private function that unset currentFile * * @currentFile */ @@ -166,9 +169,8 @@ function unsetCurrentFile(currentFile) { /** * unified way to set current file */ -module.exports.setCurrentFile = (currentFile, options) => { +export const setCurrentFile = (currentFile, options) => { const o = options; - const CENTER = true; const currentFileWas = DOM.getCurrentFile(); if (!currentFile) @@ -196,13 +198,15 @@ module.exports.setCurrentFile = (currentFile, options) => { * but it should be false * to prevent default behavior */ - if (!o || o.history !== false) { + if (!o || o.history) { const historyPath = path === '/' ? path : FS + path; DOM.setHistory(historyPath, null, historyPath); } } /* scrolling to current file */ + const CENTER = true; + DOM.scrollIntoViewIfNeeded(currentFile, CENTER); CloudCmd.emit('current-file', currentFile); @@ -212,13 +216,18 @@ module.exports.setCurrentFile = (currentFile, options) => { return DOM; }; +export const setCurrentByName = (name) => { + const current = DOM.getCurrentByName(name); + return DOM.setCurrentFile(current); +}; + /* * set current file by position * * @param layer - element * @param - position {x, y} */ -module.exports.getCurrentByPosition = ({x, y}) => { +export const getCurrentByPosition = ({x, y}) => { const element = document.elementFromPoint(x, y); const getEl = (el) => { @@ -250,7 +259,7 @@ module.exports.getCurrentByPosition = ({x, y}) => { * * @param currentFile */ -module.exports.isCurrentFile = (currentFile) => { +export const isCurrentFile = (currentFile) => { if (!currentFile) return false; @@ -262,12 +271,11 @@ module.exports.isCurrentFile = (currentFile) => { * * @param name */ - -module.exports.setTitle = (name) => { +export const setTitle = (name) => { if (!Title) Title = DOM.getByTag('title')[0] || createElement('title', { innerHTML: name, - parent: document.head + parent: document.head, }); Title.textContent = name; @@ -275,3 +283,29 @@ module.exports.setTitle = (name) => { return DOM; }; +/** + * check is current file is a directory + * + * @param currentFile + */ +export const isCurrentIsDir = (currentFile) => { + const current = currentFile || DOM.getCurrentFile(); + const path = DOM.getCurrentPath(current); + const fileType = DOM.getCurrentType(current); + + const isZip = path.endsWith('.zip'); + const isDir = /^directory(-link)?/.test(fileType); + + return isDir || isZip; +}; + +export const getCurrentType = (currentFile) => { + const current = currentFile || DOM.getCurrentFile(); + const el = DOM.getByDataName('js-type', current); + + const type = el.className + .split(' ') + .pop(); + + return type; +}; diff --git a/client/dom/current-file.spec.js b/client/dom/current-file.spec.js index 6efcf00b..85b18a29 100644 --- a/client/dom/current-file.spec.js +++ b/client/dom/current-file.spec.js @@ -1,129 +1,114 @@ -'use strict'; +import {test, stub} from 'supertape'; +import {create} from 'auto-globals'; +import wraptile from 'wraptile'; +import * as currentFile from './current-file.js'; -const test = require('tape'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); const id = (a) => a; -const wraptile = require('wraptile'); -const returns = wraptile(id); -const currentFile = require('./current-file'); +const returns = wraptile(id); const {_CURRENT_FILE} = currentFile; test('current-file: setCurrentName: setAttribute', (t) => { - const { - DOM, - CloudCmd, - } = global; + const {DOM, CloudCmd} = globalThis; - global.DOM = getDOM(); - global.CloudCmd = getCloudCmd(); + globalThis.DOM = getDOM(); + globalThis.CloudCmd = getCloudCmd(); - const setAttribute = sinon.stub(); - const current = { - setAttribute - }; + const current = create(); + const {setAttribute} = current; currentFile.setCurrentName('hello', current); - t.ok(setAttribute.calledWith('data-name', 'js-file-aGVsbG8='), 'should call setAttribute'); - - global.DOM = DOM; - global.CloudCmd = CloudCmd; + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + t.calledWith(setAttribute, [ + 'data-name', + 'js-file-aGVsbG8=', + ], 'should call setAttribute'); t.end(); }); test('current-file: setCurrentName: setAttribute: cyrillic', (t) => { - const { - DOM, - CloudCmd, - } = global; + const {DOM, CloudCmd} = globalThis; - global.DOM = getDOM(); - global.CloudCmd = getCloudCmd(); + globalThis.DOM = getDOM(); + globalThis.CloudCmd = getCloudCmd(); - const setAttribute = sinon.stub(); - const current = { - setAttribute - }; + const current = create(); + const {setAttribute} = current; currentFile.setCurrentName('ай', current); - t.ok(setAttribute.calledWith('data-name', 'js-file-JUQwJUIwJUQwJUI5'), 'should call setAttribute'); + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; - global.DOM = DOM; - global.CloudCmd = CloudCmd; + t.calledWith(setAttribute, [ + 'data-name', + 'js-file-JUQwJUIwJUQwJUI5', + ], 'should call setAttribute'); + t.end(); +}); + +test('current-file: getCurrentName', (t) => { + const current = create(); + current.getAttribute.returns('js-file-Ymlu'); + const result = currentFile.getCurrentName(current); + + t.equal(result, 'bin'); t.end(); }); test('current-file: emit', (t) => { - const { - DOM, - CloudCmd, - } = global; + const {DOM, CloudCmd} = globalThis; - const emit = sinon.stub(); - const setAttribute = sinon.stub(); + const emit = stub(); - global.DOM = getDOM(); - global.CloudCmd = getCloudCmd({ + globalThis.DOM = getDOM(); + globalThis.CloudCmd = getCloudCmd({ emit, }); - const current = { - setAttribute, - }; + const current = create(); currentFile.setCurrentName('hello', current); - t.ok(emit.calledWith('current-file', current), 'should call emit'); - - global.DOM = DOM; - global.CloudCmd = CloudCmd; + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + t.calledWith(emit, ['current-file', current], 'should call emit'); t.end(); }); test('current-file: setCurrentName: return', (t) => { - const { - DOM, - CloudCmd, - } = global; + const {DOM, CloudCmd} = globalThis; - const setAttribute = sinon.stub(); const link = {}; - global.DOM = getDOM({ - link + globalThis.DOM = getDOM({ + link, }); - global.CloudCmd = getCloudCmd(); - - const current = { - setAttribute, - }; + globalThis.CloudCmd = getCloudCmd(); + const current = create(); const result = currentFile.setCurrentName('hello', current); + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + t.equal(result, link, 'should return link'); - - global.DOM = DOM; - global.CloudCmd = CloudCmd; - t.end(); }); test('current-file: getParentDirPath: result', (t) => { - const { - DOM, - } = global; + const {DOM} = globalThis; const getCurrentDirPath = returns('/D/Films/+++favorite films/'); const getCurrentDirName = returns('+++favorite films'); - global.DOM = getDOM({ + globalThis.DOM = getDOM({ getCurrentDirPath, getCurrentDirName, }); @@ -131,78 +116,193 @@ test('current-file: getParentDirPath: result', (t) => { const result = currentFile.getParentDirPath(); const expected = '/D/Films/'; - global.DOM = DOM; + globalThis.DOM = DOM; t.equal(result, expected, 'should return parent dir path'); t.end(); }); test('current-file: isCurrentFile: no', (t) => { - const { - DOM, - CloudCmd, - } = global; + const {DOM, CloudCmd} = globalThis; - global.DOM = getDOM(); - global.CloudCmd = getCloudCmd(); + globalThis.DOM = getDOM(); + globalThis.CloudCmd = getCloudCmd(); const result = currentFile.isCurrentFile(); - const expect = false; - global.DOM = DOM; - global.CloudCmd = CloudCmd; + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; - t.equal(result, expect, 'should equal'); + t.notOk(result); t.end(); }); test('current-file: isCurrentFile', (t) => { - const { - DOM, - CloudCmd, - } = global; + const {DOM, CloudCmd} = globalThis; - const isContainClass = sinon.stub(); + const isContainClass = stub(); - global.DOM = getDOM({ - isContainClass + globalThis.DOM = getDOM({ + isContainClass, }); - global.CloudCmd = getCloudCmd(); + globalThis.CloudCmd = getCloudCmd(); const current = {}; currentFile.isCurrentFile(current); - global.DOM = DOM; - global.CloudCmd = CloudCmd; + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; - t.ok(isContainClass.calledWith(current, _CURRENT_FILE), 'should call isContainClass'); + t.calledWith(isContainClass, [current, _CURRENT_FILE], 'should call isContainClass'); t.end(); }); -function getCloudCmd({emit} = {}) { - return { - PREFIX: '', - emit: emit || sinon.stub(), - }; -} +test('current-file: getCurrentType', (t) => { + const {DOM, CloudCmd} = globalThis; + + globalThis.DOM = getDOM(); + globalThis.CloudCmd = getCloudCmd(); + + const {getByDataName} = globalThis.DOM; + + getByDataName.returns({ + className: 'mini-icon directory', + }); + + const current = create(); + + currentFile.getCurrentType(current); + + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + + t.calledWith(getByDataName, ['js-type', current]); + t.end(); +}); -function getDOM({ - link = {}, - getCurrentDirPath = sinon.stub(), - getCurrentDirName = sinon.stub(), - getByDataName = sinon.stub(), - isContainClass = sinon.stub(), -} = {}) { +test('current-file: isCurrentIsDir: getCurrentType', (t) => { + const {DOM, CloudCmd} = globalThis; + + globalThis.DOM = getDOM(); + globalThis.CloudCmd = getCloudCmd(); + + const {getCurrentType} = globalThis.DOM; + + const current = create(); + + currentFile.isCurrentIsDir(current); + + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + + t.calledWith(getCurrentType, [current]); + t.end(); +}); + +test('current-file: isCurrentIsDir: directory', (t) => { + const {DOM, CloudCmd} = globalThis; + + globalThis.DOM = getDOM({ + getCurrentType: stub().returns('directory'), + }); + + globalThis.CloudCmd = getCloudCmd(); + + const current = create(); + + const result = currentFile.isCurrentIsDir(current); + + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + + t.ok(result); + t.end(); +}); + +test('current-file: isCurrentIsDir: directory-link', (t) => { + const {DOM, CloudCmd} = globalThis; + + globalThis.DOM = getDOM({ + getCurrentType: stub().returns('directory-link'), + }); + + globalThis.CloudCmd = getCloudCmd(); + + const current = create(); + + const result = currentFile.isCurrentIsDir(current); + + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + + t.ok(result); + t.end(); +}); + +test('current-file: isCurrentIsDir: file', (t) => { + const {DOM, CloudCmd} = globalThis; + + globalThis.DOM = getDOM({ + getCurrentType: stub().returns('file'), + }); + + globalThis.CloudCmd = getCloudCmd(); + + const current = create(); + + const result = currentFile.isCurrentIsDir(current); + + globalThis.DOM = DOM; + globalThis.CloudCmd = CloudCmd; + + t.notOk(result); + t.end(); +}); + +const getCloudCmd = ({emit} = {}) => ({ + prefix: '', + emit: emit || stub(), +}); + +test('current-file: parseNameAttribute', (t) => { + const result = currentFile._parseNameAttribute('js-file-aGVsbG8mbmJzcDt3b3JsZA=='); + const expected = 'hello\xa0world'; + + t.equal(result, expected); + t.end(); +}); + +test('current-file: parseHrefAttribute', (t) => { + const prefix = '/api/v1'; + const result = currentFile._parseHrefAttribute(prefix, '/api/v1/fs/hello world'); + const expected = '/hello\xa0world'; + + t.equal(result, expected); + t.end(); +}); + +function getDOM(overrides = {}) { + const { + link = {}, + getCurrentDirPath = stub(), + getCurrentDirName = stub(), + getByDataName = stub(), + isContainClass = stub(), + getCurrentType = stub(), + getCurrentPath = stub().returns(''), + } = overrides; + return { getCurrentDirPath, getCurrentDirName, + getCurrentPath, getByDataName, isContainClass, + getCurrentType, CurrentInfo: { link, dirPath: '/', - } + }, }; } - diff --git a/client/dom/dialog.js b/client/dom/dialog.js index 97a65db2..b1791d92 100644 --- a/client/dom/dialog.js +++ b/client/dom/dialog.js @@ -1,19 +1,18 @@ +import {tryToCatch} from 'try-to-catch'; +import * as smalltalk from 'smalltalk'; -'use strict'; +const title = 'Cloud Commander'; -const { - alert, - prompt, - confirm, -}= require('smalltalk'); +export const alert = (...a) => smalltalk.alert(title, ...a, { + cancel: false, +}); -module.exports = { - alert, - prompt, - confirm, +export const prompt = (...a) => tryToCatch(smalltalk.prompt, title, ...a); +export const confirm = (...a) => tryToCatch(smalltalk.confirm, title, ...a); +export const progress = (...a) => smalltalk.progress(title, ...a); + +alert.noFiles = () => { + return smalltalk.alert(title, 'No files selected!', { + cancel: false, + }); }; - -module.exports.alert.noFiles = (title) => { - return alert(title, 'No files selected!'); -}; - diff --git a/client/dom/directory.js b/client/dom/directory.js index 7a58025b..efbca119 100644 --- a/client/dom/directory.js +++ b/client/dom/directory.js @@ -1,33 +1,29 @@ -/* global CloudCmd */ +/* global DOM, CloudCmd */ +import philip from 'philip'; +import * as Dialog from '#dom/dialog'; +import {FS} from '#common/cloudfunc'; +import * as Images from '#dom/images'; -'use strict'; - -const philip = require('philip'); - -const Images = require('./images'); -const {FS} = require('../../common/cloudfunc'); -const DOM = require('.'); - -const { - getCurrentDirPath: getPathWhenRootEmpty, -} = DOM; - -module.exports = (items) => { - const Dialog = DOM.Dialog; - +export const uploadDirectory = (items) => { if (items.length) Images.show('top'); - const entries = [...items].map((item) => { - return item.webkitGetAsEntry(); + const entries = Array + .from(items) + .map((item) => item.webkitGetAsEntry()); + + const dirPath = DOM.getCurrentDirPath(); + const path = dirPath.replace(/\/$/, ''); + + const progress = Dialog.progress('Uploading...'); + + progress.catch(() => { + Dialog.alert('Upload aborted'); + uploader.abort(); }); - const dirPath = getPathWhenRootEmpty(); - const path = dirPath - .replace(/\/$/, ''); - const uploader = philip(entries, (type, name, data, i, n, callback) => { - const prefixURL = CloudCmd.PREFIX_URL; + const {prefixURL} = CloudCmd; const full = prefixURL + FS + path + name; let upload; @@ -49,7 +45,7 @@ module.exports = (items) => { const max = next - current; const value = current + percent(count, 100, max); - setProgress(value); + progress.setProgress(value); }); }); @@ -58,25 +54,11 @@ module.exports = (items) => { uploader.abort(); }); - uploader.on('progress', setProgress); uploader.on('end', CloudCmd.refresh); }; -function percent(i, n, per = 100) { - return Math.round(i * per / n); -} +const percent = (i, n, per = 100) => Math.round(i * per / n); -function setProgress(count) { - DOM.Images - .setProgress(count) - .show('top'); -} - -function uploadFile(url, data) { - return DOM.load.put(url, data); -} - -function uploadDir(url) { - return DOM.load.put(url + '?dir'); -} +const uploadFile = (url, data) => DOM.load.put(url, data); +const uploadDir = (url) => DOM.load.put(`${url}?dir`); diff --git a/client/dom/dom-tree.js b/client/dom/dom-tree.js index c96dc88d..fad5ad40 100644 --- a/client/dom/dom-tree.js +++ b/client/dom/dom-tree.js @@ -1,8 +1,15 @@ -'use strict'; +import currify from 'currify'; -const currify = require('currify/legacy'); - -const DOM = module.exports; +const DOM = { + show, + hide, + getByClass, + getByClassAll, + getByDataName, + getById, + getByTag, + isContainClass, +}; /** * check class of element @@ -10,7 +17,7 @@ const DOM = module.exports; * @param element * @param className */ -const isContainClass = (element, className) => { +export function isContainClass(element, className) { if (!element) throw Error('element could not be empty!'); @@ -18,67 +25,68 @@ const isContainClass = (element, className) => { throw Error('className could not be empty!'); if (Array.isArray(className)) - return className.some(currify(isContainClass, element)); + return className.some(currify( + isContainClass, + element, + )); - const classList = element.classList; + const {classList} = element; return classList.contains(className); -}; - -module.exports.isContainClass = isContainClass; +} /** * Function search element by tag * @param tag - className * @param element - element */ -module.exports.getByTag = (tag, element = document) => { +export function getByTag(tag, element = document) { return element.getElementsByTagName(tag); -}; +} /** * Function search element by id - * @param Id - id + * @param id + * @param element */ -module.exports.getById = (id, element = document) => { - return element.querySelector('#' + id); -}; +export function getById(id, element = document) { + return element.querySelector(`#${id}`); +} /** * Function search first element by class name * @param className - className * @param element - element */ -module.exports.getByClass = (className, element = document) => { +export function getByClass(className, element = document) { return DOM.getByClassAll(className, element)[0]; -}; +} -module.exports.getByDataName = (attribute, element = document) => { - const selector = '[' + 'data-name="' + attribute + '"]'; +export function getByDataName(attribute, element = document) { + const selector = '[' + 'data-name="' + attribute + '"]'; return element.querySelector(selector); -}; +} /** * Function search element by class name - * @param pClass - className - * @param element - element + * @param className + * @param element */ -module.exports.getByClassAll = (className, element) => { +export function getByClassAll(className, element) { return (element || document).getElementsByClassName(className); -}; +} /** * add class=hidden to element * * @param element */ -module.exports.hide = (element) => { +export function hide(element) { element.classList.add('hidden'); return DOM; -}; +} -module.exports.show = (element) => { +export function show(element) { element.classList.remove('hidden'); return DOM; -}; - +} diff --git a/client/dom/dom-tree.spec.js b/client/dom/dom-tree.spec.js index b9226166..53b376c7 100644 --- a/client/dom/dom-tree.spec.js +++ b/client/dom/dom-tree.spec.js @@ -1,57 +1,152 @@ -'use strict'; - -const test = require('tape'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); -const tryCatch = require('try-catch'); - -const { +import {test, stub} from 'supertape'; +import {create} from 'auto-globals'; +import {tryCatch} from 'try-catch'; +import { isContainClass, -} = require('./dom-tree'); + getByTag, + getById, + getByClass, + getByDataName, + getByClassAll, + hide, + show, +} from './dom-tree.js'; test('dom: isContainClass: no element', (t) => { const [e] = tryCatch(isContainClass); + t.equal(e.message, 'element could not be empty!', 'should throw when no element'); t.end(); }); test('dom: isContainClass: no className', (t) => { const [e] = tryCatch(isContainClass, {}); + t.equal(e.message, 'className could not be empty!', 'should throw when no element'); t.end(); }); test('dom: isContainClass: contains', (t) => { - const contains = sinon.stub(); - const el = { - classList: { - contains, - } - }; + const el = create(); + const {contains} = el.classList; const className = 'hello'; isContainClass(el, className); - t.ok(contains.calledWith(className), 'should call contains'); + t.calledWith(contains, [className], 'should call contains'); t.end(); }); test('dom: isContainClass: contains: array', (t) => { - const contains = sinon.stub(); - const el = { - classList: { - contains, - } - }; + const el = create(); + const {contains} = el.classList; const className = 'hello'; - isContainClass(el, [ - 'world', - className, - 'hello', - ]); + isContainClass(el, ['world', className, 'hello']); - t.ok(contains.calledWith(className), 'should call contains'); + t.calledWith(contains, [className], 'should call contains'); t.end(); }); +test('dom: getByTag', (t) => { + const getElementsByTagName = stub(); + const element = { + getElementsByTagName, + }; + + getByTag('div', element); + + t.calledWith(getElementsByTagName, ['div'], 'should call getElementsByTagName'); + t.end(); +}); + +test('dom: getById', (t) => { + const querySelector = stub(); + const element = { + querySelector, + }; + + getById('my-id', element); + + t.calledWith(querySelector, ['#my-id'], 'should call querySelector with id selector'); + t.end(); +}); + +test('dom: getByClassAll', (t) => { + const getElementsByClassName = stub(); + const element = { + getElementsByClassName, + }; + + getByClassAll('my-class', element); + + t.calledWith(getElementsByClassName, ['my-class'], 'should call getElementsByClassName'); + t.end(); +}); + +test('dom: getByClass: calls getByClassAll', (t) => { + const element = { + getElementsByClassName: stub().returns(['first']), + }; + + const result = getByClass('my-class', element); + + t.equal(result, 'first', 'should return first element from class list'); + t.end(); +}); + +test('dom: getByDataName', (t) => { + const querySelector = stub(); + const element = { + querySelector, + }; + + getByDataName('hello', element); + + t.calledWith(querySelector, ['[data-name="hello"]'], 'should call querySelector with data-name selector'); + t.end(); +}); + +test('dom: hide', (t) => { + const add = stub(); + const element = { + classList: { + add, + }, + }; + + hide(element); + + t.calledWith(add, ['hidden'], 'should add hidden class'); + t.end(); +}); + +test('dom: show', (t) => { + const remove = stub(); + const element = { + classList: { + remove, + }, + }; + + show(element); + + t.calledWith(remove, ['hidden'], 'should remove hidden class'); + t.end(); +}); + +test('dom: getByClassAll: without element uses document', (t) => { + const getElementsByClassName = stub(); + const prevDocument = globalThis.document; + + globalThis.document = { + getElementsByClassName, + }; + + getByClassAll('my-class'); + + globalThis.document = prevDocument; + + t.calledWith(getElementsByClassName, ['my-class'], 'should fallback to document when no element'); + t.end(); +}); diff --git a/client/dom/events/event-store.js b/client/dom/events/event-store.js index 6d9273c0..1cbfe7a4 100644 --- a/client/dom/events/event-store.js +++ b/client/dom/events/event-store.js @@ -1,8 +1,6 @@ -'use strict'; - let list = []; -module.exports.add = (el, name, fn) => { +export const add = (el, name, fn) => { list.push([ el, name, @@ -10,11 +8,8 @@ module.exports.add = (el, name, fn) => { ]); }; -module.exports.clear = () => { +export const clear = () => { list = []; }; -module.exports.get = () => { - return list; -}; - +export const get = () => list; diff --git a/client/dom/events/event-store.spec.js b/client/dom/events/event-store.spec.js index 0f1761d6..6a623939 100644 --- a/client/dom/events/event-store.spec.js +++ b/client/dom/events/event-store.spec.js @@ -1,7 +1,5 @@ -'use strict'; - -const test = require('tape'); -const eventStore = require('./event-store'); +import {test} from 'supertape'; +import * as eventStore from './event-store.js'; test('event-store: get', (t) => { const el = {}; @@ -10,11 +8,16 @@ test('event-store: get', (t) => { eventStore.add(el, name, fn); const result = eventStore.get(); + const expected = [ - [el, name, fn], + [ + el, + name, + fn, + ], ]; - t.deepEqual(expected, result, 'should equal'); + t.deepEqual(result, expected); t.end(); }); @@ -29,6 +32,6 @@ test('event-store: clear', (t) => { const result = eventStore.get(); const expected = []; - t.deepEqual(expected, result, 'should equal'); + t.deepEqual(result, expected); t.end(); }); diff --git a/client/dom/events/index.js b/client/dom/events/index.js index 199c7b11..c49d2333 100644 --- a/client/dom/events/index.js +++ b/client/dom/events/index.js @@ -1,249 +1,203 @@ -'use strict'; +import itype from 'itype'; +import * as EventStore from './event-store.js'; -const itype = require('itype/legacy'); -const EventStore = require('./event-store'); - -module.exports = new EventsProto(); - -function EventsProto() { - const Events = this; +/** + * safe add event listener + * + * @param type + * @param element - document by default + * @param listener + */ +export const add = (type, element, listener) => { + checkType(type); - const getEventOptions = (eventName) => { - if (eventName !== 'touchstart') - return false; + parseArgs(type, element, listener, (element, args) => { + const [name, fn, options] = args; - return { - passive: true - }; + element.addEventListener(name, fn, options); + EventStore.add(element, name, fn); + }); + + return Events; +}; + +/** + * safe add event listener + * + * @param type + * @param listener + * @param element - document by default + */ +export const addOnce = (type, element, listener) => { + const once = (event) => { + Events.remove(type, element, once); + listener(event); }; - function parseArgs(eventName, element, listener, callback) { - let isFunc; - const args = [ - eventName, - element, - listener, - callback, - ]; - - const EVENT_NAME = 1; - const ELEMENT = 0; - const type = itype(eventName); - - switch(type) { - default: - if (!/element$/.test(type)) - throw Error('unknown eventName: ' + type); - - parseArgs( - args[EVENT_NAME], - args[ELEMENT], - listener, - callback - ); - break; - - case 'string': - isFunc = itype.function(element); - - if (isFunc) { - listener = element; - element = null; - } - - if (!element) - element = window; - - callback(element, [ - eventName, - listener, - getEventOptions(eventName), - ]); - break; - - case 'array': - eventName.forEach((eventName) => { - parseArgs( - eventName, - element, - listener, - callback - ); - }); - break; - - case 'object': - Object.keys(eventName).forEach((name) => { - const eventListener = eventName[name]; - - parseArgs( - name, - element, - eventListener, - callback - ); - }); - - break; - } + if (!listener) { + listener = element; + element = null; } - /** - * safe add event listener - * - * @param type - * @param element {document by default} - * @param listener - */ - this.add = (type, element, listener) => { - checkType(type); - - parseArgs(type, element, listener, (element, args) => { - const [name, fn, options] = args; - - element.addEventListener(name, fn, options); - EventStore.add(element, name, fn); - }); - - return Events; - }; + add(type, element, once); - /** - * safe add event listener - * - * @param type - * @param listener - * @param element {document by default} - */ - this.addOnce = (type, element, listener) => { - const once = (event) => { - Events.remove(type, element, once); - listener(event); - }; + return Events; +}; + +/** + * safe remove event listener + * + * @param type + * @param listener + * @param element - document by default + */ +export const remove = (type, element, listener) => { + checkType(type); + + parseArgs(type, element, listener, (element, args) => { + element.removeEventListener(...args); + }); + + return Events; +}; + +/** + * remove all added event listeners + */ +export const removeAll = () => { + const events = EventStore.get(); + + for (const [el, name, fn] of events) + el.removeEventListener(name, fn); + + EventStore.clear(); +}; + +/** + * safe add event keydown listener + * + * @param args + */ +export const addKey = function(...args) { + return add('keydown', ...args); +}; + +/** + * safe remove event click listener + * + * @param args + */ +export const rmKey = function(...args) { + return Events.remove('keydown', ...args); +}; + +/** + * safe add event click listener + */ +export const addClick = function(...args) { + return Events.add('click', ...args); +}; + +/** + * safe remove event click listener + */ +export const rmClick = function(...args) { + return remove('click', ...args); +}; + +export const addContextMenu = function(...args) { + return add('contextmenu', ...args); +}; + +/** + * safe add load listener + */ +export const addLoad = function(...args) { + return add('load', ...args); +}; + +function checkType(type) { + if (!type) + throw Error('type could not be empty!'); +} + +const getEventOptions = (eventName) => { + if (eventName !== 'touchstart') + return false; + + return { + passive: true, + }; +}; + +function parseArgs(eventName, element, listener, callback) { + let isFunc; + const args = [ + eventName, + element, + listener, + callback, + ]; + + const EVENT_NAME = 1; + const ELEMENT = 0; + const type = itype(eventName); + + switch(type) { + default: + if (!type.endsWith('element')) + throw Error(`unknown eventName: ${type}`); - if (!listener) { - listener = element; - element = null; + parseArgs(args[EVENT_NAME], args[ELEMENT], listener, callback); + break; + + case 'string': + isFunc = itype.function(element); + + if (isFunc) { + listener = element; + element = null; } - this.add(type, element, once); + if (!element) + element = window; - return Events; - }; + callback(element, [ + eventName, + listener, + getEventOptions(eventName), + ]); + break; - /** - * safe remove event listener - * - * @param type - * @param listener - * @param element {document by default} - */ - this.remove = (type, element, listener) => { - checkType(type); + case 'array': - parseArgs(type, element, listener, (element, args) => { - element.removeEventListener.apply(element, args); - }); + for (const name of eventName) { + parseArgs(name, element, listener, callback); + } - return Events; - }; + break; - /** - * remove all added event listeners - * - * @param listener - */ - this.removeAll = () => { - const events = EventStore.get(); + case 'object': - for (const [el, name, fn] of events) - el.removeEventListener(name, fn); + for (const name of Object.keys(eventName)) { + const eventListener = eventName[name]; + + parseArgs(name, element, eventListener, callback); + } - EventStore.clear(); - }; - - /** - * safe add event keydown listener - * - * @param listener - */ - this.addKey = function(...argsArr) { - const name = 'keydown'; - const args = [name, ...argsArr]; - - return Events.add(...args); - }; - - /** - * safe remove event click listener - * - * @param listener - */ - this.rmKey = function(...argsArr) { - const name = 'keydown'; - const args = [name, ...argsArr]; - - return Events.remove(...args); - }; - - /** - * safe add event click listener - * - * @param listener - */ - this.addClick = function(...argsArr) { - const name = 'click'; - const args = [name, ...argsArr]; - - return Events.add(...args); - }; - - /** - * safe remove event click listener - * - * @param listener - */ - this.rmClick = function(...argsArr) { - const name = 'click'; - const args = [name, ...argsArr]; - - return Events.remove(...args); - }; - - this.addContextMenu = function(...argsArr) { - const name = 'contextmenu'; - const args = [name, ...argsArr]; - - return Events.add(...args); - }; - - /** - * safe add event click listener - * - * @param listener - */ - this.addError = function(...argsArr) { - const name = 'error'; - const args = [name, ...argsArr]; - - return Events.add(...args); - }; - - /** - * safe add load click listener - * - * @param listener - */ - this.addLoad = function(...argsArr) { - const name = 'load'; - const args = [name, ...argsArr]; - - return Events.add(...args); - }; - - function checkType(type) { - if (!type) - throw Error('type could not be empty!'); + break; } } +const Events = { + add, + addClick, + addContextMenu, + addKey, + addLoad, + addOnce, + remove, + removeAll, + rmClick, + rmKey, +}; diff --git a/client/dom/files.js b/client/dom/files.js index 562738f0..395ac0fa 100644 --- a/client/dom/files.js +++ b/client/dom/files.js @@ -1,104 +1,82 @@ /* global CloudCmd */ - -'use strict'; - -const itype = require('itype/legacy'); -const currify = require('currify/legacy'); -const exec = require('execon'); - -const load = require('./load'); -const RESTful = require('./rest'); +import itype from 'itype'; +import {promisify} from 'es6-promisify'; +import * as load from '#dom/load'; +import * as RESTful from '#dom/rest'; const Promises = {}; const FILES_JSON = 'config|modules'; const FILES_HTML = 'file|path|link|pathLink|media'; const FILES_HTML_ROOT = 'view/media-tmpl|config-tmpl|upload'; const DIR_HTML = '/tmpl/'; -const DIR_HTML_FS = DIR_HTML + 'fs/'; +const DIR_HTML_FS = `${DIR_HTML}fs/`; const DIR_JSON = '/json/'; const timeout = getTimeoutOnce(2000); -const get = currify(getFile); -const unaryMap = (array, fn) => array.map((a) => fn(a)); +export const get = getFile; -module.exports.get = get; - -function getFile(name, callback) { +function getFile(name) { const type = itype(name); - let array; + check(name); - check(name, callback); + if (type === 'string') + return getModule(name); - switch(type) { - case 'string': - getModule(name, callback); - break; - - case 'array': - array = unaryMap(name, get); - - exec.parallel(array, callback); - break; - } + if (type === 'array') + return Promise.all(name.map(getFile)); } -function check(name, callback) { +function check(name) { if (!name) throw Error('name could not be empty!'); - - if (typeof callback !== 'function') - throw Error('callback should be a function'); } -function getModule(name, callback) { - let path; - - const regExpHTML = new RegExp(FILES_HTML + '|' + FILES_HTML_ROOT); - const regExpJSON = new RegExp(FILES_JSON); +function getModule(name) { + const regExpHTML = RegExp(FILES_HTML + '|' + FILES_HTML_ROOT); + const regExpJSON = RegExp(FILES_JSON); const isHTML = regExpHTML.test(name); const isJSON = regExpJSON.test(name); - if (!isHTML && !isJSON) { - showError(name); - } else if (name === 'config') { - getConfig(callback); - } else { - path = getPath(name, isHTML, isJSON); - - getSystemFile(path, callback); - } + if (!isHTML && !isJSON) + return showError(name); + if (name === 'config') + return getConfig(); + + const path = getPath(name, isHTML, isJSON); + + return getSystemFile(path); } function getPath(name, isHTML, isJSON) { let path; - const regExp = new RegExp(FILES_HTML_ROOT); + const regExp = RegExp(FILES_HTML_ROOT); const isRoot = regExp.test(name); if (isHTML) { if (isRoot) path = DIR_HTML + name.replace('-tmpl', ''); else - path = DIR_HTML_FS + name; + path = DIR_HTML_FS + name; path += '.hbs'; } else if (isJSON) { - path = DIR_JSON + name + '.json'; + path = DIR_JSON + name + '.json'; } return path; } function showError(name) { - const str = 'Wrong file name: ' + name; - const error = new Error(str); + const str = `Wrong file name: ${name}`; + const error = Error(str); - throw(error); + throw error; } -function getSystemFile(file, callback) { - const prefix = CloudCmd.PREFIX; +const getSystemFile = promisify((file, callback) => { + const {prefix} = CloudCmd; if (!Promises[file]) Promises[file] = new Promise((success, error) => { @@ -107,7 +85,7 @@ function getSystemFile(file, callback) { load.ajax({ url, success, - error + error, }); }); @@ -117,36 +95,29 @@ function getSystemFile(file, callback) { Promises[file] = null; callback(error); }); -} +}); -function getConfig(callback) { +const getConfig = async () => { let is; if (!Promises.config) - Promises.config = new Promise((resolve, reject) => { + Promises.config = () => { is = true; - RESTful.Config.read((error, data) => { - if (error) - return reject(error); - - resolve(data); - }); - }); + return RESTful.Config.read(); + }; - Promises.config.then((data) => { + const [, data] = await Promises.config(); + + if (data) is = false; - - callback(null, data); - - timeout(() => { - if (!is) - Promises.config = null; - }); - }, () => { + + timeout(() => { if (!is) Promises.config = null; }); -} + + return data; +}; function getTimeoutOnce(time) { let is; @@ -163,4 +134,3 @@ function getTimeoutOnce(time) { }, time); }; } - diff --git a/client/dom/images.js b/client/dom/images.js index 9e9c3fe8..75663e72 100644 --- a/client/dom/images.js +++ b/client/dom/images.js @@ -1,22 +1,13 @@ /* global DOM */ - -'use strict'; - -const createElement = require('@cloudcmd/create-element'); - -const Images = module.exports; +import createElement from '@cloudcmd/create-element'; const LOADING = 'loading'; const HIDDEN = 'hidden'; const ERROR = 'error'; -const LoadingImage = LOADING + getLoadingType(); +const getLoadingType = () => isSVG() ? '-svg' : '-gif'; -function getLoadingType() { - return isSVG() ? '-svg' : '-gif'; -} - -module.exports.get = getElement; +export const get = getElement; /** * check SVG SMIL animation support @@ -40,47 +31,55 @@ function getElement() { id: 'js-status-image', className: 'icon', dataName: 'progress', - notAppend: true + notAppend: true, }); } /* Функция создаёт картинку загрузки */ -module.exports.loading = () => { +export const loading = () => { const element = getElement(); - const classList = element.classList; + const {classList} = element; + const loadingImage = LOADING + getLoadingType(); - classList.add(LOADING, LoadingImage); + classList.add(LOADING, loadingImage); classList.remove(ERROR, HIDDEN); return element; }; /* Функция создаёт картинку ошибки загрузки */ -module.exports.error = () => { +export const error = () => { const element = getElement(); - const classList = element.classList; + const {classList} = element; + const loadingImage = LOADING + getLoadingType(); classList.add(ERROR); - classList.remove(HIDDEN, LOADING, LoadingImage); + classList.remove(HIDDEN, LOADING, loadingImage); return element; }; -module.exports.show = show; -module.exports.show.load = show; -module.exports.show.error = error; +show.load = show; +show.error = (text) => { + const image = Images.error(); + + DOM.show(image); + image.title = text; + + return image; +}; /** * Function shows loading spinner * position = {top: true}; */ -function show(position, panel) { +export function show(position, panel) { const image = Images.loading(); const parent = image.parentElement; const refreshButton = DOM.getRefreshButton(panel); let current; - + if (position === 'top') { current = refreshButton.parentElement; } else { @@ -92,7 +91,7 @@ function show(position, panel) { current = refreshButton.parentElement; } - if (!parent || (parent && parent !== current)) + if (!parent || parent && parent !== current) current.appendChild(image); DOM.show(image); @@ -100,34 +99,25 @@ function show(position, panel) { return image; } -function error(text) { - const image = Images.error(); - - DOM.show(image); - image.title = text; - - return image; -} - /** * hide load image */ -module.exports.hide = () => { +export function hide() { const element = Images.get(); DOM.hide(element); return Images; -}; +} -module.exports.setProgress = (value, title) => { +export const setProgress = (value, title) => { const DATA = 'data-progress'; const element = Images.get(); - + if (!element) return Images; - element.setAttribute(DATA, value + '%'); + element.setAttribute(DATA, `${value}%`); if (title) element.title = title; @@ -135,7 +125,7 @@ module.exports.setProgress = (value, title) => { return Images; }; -module.exports.clearProgress = () => { +export const clearProgress = () => { const DATA = 'data-progress'; const element = Images.get(); @@ -148,3 +138,12 @@ module.exports.clearProgress = () => { return Images; }; +const Images = { + clearProgress, + setProgress, + show, + hide, + get, + error, + loading, +}; diff --git a/client/dom/index.js b/client/dom/index.js index 255250c5..a82b6f72 100644 --- a/client/dom/index.js +++ b/client/dom/index.js @@ -1,974 +1,811 @@ /* global CloudCmd */ +import * as load from '#dom/load'; +import * as Files from '#dom/files'; +import * as Dialog from '#dom/dialog'; +import * as Events from '#dom/events'; +import {getExt} from '#common/util'; +import * as Storage from '#dom/storage'; +import * as RESTful from '#dom/rest'; +import * as Images from '#dom/images'; +import renameCurrent from './operations/rename-current.js'; +import * as CurrentFile from './current-file.js'; +import * as DOMTree from './dom-tree.js'; +import * as Cmd from './cmd.js'; +import * as IO from './io/index.js'; +import {uploadDirectory} from './directory.js'; +import * as Buffer from './buffer.js'; +import {loadRemote as _loadRemote} from './load-remote.js'; +import {selectByPattern} from './select-by-pattern.js'; -'use strict'; - -const itype = require('itype/legacy'); -const exec = require('execon'); -const jonny = require('jonny/legacy'); -const Util = require('../../common/util'); - -const Images = require('./images'); -const load = require('./load'); -const Files = require('./files'); -const RESTful = require('./rest'); -const Storage = require('./storage'); -const Dialog = require('./dialog'); - -const currentFile = require('./current-file'); -const DOMTree = require('./dom-tree'); +const {assign} = Object; const DOM = { - ...DOMTree, - ...currentFile, - ...new CmdProto(), + getCurrentDirName, + getNotCurrentDirPath, + getParentDirPath, + loadRemote, + loadSocket, + promptNewDir, + promptNewFile, + unselectFiles, + getActiveFiles, + getCurrentDate, + getCurrentSize, + loadCurrentSize, + loadCurrentHash, + setCurrentSize, + getCurrentMode, + getCurrentOwner, + getCurrentData, + getRefreshButton, + getAllFiles, + expandSelection, + shrinkSelection, + setHistory, + getCurrentLink, + getFilenames, + checkStorageHash, + saveDataToStorage, + getFM, + getPanelPosition, + getCSSVar, + getPanel, + getFiles, + showPanel, + hidePanel, + remove, + deleteCurrent, + deleteSelected, + renameCurrent, + scrollIntoViewIfNeeded, + scrollByPages, + changePanel, + getPackerExt, + goToDirectory, + duplicatePanel, + swapPanels, + updateCurrentInfo, }; +assign(DOM, { + ...DOMTree, + ...CurrentFile, + ...Cmd, +}); + +export const CurrentInfo = {}; + DOM.Images = Images; DOM.load = load; DOM.Files = Files; DOM.RESTful = RESTful; +DOM.IO = IO; DOM.Storage = Storage; DOM.Dialog = Dialog; +DOM.CurrentInfo = CurrentInfo; -module.exports = DOM; +export default DOM; -DOM.uploadDirectory = require('./directory'); -DOM.Buffer = require('./buffer'); -DOM.Events = require('./events'); +DOM.uploadDirectory = uploadDirectory; +DOM.Buffer = Buffer; +DOM.Events = Events; +const isString = (a) => typeof a === 'string'; -const loadRemote = require('./load-remote'); -const selectByPattern = require('./select-by-pattern'); +const TabPanel = { + 'js-left': null, + 'js-right': null, +}; -function CmdProto() { - let CurrentInfo = {}; - - const Cmd = this; - const SELECTED_FILE = 'selected-file'; - const TITLE = 'Cloud Commander'; - const TabPanel = { - 'js-left' : null, - 'js-right' : null - }; - - this.loadRemote = (name, options, callback) => { - loadRemote(name, options, callback); - return DOM; - }; - - this.loadSocket = function(callback) { - DOM.loadRemote('socket', { - name : 'io' - }, callback); - - return DOM; - }; - - /** - * create new folder - * - */ - this.promptNewDir = function() { - promptNew('directory', '?dir'); - }; - - /** - * create new file - * - * @typeName - * @type - */ - this.promptNewFile = () => { - promptNew('file'); - }; - - function promptNew(typeName, type) { - const {Dialog} = DOM; - const dir = DOM.getCurrentDirPath(); - const msg = 'New ' + typeName || 'File'; - const getName = () => { - const name = DOM.getCurrentName(); - - if (name === '..') - return ''; - - return name; - }; - - const name = getName(); - const cancel = false; - - Dialog.prompt(TITLE, msg, name, {cancel}).then((name) => { - if (!name) - return; - - const path = (type) => { - const result = dir + name; - - if (!type) - return result; - - return result + type; - }; - - RESTful.write(path(type), (error) => { - if (error) - return; - - const currentName = name; - - CloudCmd.refresh({ - currentName - }); - }); - }); - } - - /** - * get current direcotory name - */ - this.getCurrentDirName = () => { - const href = DOM.getCurrentDirPath() - .replace(/\/$/, ''); - - const substr = href.substr(href, href.lastIndexOf('/')); - const ret = href.replace(substr + '/', '') || '/'; - - return ret; - }; - - /** - * get current direcotory path - */ - this.getParentDirPath = (panel) => { - const path = DOM.getCurrentDirPath(panel); - const dirName = DOM.getCurrentDirName() + '/'; - const index = path.lastIndexOf(dirName); - - if (path !== '/') - return path.slice(0, index); - - return path; - }; - - /** - * get not current direcotory path - */ - this.getNotCurrentDirPath = () => { - const panel = DOM.getPanel({active: false}); - const path = DOM.getCurrentDirPath(panel); - - return path; - }; - - /** - * get current file by name - */ - this.getCurrentByName = (name, panel = CurrentInfo.panel) => { - const dataName = 'js-file-' + btoa(encodeURI(name)); - const element = DOM.getByDataName(dataName, panel); - - return element; - }; - - /** - * unified way to get selected files - * - * @currentFile - */ - this.getSelectedFiles = () => { - const panel = DOM.getPanel(); - const selected = DOM.getByClassAll(SELECTED_FILE, panel); - - return [...selected]; - }; - - /* - * unselect all files - */ - this.unselectFiles = (files) => { - files = files || DOM.getSelectedFiles(); - - [...files].forEach(DOM.toggleSelectedFile); - }; - - /** - * get all selected files or current when none selected - * - * @currentFile - */ - this.getActiveFiles = () => { - const current = DOM.getCurrentFile(); - const files = DOM.getSelectedFiles(); - const name = DOM.getCurrentName(current); - - if (!files.length && name !== '..') - return [current]; - - return files; - }; - - this.getCurrentDate = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const date = DOM - .getByDataName('js-date', current) - .textContent; - - return date; - }; - - /** - * get size - * @currentFile - */ - this.getCurrentSize = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - /* если это папка - возвращаем слово dir вместо размера*/ - const size = DOM.getByDataName('js-size', current) - .textContent - .replace(/^<|>$/g, ''); - - return size; - }; - - /** - * get size - * @currentFile - */ - this.loadCurrentSize = (callback, currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const query = '?size'; - const link = DOM.getCurrentPath(current); - - Images.show.load(); - - if (name === '..') - return; - - RESTful.read(link + query, (error, size) => { - if (error) - return; - - DOM.setCurrentSize(size, current); - exec(callback, current); - Images.hide(); - }); - }; - - /** - * load hash - * @callback - * @currentFile - */ - this.loadCurrentHash = (callback, currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const query = '?hash'; - const link = DOM.getCurrentPath(current); - - RESTful.read(link + query, callback); - }; - - /** - * load current modification time of file - * @callback - * @currentFile - */ - this.loadCurrentTime = (callback, currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const query = '?time'; - const link = DOM.getCurrentPath(current); - - RESTful.read(link + query, callback); - }; - - /** - * set size - * @currentFile - */ - this.setCurrentSize = (size, currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const sizeElement = DOM.getByDataName('js-size', current); - - sizeElement.textContent = size; - }; - - /** - * @currentFile - */ - this.getCurrentMode = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const mode = DOM.getByDataName('js-mode', current); - - return mode.textContent; - }; - - /** - * @currentFile - */ - this.getCurrentOwner = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const owner = DOM.getByDataName('js-owner', current); - - return owner.textContent; - }; - - /** - * unified way to get current file content - * - * @param callback - * @param currentFile - */ - this.getCurrentData = (callback, currentFile) => { - let hash; - const Dialog = DOM.Dialog; - const Info = DOM.CurrentInfo; - const current = currentFile || DOM.getCurrentFile(); - const path = DOM.getCurrentPath(current); - const isDir = DOM.isCurrentIsDir(current); - - const func = (error, data) => { - const ONE_MEGABYTE = 1024 * 1024 * 1024; - - if (!error) { - if (itype.object(data)) - data = jonny.stringify(data); - - const length = data.length; - - if (hash && length < ONE_MEGABYTE) - DOM.saveDataToStorage(path, data, hash); - } - - callback(error, data); - }; - - if (Info.name === '..') { - Dialog.alert.noFiles(TITLE); - return callback(Error('No files selected!')); - } - - if (isDir) - return RESTful.read(path, func); - - DOM.checkStorageHash(path, (error, equal, hashNew) => { - if (error) - return callback(error); - - if (equal) - return DOM.getDataFromStorage(path, callback); - - hash = hashNew; - RESTful.read(path, func); - }); - }; - - /** - * unified way to save current file content - * - * @callback - function({data, name}) {} - * @currentFile - */ - this.saveCurrentData = (url, data, callback, query = '') => { - DOM.RESTful.write(url + query, data, (error) => { - !error && DOM.saveDataToStorage(url, data); - }); - }; - - /** - * unified way to get RefreshButton - */ - this.getRefreshButton = (panel) => { - const currentPanel = panel || DOM.getPanel(); - const refresh = DOM.getByDataName('js-refresh', currentPanel); - - return refresh; - }; - - this.setCurrentByName = (name) => { - const current = DOM.getCurrentByName(name); - return DOM.setCurrentFile(current); - }; - - /** - * select current file - * @param currentFile - */ - this.selectFile = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - - current.classList.add(SELECTED_FILE); - - return Cmd; - }; - - this.unselectFile = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - - current.classList.remove(SELECTED_FILE); - - return Cmd; - }; - - this.toggleSelectedFile = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const name = DOM.getCurrentName(current); - - if (name === '..') - return Cmd; - - current.classList.toggle(SELECTED_FILE); - - return Cmd; - }; - - this.toggleAllSelectedFiles = () => { - DOM.getAllFiles().map(DOM.toggleSelectedFile); - - return Cmd; - }; - - this.selectAllFiles = () => { - DOM.getAllFiles().map(DOM.selectFile); - - return Cmd; - }; - - this.getAllFiles = () => { - const panel = DOM.getPanel(); - const files = DOM.getFiles(panel); - const name = DOM.getCurrentName(files[0]); - - const from = (a) => a === '..' ? 1 : 0; - const i = from(name); - - return [...files].slice(i); - }; - - /** - * open dialog with expand selection - */ - this.expandSelection = () => { - const msg = 'expand'; - const files = CurrentInfo.files; - - selectByPattern(msg, files); - }; - - /** - * open dialog with shrink selection - */ - this.shrinkSelection = () => { - const msg = 'shrink'; - const files = CurrentInfo.files; - - selectByPattern(msg, files); - }; - - /** - * setting history wrapper - */ - this.setHistory = (data, title, url) => { - const ret = window.history; - - url = CloudCmd.PREFIX + url; - - if (ret) - history.pushState(data, title, url); - - return ret; - }; - - /** - * selected file check - * - * @param currentFile - */ - this.isSelected = (selected) => { - if (!selected) - return false; - - return DOM.isContainClass(selected, SELECTED_FILE); - }; - - /** - * check is current file is a directory - * - * @param currentFile - */ - this.isCurrentIsDir = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const fileType = DOM.getByDataName('js-type', current); - - return DOM.isContainClass(fileType, [ - 'directory', - 'directory-link', - ]); - }; - - /** - * get link from current (or param) file - * - * @param currentFile - current file by default - */ - this.getCurrentLink = (currentFile) => { - const current = currentFile || DOM.getCurrentFile(); - const link = DOM.getByTag('a', current); - - return link[0]; - }; - - this.getFilenames = (files) => { - if (!files) - throw Error('AllFiles could not be empty'); - - const first = files[0] || DOM.getCurrentFile(); - const name = DOM.getCurrentName(first); - - const allFiles = [...files]; - - if (name === '..') - allFiles.shift(); - - const names = allFiles.map((current) => { - return DOM.getCurrentName(current); - }); - - return names; - }; - - /** - * check storage hash - */ - this.checkStorageHash = (name, callback) => { - const parallel = exec.parallel; - const loadHash = DOM.loadCurrentHash; - const nameHash = name + '-hash'; - const getStoreHash = exec.with(Storage.get, nameHash); - - if (typeof name !== 'string') - throw Error('name should be a string!'); - - if (typeof callback !== 'function') - throw Error('callback should be a function!'); - - parallel([loadHash, getStoreHash], (error, loadHash, storeHash) => { - let equal; - const isContain = /error/.test(loadHash); - - if (isContain) - error = loadHash; - else if (loadHash === storeHash) - equal = true; - - callback(error, equal, loadHash); - }); - }; - - /** - * save data to storage - * - * @param name - * @param data - * @param hash - * @param callback - */ - this.saveDataToStorage = function(name, data, hash, callback) { - const isDir = DOM.isCurrentIsDir(); - const nameHash = name + '-hash'; - const nameData = name + '-data'; - - if (isDir) - return exec(callback); - - exec.if(hash, () => { - Storage.set(nameHash, hash); - Storage.set(nameData, data); - - exec(callback, hash); - }, (callback) => { - DOM.loadCurrentHash((error, loadHash) => { - hash = loadHash; - callback(); - }); - }); - }; - - /** - * save data to storage - * - * @param name - * @param data - * @param callback - */ - this.getDataFromStorage = (name, callback) => { - const nameHash = name + '-hash'; - const nameData = name + '-data'; - const isDir = DOM.isCurrentIsDir(); - - if (isDir) - return exec(callback); - - exec.parallel([ - exec.with(Storage.get, nameData), - exec.with(Storage.get, nameHash), - ], callback); - }; - - this.getFM = () => { - return DOM.getPanel().parentElement; - }; - - this.getPanelPosition = (panel) => { - panel = panel || DOM.getPanel(); - - return panel.dataset.name.replace('js-', ''); - }; - - /** function getting panel active, or passive - * @param options = {active: true} - */ - this.getPanel = (options) => { - let files, panel, isLeft; - let dataName = 'js-'; - - const current = DOM.getCurrentFile(); - - if (!current) { - panel = DOM.getByDataName('js-left'); - } else { - files = current.parentElement, - panel = files.parentElement, - isLeft = panel.getAttribute('data-name') === 'js-left'; - } - - /* if {active : false} getting passive panel */ - if (options && !options.active) { - dataName += isLeft ? 'right' : 'left'; - panel = DOM.getByDataName(dataName); - } - - /* if two panels showed - * then always work with passive - * panel - */ - if (window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH) - panel = DOM.getByDataName('js-left'); - - if (!panel) - throw Error('can not find Active Panel!'); - - return panel; - }; - - this.getFiles = (element) => { - const files = DOM.getByDataName('js-files', element); - return files.children || []; - }; - - /** - * shows panel right or left (or active) - */ - this.showPanel = (active) => { - const panel = DOM.getPanel({active: active}); - - if (!panel) - return false; - - DOM.show(panel); - - return true; - }; - - /** - * hides panel right or left (or active) - */ - this.hidePanel = (active) => { - const panel = DOM.getPanel({ - active - }); - - if (!panel) - return false; - - return DOM.hide(panel); - }; - - /** - * remove child of element - * @param pChild - * @param element - */ - this.remove = (child, element) => { - const parent = element || document.body; - - parent.removeChild(child); - - return DOM; - }; - - /** - * remove current file from file table - * @param current - * - */ - this.deleteCurrent = (current) => { - if (!current) - DOM.getCurrentFile(); - - const parent = current && current.parentElement; - const name = DOM.getCurrentName(current); - - if (current && name !== '..') { - const next = current.nextSibling; - const prev = current.previousSibling; - - DOM.setCurrentFile(next || prev); - parent.removeChild(current); - } - }; - - /** - * remove selected files from file table - * @Selected - */ - this.deleteSelected = (selected) => { - selected = selected || DOM.getSelectedFiles(); - - if (!selected) - return; - - selected.map(DOM.deleteCurrent); - }; - - /** - * rename current file - * - * @currentFile - */ - this.renameCurrent = (current) => { - const Dialog = DOM.Dialog; - - if (!DOM.isCurrentFile(current)) - current = DOM.getCurrentFile(); - - const from = DOM.getCurrentName(current); - - if (from === '..') - return Dialog.alert.noFiles(TITLE); - - const cancel = false; - - Dialog.prompt(TITLE, 'Rename', from, {cancel}).then((to) => { - const isExist = !!DOM.getCurrentByName(to); - const dirPath = DOM.getCurrentDirPath(); - - if (from === to) - return; - - const files = { - from : dirPath + from, - to : dirPath + to - }; - - RESTful.mv(files, (error) => { - if (error) - return; - - DOM.setCurrentName(to, current); - Storage.remove(dirPath); - - if (isExist) - CloudCmd.refresh(); - }); - }); - }; - - /** - * unified way to scrollIntoViewIfNeeded - * (native suporte by webkit only) - * @param element - * @param center - to scroll as small as possible param should be false - */ - this.scrollIntoViewIfNeeded = function(element, center = false) { - if (!element || !element.scrollIntoViewIfNeeded) - return; - - element.scrollIntoViewIfNeeded(center); - }; - - /* scroll on one page */ - this.scrollByPages = (element, pPages) => { - const ret = element && element.scrollByPages && pPages; - - if (ret) - element.scrollByPages(pPages); - - return ret; - }; - - this.changePanel = () => { - const Info = CurrentInfo; - let panel = DOM.getPanel(); - - CloudCmd.emit('passive-dir', Info.dirPath); - - const panelPassive = DOM.getPanel({ - active: false - }); - - let name = DOM.getCurrentName(); - const filesPassive = DOM.getFiles(panelPassive); - - let dataName = panel.getAttribute('data-name'); - - TabPanel[dataName] = name; - - panel = panelPassive; - dataName = panel.getAttribute('data-name'); - - name = TabPanel[dataName]; - - let files; - let current; - - if (name) { - current = DOM.getCurrentByName(name, panel); - - if (current) - files = current.parentElement; - } - - if (!files || !files.parentElement) { - current = DOM.getCurrentByName(name, panel); - - if (!current) - current = filesPassive[0]; - } - - DOM.setCurrentFile(current, { - history: true - }); - - CloudCmd.emit('active-dir', Info.dirPath); - - return DOM; - }; - - this.getPackerExt = (type) => { - if (type === 'zip') - return '.zip'; - - return '.tar.gz'; - }; - - this.goToDirectory = () => { - const msg = 'Go to directory:'; - const path = CurrentInfo.dirPath; - const Dialog = DOM.Dialog; - const cancel = false; - const setPath = (path) => ({ - path - }); - - Dialog.prompt(TITLE, msg, path, {cancel}) - .then(setPath) - .then(CloudCmd.loadDir); - }, - - this.duplicatePanel = () => { - const Info = CurrentInfo; - const isDir = Info.isDir; - const panel = Info.panelPassive; - const noCurrent = !Info.isOnePanel; - - const getPath = (isDir) => { - if (isDir) - return Info.path; - - return Info.dirPath; - }; - - const path = getPath(isDir); - - CloudCmd.loadDir({ - path, - panel, - noCurrent, - }); - }; - - this.swapPanels = () => { - const Info = CurrentInfo; - const {panel} = Info; - const {files} = Info; - const {element} = Info; - - const panelPassive = Info.panelPassive; - - const dirPath = DOM.getCurrentDirPath(); - const dirPathPassive = DOM.getNotCurrentDirPath(); - - let currentIndex = files.indexOf(element); - - CloudCmd.loadDir({ - path: dirPath, - panel: panelPassive, - noCurrent: true - }); - - CloudCmd.loadDir({ - path: dirPathPassive, - panel: panel - }, () => { - const files = Info.files; - const length = files.length - 1; - - if (currentIndex > length) - currentIndex = length; - - const el = files[currentIndex]; - - DOM.setCurrentFile(el); - }); - }; - - this.CurrentInfo = CurrentInfo, - - this.updateCurrentInfo = (currentFile) => { - const info = DOM.CurrentInfo; - const current = currentFile || DOM.getCurrentFile(); - const files = current.parentElement; - const panel = files.parentElement; - - const panelPassive = DOM.getPanel({ - active: false - }); - - const filesPassive = DOM.getFiles(panelPassive); - const name = DOM.getCurrentName(current); - - info.dir = DOM.getCurrentDirName(); - info.dirPath = DOM.getCurrentDirPath(); - info.parentDirPath = DOM.getParentDirPath(); - info.element = current; - info.ext = Util.getExt(name); - info.files = [...files.children]; - info.filesPassive = [...filesPassive]; - info.first = files.firstChild; - info.getData = DOM.getCurrentData; - info.last = files.lastChild; - info.link = DOM.getCurrentLink(current); - info.mode = DOM.getCurrentMode(current); - info.name = name; - info.path = DOM.getCurrentPath(current); - info.panel = panel; - info.panelPassive = panelPassive; - info.size = DOM.getCurrentSize(current); - info.isDir = DOM.isCurrentIsDir(); - info.isSelected = DOM.isSelected(current); - info.panelPosition = DOM.getPanel().dataset.name.replace('js-', ''); - info.isOnePanel = - info.panel.getAttribute('data-name') === - info.panelPassive.getAttribute('data-name'); - }; +export function loadRemote(name, options, callback) { + _loadRemote(name, options, callback); + return DOM; } +export function loadSocket(callback) { + DOM.loadRemote('socket', { + name: 'io', + }, callback); + + return DOM; +} + +/** + * create new folder + * + */ +export async function promptNewDir() { + await promptNew('directory'); +} + +/** + * create new file + * + * @typeName + * @type + */ +export async function promptNewFile() { + await promptNew('file'); +} + +async function promptNew(typeName) { + const {Dialog} = DOM; + const dir = DOM.getCurrentDirPath(); + const msg = `New ${typeName}` || 'File'; + + const getName = () => { + const name = DOM.getCurrentName(); + + if (name === '..') + return ''; + + return name; + }; + + const name = getName(); + const [cancel, currentName] = await Dialog.prompt(msg, name); + + if (cancel) + return; + + const path = `${dir}${currentName}`; + + if (typeName === 'directory') + await RESTful.createDirectory(path); + else + await RESTful.write(path); + + await CloudCmd.refresh({ + currentName, + }); +} + +/** + * get current directory name + */ +export function getCurrentDirName() { + const href = DOM + .getCurrentDirPath() + .replace(/\/$/, ''); + + const substr = href.substr(href, href.lastIndexOf('/')); + + return href.replace(`${substr}/`, '') || '/'; +} + +/** + * get current directory path + */ +export function getParentDirPath(panel) { + const path = DOM.getCurrentDirPath(panel); + const dirName = DOM.getCurrentDirName() + '/'; + const index = path.lastIndexOf(dirName); + + if (path !== '/') + return path.slice(0, index); + + return path; +} + +/** + * get not current directory path + */ +export function getNotCurrentDirPath() { + const panel = DOM.getPanel({ + active: false, + }); + + return DOM.getCurrentDirPath(panel); +} + +/* + * unselect all files + */ +export function unselectFiles(files) { + files = files || DOM.getSelectedFiles(); + + Array + .from(files) + .forEach(DOM.toggleSelectedFile); +} + +/** + * get all selected files or current when none selected + * + * @currentFile + */ +export function getActiveFiles() { + const current = DOM.getCurrentFile(); + const files = DOM.getSelectedFiles(); + const name = DOM.getCurrentName(current); + + if (!files.length && name !== '..') + return [current]; + + return files; +} + +export function getCurrentDate(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + + return DOM.getByDataName('js-date', current).textContent; +} + +/** + * get size + * @currentFile + */ +export function getCurrentSize(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + + /* если это папка - возвращаем слово dir вместо размера*/ + const size = DOM + .getByDataName('js-size', current) + .textContent + .replace(/^<|>$/g, ''); + + return size; +} + +/** + * get size + * @currentFile + */ +export async function loadCurrentSize(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + const query = '?size'; + const link = DOM.getCurrentPath(current); + + Images.show.load(); + + if (name === '..') + return; + + const [, size] = await RESTful.read(link + query); + + DOM.setCurrentSize(size, current); + Images.hide(); + + return current; +} + +/** + * load hash + * @callback + * @currentFile + */ +export async function loadCurrentHash(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + const query = '?hash'; + const link = DOM.getCurrentPath(current); + + const [, data] = await RESTful.read(link + query); + + return data; +} + +/** + * set size + * @currentFile + */ +export function setCurrentSize(size, currentFile) { + const current = currentFile || DOM.getCurrentFile(); + const sizeElement = DOM.getByDataName('js-size', current); + + sizeElement.textContent = size; +} + +/** + * @currentFile + */ +export function getCurrentMode(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + const mode = DOM.getByDataName('js-mode', current); + + return mode.textContent; +} + +/** + * @currentFile + */ +export function getCurrentOwner(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + const owner = DOM.getByDataName('js-owner', current); + + return owner.textContent; +} + +/** + * unified way to get current file content + * + * @param currentFile + */ +export async function getCurrentData(currentFile) { + const {Dialog} = DOM; + const Info = DOM.CurrentInfo; + const current = currentFile || DOM.getCurrentFile(); + const path = DOM.getCurrentPath(current); + const isDir = DOM.isCurrentIsDir(current); + + if (Info.name === '..') { + Dialog.alert.noFiles(); + return [ + Error('No Files'), + ]; + } + + if (isDir) + return await RESTful.read(path); + + const [hashNew, hash] = await DOM.checkStorageHash(path); + + if (!hashNew) + return [ + Error(`Can't get hash of a file`), + ]; + + if (hash === hashNew) + return [null, await Storage.get(`${path}-data`)]; + + const [e, data] = await RESTful.read(path); + + if (e) + return [ + e, + null, + ]; + + const ONE_MEGABYTE = 1024 ** 2 * 1024; + const {length} = data; + + if (hash && length < ONE_MEGABYTE) + await DOM.saveDataToStorage(path, data, hashNew); + + return [null, data]; +} + +/** + * unified way to get RefreshButton + */ +export function getRefreshButton(panel = DOM.getPanel()) { + return DOM.getByDataName('js-refresh', panel); +} + +export function getAllFiles() { + const panel = DOM.getPanel(); + const files = DOM.getFiles(panel); + const name = DOM.getCurrentName(files[0]); + + const from = (a) => a === '..' ? 1 : 0; + const i = from(name); + + return Array + .from(files) + .slice(i); +} + +/** + * open dialog with expand selection + */ +export async function expandSelection() { + const msg = 'expand'; + const {files} = CurrentInfo; + + await selectByPattern(msg, files); +} + +/** + * open dialog with shrink selection + */ +export async function shrinkSelection() { + const msg = 'shrink'; + const {files} = CurrentInfo; + + await selectByPattern(msg, files); +} + +/** + * setting history wrapper + */ +export function setHistory(data, title, url) { + const ret = globalThis.history; + const {prefix} = CloudCmd; + + url = prefix + url; + + if (ret) + history.pushState(data, title, url); + + return ret; +} + +/** + * get link from current (or param) file + * + * @param currentFile - current file by default + */ +export function getCurrentLink(currentFile) { + const current = currentFile || DOM.getCurrentFile(); + const link = DOM.getByTag('a', current); + + return link[0]; +} + +export function getFilenames(files) { + if (!files) + throw Error('AllFiles could not be empty'); + + const first = files[0] || DOM.getCurrentFile(); + const name = DOM.getCurrentName(first); + + const allFiles = Array.from(files); + + if (name === '..') + allFiles.shift(); + + return allFiles.map(DOM.getCurrentName); +} + +/** + * check storage hash + */ +export async function checkStorageHash(name) { + const nameHash = `${name}-hash`; + + if (!isString(name)) + throw Error('name should be a string!'); + + const [loadHash, storeHash] = await Promise.all([ + DOM.loadCurrentHash(), + Storage.get(nameHash), + ]); + + return [loadHash, storeHash]; +} + +/** + * save data to storage + * + * @param name + * @param data + * @param hash + */ +export async function saveDataToStorage(name, data, hash) { + const isDir = DOM.isCurrentIsDir(); + + if (isDir) + return; + + hash = hash || await DOM.loadCurrentHash(); + + const nameHash = `${name}-hash`; + const nameData = `${name}-data`; + + await Storage.set(nameHash, hash); + await Storage.set(nameData, data); + + return hash; +} + +export function getFM() { + const {parentElement} = DOM.getPanel(); + return parentElement; +} + +export function getPanelPosition(panel) { + panel = panel || DOM.getPanel(); + + return panel.dataset.name.replace('js-', ''); +} + +export function getCSSVar(name, {body = document.body} = {}) { + const bodyStyle = getComputedStyle(body); + return bodyStyle.getPropertyValue(`--${name}`); +} + +/** function getting panel active, or passive + * @param options = {active: true} + */ +export function getPanel(options) { + let files; + let panel; + let isLeft; + let dataName = 'js-'; + + const current = DOM.getCurrentFile(); + + if (!current) { + panel = DOM.getByDataName('js-left'); + } else { + files = current.parentElement; + panel = files.parentElement; + isLeft = panel.getAttribute('data-name') === 'js-left'; + } + + /* if {active : false} getting passive panel */ + if (options && !options.active) { + dataName += isLeft ? 'right' : 'left'; + panel = DOM.getByDataName(dataName); + } + + /* if two panels showed + * then always work with passive + * panel + */ + if (globalThis.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH) + panel = DOM.getByDataName('js-left'); + + if (!panel) + throw Error('can not find Active Panel!'); + + return panel; +} + +export function getFiles(element) { + const files = DOM.getByDataName('js-files', element); + return files.children || []; +} + +/** + * shows panel right or left (or active) + */ +export function showPanel(active) { + const panel = DOM.getPanel({ + active, + }); + + if (!panel) + return false; + + DOM.show(panel); + + return true; +} + +/** + * hides panel right or left (or active) + */ +export function hidePanel(active) { + const panel = DOM.getPanel({ + active, + }); + + if (!panel) + return false; + + return DOM.hide(panel); +} + +/** + * remove child of element + * @param child + * @param element + */ +export function remove(child, element) { + const parent = element || document.body; + + parent.removeChild(child); + + return DOM; +} + +/** + * remove current file from file table + * @param current + * + */ +export function deleteCurrent(current) { + if (!current) + DOM.getCurrentFile(); + + const parent = current?.parentElement; + const name = DOM.getCurrentName(current); + + if (current && name !== '..') { + const next = current.nextSibling; + const prev = current.previousSibling; + + DOM.setCurrentFile(next || prev); + parent.removeChild(current); + } +} + +/** + * remove selected files from file table + * @Selected + */ +export function deleteSelected(selected) { + selected = selected || DOM.getSelectedFiles(); + + if (!selected) + return; + + selected.map(DOM.deleteCurrent); +} + +/** + * rename current file + * + * @currentFile + */ +export function scrollIntoViewIfNeeded(element, center = false) { + if (!element || !element.scrollIntoViewIfNeeded) + return; + + element.scrollIntoViewIfNeeded(center); +} + +/* scroll on one page */ +export function scrollByPages(element, pPages) { + const ret = element?.scrollByPages && pPages; + + if (ret) + element.scrollByPages(pPages); + + return ret; +} + +export function changePanel() { + const Info = CurrentInfo; + let panel = DOM.getPanel(); + + CloudCmd.emit('passive-dir', Info.dirPath); + + const panelPassive = DOM.getPanel({ + active: false, + }); + + let name = DOM.getCurrentName(); + const filesPassive = DOM.getFiles(panelPassive); + + let dataName = panel.getAttribute('data-name'); + + TabPanel[dataName] = name; + + panel = panelPassive; + dataName = panel.getAttribute('data-name'); + + name = TabPanel[dataName]; + + let files; + let current; + + if (name) { + current = DOM.getCurrentByName(name, panel); + + if (current) + files = current.parentElement; + } + + if (!files || !files.parentElement) { + current = DOM.getCurrentByName(name, panel); + + if (!current) + [current] = filesPassive; + } + + DOM.setCurrentFile(current, { + history: true, + }); + + CloudCmd.emit('active-dir', Info.dirPath); + + return DOM; +} + +export function getPackerExt(type) { + if (type === 'zip') + return '.zip'; + + return '.tar.gz'; +} + +export async function goToDirectory(overrides = {}) { + const {Dialog} = DOM; + const { + prompt = Dialog.prompt, + changeDir = CloudCmd.changeDir, + } = overrides; + + const msg = 'Go to directory:'; + const {dirPath} = CurrentInfo; + + const [cancel, path = dirPath] = await prompt(msg, dirPath); + + if (cancel) + return; + + await changeDir(path); +} + +export async function duplicatePanel() { + const Info = CurrentInfo; + const {isDir} = Info; + const panel = Info.panelPassive; + const noCurrent = !Info.isOnePanel; + + const getPath = (isDir) => { + if (isDir) + return Info.path; + + return Info.dirPath; + }; + + const path = getPath(isDir); + + await CloudCmd.changeDir(path, { + panel, + noCurrent, + }); +} + +export async function swapPanels() { + const Info = CurrentInfo; + const { + panel, + files, + element, + panelPassive, + } = Info; + + const path = DOM.getCurrentDirPath(); + const dirPathPassive = DOM.getNotCurrentDirPath(); + + let currentIndex = files.indexOf(element); + + await CloudCmd.changeDir(path, { + panel: panelPassive, + noCurrent: true, + }); + + await CloudCmd.changeDir(dirPathPassive, { + panel, + }); + + const length = Info.files.length - 1; + + if (currentIndex > length) + currentIndex = length; + + const el = Info.files[currentIndex]; + + DOM.setCurrentFile(el); +} + +export function updateCurrentInfo(currentFile) { + const info = DOM.CurrentInfo; + const current = currentFile || DOM.getCurrentFile(); + const files = current.parentElement; + + const panelPassive = DOM.getPanel({ + active: false, + }); + + const filesPassive = DOM.getFiles(panelPassive); + const name = DOM.getCurrentName(current); + + info.dir = DOM.getCurrentDirName(); + info.dirPath = DOM.getCurrentDirPath(); + info.parentDirPath = DOM.getParentDirPath(); + info.element = current; + info.ext = getExt(name); + info.files = Array.from(files.children); + info.filesPassive = Array.from(filesPassive); + info.first = files.firstChild; + info.getData = DOM.getCurrentData; + info.last = files.lastChild; + info.link = DOM.getCurrentLink(current); + info.mode = DOM.getCurrentMode(current); + info.name = name; + info.path = DOM.getCurrentPath(current); + info.panel = files.parentElement || DOM.getPanel(); + info.panelPassive = panelPassive; + info.size = DOM.getCurrentSize(current); + info.isDir = DOM.isCurrentIsDir(); + info.isSelected = DOM.isSelected(current); + info.panelPosition = DOM + .getPanel() + .dataset + .name + .replace('js-', ''); + info.isOnePanel = info.panel.getAttribute('data-name') === info.panelPassive.getAttribute('data-name'); +} diff --git a/client/dom/index.spec.js b/client/dom/index.spec.js new file mode 100644 index 00000000..268efe5f --- /dev/null +++ b/client/dom/index.spec.js @@ -0,0 +1,52 @@ +import {test, stub} from 'supertape'; +import {getCSSVar, goToDirectory} from '#dom'; + +globalThis.CloudCmd = {}; + +test('cloudcmd: client: dom: goToDirectory', async (t) => { + const path = ''; + const changeDir = stub(); + const prompt = stub().returns([null, path]); + + await goToDirectory({ + prompt, + changeDir, + }); + + t.calledWith(changeDir, [path]); + t.end(); +}); + +test('cloudcmd: client: dom: getCSSVar', (t) => { + const body = {}; + const getPropertyValue = stub().returns(0); + + globalThis.getComputedStyle = stub().returns({ + getPropertyValue, + }); + const result = getCSSVar('hello', { + body, + }); + + delete globalThis.getComputedStyle; + + t.notOk(result); + t.end(); +}); + +test('cloudcmd: client: dom: getCSSVar: 1', (t) => { + const body = {}; + const getPropertyValue = stub().returns(1); + + globalThis.getComputedStyle = stub().returns({ + getPropertyValue, + }); + const result = getCSSVar('hello', { + body, + }); + + delete globalThis.getComputedStyle; + + t.ok(result); + t.end(); +}); diff --git a/client/dom/io/index.js b/client/dom/io/index.js new file mode 100644 index 00000000..192769e6 --- /dev/null +++ b/client/dom/io/index.js @@ -0,0 +1,166 @@ +import {FS} from '#common/cloudfunc'; +import {sendRequest as _sendRequest} from './send-request.js'; + +const {assign} = Object; + +const imgPosition = { + top: true, +}; + +export const remove = async (url, data, overrides = {}) => { + const { + sendRequest = _sendRequest, + } = overrides; + + const request = { + method: 'DELETE', + url: FS + url, + imgPosition: { + top: Boolean(data), + }, + }; + + if (data) + assign(request, { + data, + url: `${request.url}?files`, + }); + + return await sendRequest(request); +}; + +export const patch = async (url, data) => { + return await _sendRequest({ + method: 'PATCH', + url: FS + url, + data, + imgPosition, + }); +}; + +export const write = async (url, data) => { + return await _sendRequest({ + method: 'PUT', + url: FS + url, + data, + imgPosition, + }); +}; + +export const createDirectory = async (url, overrides = {}) => { + const { + sendRequest = _sendRequest, + } = overrides; + + return await sendRequest({ + method: 'PUT', + url: `${FS}${url}?dir`, + imgPosition, + }); +}; + +export const read = async (url, dataType = 'text') => { + const notLog = !url.includes('?'); + + return await _sendRequest({ + method: 'GET', + url: FS + url, + notLog, + dataType, + }); +}; + +export const copy = async (from, to, names) => { + return await _sendRequest({ + method: 'PUT', + url: '/copy', + data: { + from, + to, + names, + }, + imgPosition, + }); +}; + +export const pack = async (data) => { + return await _sendRequest({ + method: 'PUT', + url: '/pack', + data, + }); +}; + +export const extract = async (data) => { + return await _sendRequest({ + method: 'PUT', + url: '/extract', + data, + }); +}; + +export const move = async (from, to, names) => { + return await _sendRequest({ + method: 'PUT', + url: '/move', + data: { + from, + to, + names, + }, + imgPosition, + }); +}; + +export const rename = async (from, to) => { + return await _sendRequest({ + method: 'PUT', + url: '/rename', + data: { + from, + to, + }, + imgPosition, + }); +}; + +export const Config = { + read: async () => { + return await _sendRequest({ + method: 'GET', + url: '/config', + imgPosition, + notLog: true, + }); + }, + + write: async (data) => { + return await _sendRequest({ + method: 'PATCH', + url: '/config', + data, + imgPosition, + }); + }, +}; + +export const Markdown = { + read: async (url) => { + return await _sendRequest({ + method: 'GET', + url: `/markdown${url}`, + imgPosition, + notLog: true, + }); + }, + + render: async (data) => { + return await _sendRequest({ + method: 'PUT', + url: '/markdown', + data, + imgPosition, + notLog: true, + }); + }, +}; diff --git a/client/dom/io/index.spec.js b/client/dom/io/index.spec.js new file mode 100644 index 00000000..8e9e2d08 --- /dev/null +++ b/client/dom/io/index.spec.js @@ -0,0 +1,61 @@ +import {test, stub} from 'supertape'; +import * as io from './index.js'; + +test('client: dom: io', (t) => { + const sendRequest = stub(); + + io.createDirectory('/hello', { + sendRequest, + }); + + const expected = { + imgPosition: { + top: true, + }, + method: 'PUT', + url: '/fs/hello?dir', + }; + + t.calledWith(sendRequest, [expected]); + t.end(); +}); + +test('client: dom: io: remove: no files', async (t) => { + const sendRequest = stub(); + + await io.remove('/hello', null, { + sendRequest, + }); + + const expected = { + imgPosition: { + top: false, + }, + method: 'DELETE', + url: '/fs/hello', + }; + + t.calledWith(sendRequest, [expected]); + t.end(); +}); + +test('client: dom: io: remove: files', async (t) => { + const sendRequest = stub(); + const files = ['world']; + + await io.remove('/hello', files, { + sendRequest, + }); + + const expected = { + imgPosition: { + top: true, + }, + data: ['world'], + method: 'DELETE', + url: '/fs/hello?files', + }; + + t.calledWith(sendRequest, [expected]); + t.end(); +}); diff --git a/client/dom/io/send-request.js b/client/dom/io/send-request.js new file mode 100644 index 00000000..177d34b5 --- /dev/null +++ b/client/dom/io/send-request.js @@ -0,0 +1,48 @@ +/* global CloudCmd */ +import {promisify} from 'es6-promisify'; +import * as Images from '#dom/images'; +import * as load from '#dom/load'; + +export const sendRequest = promisify((params, callback) => { + const p = params; + const {prefixURL} = CloudCmd; + + p.url = prefixURL + p.url; + p.url = encodeURI(p.url); + + p.url = replaceHash(p.url); + + load.ajax({ + method: p.method, + url: p.url, + data: p.data, + dataType: p.dataType, + error: (jqXHR) => { + const response = jqXHR.responseText; + + const {statusText, status} = jqXHR; + + const text = status === 404 ? response : statusText; + + callback(Error(text)); + }, + success: (data) => { + Images.hide(); + + if (!p.notLog) + CloudCmd.log(data); + + callback(null, data); + }, + }); +}); + +export const _replaceHash = replaceHash; + +function replaceHash(url) { + /* + * if we send ajax request - + * no need in hash so we escape # + */ + return url.replace(/#/g, '%23'); +} diff --git a/client/dom/io/send-request.spec.js b/client/dom/io/send-request.spec.js new file mode 100644 index 00000000..f8a960d8 --- /dev/null +++ b/client/dom/io/send-request.spec.js @@ -0,0 +1,11 @@ +import {test} from 'supertape'; +import {_replaceHash} from './send-request.js'; + +test('cloudcmd: client: io: replaceHash', (t) => { + const url = '/hello/####world'; + const result = _replaceHash(url); + const expected = '/hello/%23%23%23%23world'; + + t.equal(result, expected); + t.end(); +}); diff --git a/client/dom/load-remote.js b/client/dom/load-remote.js index 2b1578bc..5be8e327 100644 --- a/client/dom/load-remote.js +++ b/client/dom/load-remote.js @@ -1,68 +1,58 @@ -'use strict'; - /* global CloudCmd */ +import {callbackify} from 'node:util'; +import {rendy} from 'rendy'; +import itype from 'itype'; +import * as load from 'load.js'; +import {tryToCatch} from 'try-to-catch'; +import {findObjByNameInArr} from '#common/util'; +import * as Files from '#dom/files'; -const exec = require('execon'); -const rendy = require('rendy/legacy'); -const itype = require('itype/legacy'); -const wraptile = require('wraptile/legacy'); -const load = require('load.js'); - -const {findObjByNameInArr} = require('../../common/util'); - -const Files = require('./files'); -const parallel = wraptile(load.parallel); - -module.exports = (name, options, callback = options) => { - const {PREFIX, config} = CloudCmd; +export const loadRemote = callbackify(async (name, options) => { + const {prefix, config} = CloudCmd; const o = options; if (o.name && window[o.name]) - return callback(); + return; - Files.get('modules', (error, modules) => { - const online = config('online') && navigator.onLine; - const module = findObjByNameInArr(modules.remote, name); + const modules = await Files.get('modules'); + + const online = config('online') && navigator.onLine; + const module = findObjByNameInArr(modules.remote, name); + + const isArray = itype.array(module.local); + const {version} = module; + + let remoteTmpls; + let local; + + if (isArray) { + remoteTmpls = module.remote; + ({local} = module); + } else { + remoteTmpls = [module.remote]; + local = [module.local]; + } + + const localURL = []; + + for (const url of local) { + localURL.push(prefix + url); + } + + const remoteURL = []; + + for (const tmpl of remoteTmpls) { + remoteURL.push(rendy(tmpl, { + version, + })); + } + + if (online) { + const [e] = await tryToCatch(load.parallel, remoteURL); - const isArray = itype.array(module.local); - const version = module.version; - - let remoteTmpls, local; - if (isArray) { - remoteTmpls = module.remote; - local = module.local; - } else { - remoteTmpls = [module.remote]; - local = [module.local]; - } - - const localURL = local.map((url) => { - return PREFIX + url; - }); - - const remoteURL = remoteTmpls.map((tmpl) => { - return rendy(tmpl, { - version: version - }); - }); - - const on = funcON(localURL, remoteURL, callback); - const off = funcOFF(localURL, callback); - - exec.if(online, on, off); - }); -}; - -function funcOFF(local, callback) { - return parallel(local, callback); -} - -function funcON (local, remote,callback) { - return parallel(remote, (error) => { - if (error) - return funcOFF(); - - callback(); - }); -} - + if (!e) + return; + } + + await load.parallel(localURL); +}); diff --git a/client/dom/load.js b/client/dom/load.js index 022b01e4..8c7011c1 100644 --- a/client/dom/load.js +++ b/client/dom/load.js @@ -1,12 +1,8 @@ -'use strict'; - -const itype = require('itype/legacy'); -const jonny = require('jonny/legacy'); -const Emitify = require('emitify/legacy'); -const exec = require('execon'); -const Images = require('./images'); - -module.exports.getIdBySrc = getIdBySrc; +import itype from 'itype'; +import jonny from 'jonny'; +import Emitify from 'emitify'; +import exec from 'execon'; +import * as Images from '#dom/images'; /** * Function gets id by src @@ -14,17 +10,18 @@ module.exports.getIdBySrc = getIdBySrc; * * Example: http://domain.com/1.js -> 1_js */ -function getIdBySrc(src) { +export function getIdBySrc(src) { const isStr = itype.string(src); if (!isStr) return; - if (~src.indexOf(':')) + if (src.includes(':')) src += '-join'; const num = src.lastIndexOf('/') + 1; const sub = src.substr(src, num); + const id = src .replace(sub, '') .replace(/\./g, '-'); @@ -37,34 +34,37 @@ function getIdBySrc(src) { * * @param params */ -module.exports.ajax = (params) => { +export const ajax = (params) => { const p = params; const isObject = itype.object(p.data); const isArray = itype.array(p.data); const isArrayBuf = itype(p.data) === 'arraybuffer'; const type = p.type || p.method || 'GET'; - const headers = p.headers || {}; + + const {headers = {}} = p; + const xhr = new XMLHttpRequest(); xhr.open(type, p.url, true); - Object.keys(headers).forEach((name) => { + for (const name of Object.keys(headers)) { const value = headers[name]; xhr.setRequestHeader(name, value); - }); + } if (p.responseType) xhr.responseType = p.responseType; let data; + if (!isArrayBuf && isObject || isArray) data = jonny.stringify(p.data); else - data = p.data; + ({data} = p); xhr.onreadystatechange = (event) => { const xhr = event.target; - const OK = 200; + const OK = 200; if (xhr.readyState !== xhr.DONE) return; @@ -72,30 +72,30 @@ module.exports.ajax = (params) => { Images.clearProgress(); const TYPE_JSON = 'application/json'; - const type = xhr.getResponseHeader('content-type'); + const type = xhr.getResponseHeader('content-type'); if (xhr.status !== OK) return exec(p.error, xhr); const notText = p.dataType !== 'text'; - const isContain = ~type.indexOf(TYPE_JSON); + const isContain = type.includes(TYPE_JSON); let data = xhr.response; + if (type && isContain && notText) data = jonny.parse(xhr.response) || xhr.response; - + exec(p.success, data, xhr.statusText, xhr); }; xhr.send(data); }; -module.exports.put = (url, body) => { +export const put = (url, body) => { const emitter = Emitify(); const xhr = new XMLHttpRequest(); - url = encodeURI(url) - .replace('#', '%23'); + url = encodeURI(url).replace(/#/g, '#'); xhr.open('put', url, true); @@ -103,8 +103,8 @@ module.exports.put = (url, body) => { if (!event.lengthComputable) return; - const percent = (event.loaded / event.total) * 100; - const count = Math.round(percent); + const percent = event.loaded / event.total * 100; + const count = Math.round(percent); emitter.emit('progress', count); }; @@ -116,8 +116,10 @@ module.exports.put = (url, body) => { if (!over) return; - if (xhr.status === OK) + if (xhr.status === OK) { + emitter.emit('progress', 100); return emitter.emit('end'); + } const error = Error(xhr.responseText); emitter.emit('error', error); @@ -127,4 +129,3 @@ module.exports.put = (url, body) => { return emitter; }; - diff --git a/client/dom/operations/rename-current.js b/client/dom/operations/rename-current.js new file mode 100644 index 00000000..8b6536d3 --- /dev/null +++ b/client/dom/operations/rename-current.js @@ -0,0 +1,66 @@ +/* global CloudCmd */ +import capitalize from 'just-capitalize'; +import * as _Dialog from '#dom/dialog'; +import * as Storage from '#dom/storage'; +import * as RESTful from '#dom/rest'; +import * as _currentFile from '../current-file.js'; + +export default async (current, overrides = {}) => { + const { + refresh = CloudCmd.refresh, + Dialog = _Dialog, + currentFile = _currentFile, + } = overrides; + + const { + isCurrentFile, + getCurrentName, + getCurrentFile, + getCurrentByName, + getCurrentType, + getCurrentDirPath, + setCurrentName, + } = currentFile; + + if (!isCurrentFile(current)) + current = getCurrentFile(); + + const from = getCurrentName(current); + + if (from === '..') + return Dialog.alert.noFiles(); + + const [cancel, to] = await Dialog.prompt('Rename', from); + + if (cancel) + return; + + const nextFile = getCurrentByName(to); + + if (nextFile) { + const type = getCurrentType(nextFile); + const msg = `${capitalize(type)} "${to}" already exists. Proceed?`; + const [cancel] = await Dialog.confirm(msg); + + if (cancel) + return; + } + + if (from === to) + return; + + const dirPath = getCurrentDirPath(); + + const fromFull = `${dirPath}${from}`; + const toFull = `${dirPath}${to}`; + + const [e] = await RESTful.rename(fromFull, toFull); + + if (e) + return; + + setCurrentName(to, current); + + Storage.remove(dirPath); + refresh(); +}; diff --git a/client/dom/operations/rename-current.spec.js b/client/dom/operations/rename-current.spec.js new file mode 100644 index 00000000..a5ebb415 --- /dev/null +++ b/client/dom/operations/rename-current.spec.js @@ -0,0 +1,86 @@ +import {test, stub} from 'supertape'; +import renameCurrent from './rename-current.js'; + +test('cloudcmd: client: dom: renameCurrent: isCurrentFile', async (t) => { + const current = {}; + const isCurrentFile = stub(); + + const currentFile = stubCurrentFile({ + isCurrentFile, + }); + + await renameCurrent(current, { + Dialog: stubDialog(), + currentFile, + }); + + t.calledWith(isCurrentFile, [current], 'should call isCurrentFile'); + t.end(); +}); + +test('cloudcmd: client: dom: renameCurrent: file exist', async (t) => { + const current = {}; + const name = 'hello'; + + const prompt = stub().returns([null, name]); + const confirm = stub().returns([true]); + + const getCurrentByName = stub().returns(current); + const getCurrentType = stub().returns('directory'); + + const Dialog = stubDialog({ + confirm, + prompt, + }); + + const currentFile = stubCurrentFile({ + getCurrentByName, + getCurrentType, + }); + + await renameCurrent(null, { + Dialog, + currentFile, + }); + + const expected = 'Directory "hello" already exists. Proceed?'; + + t.calledWith(confirm, [expected], 'should call confirm'); + t.end(); +}); + +const stubDialog = (fns = {}) => { + const { + alert = stub().returns([]), + confirm = stub().returns([]), + prompt = stub().returns([]), + } = fns; + + return { + alert, + confirm, + prompt, + }; +}; + +const stubCurrentFile = (fns = {}) => { + const { + isCurrentFile = stub(), + getCurrentName = stub(), + getCurrentFile = stub(), + getCurrentByName = stub(), + getCurrentType = stub(), + getCurrentDirPath = stub(), + setCurrentName = stub(), + } = fns; + + return { + isCurrentFile, + getCurrentName, + getCurrentFile, + getCurrentByName, + getCurrentType, + getCurrentDirPath, + setCurrentName, + }; +}; diff --git a/client/dom/rest.js b/client/dom/rest.js index 6e0faa01..3cf2fb66 100644 --- a/client/dom/rest.js +++ b/client/dom/rest.js @@ -1,220 +1,40 @@ -'use strict'; +import {tryToCatch} from 'try-to-catch'; +import * as Dialog from '#dom/dialog'; +import * as Images from '#dom/images'; +import {encode} from '#common/entity'; +import * as IO from './io/index.js'; -/* global CloudCmd, DOM */ +const handleError = (promise) => async (...args) => { + const [e, data] = await tryToCatch(promise, ...args); + + if (!e) + return [e, data]; + + const encoded = encode(e.message); + + Images.show.error(encoded); + Dialog.alert(encoded); + + return [e, data]; +}; -const itype = require('itype/legacy'); +export const remove = handleError(IO.remove); +export const patch = handleError(IO.patch); +export const write = handleError(IO.write); +export const createDirectory = handleError(IO.createDirectory); +export const read = handleError(IO.read); +export const copy = handleError(IO.copy); +export const pack = handleError(IO.pack); +export const extract = handleError(IO.extract); +export const move = handleError(IO.move); +export const rename = handleError(IO.rename); -const {FS} = require('../../common/cloudfunc'); -const { - encode, -} = require('../../common/entity'); +export const Config = { + read: handleError(IO.Config.read), + write: handleError(IO.Config.write), +}; -module.exports = new RESTful(); - -const Images = require('./images'); -const load = require('./load'); - -function RESTful() { - this.delete = (url, data, callback) => { - const isFunc = itype.function(data); - - if (!callback && isFunc) { - callback = data; - data = null; - } - - sendRequest({ - method : 'DELETE', - url : FS + url, - data, - callback, - imgPosition : { top: !!data } - }); - }; - - this.patch = (url, data, callback) => { - const isFunc = itype.function(data); - - if (!callback && isFunc) { - callback = data; - data = null; - } - - const imgPosition = { - top: true - }; - - sendRequest({ - method: 'PATCH', - url: FS + url, - data, - callback, - imgPosition, - }); - }; - - this.write = (url, data, callback) => { - const isFunc = itype.function(data); - - if (!callback && isFunc) { - callback = data; - data = null; - } - - sendRequest({ - method: 'PUT', - url: FS + url, - data, - callback, - imgPosition : { top: true } - }); - }; - - this.read = (url, dataType, callback) => { - const isQuery = /\?/.test(url); - const isBeautify = /\?beautify$/.test(url); - const isMinify = /\?minify$/.test(url); - const notLog = !isQuery || isBeautify || isMinify; - const isFunc = itype.function(dataType); - - if (!callback && isFunc) { - callback = dataType; - dataType = 'text'; - } - - sendRequest({ - method: 'GET', - url: FS + url, - callback, - notLog, - dataType, - }); - }; - - this.cp = (data, callback) => { - sendRequest({ - method: 'PUT', - url: '/cp', - data, - callback, - imgPosition : { top: true } - }); - }; - - this.pack = (data, callback) => { - sendRequest({ - method : 'PUT', - url : '/pack', - data, - callback, - }); - }; - - this.extract = function(data, callback) { - sendRequest({ - method : 'PUT', - url : '/extract', - data : data, - callback : callback - }); - }; - - this.mv = function(data, callback) { - sendRequest({ - method : 'PUT', - url : '/mv', - data : data, - callback : callback, - imgPosition : { top: true } - }); - }; - - this.Config = { - read: function(callback) { - sendRequest({ - method : 'GET', - url : '/config', - callback : callback, - imgPosition : { top: true }, - notLog : true - }); - }, - - write: function(data, callback) { - sendRequest({ - method : 'PATCH', - url : '/config', - data : data, - callback : callback, - imgPosition : { top: true } - }); - } - }; - - this.Markdown = { - read : function(url, callback) { - sendRequest({ - method : 'GET', - url : '/markdown' + url, - callback : callback, - imgPosition : { top: true }, - notLog : true - }); - }, - - render : function(data, callback) { - sendRequest({ - method : 'PUT', - url : '/markdown', - data : data, - callback : callback, - imgPosition : { top: true }, - notLog : true - }); - } - }; - - function sendRequest(params) { - const p = params; - const prefixUrl = CloudCmd.PREFIX_URL; - - p.url = prefixUrl + p.url; - p.url = encodeURI(p.url); - - /* - * if we send ajax request - - * no need in hash so we escape # - */ - p.url = p.url.replace('#', '%23'); - - load.ajax({ - method : p.method, - url : p.url, - data : p.data, - dataType : p.dataType, - error : (jqXHR) => { - const response = jqXHR.responseText; - const statusText = jqXHR.statusText; - const status = jqXHR.status; - const text = status === 404 ? response : statusText; - const encoded = encode(text); - - Images.show.error(encoded); - - setTimeout(() => { - DOM.Dialog.alert(CloudCmd.TITLE, encoded); - }, 100); - - p.callback(Error(text)); - }, - success: (data) => { - Images.hide(); - - if (!p.notLog) - CloudCmd.log(data); - - p.callback(null, data); - } - }); - } -} +export const Markdown = { + read: handleError(IO.Markdown.read), + render: handleError(IO.Markdown.render), +}; diff --git a/client/dom/select-by-pattern.js b/client/dom/select-by-pattern.js index 870d722f..0bada6ef 100644 --- a/client/dom/select-by-pattern.js +++ b/client/dom/select-by-pattern.js @@ -1,52 +1,46 @@ -'use strict'; - -/* global DOM */ +import {alert, prompt} from '#dom/dialog'; +import {getRegExp} from '#common/util'; +import {getCurrentName} from './current-file.js'; +import { + isSelected, + toggleSelectedFile, +} from './cmd.js'; let SelectType = '*.*'; -const TITLE = 'Cloud Commander'; -const {getRegExp} = require('../../common/util'); - -module.exports = (msg, files) => { - const allMsg = `Specify file type for ${msg} selection`; - const cancel = false; - const {Dialog} = DOM; +export const selectByPattern = async (msg, files) => { + if (!files) + return; - Dialog.prompt(TITLE, allMsg, SelectType, {cancel}).then((type) => { - SelectType = type; + const allMsg = `Specify file type for ${msg} selection`; + const [cancel, type] = await prompt(allMsg, SelectType); + + if (cancel) + return; + + SelectType = type; + + const regExp = getRegExp(type); + let matches = 0; + + for (const current of files) { + const name = getCurrentName(current); - const regExp = getRegExp(type); + if (name === '..' || !regExp.test(name)) + continue; - if (!files) - return; + ++matches; - let matches = 0; + let selected = isSelected(current); + const shouldSel = msg === 'expand'; - files.forEach((current) => { - const name = DOM.getCurrentName(current); - - if (name === '..') - return; - - const isMatch = regExp.test(name); - - if (!isMatch) - return; - - ++matches; - - let isSelected = DOM.isSelected(current); - const shouldSel = msg === 'expand'; - - if (shouldSel) - isSelected = !isSelected; - - if (isSelected) - DOM.toggleSelectedFile(current); - }); + if (shouldSel) + selected = !selected; - if (!matches) - Dialog.alert('Select Files', 'No matches found!'); - }); + if (selected) + toggleSelectedFile(current); + } + + if (!matches) + alert('No matches found!'); }; - diff --git a/client/dom/storage.js b/client/dom/storage.js index 495c654e..d5cf231f 100644 --- a/client/dom/storage.js +++ b/client/dom/storage.js @@ -1,66 +1,26 @@ -'use strict'; +const {parse, stringify} = JSON; -const itype = require('itype/legacy'); -const jonny = require('jonny/legacy'); -const exec = require('execon'); -const tryCatch = require('try-catch'); -const setItem = localStorage.setItem.bind(localStorage); - -/** remove element */ -module.exports.remove = (item, callback) => { - localStorage.removeItem(item); - exec(callback, null); - - return module.exports; +export const set = (name, data) => { + localStorage.setItem(name, data); }; -module.exports.removeMatch = (string, callback) => { - const reg = RegExp('^' + string + '.*$'); - const test = (a) => reg.test(a); - const remove = (a) => localStorage.removeItem(a); - - Object.keys(localStorage) - .filter(test) - .forEach(remove); - - exec(callback); - - return module.exports; +export const setJson = (name, data) => { + localStorage.setItem(name, stringify(data)); }; -/** если доступен localStorage и - * в нём есть нужная нам директория - - * записываем данные в него - */ -module.exports.set = (name, data, callback) => { - let str, error; - - if (itype.object(data)) - str = jonny.stringify(data); - - if (name) - [error] = tryCatch(setItem, name, str || data); - - exec(callback, error); - - return module.exports; -}, +export const get = (name) => { + return localStorage.getItem(name); +}; -/** Если доступен Storage принимаем из него данные*/ -module.exports.get = (name, callback) => { - const ret = localStorage.getItem(name); - - exec(callback, null, ret); - - return module.exports; -}, +export const getJson = (name) => { + const data = localStorage.getItem(name); + return parse(data); +}; -/** функция чистит весь кэш для всех каталогов*/ -module.exports.clear = (callback) => { +export const clear = () => { localStorage.clear(); - - exec(callback); - - return module.exports; }; +export const remove = (item) => { + localStorage.removeItem(item); +}; diff --git a/client/dom/storage.spec.js b/client/dom/storage.spec.js new file mode 100644 index 00000000..c538952d --- /dev/null +++ b/client/dom/storage.spec.js @@ -0,0 +1,105 @@ +import {test, stub} from 'supertape'; +import * as storage from '#dom/storage'; + +const {stringify} = JSON; + +test('cloudcmd: client: storage: set', async (t) => { + const {localStorage} = globalThis; + const setItem = stub(); + + globalThis.localStorage = { + setItem, + }; + + await storage.set('hello', 'world'); + globalThis.localStorage = localStorage; + + t.calledWith(setItem, ['hello', 'world'], 'should call setItem'); + t.end(); +}); + +test('cloudcmd: client: storage: get', async (t) => { + const {localStorage} = globalThis; + const getItem = stub().returns('world'); + + globalThis.localStorage = { + getItem, + }; + + const result = await storage.get('hello'); + + globalThis.localStorage = localStorage; + + t.equal(result, 'world'); + t.end(); +}); + +test('cloudcmd: client: storage: getJson', async (t) => { + const {localStorage} = globalThis; + const expected = { + hello: 'world', + }; + + const getItem = stub().returns(stringify(expected)); + + globalThis.localStorage = { + getItem, + }; + + const result = await storage.getJson('hello'); + + globalThis.localStorage = localStorage; + + t.deepEqual(result, expected); + t.end(); +}); + +test('cloudcmd: client: storage: setJson', async (t) => { + const {localStorage} = globalThis; + const data = { + hello: 'world', + }; + + const expected = stringify(data); + const setItem = stub(); + + globalThis.localStorage = { + setItem, + }; + + await storage.setJson('hello', data); + globalThis.localStorage = localStorage; + + t.calledWith(setItem, ['hello', expected]); + t.end(); +}); + +test('cloudcmd: client: storage: remove', async (t) => { + const {localStorage} = globalThis; + const removeItem = stub(); + + globalThis.localStorage = { + removeItem, + }; + + await storage.remove('hello'); + globalThis.localStorage = localStorage; + + t.calledWith(removeItem, ['hello'], 'should call removeItem'); + t.end(); +}); + +test('cloudcmd: client: storage: clear', async (t) => { + const {localStorage} = globalThis; + const clear = stub(); + + globalThis.localStorage = { + clear, + }; + + await storage.clear(); + globalThis.localStorage = localStorage; + + t.calledWithNoArgs(clear, 'should call clear'); + t.end(); +}); diff --git a/client/dom/upload-files.js b/client/dom/upload-files.js index accbb203..1c37fe1b 100644 --- a/client/dom/upload-files.js +++ b/client/dom/upload-files.js @@ -1,30 +1,19 @@ -'use strict'; - /* global CloudCmd */ +import {eachSeries} from 'execon'; +import wraptile from 'wraptile'; +import * as load from '#dom/load'; +import {alert} from '#dom/dialog'; +import {FS} from '#common/cloudfunc'; +import * as Images from '#dom/images'; +import {getCurrentDirPath} from './current-file.js'; -const {eachSeries} = require('execon'); -const wraptile = require('wraptile/legacy'); - -const DOM = require('.'); -const load = require('./load'); -const Images = require('./images'); -const {alert} = require('./dialog'); - -const {FS} = require('../../common/cloudfunc'); - -const {TITLE} = CloudCmd; - -const onEnd = wraptile(_onEnd); const loadFile = wraptile(_loadFile); +const onEnd = wraptile(_onEnd); -const { - getCurrentDirPath: getPathWhenRootEmpty -} = DOM; - -module.exports = (dir, files) => { +export const uploadFiles = (dir, files) => { if (!files) { files = dir; - dir = getPathWhenRootEmpty(); + dir = getCurrentDirPath(); } const n = files.length; @@ -32,7 +21,7 @@ module.exports = (dir, files) => { if (!n) return; - const array = [...files]; + const array = Array.from(files); const {name} = files[0]; eachSeries(array, loadFile(dir, n), onEnd(name)); @@ -40,17 +29,17 @@ module.exports = (dir, files) => { function _onEnd(currentName) { CloudCmd.refresh({ - currentName + currentName, }); } function _loadFile(dir, n, file, callback) { let i = 0; - const name = file.name; + const {name} = file; const path = dir + name; - const {PREFIX_URL} = CloudCmd; - const api = PREFIX_URL + FS; + const {prefixURL} = CloudCmd; + const api = prefixURL + FS; const percent = (i, n, per = 100) => { return Math.round(i * per / n); @@ -60,7 +49,8 @@ function _loadFile(dir, n, file, callback) { ++i; - load.put(api + path, file) + load + .put(api + path, file) .on('error', showError) .on('end', callback) .on('progress', (count) => { @@ -73,6 +63,5 @@ function _loadFile(dir, n, file, callback) { } function showError({message}) { - alert(TITLE, message); + alert(message); } - diff --git a/client/get-json-from-file-table.js b/client/get-json-from-file-table.js new file mode 100644 index 00000000..ea90f366 --- /dev/null +++ b/client/get-json-from-file-table.js @@ -0,0 +1,44 @@ +/* global DOM */ +/** + * Функция генерирует JSON из html-таблицы файлов и + * используеться при первом заходе в корень + */ +export const getJsonFromFileTable = () => { + const Info = DOM.CurrentInfo; + const path = DOM.getCurrentDirPath(); + const infoFiles = Info.files || []; + + const files = infoFiles + .filter(notParent) + .map(parse); + + const fileTable = { + path, + files, + }; + + return fileTable; +}; + +const notParent = (current) => { + const name = DOM.getCurrentName(current); + return name !== '..'; +}; + +const parse = (current) => { + const name = DOM.getCurrentName(current); + const size = DOM.getCurrentSize(current); + const owner = DOM.getCurrentOwner(current); + const mode = DOM.getCurrentMode(current); + const date = DOM.getCurrentDate(current); + const type = DOM.getCurrentType(current); + + return { + name, + size, + mode, + owner, + date, + type, + }; +}; diff --git a/client/input.js b/client/input.js deleted file mode 100644 index 459ca7a4..00000000 --- a/client/input.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -const currify = require('currify/legacy'); - -const isType = currify((type, object, name) => { - return typeof object[name] === type; -}); - -const isBool = isType('boolean'); - -module.exports.getElementByName = getElementByName; - -function getElementByName(selector, element) { - const str = `[data-name="js-${selector}"]`; - - return element - .querySelector(str); -} - -module.exports.getName = (element) => { - const name = element - .getAttribute('data-name') - .replace(/^js-/, ''); - - return name; -}; - -module.exports.convert = (config) => { - const result = { - ...config - }; - - const array = Object.keys(result); - - array - .filter(isBool(result)) - .forEach((name) => { - const item = result[name]; - - result[name] = setState(item); - }); - - return result; -}; - -function setState(state) { - if (state) - return ' checked'; - - return ''; -} - -module.exports.getValue = (name, element) => { - const el = getElementByName(name, element); - const type = el.type; - - switch(type) { - case 'checkbox': - return el.checked; - - case 'number': - return Number(el.value); - - default: - return el.value; - } -}; - -module.exports.setValue = (name, value, element) => { - const el = getElementByName(name, element); - const type = el.type; - - switch(type) { - case 'checkbox': - el.checked = value; - break; - - default: - el.value = value; - break; - } -}; - diff --git a/client/key/binder.js b/client/key/binder.js new file mode 100644 index 00000000..6aec97ea --- /dev/null +++ b/client/key/binder.js @@ -0,0 +1,15 @@ +export const createBinder = () => { + let binded = false; + + return { + isBind() { + return binded; + }, + setBind() { + binded = true; + }, + unsetBind() { + binded = false; + }, + }; +}; diff --git a/client/key/binder.spec.js b/client/key/binder.spec.js new file mode 100644 index 00000000..f9d54fdd --- /dev/null +++ b/client/key/binder.spec.js @@ -0,0 +1,28 @@ +import {test} from 'supertape'; +import {createBinder} from './binder.js'; + +test('client: key: binder: isBind: default', (t) => { + const binder = createBinder(); + + t.notOk(binder.isBind(), 'should not be bind by default'); + t.end(); +}); + +test('client: key: binder: setBind', (t) => { + const binder = createBinder(); + + binder.setBind(); + + t.ok(binder.isBind(), 'should be bind'); + t.end(); +}); + +test('client: key: binder: unsetBind', (t) => { + const binder = createBinder(); + + binder.setBind(); + binder.unsetBind(); + + t.notOk(binder.isBind(), 'should not be bind'); + t.end(); +}); diff --git a/client/key/index.js b/client/key/index.js index a568ef18..283a7f11 100644 --- a/client/key/index.js +++ b/client/key/index.js @@ -1,483 +1,544 @@ /* global CloudCmd, DOM */ +import clipboard from '@cloudcmd/clipboard'; +import {fullstore} from 'fullstore'; +import * as Events from '#dom/events'; +import * as Buffer from '../dom/buffer.js'; +import * as KEY from './key.js'; +import _vim from './vim/index.js'; +import setCurrentByChar from './set-current-by-char.js'; +import {createBinder} from './binder.js'; -'use strict'; - -const Info = DOM.CurrentInfo; - -const exec = require('execon'); -const clipboard = require('@cloudcmd/clipboard'); -const wraptile = require('wraptile/legacy'); - -const Events = require('../dom/events'); -const Buffer = require('../dom/buffer'); -const KEY = require('./key'); -const vim = require('./vim'); -const setCurrentByChar = require('./set-current-by-char'); -const fullstore = require('fullstore/legacy'); const Chars = fullstore(); +const toggleVim = (keyCode, overrides = {}) => { + const {_config, config} = overrides; + + if (!config('vim') && keyCode === KEY.ESC) + _config('vim', true); +}; + +const isUndefined = (a) => typeof a === 'undefined'; + Chars([]); -KeyProto.prototype = KEY; -CloudCmd.Key = KeyProto; +const {assign} = Object; +const binder = createBinder(); -function KeyProto() { - let Binded; +const bind = () => { + Events.addKey(listener, true); + binder.setBind(); +}; + +export const Key = assign(binder, KEY, { + bind, +}); + +export const _listener = listener; + +function getChar(event) { + /* + * event.keyIdentifier deprecated in chrome v51 + * but event.key is absent in chrome <= v51 + */ + const { + key, + shift, + keyCode, + keyIdentifier, + } = event; - const Key = this; + const char = key || fromCharCode(keyIdentifier); + const symbol = getSymbol(shift, keyCode); - this.isBind = () => { - return Binded; - }; - - this.setBind = () => { - Binded = true; - }; - - this.unsetBind = () => { - Binded = false; - }; - - this.bind = () => { - Events.addKey(listener); - Binded = true; - }; - - function getChar(event) { - /* - * event.keyIdentifier deprecated in chrome v51 - * but event.key is absent in chrome <= v51 - */ - - if (event.key) - return event.key; - - return fromCharCode(event.keyIdentifier); - } - - function listener(event) { - const keyCode = event.keyCode; - const alt = event.altKey; - const ctrl = event.ctrlKey; - const shift = event.shiftKey; - const meta = event.metaKey; - const isBetween = keyCode >= KEY.ZERO && keyCode <= KEY.Z; - const isNumpad = /Numpad/.test(event.code); - - let char = getChar(event); - let isSymbol = ~['.', '_', '-', '+', '='].indexOf(char); - - if (!isSymbol) { - isSymbol = getSymbol(shift, keyCode); - - if (isSymbol) - char = isSymbol; - } - - if (!Key.isBind()) - return; - - const isVim = CloudCmd.config('vim'); - - if (!isVim && !isNumpad && !alt && !ctrl && !meta && (isBetween || isSymbol)) - return setCurrentByChar(char, Chars); - - Chars([]); - switchKey(event); - - if (keyCode >= KEY.F1 && keyCode <= KEY.F10) - return; - - if (isVim) - vim(char, event); - } - - function getSymbol(shift, keyCode) { - switch (keyCode) { - case KEY.DOT: - return '.'; - - case KEY.HYPHEN: - return shift ? '_' : '-'; - - case KEY.EQUAL: - return shift ? '+' : '='; - } - } - - function fromCharCode(keyIdentifier) { - const code = keyIdentifier.substring(2); - const hex = parseInt(code, 16); - const char = String.fromCharCode(hex); - - return char; - } - - function switchKey(event) { - let i, isSelected, prev, next; - let current = Info.element; - let dataName; - - const name = Info.name; - - const {Operation} = CloudCmd; - const panel = Info.panel; - const path = Info.path; - const isDir = Info.isDir; - - const keyCode = event.keyCode; - const alt = event.altKey; - const shift = event.shiftKey; - const ctrl = event.ctrlKey; - const meta = event.metaKey; - const ctrlMeta = ctrl || meta; - - if (current) { - prev = current.previousSibling; - next = current.nextSibling; - } - - switch (keyCode) { - case Key.TAB: - DOM.changePanel(); - event.preventDefault(); - break; - - case Key.INSERT: - DOM .toggleSelectedFile(current) - .setCurrentFile(next); - break; - - case Key.INSERT_MAC: - DOM .toggleSelectedFile(current) - .setCurrentFile(next); - break; - - case Key.DELETE: - if (shift) - Operation.show('delete:silent'); - else - Operation.show('delete'); - break; - - case Key.ASTERISK: - DOM.toggleAllSelectedFiles(current); - break; - - case Key.PLUS: - DOM.expandSelection(); - event.preventDefault(); - break; - - case Key.MINUS: - DOM.shrinkSelection(); - event.preventDefault(); - break; - - case Key.F1: - CloudCmd.Help.show(); - event.preventDefault(); - break; - - case Key.F2: - DOM.renameCurrent(current); - break; - - case Key.F3: - if (shift) - CloudCmd.Markdown.show(path); - else if (ctrlMeta) - CloudCmd.sortPanel('name'); - else - CloudCmd.View.show(); - - event.preventDefault(); - break; - - case Key.F4: - if (shift) - CloudCmd.EditFileVim.show(); - else - CloudCmd.EditFile.show(); - - event.preventDefault(); - break; - - case Key.F5: - if (ctrlMeta) - CloudCmd.sortPanel('date'); - else if (alt) - Operation.show('pack'); - else - Operation.show('copy'); - - event.preventDefault(); - break; - - case Key.F6: - if (ctrlMeta) - CloudCmd.sortPanel('size'); - else - Operation.show('move'); - - event.preventDefault(); - break; - - case Key.F7: - if (shift) - DOM.promptNewFile(); - else - DOM.promptNewDir(); - - event.preventDefault(); - break; - - case Key.F8: - Operation.show('delete'); - event.preventDefault(); - break; - - case Key.F9: - if (alt) - Operation.show('extract'); - else - CloudCmd.Menu.show(); - event.preventDefault(); - break; - - case Key.F10: - CloudCmd.Config.show(); - event.preventDefault(); - break; - - case Key.TRA: - event.preventDefault(); - - if (shift) - return CloudCmd.Terminal.show(); - - CloudCmd.Konsole.show(); - break; - - case KEY.BRACKET_CLOSE: - CloudCmd.Konsole.show(); - event.preventDefault(); - break; - - case Key.SPACE: - if (!isDir || name === '..') - isSelected = true; - else - isSelected = DOM.isSelected(current); - - exec.if(isSelected, () => { - DOM.toggleSelectedFile(current); - }, (callback) => { - DOM.loadCurrentSize(callback, current); - }); - - event.preventDefault(); - break; - - case Key.U: - if (ctrlMeta) { - DOM.swapPanels(); - event.preventDefault(); - } - break; - - /* navigation on file table: * - * in case of pressing button 'up', * - * select previous row */ - case Key.UP: - if (shift) - DOM.toggleSelectedFile(current); - - DOM.setCurrentFile(prev); - event.preventDefault(); - break; - - /* in case of pressing button 'down', * - * select next row */ - case Key.DOWN: - if (shift) - DOM.toggleSelectedFile(current); - - DOM.setCurrentFile(next); - event.preventDefault(); - break; - - case Key.LEFT: - if (!alt) - return; - - event.preventDefault(); - - dataName = Info.panel.getAttribute('data-name'); - - if (dataName === 'js-right') - DOM.duplicatePanel(); - - break; - - case Key.RIGHT: - if (!alt) - return; - - event.preventDefault(); - - dataName = Info.panel.getAttribute('data-name'); - - if (dataName === 'js-left') - DOM.duplicatePanel(); - - break; - - /* in case of pressing button 'Home', * - * go to top element */ - case Key.HOME: - DOM.setCurrentFile(Info.first); - event.preventDefault(); - break; - - /* in case of pressing button 'End', select last element */ - case Key.END: - DOM.setCurrentFile(Info.last); - event.preventDefault(); - break; - - /* если нажали клавишу page down проматываем экран */ - case Key.PAGE_DOWN: - DOM.scrollByPages(panel, 1); - - for (i = 0; i < 30; i++) { - if (!current.nextSibling) - break; - - current = current.nextSibling; - } - - DOM.setCurrentFile(current); - event.preventDefault(); - break; - - /* если нажали клавишу page up проматываем экран */ - case Key.PAGE_UP: - DOM.scrollByPages(panel, -1); - - for (i = 0; i < 30; i++) { - if (!current.previousSibling) - break; - - current = current.previousSibling; - } - - DOM.setCurrentFile(current); - event.preventDefault(); - break; - - /* open directory */ - case Key.ENTER: - if (Info.isDir) - CloudCmd.loadDir({ - path: path === '/' ? '/' : path + '/' - }); - break; - - case Key.BACKSPACE: - CloudCmd.goToParentDir(); - event.preventDefault(); - break; - - case Key.BACKSLASH: - if (ctrlMeta) - CloudCmd.loadDir({ - path: '/' - }); - break; - - case Key.A: - if (ctrlMeta) { - DOM.selectAllFiles(); - event.preventDefault(); - } - - break; - - case Key.G: - if (alt) { - DOM.goToDirectory(); - event.preventDefault(); - } - - break; - - case Key.M: - if (ctrlMeta) { - if (shift) - CloudCmd.EditNamesVim.show(); - else - CloudCmd.EditNames.show(); - - event.preventDefault(); - } - - break; - - case Key.P: - if (!ctrlMeta) - return; - - event.preventDefault(); - clipboard - .writeText(Info.dirPath) - .catch(CloudCmd.log); - - break; - /** - * обновляем страницу, - * загружаем содержимое каталога - * при этом данные берём всегда с - * сервера, а не из кэша - * (обновляем кэш) - */ - case Key.R: - if (ctrlMeta) { - CloudCmd.log('reloading page...\n'); - CloudCmd.refresh(); - event.preventDefault(); - } - break; - - case Key.C: - if (ctrlMeta) - Buffer.copy(); - break; - - case Key.X: - if (ctrlMeta) - Buffer.cut(); - break; - - case Key.V: - if (ctrlMeta) - Buffer.paste(); - break; - - case Key.Z: - if (ctrlMeta) - Buffer.clear(); - break; - - /* чистим хранилище */ - case Key.D: - if (ctrlMeta) { - CloudCmd.log('clearing storage...'); - DOM.Storage.clear(wraptile(CloudCmd.log, 'storage cleared')); - event.preventDefault(); - } - break; - } - } + return [symbol, char]; } +async function listener(event, overrides = {}) { + const { + config = CloudCmd.config, + _config = CloudCmd._config, + switchKey = _switchKey, + vim = _vim, + } = overrides; + + const {keyCode} = event; + + // strange chrome bug calls listener twice + // in second time event misses a lot fields + if (isUndefined(event.altKey)) + return; + + const alt = event.altKey; + const ctrl = event.ctrlKey; + const meta = event.metaKey; + const isBetween = keyCode >= KEY.ZERO && keyCode <= KEY.Z; + const isNumpad = /Numpad/.test(event.code); + + const [symbol, char] = getChar(event); + + if (!binder.isBind()) + return; + + toggleVim(keyCode, { + config, + _config, + }); + + const isVim = config('vim'); + + if (!isVim && !isNumpad && !alt && !ctrl && !meta && (isBetween || symbol)) + return setCurrentByChar(char, Chars); + + Chars([]); + await switchKey(event); + + if (keyCode >= KEY.F1 && keyCode <= KEY.F10) + return; + + if (isVim) + vim(char, event); +} + +function getSymbol(shift, keyCode) { + switch(keyCode) { + case KEY.DOT: + return '.'; + + case KEY.HYPHEN: + return shift ? '_' : '-'; + + case KEY.EQUAL: + return shift ? '+' : '='; + } + + return ''; +} + +function fromCharCode(keyIdentifier) { + const code = keyIdentifier.substring(2); + const hex = parseInt(code, 16); + + return String.fromCharCode(hex); +} + +async function _switchKey(event) { + const Info = DOM.CurrentInfo; + let i; + let isSelected; + let prev; + let next; + let current = Info.element; + let dataName; + + const { + name, + panel, + path, + isDir, + } = Info; + + const { + Operation, + changeDir, + config, + } = CloudCmd; + + const {keyCode} = event; + + const alt = event.altKey; + const shift = event.shiftKey; + const ctrl = event.ctrlKey; + const meta = event.metaKey; + const ctrlMeta = ctrl || meta; + + if (current) { + prev = current.previousSibling; + next = current.nextSibling; + } + + switch(keyCode) { + case KEY.TAB: + DOM.changePanel(); + event.preventDefault(); + break; + + case KEY.INSERT: + DOM + .toggleSelectedFile(current) + .setCurrentFile(next); + break; + + case KEY.INSERT_MAC: + DOM + .toggleSelectedFile(current) + .setCurrentFile(next); + break; + + case KEY.DELETE: + if (shift) + Operation.show('delete:silent'); + else + Operation.show('delete'); + + break; + + case KEY.ASTERISK: + DOM.toggleAllSelectedFiles(current); + break; + + case KEY.PLUS: + DOM.expandSelection(); + event.preventDefault(); + break; + + case KEY.MINUS: + DOM.shrinkSelection(); + event.preventDefault(); + break; + + case KEY.F1: + CloudCmd.Help.show(); + event.preventDefault(); + break; + + case KEY.F2: + CloudCmd.UserMenu.show(); + break; + + case KEY.F3: + event.preventDefault(); + + if (Info.isDir) + await changeDir(path); + else if (shift) + CloudCmd.View.show(null, { + raw: true, + }); + else if (ctrlMeta) + CloudCmd.sortPanel('name'); + else + CloudCmd.View.show(); + + break; + + case KEY.F4: + if (config('vim')) + CloudCmd.EditFileVim.show(); + else + CloudCmd.EditFile.show(); + + event.preventDefault(); + break; + + case KEY.F5: + if (ctrlMeta) + CloudCmd.sortPanel('date'); + else if (alt) + Operation.show('pack'); + else + Operation.show('copy'); + + event.preventDefault(); + break; + + case KEY.F6: + if (ctrlMeta) + CloudCmd.sortPanel('size'); + else if (shift) + DOM.renameCurrent(current); + else + Operation.show('move'); + + event.preventDefault(); + break; + + case KEY.F7: + if (shift) + DOM.promptNewFile(); + else + DOM.promptNewDir(); + + event.preventDefault(); + break; + + case KEY.F8: + Operation.show('delete'); + event.preventDefault(); + break; + + case KEY.F9: + if (alt) + Operation.show('extract'); + else + CloudCmd.Menu.show(); + + event.preventDefault(); + break; + + case KEY.F10: + CloudCmd.Config.show(); + event.preventDefault(); + break; + + case KEY.TRA: + event.preventDefault(); + + if (shift) + return CloudCmd.Terminal.show(); + + CloudCmd.Konsole.show(); + break; + + case KEY.BRACKET_CLOSE: + CloudCmd.Konsole.show(); + event.preventDefault(); + break; + + case KEY.SPACE: + event.preventDefault(); + + if (!isDir || name === '..') + isSelected = true; + else + isSelected = DOM.isSelected(current); + + if (!isSelected) + await DOM.loadCurrentSize(current); + + DOM.toggleSelectedFile(current); + + break; + + case KEY.U: + if (ctrlMeta) { + DOM.swapPanels(); + event.preventDefault(); + } + + break; + + /* navigation on file table: * + * in case of pressing button 'up', * + * select previous row */ + case KEY.UP: + if (shift) + DOM.toggleSelectedFile(current); + + DOM.setCurrentFile(prev); + event.preventDefault(); + break; + + /* in case of pressing button 'down', * + * select next row */ + case KEY.DOWN: + if (shift) + DOM.toggleSelectedFile(current); + + DOM.setCurrentFile(next); + event.preventDefault(); + break; + + case KEY.LEFT: + if (!alt) + return; + + event.preventDefault(); + + dataName = Info.panel.getAttribute('data-name'); + + if (dataName === 'js-right') + DOM.duplicatePanel(); + + break; + + case KEY.RIGHT: + if (!alt) + return; + + event.preventDefault(); + + dataName = Info.panel.getAttribute('data-name'); + + if (dataName === 'js-left') + DOM.duplicatePanel(); + + break; + + /* in case of pressing button 'Home', * + * go to top element */ + case KEY.HOME: + DOM.setCurrentFile(Info.first); + event.preventDefault(); + break; + + /* in case of pressing button 'End', select last element */ + case KEY.END: + DOM.setCurrentFile(Info.last); + event.preventDefault(); + break; + + /* если нажали клавишу page down проматываем экран */ + case KEY.PAGE_DOWN: + DOM.scrollByPages(panel, 1); + + for (i = 0; i < 30; i++) { + if (!current.nextSibling) + break; + + current = current.nextSibling; + } + + DOM.setCurrentFile(current); + event.preventDefault(); + break; + + /* если нажали клавишу page up проматываем экран */ + case KEY.PAGE_UP: + DOM.scrollByPages(panel, -1); + + for (i = 0; i < 30; i++) { + if (!current.previousSibling) + break; + + current = current.previousSibling; + } + + DOM.setCurrentFile(current); + event.preventDefault(); + break; + + case KEY.ENTER: + if (Info.isDir) + await changeDir(path); + else + CloudCmd.View.show(); + + break; + + case KEY.BACKSPACE: + CloudCmd.goToParentDir(); + event.preventDefault(); + break; + + case KEY.BACKSLASH: + if (ctrlMeta) + await changeDir('/'); + + break; + + case KEY.A: + if (ctrlMeta) { + DOM.selectAllFiles(); + event.preventDefault(); + } + + break; + + case KEY.G: + if (alt) { + DOM.goToDirectory(); + event.preventDefault(); + } + + break; + + case KEY.L: + if (ctrlMeta && shift) { + CloudCmd.logOut(); + event.preventDefault(); + } + + break; + + case KEY.M: + if (ctrlMeta) { + if (config('vim')) + CloudCmd.EditNamesVim.show(); + else + CloudCmd.EditNames.show(); + + event.preventDefault(); + } + + break; + + case KEY.P: + if (!ctrlMeta) + return; + + event.preventDefault(); + clipboard + .writeText(Info.dirPath) + .catch(CloudCmd.log); + + break; + + /** + * обновляем страницу, + * загружаем содержимое каталога + * при этом данные берём всегда с + * сервера, а не из кэша + * (обновляем кэш) + */ + case KEY.R: + if (ctrlMeta) { + CloudCmd.log('reloading page...\n'); + CloudCmd.refresh(); + event.preventDefault(); + } + + break; + + case KEY.C: + if (ctrlMeta) + Buffer.copy(); + + break; + + case KEY.X: + if (ctrlMeta) + Buffer.cut(); + + break; + + case KEY.V: + if (ctrlMeta) + Buffer.paste(); + + break; + + case KEY.Z: + if (ctrlMeta) + Buffer.clear(); + + break; + + case KEY.COLON: + CloudCmd.CommandLine.show(); + event.preventDefault(); + break; + + /* чистим хранилище */ + case KEY.D: + if (ctrlMeta) { + CloudCmd.log('clearing storage...'); + await DOM.Storage.clear(); + CloudCmd.log('storage cleared'); + event.preventDefault(); + } + + break; + + case KEY.DOT: + if (meta && shift) { + const showDotFiles = !CloudCmd.config('showDotFiles'); + CloudCmd._config('showDotFiles', showDotFiles); + CloudCmd.refresh(); + await DOM.RESTful.Config.write({ + showDotFiles, + }); + } + + break; + } +} diff --git a/client/key/index.spec.js b/client/key/index.spec.js new file mode 100644 index 00000000..bec92b31 --- /dev/null +++ b/client/key/index.spec.js @@ -0,0 +1,56 @@ +import autoGlobals from 'auto-globals'; +import supertape from 'supertape'; +import {ESC} from './key.js'; +import {Key, _listener} from './index.js'; +import {getDOM, getCloudCmd} from './vim/globals.fixture.js'; + +const test = autoGlobals(supertape); +const {stub} = supertape; + +globalThis.DOM = getDOM(); +globalThis.CloudCmd = getCloudCmd(); + +test('cloudcmd: client: key: enable vim', async (t) => { + const vim = stub(); + const config = stub().returns(true); + const _config = stub(); + + const event = { + keyCode: ESC, + key: 'Escape', + altKey: false, + }; + + Key.setBind(); + + await _listener(event, { + vim, + config, + _config, + switchKey: stub(), + }); + + t.calledWith(vim, ['Escape', event]); + t.end(); +}); + +test('cloudcmd: client: key: disable vim', async (t) => { + const _config = stub(); + const config = stub(); + + const event = { + keyCode: ESC, + key: 'Escape', + altKey: false, + }; + + Key.setBind(); + await _listener(event, { + config, + _config, + switchKey: stub(), + }); + + t.calledWith(_config, ['vim', true]); + t.end(); +}); diff --git a/client/key/key.js b/client/key/key.js index 197e521e..6772e34c 100644 --- a/client/key/key.js +++ b/client/key/key.js @@ -1,81 +1,58 @@ -'use strict'; - -module.exports = { - BACKSPACE : 8, - TAB : 9, - ENTER : 13, - ESC : 27, - - SPACE : 32, - PAGE_UP : 33, - PAGE_DOWN : 34, - END : 35, - HOME : 36, - - LEFT : 37, - UP : 38, - RIGHT : 39, - DOWN : 40, - - INSERT : 45, - DELETE : 46, - - ZERO : 48, - - SEMICOLON : 52, - - COLON : 54, - - A : 65, - - C : 67, - D : 68, - - G : 71, - - J : 74, - K : 75, - - M : 77, - - O : 79, - P : 80, - Q : 81, - R : 82, - S : 83, - T : 84, - U : 85, - - V : 86, - - X : 88, - - Z : 90, - - INSERT_MAC : 96, - - ASTERISK : 106, - PLUS : 107, - MINUS : 109, - - F1 : 112, - F2 : 113, - F3 : 114, - F4 : 115, - F5 : 116, - F6 : 117, - F7 : 118, - F8 : 119, - F9 : 120, - F10 : 121, - - EQUAL : 187, - HYPHEN : 189, - DOT : 190, - SLASH : 191, - TRA : 192, /* Typewritten Reverse Apostrophe (`) */ - BACKSLASH : 220, - - BRACKET_CLOSE: 221 -}; - +export const BACKSPACE = 8; +export const TAB = 9; +export const ENTER = 13; +export const CAPSLOCK = 20; +export const ESC = 27; +export const SPACE = 32; +export const PAGE_UP = 33; +export const PAGE_DOWN = 34; +export const END = 35; +export const HOME = 36; +export const LEFT = 37; +export const UP = 38; +export const RIGHT = 39; +export const DOWN = 40; +export const INSERT = 45; +export const DELETE = 46; +export const ZERO = 48; +export const SEMICOLON = 52; +export const A = 65; +export const C = 67; +export const D = 68; +export const G = 71; +export const J = 74; +export const K = 75; +export const L = 76; +export const M = 77; +export const O = 79; +export const P = 80; +export const Q = 81; +export const R = 82; +export const S = 83; +export const T = 84; +export const U = 85; +export const V = 86; +export const X = 88; +export const Z = 90; +export const INSERT_MAC = 96; +export const ASTERISK = 106; +export const PLUS = 107; +export const MINUS = 109; +export const F1 = 112; +export const F2 = 113; +export const F3 = 114; +export const F4 = 115; +export const F5 = 116; +export const F6 = 117; +export const F7 = 118; +export const F8 = 119; +export const F9 = 120; +export const F10 = 121; +export const COLON = 186; +export const EQUAL = 187; +export const HYPHEN = 189; +export const DOT = 190; +export const SLASH = 191; +export const TRA = 192; +export const BACKSLASH = 220; +export const BRACKET_CLOSE = 221; diff --git a/client/key/set-current-by-char.js b/client/key/set-current-by-char.js index d010fa86..92764f11 100644 --- a/client/key/set-current-by-char.js +++ b/client/key/set-current-by-char.js @@ -1,23 +1,20 @@ /* global DOM */ +import {escapeRegExp} from '#common/util'; -'use strict'; - -const Info = DOM.CurrentInfo; -const {escapeRegExp} = require('../../common/util'); - -module.exports = function setCurrentByChar(char, charStore) { +export default function setCurrentByChar(char, charStore) { + const Info = DOM.CurrentInfo; let firstByName; let skipCount = 0; - let setted = false; + let set = false; let i = 0; const escapeChar = escapeRegExp(char); - const regExp = new RegExp('^' + escapeChar + '.*$', 'i'); + const regExp = new RegExp(`^${escapeChar}.*$`, 'i'); const {files} = Info; const chars = charStore(); const n = chars.length; - while(i < n && char === chars[i]) + while (i < n && char === chars[i]) i++; if (!i) @@ -31,19 +28,21 @@ module.exports = function setCurrentByChar(char, charStore) { const isTest = (a) => regExp.test(a); const isRoot = (a) => a === '..'; const not = (f) => (a) => !f(a); + const setCurrent = (name) => { const byName = DOM.getCurrentByName(name); if (!skipCount) { - setted = true; + set = true; DOM.setCurrentFile(byName); - return true; - } else { - if (skipN === skipCount) - firstByName = byName; - --skipCount; + return true; } + + if (skipN === skipCount) + firstByName = byName; + + --skipCount; }; names @@ -51,9 +50,8 @@ module.exports = function setCurrentByChar(char, charStore) { .filter(not(isRoot)) .some(setCurrent); - if (!setted) { + if (!set) { DOM.setCurrentFile(firstByName); charStore([char]); } -}; - +} diff --git a/client/key/vim/find.js b/client/key/vim/find.js index bbf1d380..e8db825a 100644 --- a/client/key/vim/find.js +++ b/client/key/vim/find.js @@ -1,41 +1,36 @@ -'use strict'; -/* global DOM */ - -const fullstore = require('fullstore/legacy'); -const limier = require('limier/legacy'); -const Info = DOM.CurrentInfo; +import {fullstore} from 'fullstore'; +import limier from 'limier'; const searchStore = fullstore([]); const searchIndex = fullstore(0); -module.exports.find = (value) => { - const names = Info.files.map(DOM.getCurrentName); +export const find = (value, names) => { const result = limier(value, names); searchStore(result); searchIndex(0); - DOM.setCurrentByName(result[0]); + return result; }; -module.exports.findNext = () => { +export const findNext = () => { const names = searchStore(); const index = next(searchIndex(), names.length); searchIndex(index); - DOM.setCurrentByName(names[searchIndex()]); + return names[searchIndex()]; }; -module.exports.findPrevious = () => { +export const findPrevious = () => { const names = searchStore(); const index = previous(searchIndex(), names.length); searchIndex(index); - DOM.setCurrentByName(names[index]); + return names[index]; }; -module.exports._next = next; -module.exports._previous = previous; +export const _next = next; +export const _previous = previous; function next(index, length) { if (index === length - 1) @@ -50,4 +45,3 @@ function previous(index, length) { return --index; } - diff --git a/client/key/vim/find.spec.js b/client/key/vim/find.spec.js index 6f2dd2a1..191a3652 100644 --- a/client/key/vim/find.spec.js +++ b/client/key/vim/find.spec.js @@ -1,58 +1,14 @@ -'use strict'; - -const test = require('tape'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); -const dir = './'; - -const { - getDOM, -} = require('./globals.fixture'); - -global.DOM = getDOM(); - -const { +import test from 'supertape'; +import {getDOM} from './globals.fixture.js'; +import { + _next, + _previous, find, findNext, findPrevious, - _next, - _previous, -} = require(dir + 'find'); +} from './find.js'; -test('cloudcmd: client: vim: find', (t) => { - const {DOM} = global; - const setCurrentByName = sinon.stub(); - - DOM.setCurrentByName = setCurrentByName; - DOM.Dialog.prompt = Promise.resolve.bind(Promise); - - find(''); - - t.ok(setCurrentByName.calledWith(null), 'should call setCurrentByName'); - t.end(); -}); - -test('cloudcmd: client: vim: findNext', (t) => { - const {DOM} = global; - const setCurrentByName = sinon.stub(); - DOM.setCurrentByName = setCurrentByName; - - findNext(); - - t.ok(setCurrentByName.calledWith(null), 'should call setCurrentByName'); - t.end(); -}); - -test('cloudcmd: client: vim: findPrevious', (t) => { - const {DOM} = global; - const setCurrentByName = sinon.stub(); - - DOM.setCurrentByName = setCurrentByName; - findPrevious(); - - t.ok(setCurrentByName.calledWith(null), 'should call setCurrentByName'); - t.end(); -}); +globalThis.DOM = getDOM(); test('cloudcmd: client: vim: _next', (t) => { const result = _next(1, 2); @@ -61,6 +17,13 @@ test('cloudcmd: client: vim: _next', (t) => { t.end(); }); +test('cloudcmd: client: vim: _next: increment', (t) => { + const result = _next(0, 2); + + t.equal(result, 1, 'should return 1'); + t.end(); +}); + test('cloudcmd: client: vim: _previous', (t) => { const result = _previous(0, 2); @@ -68,3 +31,25 @@ test('cloudcmd: client: vim: _previous', (t) => { t.end(); }); +test('cloudcmd: client: vim: _previous: decrement', (t) => { + const result = _previous(1, 2); + + t.equal(result, 0, 'should return 0'); + t.end(); +}); + +test('cloudcmd: client: vim: findNext: after find', (t) => { + find('a', ['alpha', 'beta', 'apple']); + const result = findNext(); + + t.equal(result, 'beta', 'should return next found name'); + t.end(); +}); + +test('cloudcmd: client: vim: findPrevious: after find', (t) => { + find('a', ['alpha', 'beta', 'apple']); + const result = findPrevious(); + + t.equal(result, 'apple', 'should return previous found name'); + t.end(); +}); diff --git a/client/key/vim/globals.fixture.js b/client/key/vim/globals.fixture.js index 81994ecf..c49894d7 100644 --- a/client/key/vim/globals.fixture.js +++ b/client/key/vim/globals.fixture.js @@ -1,20 +1,19 @@ -'use strict'; +const noop = () => {}; -module.exports.getDOM = () => { - const resolve = Promise.resolve.bind(Promise); +export const getDOM = () => { + const prompt = Promise.resolve.bind(Promise); const CurrentInfo = { element: {}, files: [], }; - const noop = () => {}; const Buffer = { copy: noop, paste: noop, }; const Dialog = { - prompt: resolve + prompt, }; return { @@ -28,16 +27,20 @@ module.exports.getDOM = () => { getCurrentName: noop, setCurrentByName: noop, toggleSelectedFile: noop, + prompNewDirectory: noop, + promptNewFile: noop, }; }; -module.exports.getCloudCmd = () => { +export const getCloudCmd = () => { const show = () => {}; return { - Operation: { - show - } + Operation: { + show, + }, + + config: noop, + _config: noop, }; }; - diff --git a/client/key/vim/index.js b/client/key/vim/index.js index 1c14d764..981f6f19 100644 --- a/client/key/vim/index.js +++ b/client/key/vim/index.js @@ -1,199 +1,167 @@ -'use strict'; -/* global CloudCmd, DOM */ +import vim from './vim.js'; +import * as finder from './find.js'; +import { + setCurrent, + selectFileNotParent, +} from './set-current.js'; -const KEY = require('../key'); -const Info = DOM.CurrentInfo; -const Dialog = DOM.Dialog; - -const fullstore = require('fullstore/legacy'); -const store = fullstore(''); -const visual = fullstore(false); -const { - find, - findNext, - findPrevious, -} = require('./find'); - -const TITLE = 'Cloud Commander'; - -const stopVisual = () => { - visual(false); +export default (key, event, overrides = {}) => { + const defaults = { + ...globalThis.DOM, + ...globalThis.CloudCmd, + }; + + const deps = { + ...defaults, + ...overrides, + }; + + const operations = getOperations(event, deps); + + vim(key, operations, deps); }; -const end = () => { - store(''); +const getOperations = (event, deps) => { + const { + Info = globalThis.DOM.CurrentInfo, + CloudCmd = globalThis.CloudCmd, + Operation, + unselectFiles, + setCurrentFile, + setCurrentByName, + getCurrentName, + prompt = globalThis.DOM.Dialog.prompt, + preventDefault = event?.preventDefault?.bind(event), + stopImmediatePropagation = event?.preventDefault?.bind(event), + promptNewFile = globalThis.DOM.promptNewFile, + toggleSelectedFile, + Buffer = {}, + createFindNext = _createFindNext, + createFindPrevious = _createFindPrevious, + createMakeFile = _createMakeFile, + renameCurrent, + } = deps; + + return { + makeFile: createMakeFile({ + promptNewFile, + preventDefault, + stopImmediatePropagation, + }), + findNext: createFindNext({ + setCurrentByName, + }), + findPrevious: createFindPrevious({ + setCurrentByName, + }), + escape: unselectFiles, + rename: () => { + event.preventDefault(); + renameCurrent(); + }, + remove: () => { + Operation.show('delete'); + }, + operationCopy: () => { + event.preventDefault(); + Operation.show('copy'); + }, + operationMove: () => { + event.preventDefault(); + Operation.show('move'); + }, + + makeDirectory: () => { + event.stopImmediatePropagation(); + event.preventDefault(); + globalThis.DOM.promptNewDir(); + }, + + terminal: () => { + CloudCmd.Terminal.show(); + }, + + edit: () => { + CloudCmd.EditFileVim.show(); + }, + + copy: () => { + Buffer.copy(); + unselectFiles(); + }, + + select: () => { + const current = Info.element; + toggleSelectedFile(current); + }, + + paste: Buffer.paste, + + moveNext: ({count, isVisual, isDelete}) => { + setCurrent('next', { + count, + isVisual, + isDelete, + }, { + Info, + setCurrentFile, + unselectFiles, + Operation, + }); + }, + + movePrevious: ({count, isVisual, isDelete}) => { + setCurrent('previous', { + count, + isVisual, + isDelete, + }, { + Info, + setCurrentFile, + unselectFiles, + Operation, + }); + }, + + find: async () => { + preventDefault(); + const [, value] = await prompt('Find', ''); + + if (!value) + return; + + const names = Info.files.map(getCurrentName); + const [result] = finder.find(value, names); + + setCurrentByName(result); + }, + }; }; -const rmFirst = (a) => { - return a - .split('') - .slice(1) - .join(''); +export const selectFile = selectFileNotParent; + +const _createFindPrevious = (overrides = {}) => () => { + const {setCurrentByName} = overrides; + const name = finder.findPrevious(); + + setCurrentByName(name); }; -module.exports = (key, event) => { - const current = Info.element; - const keyCode = event.keyCode; - const prevStore = store(); +const _createFindNext = (overrides = {}) => () => { + const {setCurrentByName} = overrides; + const name = finder.findNext(); - const value = store(prevStore.concat(key)); - - if (keyCode === KEY.ENTER) - return end(); - - if (keyCode === KEY.ESC) { - DOM.unselectFiles(); - visual(false); - return end(); - } - - if (key === 'j') { - move('next', { - prevStore, - current, - }); - - return end(); - } - - if (key === 'k') { - move('previous', { - prevStore, - current, - }); - - return end(); - } - - if (/gg/.test(value)) { - move('previous', { - current, - prevStore, - max: Infinity, - }); - - return end(); - } - - if (key === 'd' && (visual() || prevStore === 'd')) { - CloudCmd.Operation.show('delete'); - stopVisual(); - return end(); - } - - if (key === 'G') { - move('next', { - current, - prevStore, - max: Infinity, - }); - - return end(); - } - - if (key === 'y') { - if (!visual()) - return end(); - - DOM.Buffer.copy(); - stopVisual(); - DOM.unselectFiles(); - return end(); - } - - if (/^p$/i.test(key)) { - DOM.Buffer.paste(); - return end(); - } - - if (/^v$/i.test(key)) { - DOM.toggleSelectedFile(current); - visual(!visual()); - - return end(); - } - - if (key === '/') { - event.preventDefault(); - - Dialog.prompt(TITLE, 'Find', '', {cancel: false}) - .then(find); - - return end(); - } - - if (key === 'n') { - findNext(); - return end(); - } - - if (key === 'N') { - findPrevious(); - return end(); - } + setCurrentByName(name); }; -module.exports.selectFile = selectFile; - -function move(sibling, {max, current, prevStore}) { - const isDelete = prevStore[0] === 'd'; +const _createMakeFile = (overrides = {}) => () => { + const { + promptNewFile, + stopImmediatePropagation, + preventDefault, + } = overrides; - if (isDelete) { - visual(true); - prevStore = rmFirst(prevStore); - } - - const n = max || getNumber(prevStore); - - if (isNaN(n)) - return; - - setCurrent({ - n, - current, - sibling, - visual: visual(), - }); - - if (isDelete) - CloudCmd.Operation.show('delete'); -} - -function getNumber(value) { - if (!value) - return 1; - - if (value === 'g') - return 1; - - return parseInt(value); -} - -function selectFile(current) { - const name = DOM.getCurrentName(current); - - if (name === '..') - return; - - DOM.selectFile(current); -} - -function setCurrent({n, current, visual, sibling}) { - const select = visual ? selectFile : DOM.unselectFile; - - select(current); - - const position = `${sibling}Sibling`; - for (let i = 0; i < n; i++) { - const next = current[position]; - - if (!next) - break; - - current = next; - select(current); - } - - DOM.setCurrentFile(current); -} - + stopImmediatePropagation(); + preventDefault(); + promptNewFile(); +}; diff --git a/client/key/vim/index.spec.js b/client/key/vim/index.spec.js index 32ec407f..231c6577 100644 --- a/client/key/vim/index.spec.js +++ b/client/key/vim/index.spec.js @@ -1,426 +1,756 @@ -'use strict'; +import {test, stub} from 'supertape'; +import {getDOM, getCloudCmd} from './globals.fixture.js'; +import vim, {selectFile as vimSelectFile} from './index.js'; +import * as finder from './find.js'; -const test = require('tape'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); -const dir = '../'; -const KEY = require(dir + 'key'); +globalThis.DOM = getDOM(); +globalThis.CloudCmd = getCloudCmd(); -const { - getDOM, - getCloudCmd, -} = require('./globals.fixture'); - -global.DOM = getDOM(); -global.CloudCmd = getCloudCmd(); - -const DOM = global.DOM; -const Buffer = DOM.Buffer; - -const vim = require(dir + 'vim'); +const {assign} = Object; +const {DOM} = globalThis; +const {Buffer} = DOM; test('cloudcmd: client: key: set next file: no', (t) => { - const element = { + const element = {}; + const setCurrentFile = stub(); + const unselectFiles = stub(); + + const Info = { + element, }; - const setCurrentFile = sinon.stub(); - - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; - - vim('j', {}); - - t.ok(setCurrentFile.calledWith(element), 'should set next file'); + vim('j', {}, { + Info, + setCurrentFile, + unselectFiles, + }); + t.calledWith(setCurrentFile, [element], 'should set next file'); t.end(); }); -test('cloudcmd: client: key: set next file current', (t) => { +test('cloudcmd: client: key: set next file current: j', async (t) => { const nextSibling = 'hello'; const element = { - nextSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); + const setCurrentFile = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; + const Info = { + element, + }; - vim('j', {}); - - t.ok(setCurrentFile.calledWith(nextSibling), 'should set next file'); + await vim('j', {}, { + Info, + setCurrentFile, + unselectFiles: stub(), + }); + t.calledWith(setCurrentFile, [nextSibling], 'should set next file'); t.end(); }); -test('cloudcmd: client: key: set next file current', (t) => { +test('cloudcmd: client: key: set next file current: mjj', (t) => { const nextSibling = 'hello'; const element = { - nextSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); + const setCurrentFile = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; + const Info = { + element, + }; - vim('m', {}); - vim('j', {}); - vim('j', {}); + const deps = { + Info, + setCurrentFile, + unselectFiles: stub(), + }; - t.ok(setCurrentFile.calledWith(nextSibling), 'should set next file'); + vim('m', {}, deps); + vim('j', {}, deps); + vim('j', {}, deps); + t.calledWith(setCurrentFile, [nextSibling], 'should set next file'); t.end(); }); test('cloudcmd: client: key: set next file current: g', (t) => { const nextSibling = 'hello'; const element = { - nextSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); + const setCurrentFile = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; + const Info = { + element, + }; - vim('g', {}); - vim('j', {}); + const deps = { + Info, + setCurrentFile, + unselectFiles: stub(), + }; - t.ok(setCurrentFile.calledWith(nextSibling), 'should ignore g'); + vim('g', {}, deps); + vim('j', {}, deps); + t.calledWith(setCurrentFile, [nextSibling], 'should ignore g'); t.end(); }); test('cloudcmd: client: key: set +2 file current', (t) => { const last = {}; - const nextSibling = { - nextSibling: last - }; - const element = { - nextSibling + const setCurrentFile = stub(); + const element = {}; + + const Info = { + element, }; - const setCurrentFile = sinon.stub(); - - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; + const deps = { + setCurrentFile, + Info, + unselectFiles: stub(), + }; const event = {}; - vim('2', event); - vim('j', event); - - t.ok(setCurrentFile.calledWith(last), 'should set next file'); + vim('2', event, deps); + vim('j', event, deps); + t.calledWith(setCurrentFile, [last], 'should set next file'); t.end(); }); test('cloudcmd: client: key: select +2 files from current before delete', (t) => { const last = {}; const nextSibling = { - nextSibling: last + nextSibling: last, }; + const element = { - nextSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); + const setCurrentFile = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; - global.DOM.selectFile = sinon.stub(); - global.DOM.getCurrentName = () => false; - global.CloudCmd.Operation.show = sinon.stub(); + const Info = { + element, + }; + + const Operation = { + show: stub(), + }; + + const selectFile = stub(); + const getCurrentName = stub().returns('x'); const event = {}; - vim('d', event); - vim('2', event); - vim('j', event); + const deps = { + Info, + setCurrentFile, + selectFile, + getCurrentName, + Operation, + }; - t.ok(setCurrentFile.calledWith(last), 'should set next file'); + vim('d', event, deps); + vim('2', event, deps); + vim('j', event, deps); + t.calledWith(setCurrentFile, [last], 'should set next file'); t.end(); }); test('cloudcmd: client: key: delete +2 files from current', (t) => { const last = {}; const nextSibling = { - nextSibling: last + nextSibling: last, }; + const element = { - nextSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); - const show = sinon.stub(); + const setCurrentFile = stub(); + const show = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; - global.DOM.selectFile = sinon.stub(); - global.DOM.getCurrentName = () => false; - global.CloudCmd.Operation.show = show; + const deps = { + Info: { + element, + }, + Operation: { + show, + }, + setCurrentFile, + selectFile: stub(), + getCurrentName: stub().returns('x'), + unselectFiles: stub(), + }; const event = {}; - vim('d', event); - vim('2', event); - vim('j', event); - - t.ok(show.calledWith('delete'), 'should call delete'); + vim('d', event, deps); + vim('2', event, deps); + vim('j', event, deps); + t.calledWith(show, ['delete'], 'should call delete'); t.end(); }); test('cloudcmd: client: key: set previous file current', (t) => { const previousSibling = 'hello'; const element = { - previousSibling + previousSibling, }; - const setCurrentFile = sinon.stub(); + const setCurrentFile = stub(); + const unselectFiles = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; + const Info = { + element, + }; - vim('k', {}); + const deps = { + Info, + setCurrentFile, + unselectFiles, + }; - t.ok(setCurrentFile.calledWith(previousSibling), 'should set previous file'); + vim('k', {}, deps); + t.calledWith(setCurrentFile, [previousSibling], 'should set previous file'); t.end(); }); test('cloudcmd: client: key: copy: no', (t) => { - const copy = sinon.stub(); + const copy = stub(); - Buffer.copy = copy; - - vim('y', {}); - - t.notOk(copy.called, 'should not copy files'); + vim('y', {}, { + unselectFiles: stub(), + Buffer: { + copy, + }, + }); + t.notCalled(copy, 'should not copy files'); t.end(); }); test('cloudcmd: client: key: copy', (t) => { - const copy = sinon.stub(); + const copy = stub(); + const Info = { + element: {}, + }; - Buffer.copy = copy; + const toggleSelectedFile = stub(); + const unselectFiles = stub(); - vim('v', {}); - vim('y', {}); + const deps = { + Info, + unselectFiles, + toggleSelectedFile, + Buffer: { + copy, + }, + }; - t.ok(copy.calledWith(), 'should copy files'); + vim('v', {}, deps); + vim('y', {}, deps); + + t.calledWithNoArgs(copy, 'should copy files'); t.end(); }); test('cloudcmd: client: key: copy: unselectFiles', (t) => { - const unselectFiles = sinon.stub(); + const unselectFiles = stub(); + const Info = { + element: {}, + }; - DOM.unselectFiles = unselectFiles; + const toggleSelectedFile = stub(); - vim('v', {}); - vim('y', {}); + const deps = { + Info, + unselectFiles, + toggleSelectedFile, + Buffer: { + copy: stub(), + }, + }; - t.ok(unselectFiles.calledWith(), 'should unselect files'); + vim('v', {}, deps); + vim('y', {}, deps); + + t.calledWithNoArgs(unselectFiles, 'should unselect files'); t.end(); }); test('cloudcmd: client: key: paste', (t) => { - const paste = sinon.stub(); + const paste = stub(); Buffer.paste = paste; - vim('p', {}); - - t.ok(paste.calledWith(), 'should paste files'); + vim('p', {}, { + Buffer, + }); + t.calledWithNoArgs(paste, 'should paste files'); t.end(); }); test('cloudcmd: client: key: selectFile: ..', (t) => { - const selectFile = sinon.stub(); - const getCurrentName = sinon.stub(); - - DOM.selectFile = selectFile; - DOM.getCurrentName = () => '..'; - + const getCurrentName = stub().returns('..'); + const selectFile = stub(); const current = {}; - vim.selectFile(current); - t.notOk(getCurrentName.called, 'should not call selectFile'); + vimSelectFile(current, { + selectFile, + getCurrentName, + }); + + t.notCalled(selectFile, 'should not call selectFile'); t.end(); }); test('cloudcmd: client: key: selectFile', (t) => { - const selectFile = sinon.stub(); - - DOM.selectFile = selectFile; - DOM.getCurrentName = (a) => a.name; - + const selectFile = stub(); + const getCurrentName = stub().returns('x'); const current = {}; - vim.selectFile(current); + vimSelectFile(current, { + selectFile, + getCurrentName, + }); - t.ok(selectFile.calledWith(current), 'should call selectFile'); + t.calledWith(selectFile, [current], 'should call selectFile'); t.end(); }); -test('cloudcmd: client: key: set last file current', (t) => { +test('cloudcmd: client: key: set last file current: shift + g', async (t) => { const last = 'last'; const nextSibling = { - nextSibling: last + nextSibling: last, }; + const element = { - nextSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); + const setCurrentFile = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; - - vim('G', {}); - - t.ok(setCurrentFile.calledWith(last), 'should set last file'); + await vim('G', {}, { + Info: { + element, + }, + setCurrentFile, + unselectFiles: stub(), + }); + t.calledWith(setCurrentFile, [last], 'should set last file'); t.end(); }); -test('cloudcmd: client: key: set first file current', (t) => { - const first = 'first'; - const previousSibling= { - previousSibling: first +test('cloudcmd: client: key: set last file current: $', (t) => { + const last = 'last'; + const nextSibling = { + nextSibling: last, }; const element = { - previousSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); + const setCurrentFile = stub(); - global.DOM.CurrentInfo.element = element; - global.DOM.setCurrentFile = setCurrentFile; + vim('$', {}, { + Info: { + element, + }, + setCurrentFile, + unselectFiles: stub(), + }); - vim('g', {}); - vim('g', {}); + t.calledWith(setCurrentFile, [last], 'should set last file'); + t.end(); +}); + +test('cloudcmd: client: key: set first file current: gg', (t) => { + const first = 'first'; + const previousSibling = { + previousSibling: first, + }; - t.ok(setCurrentFile.calledWith(first), 'should set first file'); + const element = { + previousSibling, + }; + const Operation = { + show: stub(), + }; + + const unselectFiles = stub(); + const setCurrentFile = stub(); + + const deps = { + Operation, + unselectFiles, + setCurrentFile, + Info: { + element, + }, + }; + + vim('g', {}, deps); + vim('g', {}, deps); + + t.calledWith(setCurrentFile, [first], 'should set first file'); + t.end(); +}); + +test('cloudcmd: client: key: set first file current: ^', async (t) => { + const first = 'first'; + const previousSibling = { + previousSibling: first, + }; + + const element = { + previousSibling, + }; + + const Operation = { + show: stub(), + }; + + const unselectFiles = stub(); + const setCurrentFile = stub(); + + const deps = { + setCurrentFile, + Info: { + element, + }, + unselectFiles, + Operation, + }; + + await vim('^', {}, deps); + + t.calledWith(setCurrentFile, [first], 'should set first file'); t.end(); }); test('cloudcmd: client: key: visual', (t) => { - const element = { + const element = {}; + const toggleSelectedFile = stub(); + + const Info = { + element, }; - const toggleSelectedFile = sinon.stub(); - - global.DOM.CurrentInfo.element = element; - global.DOM.toggleSelectedFile = toggleSelectedFile; - - vim('v', {}); - - t.ok(toggleSelectedFile.calledWith(element), 'should toggle selection'); + vim('v', {}, { + Info, + toggleSelectedFile, + }); + t.calledWith(toggleSelectedFile, [element], 'should toggle selection'); t.end(); }); test('cloudcmd: client: key: ESC', (t) => { - const element = { + const element = {}; + const unselectFiles = stub(); + + const Info = { + element, }; - const unselectFiles = sinon.stub(); - - global.DOM.CurrentInfo.element = element; - global.DOM.unselectFiles = unselectFiles ; - - vim('', { - keyCode: KEY.ESC + vim('Escape', null, { + Info, + unselectFiles, }); - t.ok(unselectFiles.calledWith(), 'should toggle selection'); - + t.calledWithNoArgs(unselectFiles, 'should toggle selection'); t.end(); }); -test('cloudcmd: client: key: Enter', (t) => { +test('cloudcmd: client: key: Enter', async (t) => { const nextSibling = 'hello'; const element = { - nextSibling + nextSibling, }; - const setCurrentFile = sinon.stub(); + const unselectFiles = stub(); + const setCurrentFile = stub(); - DOM.CurrentInfo.element = element; - DOM.setCurrentFile = setCurrentFile; + const Info = { + element, + }; - vim('', { - keyCode: KEY.ENTER + await vim('Enter', null, { + Info, + setCurrentFile, + unselectFiles, }); - vim('j', {}); - - t.ok(setCurrentFile.calledWith(nextSibling), 'should set next file'); + await vim('j', null, { + Info, + setCurrentFile, + unselectFiles, + }); + t.calledWith(setCurrentFile, [nextSibling], 'should set next file'); t.end(); }); test('cloudcmd: client: key: /', (t) => { - const preventDefault = sinon.stub(); + const preventDefault = stub(); const element = {}; - DOM.CurrentInfo.element = element; - DOM.getCurrentName = () => ''; + const Info = { + element, + files: [], + }; - vim('/', { - preventDefault + const getCurrentName = stub().returns(''); + + const event = { + preventDefault, + }; + + const prompt = stub().returns([]); + + vim('/', event, { + getCurrentName, + Info, + prompt, }); - t.ok(preventDefault.calledWith(), 'should call preventDefault'); + t.calledWithNoArgs(preventDefault); + t.end(); +}); + +test('cloudcmd: client: find', (t) => { + assign(DOM.Dialog, { + prompt: stub().returns([]), + }); + + const setCurrentByName = stub(); + + assign(DOM, { + setCurrentByName, + }); + + const event = { + preventDefault: stub(), + }; + + vim('/', event); + + t.notCalled(setCurrentByName); t.end(); }); test('cloudcmd: client: key: n', (t) => { - const findNext = sinon.stub(); + const findNext = stub(); + const createFindNext = stub().returns(findNext); - clean(dir + 'vim'); - stub(dir + 'vim/find', { - findNext - }); - - const vim = require(dir + 'vim'); const event = {}; - vim('n', event); + vim('n', event, { + createFindNext, + }); - t.ok(findNext.calledWith(), 'should call findNext'); + t.calledWithNoArgs(findNext, 'should call findNext'); t.end(); }); test('cloudcmd: client: key: N', (t) => { - const findPrevious = sinon.stub(); - - clean(dir + 'vim'); - stub(dir + 'vim/find', { - findPrevious, - }); - - const vim = require(dir + 'vim'); + const findPrevious = stub(); + const createFindPrevious = stub().returns(findPrevious); const event = {}; - vim('N', event); + vim('N', event, { + createFindPrevious, + }); - t.ok(findPrevious.calledWith(), 'should call findPrevious'); + t.calledWithNoArgs(findPrevious); t.end(); }); -function clean(path) { - delete require.cache[require.resolve(path)]; -} +test('cloudcmd: client: key: make directory', async (t) => { + const {DOM} = globalThis; + + assign(DOM, { + promptNewDir: stub(), + }); + + const event = { + stopImmediatePropagation: stub(), + preventDefault: stub(), + }; + + await vim('m', event); + await vim('d', event); + + t.calledWithNoArgs(DOM.promptNewDir); + t.end(); +}); -function stub(name, fn) { - require.cache[require.resolve(name)].exports = fn; -} +test('cloudcmd: client: key: make file', (t) => { + const promptNewFile = stub(); + + const event = { + stopImmediatePropagation: stub(), + preventDefault: stub(), + }; + + vim('m', event); + vim('f', event, { + promptNewFile, + }); + + t.calledWithNoArgs(promptNewFile); + t.end(); +}); +test('cloudcmd: client: vim: terminal', (t) => { + const CloudCmd = { + Terminal: { + show: stub(), + }, + }; + + const event = {}; + + vim('t', event, { + CloudCmd, + }); + vim('t', event, { + CloudCmd, + }); + + t.calledWithNoArgs(CloudCmd.Terminal.show); + t.end(); +}); + +test('cloudcmd: client: vim: edit', async (t) => { + globalThis.DOM = getDOM(); + globalThis.CloudCmd = getCloudCmd(); + + const {CloudCmd} = globalThis; + + assign(CloudCmd, { + EditFileVim: { + show: stub(), + }, + }); + + const event = {}; + + await vim('e', event); + + t.calledWithNoArgs(CloudCmd.EditFileVim.show); + t.end(); +}); + +test('cloudcmd: client: vim: rename', async (t) => { + const DOM = getDOM(); + const renameCurrent = stub(); + + assign(DOM, { + renameCurrent, + }); + + const event = { + preventDefault: stub(), + }; + + await vim('rr', event, DOM); + + t.calledWithNoArgs(renameCurrent); + t.end(); +}); + +test('cloudcmd: client: key: cc: operationCopy', (t) => { + const show = stub(); + const preventDefault = stub(); + + const Operation = { + show, + }; + + const event = { + preventDefault, + }; + + vim('c', event, { + Operation, + }); + + vim('c', event, { + Operation, + }); + + t.calledWith(show, ['copy'], 'should show copy operation'); + t.end(); +}); + +test('cloudcmd: client: key: mm: operationMove', (t) => { + const show = stub(); + const preventDefault = stub(); + + const Operation = { + show, + }; + + const event = { + preventDefault, + }; + + vim('m', event, { + Operation, + }); + + vim('m', event, { + Operation, + }); + + t.calledWith(show, ['move'], 'should show move operation'); + t.end(); +}); + +test('cloudcmd: client: key: n: findNext: real', (t) => { + const setCurrentByName = stub(); + + finder.find('a', ['alpha', 'beta', 'apple']); + + const event = {}; + + vim('n', event, { + setCurrentByName, + }); + + t.calledWith(setCurrentByName, ['beta'], 'should set current by next found name'); + t.end(); +}); + +test('cloudcmd: client: key: N: findPrevious: real', (t) => { + const setCurrentByName = stub(); + + finder.find('a', ['alpha', 'beta', 'apple']); + + const event = {}; + + vim('N', event, { + setCurrentByName, + }); + + t.calledWith(setCurrentByName, ['apple'], 'should set current by previous found name'); + t.end(); +}); diff --git a/client/key/vim/set-current.js b/client/key/vim/set-current.js new file mode 100644 index 00000000..a2fc8646 --- /dev/null +++ b/client/key/vim/set-current.js @@ -0,0 +1,33 @@ +/* global DOM */ +export function selectFileNotParent(current, {getCurrentName, selectFile} = DOM) { + const name = getCurrentName(current); + + if (name === '..') + return; + + selectFile(current); +} + +export const setCurrent = (sibling, {count, isVisual, isDelete}, {Info, setCurrentFile, unselectFiles, Operation}) => { + let current = Info.element; + const select = isVisual ? selectFileNotParent : unselectFiles; + + select(current); + + const position = `${sibling}Sibling`; + + for (let i = 0; i < count; i++) { + const next = current[position]; + + if (!next) + break; + + current = next; + select(current); + } + + setCurrentFile(current); + + if (isDelete) + Operation.show('delete'); +}; diff --git a/client/key/vim/vim.js b/client/key/vim/vim.js new file mode 100644 index 00000000..95a27caf --- /dev/null +++ b/client/key/vim/vim.js @@ -0,0 +1,220 @@ +import {fullstore} from 'fullstore'; + +const store = fullstore(''); +const visual = fullstore(false); + +const stopVisual = () => { + visual(false); +}; + +const end = () => { + store(''); +}; + +const rmFirst = (a) => { + return a + .split('') + .slice(1) + .join(''); +}; + +const noop = () => {}; + +export default (key, operations = {}) => { + const prevStore = store(); + const isVisual = visual(); + const value = store(prevStore.concat(key)); + + const { + escape = noop, + moveNext = noop, + movePrevious = noop, + remove = noop, + copy = noop, + paste = noop, + select = noop, + find = noop, + findNext = noop, + findPrevious = noop, + makeFile = noop, + makeDirectory = noop, + terminal = noop, + edit = noop, + operationCopy = noop, + operationMove = noop, + rename = noop, + } = operations; + + if (key === 'Enter') + return end(); + + if (key === 'Escape') { + visual(false); + escape(); + + return end(); + } + + if (key === 'j' || key === 'w') { + const { + count, + isDelete, + isVisual, + } = handleDelete(prevStore); + + !isNaN(count) && moveNext({ + count, + isVisual, + isDelete, + }); + + return end(); + } + + if (key === 'k' || key === 'b') { + const { + count, + isDelete, + isVisual, + } = handleDelete(prevStore); + + !isNaN(count) && movePrevious({ + count, + isVisual, + isDelete, + }); + + return end(); + } + + if (value === 'gg' || key === '^') { + const {isDelete, isVisual} = handleDelete(prevStore); + + movePrevious({ + count: Infinity, + isVisual, + isDelete, + }); + + return end(); + } + + if (value === 'md') { + makeDirectory(); + return end(); + } + + if (value === 'tt') { + terminal(); + return end(); + } + + if (value === 'e') { + edit(); + return end(); + } + + if (value === 'cc') { + operationCopy(); + return end(); + } + + if (value === 'mm') { + operationMove(); + return end(); + } + + if (value === 'mf') { + makeFile(); + return end(); + } + + if (value === 'rr') { + rename(); + return end(); + } + + if (key === 'd' && (visual() || prevStore === 'd')) { + stopVisual(); + remove(); + + return end(); + } + + if (key === 'G' || key === '$') { + moveNext({ + count: Infinity, + isVisual, + }); + + return end(); + } + + if (key === 'y') { + if (!visual()) + return end(); + + stopVisual(); + copy(); + + return end(); + } + + if (/^p$/i.test(key)) { + paste(); + return end(); + } + + if (/^v$/i.test(key)) { + visual(!visual()); + select(); + + return end(); + } + + if (key === '/') { + find(); + return end(); + } + + if (key === 'n') { + findNext(); + return end(); + } + + if (key === 'N') { + findPrevious(); + return end(); + } + + if (key === ' ') + return end(); +}; + +function handleDelete(prevStore) { + const isDelete = prevStore[0] === 'd'; + + if (isDelete) { + visual(true); + prevStore = rmFirst(prevStore); + } + + const count = getNumber(prevStore); + const isVisual = visual(); + + return { + count, + isDelete, + isVisual, + }; +} + +function getNumber(value) { + if (!value) + return 1; + + if (value === 'g') + return 1; + + return parseInt(value); +} diff --git a/client/key/vim/vim.spec.js b/client/key/vim/vim.spec.js new file mode 100644 index 00000000..02fd52d4 --- /dev/null +++ b/client/key/vim/vim.spec.js @@ -0,0 +1,100 @@ +import {test, stub} from 'supertape'; +import vim from './vim.js'; + +test('vim: no operations', (t) => { + const result = vim('hello', {}); + + t.notOk(result); + t.end(); +}); + +test('vim: space', (t) => { + const moveNext = stub(); + + vim(' '); + vim('j', { + moveNext, + }); + + const args = [{ + count: 1, + isDelete: false, + isVisual: false, + }]; + + t.calledWith(moveNext, args); + t.end(); +}); + +test('vim: ^', (t) => { + const movePrevious = stub(); + + vim('^', { + movePrevious, + }); + + const expected = { + count: Infinity, + isVisual: false, + isDelete: false, + }; + + t.calledWith(movePrevious, [expected], 'should call movePrevious'); + t.end(); +}); + +test('vim: cc', (t) => { + const operationCopy = stub(); + + vim('cc', { + operationCopy, + }); + + t.calledWithNoArgs(operationCopy); + t.end(); +}); + +test('vim: mm', (t) => { + const operationMove = stub(); + + vim('mm', { + operationMove, + }); + + t.calledWithNoArgs(operationMove); + t.end(); +}); + +test('vim: w', (t) => { + const moveNext = stub(); + + vim('w', { + moveNext, + }); + + const expected = { + count: 1, + isVisual: false, + isDelete: false, + }; + + t.calledWith(moveNext, [expected], 'should call moveNext'); + t.end(); +}); + +test('vim: b', (t) => { + const movePrevious = stub(); + + vim('b', { + movePrevious, + }); + + const expected = { + count: 1, + isVisual: false, + isDelete: false, + }; + + t.calledWith(movePrevious, [expected], 'should call movePrevious'); + t.end(); +}); diff --git a/client/listeners/get-index.js b/client/listeners/get-index.js index d7870608..45ce85e8 100644 --- a/client/listeners/get-index.js +++ b/client/listeners/get-index.js @@ -1,11 +1,10 @@ -'use strict'; +import currify from 'currify'; -module.exports = (array, item) => { +export const getIndex = currify((array, item) => { const index = array.indexOf(item); if (!~index) return 0; return index; -}; - +}); diff --git a/test/client/listeners/get-index.js b/client/listeners/get-index.spec.js similarity index 65% rename from test/client/listeners/get-index.js rename to client/listeners/get-index.spec.js index 16dd6999..0380cdc1 100644 --- a/test/client/listeners/get-index.js +++ b/client/listeners/get-index.spec.js @@ -1,9 +1,5 @@ -'use strict'; - -const test = require('tape'); - -const dir = '../../../client/listeners'; -const getIndex = require(`${dir}/get-index`); +import test from 'supertape'; +import {getIndex} from './get-index.js'; test('cloudcmd: client: listeners: getIndex: not found', (t) => { const array = ['hello']; @@ -13,9 +9,11 @@ test('cloudcmd: client: listeners: getIndex: not found', (t) => { }); test('cloudcmd: client: listeners: getIndex: found', (t) => { - const array = ['hello', 'world']; + const array = [ + 'hello', + 'world', + ]; t.equal(getIndex(array, 'world'), 1, 'should return index'); t.end(); }); - diff --git a/client/listeners/get-range.js b/client/listeners/get-range.js index ef1ea0f8..839c2287 100644 --- a/client/listeners/get-range.js +++ b/client/listeners/get-range.js @@ -1,6 +1,4 @@ -'use strict'; - -module.exports = (indexFrom, indexTo, files) => { +export const getRange = (indexFrom, indexTo, files) => { if (indexFrom < indexTo) return files.slice(indexFrom, indexTo + 1); @@ -9,4 +7,3 @@ module.exports = (indexFrom, indexTo, files) => { return [files[indexFrom]]; }; - diff --git a/client/listeners/get-range.spec.js b/client/listeners/get-range.spec.js new file mode 100644 index 00000000..77c950f4 --- /dev/null +++ b/client/listeners/get-range.spec.js @@ -0,0 +1,52 @@ +import test from 'supertape'; +import {getRange} from './get-range.js'; + +test('cloudcmd: client: listeners: getRange: direct', (t) => { + const expected = [ + 'hello', + 'world', + ]; + + const files = [ + ...expected, + 'how', + 'come', + ]; + + const result = getRange(0, 1, files); + + t.deepEqual(result, expected, 'should return range'); + t.end(); +}); + +test('cloudcmd: client: listeners: getRange: reverse', (t) => { + const expected = [ + 'hello', + 'world', + ]; + + const files = [ + ...expected, + 'how', + 'come', + ]; + + const result = getRange(1, 0, files); + + t.deepEqual(result, expected, 'should return range'); + t.end(); +}); + +test('cloudcmd: client: listeners: getRange: one', (t) => { + const expected = ['hello']; + const files = [ + ...expected, + 'how', + 'come', + ]; + + const result = getRange(0, 0, files); + + t.deepEqual(result, expected, 'should return range'); + t.end(); +}); diff --git a/client/listeners/index.js b/client/listeners/index.js index 85bb0e2d..babc1e0d 100644 --- a/client/listeners/index.js +++ b/client/listeners/index.js @@ -1,38 +1,30 @@ /* global DOM, CloudCmd */ - -'use strict'; - -const exec = require('execon'); -const itype = require('itype/legacy'); -const currify = require('currify/legacy'); -const clipboard = require('@cloudcmd/clipboard'); - -const getRange = require('./get-range'); -const getIndex = currify(require('./get-index')); -const uploadFiles = require('../dom/upload-files'); - -const { - FS, - apiURL, -} = require('../../common/cloudfunc'); +import exec from 'execon'; +import itype from 'itype'; +import currify from 'currify'; +import {tryToCatch} from 'try-to-catch'; +import clipboard from '@cloudcmd/clipboard'; +import * as Events from '#dom/events'; +import {uploadFiles} from '#dom/upload-files'; +import {FS} from '#common/cloudfunc'; +import {getRange} from './get-range.js'; +import {getIndex} from './get-index.js'; const NBSP_REG = RegExp(String.fromCharCode(160), 'g'); const SPACE = ' '; -module.exports.init = () => { +export async function init() { contextMenu(); dragndrop(); unload(); pop(); resize(); - config(); header(); -}; - -CloudCmd.Listeners = module.exports; + await config(); +} const unselect = (event) => { - const isMac = /Mac/.test(window.navigator.platform); + const isMac = /Mac/.test(globalThis.navigator.platform); const { shiftKey, metaKey, @@ -46,19 +38,13 @@ const unselect = (event) => { }; const execAll = currify((funcs, event) => { - funcs.forEach((fn) => { + for (const fn of funcs) fn(event); - }); }); -const Info = DOM.CurrentInfo; -const Events = DOM.Events; const EventsFiles = { mousedown: exec.with(execIfNotUL, setCurrentFileByEvent), - click: execAll([ - onClick, - unselect, - ]), + click: execAll([onClick, exec.with(execIfNotMobile, unselect)]), dragstart: exec.with(execIfNotUL, onDragStart), dblclick: exec.with(execIfNotUL, onDblClick), touchstart: exec.with(execIfNotUL, onTouch), @@ -69,6 +55,7 @@ let EXT; function header() { const fm = DOM.getFM(); const isDataset = (el) => el.dataset; + const isPanel = (el) => { return /^js-(left|right)$/.test(el.dataset.name); }; @@ -80,8 +67,7 @@ function header() { if (parent.dataset.name !== 'js-fm-header') return; - const name = (el.dataset.name || '') - .replace('js-', ''); + const name = (el.dataset.name || '').replace('js-', ''); if (!/^(name|size|date)$/.test(name)) return; @@ -102,44 +88,48 @@ function getPath(el, path = []) { return getPath(el.parentElement, path.concat(el)); } -function config() { - DOM.Files.get('config', (e, config) => { - const type = config && config.packer; - EXT = DOM.getPackerExt(type); - }); +async function config() { + const [, config] = await tryToCatch(DOM.Files.get, 'config'); + const type = config?.packer; + + EXT = DOM.getPackerExt(type); } -module.exports.initKeysPanel = () => { +export const initKeysPanel = () => { const keysElement = DOM.getById('js-keyspanel'); if (!keysElement) return; - Events.addClick(keysElement, ({target}) => { - const id = target.id; + Events.addClick(keysElement, (event) => { + const {target} = event; + const {id} = target; + const operation = (name) => { - const Operation = CloudCmd.Operation; - const fn = Operation.show.bind(null, name); + const {Operation} = CloudCmd; - return fn; + return Operation.show.bind(null, name); }; const clickFuncs = { - 'f1' : CloudCmd.Help.show, - 'f2' : DOM.renameCurrent, - 'f3' : CloudCmd.View.show, - 'f4' : CloudCmd.EditFile.show, - 'f5' : operation('copy'), - 'f6' : operation('move'), - 'f7' : DOM.promptNewDir, - 'f8' : operation('delete'), - 'f9' : CloudCmd.Menu.show, - 'f10' : CloudCmd.Config.show, - '~' : CloudCmd.Konsole.show, - 'shift~' : CloudCmd.Terminal.show, - 'contact' : CloudCmd.Contact.show, + 'f1': CloudCmd.Help.show, + 'f2': CloudCmd.UserMenu.show, + 'f3': CloudCmd.View.show, + 'f4': CloudCmd.EditFile.show, + 'f5': operation('copy'), + 'f6': operation('move'), + 'f7': DOM.promptNewDir, + 'f8': operation('delete'), + 'f9': () => { + event.stopPropagation(); + CloudCmd.Menu.show(); + }, + 'f10': CloudCmd.Config.show, + '~': CloudCmd.Konsole.show, + 'shift~': CloudCmd.Terminal.show, + 'contact': CloudCmd.Contact.show, }; - + exec(clickFuncs[id]); }); }; @@ -148,10 +138,10 @@ const getPanel = (side) => { if (!itype.string(side)) return side; - return DOM.getByDataName('js-' + side); + return DOM.getByDataName(`js-${side}`); }; -module.exports.setOnPanel = (side) => { +export const setOnPanel = (side) => { const panel = getPanel(side); const filesElement = DOM.getByDataName('js-files', panel); @@ -167,6 +157,7 @@ function getPathListener(panel) { } function isNoCurrent(panel) { + const Info = DOM.CurrentInfo; const infoPanel = Info.panel; if (!infoPanel) @@ -178,20 +169,20 @@ function isNoCurrent(panel) { return namePanel !== nameInfoPanel; } -function decodePath(path){ +function decodePath(path) { const url = CloudCmd.HOST; - const prefix = CloudCmd.PREFIX; + const {prefix} = CloudCmd; const prefixReg = RegExp('^' + prefix + FS); return decodeURI(path) .replace(url, '') - .replace(prefixReg, '') - // browser doesn't replace % -> %25% do it for him + .replace(prefixReg, '') // browser doesn't replace % -> %25% do it for him .replace('%%', '%25%') .replace(NBSP_REG, SPACE) || '/'; } -function onPathElementClick(panel, event) { +async function onPathElementClick(panel, event) { + const Info = DOM.CurrentInfo; event.preventDefault(); const element = event.target; @@ -204,7 +195,7 @@ function onPathElementClick(panel, event) { if (attr === 'js-refresh') return CloudCmd.refresh({ panel, - noCurrent + noCurrent, }); if (attr !== 'js-path-link') @@ -213,19 +204,26 @@ function onPathElementClick(panel, event) { const {href} = element; const path = decodePath(href); - CloudCmd.loadDir({ - path, + await CloudCmd.changeDir(path, { isRefresh: false, - panel: noCurrent ? panel : Info.panel + panel: noCurrent ? panel : Info.panel, }); } function copyPath(el) { - clipboard.writeText(el.parentElement.title) + clipboard + .writeText(el.parentElement.title) .then(CloudCmd.log) .catch(CloudCmd.log); } +function execIfNotMobile(callback, event) { + const isMobile = DOM.getCSSVar('is-mobile'); + + if (!isMobile) + callback(event); +} + function execIfNotUL(callback, event) { const {target} = event; const {tagName} = target; @@ -235,30 +233,27 @@ function execIfNotUL(callback, event) { } function onClick(event) { - const ctrl = event.ctrlKey; - - if (!ctrl) - event.preventDefault(); - + event.preventDefault(); changePanel(event.target); } function toggleSelect(key, files) { - const isMac = /Mac/.test(window.navigator.platform); + const isMac = /Mac/.test(globalThis.navigator.platform); if (!key) throw Error('key should not be undefined!'); const [file] = files; - if (isMac && key.meta || key.ctrl) + if (isMac && key.meta) return DOM.toggleSelectedFile(file); if (key.shift) - return files.forEach(DOM.selectFile); + return files.map(DOM.selectFile); } function changePanel(element) { + const Info = DOM.CurrentInfo; const {panel} = Info; const files = DOM.getByDataName('js-files', panel); const ul = getULElement(element); @@ -267,21 +262,20 @@ function changePanel(element) { DOM.changePanel(); } -function onDblClick(event) { +async function onDblClick(event) { + event.preventDefault(); + const current = getLIElement(event.target); const isDir = DOM.isCurrentIsDir(current); const path = DOM.getCurrentPath(current); - if (isDir) { - CloudCmd.loadDir({ - path: path === '/' ? '/' : path + '/' - }); - - event.preventDefault(); - } + if (!isDir) + return CloudCmd.View.show(); + + await CloudCmd.changeDir(path); } -function onTouch(event) { +async function onTouch(event) { const current = getLIElement(event.target); const isDir = DOM.isCurrentIsDir(current); @@ -293,9 +287,7 @@ function onTouch(event) { if (!isCurrent) return; - CloudCmd.loadDir({ - path: DOM.getCurrentPath(current) - }); + await CloudCmd.changeDir(DOM.getCurrentPath(current)); } /* @@ -303,8 +295,10 @@ function onTouch(event) { * in Chrome (HTML5) */ function onDragStart(event) { + const Info = DOM.CurrentInfo; + const {prefixURL} = CloudCmd; const element = getLIElement(event.target); - const isDir = Info.isDir; + const {isDir} = Info; let link = DOM.getCurrentLink(element); let name = DOM.getCurrentName(element); @@ -313,13 +307,15 @@ function onDragStart(event) { name += EXT; link = document.createElement('a'); link.textContent = name; - link.href = apiURL + '/pack' + Info.path + EXT; + link.href = prefixURL + '/pack' + Info.path + EXT; } - event.dataTransfer.setData('DownloadURL', - 'application/octet-stream' + ':' + - name + ':' + - link); + event.dataTransfer.setData( + 'DownloadURL', + 'application/octet-stream' + ':' + name + + ':' + + link, + ); } function getLIElement(element) { @@ -340,13 +336,14 @@ function getULElement(element) { } function setCurrentFileByEvent(event) { + const Info = DOM.CurrentInfo; const BUTTON_LEFT = 0; const key = { alt: event.altKey, ctrl: event.ctrlKey, meta: event.metaKey, - shift: event.shiftKey + shift: event.shiftKey, }; const element = getLIElement(event.target); @@ -383,7 +380,7 @@ function contextMenu() { Events.addOnce('contextmenu', fm, (event) => { CloudCmd.Menu.show({ x: event.clientX, - y: event.clientY + y: event.clientY, }); }); @@ -394,21 +391,17 @@ function contextMenu() { function dragndrop() { const panels = DOM.getByClassAll('panel'); - const select = () => { - [...panels].forEach((panel) => { - panel.classList.add('selected-panel'); - }); + const select = ({target}) => { + target.classList.add('selected-panel'); }; - const unselect = () => { - [...panels].forEach((panel) => { - panel.classList.remove('selected-panel'); - }); + const unselect = ({target}) => { + target.classList.remove('selected-panel'); }; const onDrop = (event) => { - const files = event.dataTransfer.files; - const items = event.dataTransfer.items; + const {files, items} = event.dataTransfer; + const {length: filesCount} = files; event.preventDefault(); @@ -417,7 +410,10 @@ function dragndrop() { return uploadFiles(files); const isFile = (item) => item.kind === 'file'; - const dirFiles = [...items].filter(isFile); + + const dirFiles = Array + .from(items) + .filter(isFile); if (dirFiles.length) return DOM.uploadDirectory(dirFiles); @@ -429,13 +425,13 @@ function dragndrop() { }; /** - * In Mac OS Chrome dropEffect = 'none' + * In macOS Chrome dropEffect = 'none' * so drop do not firing up when try * to upload file from download bar */ const onDragOver = (event) => { - const dataTransfer = event.dataTransfer; - const effectAllowed = dataTransfer.effectAllowed; + const {dataTransfer} = event; + const {effectAllowed} = dataTransfer; if (/move|linkMove/.test(effectAllowed)) dataTransfer.dropEffect = 'move'; @@ -445,19 +441,18 @@ function dragndrop() { event.preventDefault(); }; - Events.add('dragenter', select); - Events.add(['dragleave', 'drop'], unselect); - - [...panels].forEach((panel) => { - Events.add('dragover', panel, onDragOver) - .add('drop', panel, onDrop); - }); + for (const panel of panels) + Events + .add('dragover', panel, onDragOver) + .add('drop', panel, onDrop) + .add('dragenter', select) + .add(['dragleave', 'drop'], unselect); } function unload() { - DOM.Events.add(['unload', 'beforeunload'], (event) => { - const Key = CloudCmd.Key; - const isBind = Key && Key.isBind(); + Events.add(['unload', 'beforeunload'], (event) => { + const {Key} = CloudCmd; + const isBind = Key?.isBind(); if (isBind) return; @@ -468,15 +463,15 @@ function unload() { } function pop() { - Events.add('popstate', ({state}) => { + Events.add('popstate', async ({state}) => { const path = (state || '').replace(FS, ''); if (!path) return CloudCmd.route(location.hash); const history = false; - CloudCmd.loadDir({ - path, + + await CloudCmd.changeDir(path, { history, }); }); @@ -484,7 +479,8 @@ function pop() { function resize() { Events.add('resize', () => { - const is = window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH; + const Info = DOM.CurrentInfo; + const is = globalThis.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH; if (!is) return; @@ -504,4 +500,3 @@ function resize() { DOM.changePanel(); }); } - diff --git a/client/load-module.js b/client/load-module.js index 130d1de6..7fc2c328 100644 --- a/client/load-module.js +++ b/client/load-module.js @@ -1,49 +1,45 @@ -'use strict'; - /* global CloudCmd */ +import exec from 'execon'; +import {tryToCatch} from 'try-to-catch'; +import {js as loadJS} from 'load.js'; +import pascalCase from 'just-pascal-case'; -const exec = require('execon'); -const tryToCatch = require('try-to-catch/legacy'); -const {promisify} = require('es6-promisify'); -const loadJS = promisify(require('load.js').js); - -const { - kebabToCamelCase, -} = require('../common/util'); +const noJS = (a) => a.replace(/.js$/, ''); /** * function load modules * @params = {name, path, func, dobefore, arg} */ -module.exports = function loadModule(params) { +export const loadModule = (params) => { if (!params) return; const {path} = params; - const name = params.name || path && kebabToCamelCase(path); + + const name = path && noJS(pascalCase(path)); const doBefore = params.dobefore; if (CloudCmd[name]) return; - CloudCmd[name] = () => { + CloudCmd[name] = async () => { exec(doBefore); - const prefix = CloudCmd.PREFIX; - const pathFull = prefix + CloudCmd.DIRCLIENT_MODULES + path + '.js'; - return loadJS(pathFull).then(async () => { - const newModule = async (f) => f && f(); - const module = CloudCmd[name]; - - Object.assign(newModule, module); - - CloudCmd[name] = newModule; - - CloudCmd.log('init', name); - await module.init(); - - return newModule; - }); + const {DIR_MODULES} = CloudCmd; + const pathFull = `${DIR_MODULES}/${path}.js`; + + await loadJS(pathFull); + const newModule = async (f) => f && f(); + const module = CloudCmd[name]; + + Object.assign(newModule, module); + + CloudCmd[name] = newModule; + CloudCmd.log('init', name); + + await module.init(); + + return newModule; }; CloudCmd[name].show = async (...args) => { @@ -53,9 +49,8 @@ module.exports = function loadModule(params) { const [e, a] = await tryToCatch(m); if (e) - return console.error(e); + return; - a.show(...args); + return await a.show(...args); }; }; - diff --git a/client/modules/cloud.js b/client/modules/cloud.js index 32d83a1d..cfe0d708 100644 --- a/client/modules/cloud.js +++ b/client/modules/cloud.js @@ -1,28 +1,32 @@ /* global CloudCmd, filepicker */ - -'use strict'; - -const exec = require('execon'); -const currify = require('currify/legacy'); -const {promisify} = require('es6-promisify'); -const loadJS = require('load.js').js; +import exec from 'execon'; +import currify from 'currify'; +import load from 'load.js'; +import {ajax} from '#dom/load'; +import * as Files from '#dom/files'; +import * as Images from '#dom/images'; const {log} = CloudCmd; -const {ajax} = require('../dom/load'); -const Files = require('../dom/files'); -const Images = require('../dom/images'); - const upload = currify(_upload); const Name = 'Cloud'; -CloudCmd[Name] = module.exports; -module.exports.init = async () => { - await loadFiles(); +CloudCmd[Name] = { + init, + uploadFile, + saveFile, }; -module.exports.uploadFile = (filename, data) => { +export async function init() { + const [modules] = await loadFiles(); + const {key} = modules.data.FilePicker; + + filepicker.setKey(key); + Images.hide(); +} + +export function uploadFile(filename, data) { const mimetype = ''; filepicker.store(data, { @@ -31,17 +35,14 @@ module.exports.uploadFile = (filename, data) => { }, (fpFile) => { filepicker.exportFile(fpFile, log, log); }); -}; +} -module.exports.saveFile = (callback) => { +export function saveFile(callback) { filepicker.pick(upload(callback)); -}; +} function _upload(callback, file) { - const { - url, - filename, - } = file; + const {url, filename} = file; const responseType = 'arraybuffer'; const success = exec.with(callback, filename); @@ -53,18 +54,11 @@ function _upload(callback, file) { }); } -const loadFiles = promisify((callback) => { +function loadFiles() { const js = '//api.filepicker.io/v2/filepicker.js'; - loadJS(js, () => { - Files.get('modules', (error, modules) => { - const {key} = modules.data.FilePicker; - - filepicker.setKey(key); - - Images.hide(); - exec(callback); - }); - }); -}); - + return Promise.all([ + Files.get('modules'), + load.js(js), + ]); +} diff --git a/client/modules/command-line.js b/client/modules/command-line.js new file mode 100644 index 00000000..7a1c3993 --- /dev/null +++ b/client/modules/command-line.js @@ -0,0 +1,31 @@ +/* global CloudCmd */ +import * as Dialog from '#dom/dialog'; + +export function init() {} +CloudCmd.CommandLine = { + init, + show, + hide, +}; + +export async function show() { + const [, cmd] = await Dialog.prompt('Command Line', ''); + const TERMINAL = '^(t|terminal)'; + + if (RegExp(`${TERMINAL}$`).test(cmd)) + return await CloudCmd.Terminal.show(); + + if (RegExp(TERMINAL).test(cmd)) { + const command = cmd.replace(RegExp(`${TERMINAL} `), ''); + const exitCode = await CloudCmd.TerminalRun.show({ + command: `bash -c '${command}'`, + }); + + if (exitCode === -1) + await Dialog.alert(`☝️ Looks like Terminal is disabled, start Cloud Coammnder with '--terminal' flag.`); + + return; + } +} + +export function hide() {} diff --git a/client/modules/config.js b/client/modules/config.js deleted file mode 100644 index c03f51d0..00000000 --- a/client/modules/config.js +++ /dev/null @@ -1,252 +0,0 @@ -'use strict'; - -/* global CloudCmd, DOM, io */ - -require('../../css/config.css'); - -const rendy = require('rendy/legacy'); -const exec = require('execon'); -const currify = require('currify/legacy'); -const wraptile = require('wraptile/legacy'); -const squad = require('squad/legacy'); -const {promisify} = require('es6-promisify'); -const load = require('load.js'); -const createElement = require('@cloudcmd/create-element'); - -const input = require('../input'); -const Images = require('../dom/images'); -const Events = require('../dom/events'); -const Files = require('../dom/files'); - -const {getTitle} = require('../../common/cloudfunc'); -const {Dialog, setTitle} = DOM; - -const Name = 'Config'; -CloudCmd[Name] = module.exports; -const alert = currify(Dialog.alert, Name); - -const loadSocket = promisify(DOM.loadSocket); - -const showLoad = () => { - Images.show.load('top'); -}; - -const addKey = currify((fn, input) => { - Events.addKey(input, fn); - return input; -}); - -const addChange = currify((fn, input) => { - Events.add('change', input, fn); - return input; -}); - -const Config = {}; - -let Loading = true; - -module.exports.init = async () => { - if (!CloudCmd.config('configDialog')) - return; - - showLoad(); - - await CloudCmd.View(); - await loadSocket(); - initSocket(); - Loading = false; -}; - -const config = CloudCmd.config; - -const {Key} = CloudCmd; - -let Element; -let Template; - -function getHost() { - const {host, origin, protocol} = location; - const href = origin || `${protocol}//${host}`; - - return href; -} - -function initSocket() { - const href = getHost(); - const { - prefixSocket, - PREFIX, - } = CloudCmd; - - const ONE_MINUTE = 60 * 1000; - - const socket = io.connect(href + prefixSocket + '/config', { - reconnectionAttempts: Infinity, - reconnectionDelay: ONE_MINUTE, - path: PREFIX + '/socket.io' - }); - - const save = (data) => { - onSave(data); - socket.send(data); - }; - - authCheck(socket); - - socket.on('connect', () => { - Config.save = save; - }); - - socket.on('message', onSave); - socket.on('log', CloudCmd.log); - - socket.on('disconnect', () => { - Config.save = saveHttp; - }); - - socket.on('err', alert); -} - -function authCheck(socket) { - socket.emit('auth', config('username'), config('password')); - socket.on('reject', wraptile(alert, 'Wrong credentials!')); -} - -Config.save = saveHttp; - -module.exports.show = show; - -function show() { - if (!CloudCmd.config('configDialog')) - return; - - const prefix = CloudCmd.PREFIX; - const funcs = [ - exec.with(Files.get, 'config-tmpl'), - exec.with(load.css, prefix + '/dist/config.css'), - ]; - - if (Loading) - return; - - showLoad(); - exec.parallel(funcs, fillTemplate); -} - -function fillTemplate(error, template) { - if (!Template) - Template = template; - - Files.get('config', (error, config) => { - if (error) - return alert('Could not load config!'); - - const { - editor, - packer, - columns, - configAuth, - ...obj - } = input.convert(config); - - obj[editor + '-selected'] = 'selected'; - obj[packer + '-selected'] = 'selected'; - obj[columns + '-selected'] = 'selected'; - obj.configAuth = configAuth ? '' : 'hidden'; - - const innerHTML = rendy(Template, obj); - - Element = createElement('form', { - className : 'config', - innerHTML, - }); - - const inputs = document.querySelectorAll('input, select', Element); - const [inputFirst] = inputs; - - let afterShow; - if (inputFirst) { - onAuthChange(inputFirst.checked); - afterShow = inputFirst.focus.bind(inputFirst); - } - - const getTarget = ({target}) => target; - const handleChange = squad(onChange, getTarget); - - [...inputs] - .map(addKey(onKey)) - .map(addChange(handleChange)); - - const autoSize = true; - CloudCmd.View.show(Element, { - autoSize, - afterShow, - }); - }); -} - -module.exports.hide = hide; - -function hide() { - CloudCmd.View.hide(); -} - -function onChange(el) { - const obj = {}; - const name = input.getName(el); - const data = input.getValue(name, Element); - - if (name === 'name') - onNameChange(data); - else if (name === 'auth') - onAuthChange(data); - - obj[name] = data; - - Config.save(obj); -} - -function onSave(obj) { - Object.keys(obj).forEach((name) => { - const data = obj[name]; - - CloudCmd._config(name, data); - input.setValue(name, data, Element); - }); -} - -function saveHttp(obj) { - const {RESTful} = DOM; - - RESTful.Config.write(obj, (error) => { - if (error) - return; - - onSave(obj); - }); -} - -function onAuthChange(checked) { - const elUsername = input.getElementByName('username', Element); - const elPassword = input.getElementByName('password', Element); - - elUsername.disabled = - elPassword.disabled = !checked; -} - -function onNameChange(name) { - setTitle(getTitle({ - name - })); -} - -function onKey({keyCode, target}) { - switch (keyCode) { - case Key.ESC: - return hide(); - - case Key.ENTER: - return onChange(target); - } -} - diff --git a/client/modules/config/index.js b/client/modules/config/index.js new file mode 100644 index 00000000..dfa4c105 --- /dev/null +++ b/client/modules/config/index.js @@ -0,0 +1,247 @@ +import '../../../css/config.css'; +import {rendy} from 'rendy'; +import currify from 'currify'; +import wraptile from 'wraptile'; +import squad from 'squad'; +import {promisify} from 'es6-promisify'; +import {tryToCatch} from 'try-to-catch'; +import load from 'load.js'; +import createElement from '@cloudcmd/create-element'; +import * as Events from '#dom/events'; +import * as Files from '#dom/files'; +import {getTitle} from '#common/cloudfunc'; +import * as Images from '#dom/images'; +import * as input from './input.js'; + +const {CloudCmd, DOM} = globalThis; + +const {Dialog, setTitle} = DOM; + +const Name = 'Config'; + +const loadSocket = promisify(DOM.loadSocket); + +const showLoad = () => { + Images.show.load('top'); +}; + +const addKey = currify((fn, input) => { + Events.addKey(input, fn); + return input; +}); + +const addChange = currify((fn, input) => { + Events.add('change', input, fn); + return input; +}); + +const Config = {}; + +let Template; + +const loadCSS = load.css; + +export async function init() { + if (!CloudCmd.config('configDialog')) + return; + + showLoad(); + + const {DIR_DIST} = CloudCmd; + + [Template] = await Promise.all([ + Files.get('config-tmpl'), + loadSocket(), + loadCSS(`${DIR_DIST}/config.css`), + CloudCmd.View(), + ]); + + initSocket(); +} + +const {config, Key} = CloudCmd; + +let Element; + +function getHost() { + const { + host, + origin, + protocol, + } = location; + + return origin || `${protocol}//${host}`; +} + +function initSocket() { + const href = getHost(); + const {prefixSocket, prefix} = CloudCmd; + + const ONE_MINUTE = 60 * 1000; + + const socket = globalThis.io.connect(href + prefixSocket + '/config', { + reconnectionAttempts: Infinity, + reconnectionDelay: ONE_MINUTE, + path: `${prefix}/socket.io`, + }); + + const save = (data) => { + onSave(data); + socket.send(data); + }; + + authCheck(socket); + + socket.on('connect', () => { + Config.save = save; + }); + + socket.on('message', onSave); + socket.on('log', CloudCmd.log); + + socket.on('disconnect', () => { + Config.save = saveHttp; + }); + + socket.on('err', Dialog.alert); +} + +function authCheck(socket) { + socket.emit('auth', config('username'), config('password')); + socket.on('reject', wraptile(Dialog.alert, 'Wrong credentials!')); +} + +Config.save = saveHttp; + +export async function show() { + if (!CloudCmd.config('configDialog')) + return; + + await fillTemplate(); +} + +async function fillTemplate() { + const [error, config] = await tryToCatch(Files.get, 'config'); + + if (error) + return Dialog.alert('Could not load config!'); + + const { + editor, + menu, + packer, + columns, + theme, + configAuth, + configPort, + ...obj + } = input.convert(config); + + obj[`${menu}-selected`] = 'selected'; + obj[`${editor}-selected`] = 'selected'; + obj[`${packer}-selected`] = 'selected'; + obj[`${columns}-selected`] = 'selected'; + obj[`${theme}-selected`] = 'selected'; + obj.configAuth = configAuth ? '' : 'hidden'; + obj.configPort = configPort ? '' : 'hidden'; + + const innerHTML = rendy(Template, obj); + + Element = createElement('form', { + className: 'config', + innerHTML, + }); + + const inputs = document.querySelectorAll('input, select', Element); + const [inputFirst] = inputs; + + let afterShow; + + if (inputFirst) { + onAuthChange(inputFirst.checked); + afterShow = inputFirst.focus.bind(inputFirst); + } + + const getTarget = ({target}) => target; + const handleChange = squad(onChange, getTarget); + + Array + .from(inputs) + .map(addKey(onKey)) + .map(addChange(handleChange)); + + const autoSize = true; + + CloudCmd.View.show(Element, { + autoSize, + afterShow, + }); +} + +export function hide() { + CloudCmd.View.hide(); +} + +async function onChange(el) { + const obj = {}; + const name = input.getName(el); + const data = input.getValue(name, Element); + + if (name === 'name') + onNameChange(data); + else if (name === 'auth') + onAuthChange(data); + + obj[name] = data; + + await Config.save(obj); +} + +function onSave(obj) { + for (const name of Object.keys(obj)) { + const data = obj[name]; + + CloudCmd._config(name, data); + input.setValue(name, data, Element); + } +} + +async function saveHttp(obj) { + const {RESTful} = DOM; + const [e] = await RESTful.Config.write(obj); + + if (e) + return; + + onSave(obj); +} + +function onAuthChange(checked) { + const elUsername = input.getElementByName('username', Element); + const elPassword = input.getElementByName('password', Element); + + elUsername.disabled = !checked; + elPassword.disabled = !checked; +} + +function onNameChange(name) { + setTitle(getTitle({ + name, + })); +} + +async function onKey({keyCode, target}) { + switch(keyCode) { + case Key.ESC: + return hide(); + + case Key.ENTER: + return await onChange(target); + } +} + +CloudCmd[Name] = { + init, + show, + hide, +}; diff --git a/client/modules/config/input.js b/client/modules/config/input.js new file mode 100644 index 00000000..34a4be69 --- /dev/null +++ b/client/modules/config/input.js @@ -0,0 +1,78 @@ +import {encode} from '#common/entity'; + +const isBool = (a) => typeof a === 'boolean'; +const isString = (a) => typeof a === 'string'; + +const {keys} = Object; + +export function getElementByName(selector, element) { + const str = `[data-name="js-${selector}"]`; + + return element.querySelector(str); +} + +export const getName = (element) => { + const name = element + .getAttribute('data-name') + .replace(/^js-/, ''); + + return name; +}; + +export const convert = (config) => { + const result = config; + + for (const name of keys(config)) { + const item = config[name]; + + if (isBool(item)) { + result[name] = setState(item); + continue; + } + + if (isString(item)) { + result[name] = encode(item); + continue; + } + } + + return result; +}; + +function setState(state) { + if (state) + return ' checked'; + + return ''; +} + +export const getValue = (name, element) => { + const el = getElementByName(name, element); + const {type} = el; + + switch(type) { + case 'checkbox': + return el.checked; + + case 'number': + return Number(el.value); + + default: + return el.value; + } +}; + +export const setValue = (name, value, element) => { + const el = getElementByName(name, element); + const {type} = el; + + switch(type) { + case 'checkbox': + el.checked = value; + break; + + default: + el.value = value; + break; + } +}; diff --git a/client/modules/config/input.spec.js b/client/modules/config/input.spec.js new file mode 100644 index 00000000..9d0866cd --- /dev/null +++ b/client/modules/config/input.spec.js @@ -0,0 +1,140 @@ +import {test, stub} from 'supertape'; +import { + convert, + getName, + getValue, + setValue, +} from './input.js'; + +test('cloudcmd: client: config: input: convert', (t) => { + const result = convert({ + name: 'hello ', + }); + + const expected = { + name: 'hello <world>', + }; + + t.deepEqual(result, expected); + t.end(); +}); + +test('cloudcmd: client: config: input: convert: bool', (t) => { + const result = convert({ + auth: true, + }); + + const expected = { + auth: ' checked', + }; + + t.deepEqual(result, expected); + t.end(); +}); + +test('cloudcmd: client: config: input: convert: bool false', (t) => { + const result = convert({ + auth: false, + }); + + const expected = { + auth: '', + }; + + t.deepEqual(result, expected); + t.end(); +}); + +test('cloudcmd: client: config: input: getName', (t) => { + const getAttribute = stub().returns('js-hello'); + const element = { + getAttribute, + }; + + const result = getName(element); + + t.equal(result, 'hello', 'should strip js- prefix'); + t.end(); +}); + +test('cloudcmd: client: config: input: getValue: checkbox', (t) => { + const querySelector = stub().returns({ + type: 'checkbox', + checked: true, + }); + + const element = { + querySelector, + }; + + const result = getValue('auth', element); + + t.ok(result, 'should return checked value'); + t.end(); +}); + +test('cloudcmd: client: config: input: getValue: number', (t) => { + const querySelector = stub().returns({ + type: 'number', + value: '42', + }); + + const element = { + querySelector, + }; + + const result = getValue('port', element); + + t.equal(result, 42, 'should return number'); + t.end(); +}); + +test('cloudcmd: client: config: input: getValue: default', (t) => { + const querySelector = stub().returns({ + type: 'text', + value: 'hello', + }); + + const element = { + querySelector, + }; + + const result = getValue('name', element); + + t.equal(result, 'hello', 'should return value as is'); + t.end(); +}); + +test('cloudcmd: client: config: input: setValue: checkbox', (t) => { + const el = { + type: 'checkbox', + checked: false, + }; + + const querySelector = stub().returns(el); + const element = { + querySelector, + }; + + setValue('auth', true, element); + + t.ok(el.checked, 'should set checked'); + t.end(); +}); + +test('cloudcmd: client: config: input: setValue: default', (t) => { + const el = { + type: 'text', + value: 'old', + }; + + const querySelector = stub().returns(el); + const element = { + querySelector, + }; + + setValue('name', 'new', element); + + t.equal(el.value, 'new', 'should set value'); + t.end(); +}); diff --git a/client/modules/contact.js b/client/modules/contact.js index 0bd87725..48c7bd19 100644 --- a/client/modules/contact.js +++ b/client/modules/contact.js @@ -1,36 +1,34 @@ /* global CloudCmd */ /* global DOM */ +import olark from '@cloudcmd/olark'; +import * as Images from '#dom/images'; -'use strict'; +CloudCmd.Contact = { + init, + show, + hide, +}; -CloudCmd.Contact = exports; +const {Events} = DOM; +const {Key} = CloudCmd; -const olark = require('@cloudcmd/olark'); -const Images = require('../dom/images'); - -const Events = DOM.Events; -const Key = CloudCmd.Key; - -module.exports.show = show; -module.exports.hide = hide; - -module.exports.init = () => { +export function init() { Events.addKey(onKey); olark.identify('6216-545-10-4223'); olark('api.box.onExpand', show); olark('api.box.onShow', show); olark('api.box.onShrink', hide); -}; +} -function show() { +export function show() { Key.unsetBind(); Images.hide(); olark('api.box.expand'); } -function hide() { +export function hide() { Key.setBind(); olark('api.box.hide'); } @@ -39,4 +37,3 @@ function onKey({keyCode}) { if (keyCode === Key.ESC) hide(); } - diff --git a/client/modules/edit-file-vim.js b/client/modules/edit-file-vim.js index 6846c7f3..16d557ae 100644 --- a/client/modules/edit-file-vim.js +++ b/client/modules/edit-file-vim.js @@ -1,49 +1,46 @@ -'use strict'; +import * as Events from '#dom/events'; -/* global CloudCmd */ +const {CloudCmd} = globalThis; -CloudCmd.EditFileVim = exports; - -const Events = require('../dom/events'); +CloudCmd.EditFileVim = { + init, + show, + hide, +}; const {Key} = CloudCmd; -const ConfigView = { +const ConfigView = { bindKeys: false, beforeClose: () => { Events.rmKey(listener); CloudCmd.EditFile.isChanged(); - } + }, }; -module.exports.init = async () => { +export async function init() { await CloudCmd.EditFile(); -}; +} -module.exports.show = () => { +export async function show() { Events.addKey(listener); - CloudCmd.EditFile - .show(ConfigView) + const editFile = await CloudCmd.EditFile.show(ConfigView); + + editFile .getEditor() .setKeyMap('vim'); -}; +} -module.exports.hide = hide; - -function hide() { +export function hide() { CloudCmd.Edit.hide(); } function listener(event) { - const { - keyCode, - shiftKey, - } = event; + const {keyCode, shiftKey} = event; if (shiftKey && keyCode === Key.ESC) { event.preventDefault(); hide(); } } - diff --git a/client/modules/edit-file.js b/client/modules/edit-file.js index 7fe98965..83a07e36 100644 --- a/client/modules/edit-file.js +++ b/client/modules/edit-file.js @@ -1,34 +1,35 @@ -'use strict'; - /* global CloudCmd, DOM*/ +import Format from 'format-io'; +import {fullstore} from 'fullstore'; +import exec from 'execon'; +import {supermenu} from 'supermenu'; -CloudCmd.EditFile = exports; - -const Format = require('format-io/legacy'); -const fullstore = require('fullstore/legacy'); -const exec = require('execon'); -const supermenu = require('supermenu'); - -const Info = DOM.CurrentInfo; -const Dialog = DOM.Dialog; -const config = CloudCmd.config; - -let Menu; - -const TITLE = 'Edit'; -const Images = DOM.Images; - -let MSG_CHANGED; -const isLoading = fullstore(); - -const ConfigView = { - beforeClose: () => { - exec.ifExist(Menu, 'hide'); - isChanged(); - } +CloudCmd.EditFile = { + init, + show, + hide, + isChanged, }; -module.exports.init = async () => { +const Info = DOM.CurrentInfo; + +const {Dialog, Images} = DOM; + +const {config} = CloudCmd; + +let Menu; +let MSG_CHANGED; + +const isLoading = fullstore(); + +const ConfigView = { + beforeClose: async () => { + exec.ifExist(Menu, 'hide'); + await isChanged(); + }, +}; + +export async function init() { isLoading(true); await CloudCmd.Edit(); @@ -38,7 +39,7 @@ module.exports.init = async () => { setListeners(editor); isLoading(false); -}; +} function getName() { const {name, isDir} = Info; @@ -49,7 +50,7 @@ function getName() { return name; } -module.exports.show = (options) => { +export async function show(options) { if (isLoading()) return; @@ -67,30 +68,30 @@ module.exports.show = (options) => { .getEditor() .setOption('keyMap', 'default'); - Info.getData((error, data) => { - const path = Info.path; - const name = getName(); - - if (error) - return Images.hide(); - - setMsgChanged(name); - - CloudCmd.Edit - .getEditor() - .setValueFirst(path, data) - .setModeForPath(name) - .enableKey(); - - CloudCmd.Edit.show(optionsEdit); - }); + const [error, data] = await Info.getData(); + + if (error) { + Images.hide(); + return CloudCmd.Edit; + } + + const {path} = Info; + const name = getName(); + + setMsgChanged(name); + + CloudCmd.Edit + .getEditor() + .setValueFirst(path, data) + .setModeForPath(name) + .enableKey(); + + CloudCmd.Edit.show(optionsEdit); return CloudCmd.Edit; -}; +} -module.exports.hide = hide; - -function hide() { +export function hide() { CloudCmd.Edit.hide(); } @@ -107,14 +108,14 @@ function setListeners(editor) { function authCheck(spawn) { spawn.emit('auth', config('username'), config('password')); spawn.on('reject', () => { - Dialog.alert(TITLE, 'Wrong credentials!'); + Dialog.alert('Wrong credentials!'); }); } function setMenu(event) { const position = { x: event.clientX, - y: event.clientY + y: event.clientY, }; event.preventDefault(); @@ -132,12 +133,14 @@ function setMenu(event) { CloudCmd.Edit .getEditor() .focus(); - } + }, }; const element = CloudCmd.Edit.getElement(); Menu = supermenu(element, options, getMenuData()); + + Menu.addContextMenuListener(); Menu.show(position.x, position.y); } @@ -145,56 +148,46 @@ function getMenuData() { const editor = CloudCmd.Edit.getEditor(); return { - 'Save Ctrl+S' : () => { + 'Save Ctrl+S': () => { editor.save(); }, - 'Go To Line Ctrl+G' : () => { + 'Go To Line Ctrl+G': () => { editor.goToLine(); }, - 'Cut Ctrl+X' : () => { + 'Cut Ctrl+X': () => { editor.cutToClipboard(); }, - 'Copy Ctrl+C' : () => { + 'Copy Ctrl+C': () => { editor.copyToClipboard(); }, - 'Paste Ctrl+V' : () => { + 'Paste Ctrl+V': () => { editor.pasteFromClipboard(); }, - 'Delete Del' : () => { + 'Delete Del': () => { editor.remove('right'); }, - 'Select All Ctrl+A' : () => { + 'Select All Ctrl+A': () => { editor.selectAll(); }, - 'Beautify Ctrl+B' : () => { - editor.beautify(); - }, - 'Minify Ctrl+M' : () => { - editor.minify(); - }, - 'Close Esc' : () => { - hide(); - } + 'Close Esc': hide, }; } function setMsgChanged(name) { - MSG_CHANGED = 'Do you want to save changes to ' + name + '?'; + MSG_CHANGED = `Do you want to save changes to ${name}?`; } -module.exports.isChanged = isChanged; - -function isChanged() { +export async function isChanged() { const editor = CloudCmd.Edit.getEditor(); const is = editor.isChanged(); if (!is) return; - const cancel = false; - Dialog.confirm(TITLE, MSG_CHANGED, {cancel}) - .then(() => { - editor.save(); - }); + const [cancel] = await Dialog.confirm(MSG_CHANGED); + + if (cancel) + return; + + editor.save(); } - diff --git a/client/modules/edit-names-vim.js b/client/modules/edit-names-vim.js index a12af0d1..8b3b2f89 100644 --- a/client/modules/edit-names-vim.js +++ b/client/modules/edit-names-vim.js @@ -1,48 +1,44 @@ -'use strict'; +import * as Events from '#dom/events'; -/* global CloudCmd */ +const {CloudCmd} = globalThis; -CloudCmd.EditNamesVim = exports; - -const Events = require('../dom/events'); +CloudCmd.EditNamesVim = { + init, + show, + hide, +}; const {Key} = CloudCmd; -const ConfigView = { +const ConfigView = { bindKeys: false, beforeClose: () => { Events.rmKey(listener); CloudCmd.EditNames.isChanged(); - } + }, }; -module.exports.init = async () => { +export async function init() { await CloudCmd.EditNames(); -}; +} -module.exports.show = () => { +export function show() { Events.addKey(listener); CloudCmd.EditNames .show(ConfigView) .getEditor() .setKeyMap('vim'); -}; +} -module.exports.hide = hide; - -function hide() { +export function hide() { CloudCmd.Edit.hide(); } function listener(event) { - const { - keyCode, - shiftKey, - } = event; + const {keyCode, shiftKey} = event; if (shiftKey && keyCode === Key.ESC) { event.preventDefault(); hide(); } } - diff --git a/client/modules/edit-names.js b/client/modules/edit-names.js index bd4bce69..7bc29054 100644 --- a/client/modules/edit-names.js +++ b/client/modules/edit-names.js @@ -1,50 +1,45 @@ -'use strict'; +import {tryToCatch} from 'try-to-catch'; +import exec from 'execon'; +import {supermenu} from 'supermenu'; +import {multiRename} from 'multi-rename'; -/* global CloudCmd, DOM */ +const {CloudCmd, DOM} = globalThis; -CloudCmd.EditNames = exports; - -const currify = require('currify/legacy'); -const exec = require('execon'); -const supermenu = require('supermenu'); - -const reject = Promise.reject.bind(Promise); +CloudCmd.EditNames = { + init, + show, + hide, + isChanged, +}; const Info = DOM.CurrentInfo; -const Dialog = DOM.Dialog; - -const TITLE = 'Edit Names'; -const alert = currify(Dialog.alert, TITLE); -const refresh = currify(_refresh); -const rename = currify(_rename); +const {Dialog} = DOM; let Menu; -const EditNames = exec.bind(); -const ConfigView = { - beforeClose: () => { +const ConfigView = { + beforeClose: async () => { exec.ifExist(Menu, 'hide'); DOM.Events.remove('keydown', keyListener); - isChanged(); - } + await isChanged(); + }, }; -module.exports.init = async () => { +export async function init() { await CloudCmd.Edit(); - const editor = CloudCmd.Edit.getEditor(); - setListeners(editor); -}; + setListeners(); +} -module.exports.show = (options) => { +export function show(options) { const names = getActiveNames().join('\n'); const config = { - ...ConfigView, + ...ConfigView, ...options, }; if (Info.name === '..' && names.length === 1) - return Dialog.alert.noFiles(TITLE); + return Dialog.alert.noFiles(); DOM.Events.addKey(keyListener); @@ -56,29 +51,41 @@ module.exports.show = (options) => { .disableKey(); CloudCmd.Edit.show(config); - + return CloudCmd.Edit; -}; +} -function keyListener(event) { +async function keyListener(event) { const ctrl = event.ctrlKey; const meta = event.metaKey; const ctrlMeta = ctrl || meta; - const Key = CloudCmd.Key; + const {Key} = CloudCmd; - if (!ctrlMeta || event.keyCode !== Key.S) + if (ctrlMeta && event.keyCode === Key.S) { + hide(); return; + } - EditNames.hide(); + if (ctrlMeta && event.keyCode === Key.P) { + const [, pattern] = await Dialog.prompt('Apply pattern:', '[n][e]'); + pattern && applyPattern(pattern); + } +} + +function applyPattern(pattern) { + const newNames = multiRename(pattern, getActiveNames()); + const editor = CloudCmd.Edit.getEditor(); + + editor.setValue(newNames.join('\n')); } function getActiveNames() { return DOM.getFilenames(DOM.getActiveFiles()); } -module.exports.hide = () => { +export function hide() { CloudCmd.Edit.hide(); -}; +} function setListeners() { const element = CloudCmd.Edit.getElement(); @@ -86,7 +93,7 @@ function setListeners() { DOM.Events.addOnce('contextmenu', element, setMenu); } -function applyNames() { +async function applyNames() { const dir = Info.dirPath; const from = getActiveNames(); const nameIndex = from.indexOf(Info.name); @@ -98,20 +105,23 @@ function applyNames() { const root = CloudCmd.config('root'); - Promise.resolve(root) - .then(rename(dir, from, to)) - .then(refresh(to, nameIndex)) - .catch(alert); + const response = rename(dir, from, to, root); + const [error] = await tryToCatch(refresh, to, nameIndex, response); + + if (error) + alert(error); } -function _refresh(to, nameIndex, res) { - if (res.status === 404) - return res.text().then(reject); +function refresh(to, nameIndex, res) { + if (res.status === 404) { + const error = res.text(); + throw error; + } const currentName = to[nameIndex]; CloudCmd.refresh({ - currentName + currentName, }); } @@ -122,24 +132,25 @@ function getDir(root, dir) { return root + dir; } -function _rename(path, from, to, root) { +function rename(path, from, to, root) { const dir = getDir(root, path); + const {prefix} = CloudCmd; - return fetch(CloudCmd.PREFIX + '/rename', { + return fetch(`${prefix}/rename`, { method: 'put', credentials: 'include', body: JSON.stringify({ from, to, dir, - }) + }), }); } function setMenu(event) { const position = { x: event.clientX, - y: event.clientY + y: event.clientY, }; event.preventDefault(); @@ -148,6 +159,7 @@ function setMenu(event) { return; const editor = CloudCmd.Edit.getEditor(); + const options = { beforeShow: (params) => { params.x -= 18; @@ -156,53 +168,51 @@ function setMenu(event) { afterClick: () => { editor.focus(); - } + }, }; const menuData = { - 'Save Ctrl+S' : () => { - editor.save(); - EditNames.hide(); + 'Save Ctrl+S': async () => { + await applyNames(); + hide(); }, - 'Go To Line Ctrl+G' : () => { + 'Go To Line Ctrl+G': () => { editor.goToLine(); }, - 'Cut Ctrl+X' : () => { + 'Cut Ctrl+X': () => { editor.cutToClipboard(); }, - 'Copy Ctrl+C' : () => { + 'Copy Ctrl+C': () => { editor.copyToClipboard(); }, - 'Paste Ctrl+V' : () => { + 'Paste Ctrl+V': () => { editor.pasteFromClipboard(); }, - 'Delete Del' : () => { + 'Delete Del': () => { editor.remove('right'); }, - 'Select All Ctrl+A' : () => { + 'Select All Ctrl+A': () => { editor.selectAll(); }, - 'Close Esc' : () => { - EditNames.hide(); - } + 'Close Esc': hide, }; const element = CloudCmd.Edit.getElement(); Menu = supermenu(element, options, menuData); + + Menu.addContextMenuListener(); Menu.show(position.x, position.y); } -module.exports.isChanged = isChanged; - -function isChanged() { +export async function isChanged() { const editor = CloudCmd.Edit.getEditor(); const msg = 'Apply new names?'; if (!editor.isChanged()) return; - Dialog.confirm(TITLE, msg, {cancel: false}) - .then(applyNames); + const [cancel] = await Dialog.confirm(msg); + + !cancel && await applyNames(); } - diff --git a/client/modules/edit.js b/client/modules/edit.js index 2fda3cd2..593a11cb 100644 --- a/client/modules/edit.js +++ b/client/modules/edit.js @@ -1,19 +1,28 @@ /* global CloudCmd */ +import {montag} from 'montag'; +import {promisify} from 'es6-promisify'; +import {tryToCatch} from 'try-to-catch'; +import createElement from '@cloudcmd/create-element'; +import load from 'load.js'; +import {MAX_FILE_SIZE as maxSize} from '#common/cloudfunc'; +import {time, timeEnd} from '#common/util'; -'use strict'; +export function getEditor() { + return editor; +} -const {promisify} = require('es6-promisify'); -const tryToCatch = require('try-to-catch/legacy'); -const createElement = require('@cloudcmd/create-element'); -const load = require('load.js'); -const loadJS = promisify(load.js); - -const {MAX_FILE_SIZE: maxSize} = require('../../common/cloudfunc'); -const {time, timeEnd} = require('../../common/util'); +const isFn = (a) => typeof a === 'function'; +const loadJS = load.js; const Name = 'Edit'; -CloudCmd[Name] = exports; +CloudCmd[Name] = { + init, + show, + hide, + getEditor, + getElement, +}; const EditorName = CloudCmd.config('editor'); @@ -26,23 +35,24 @@ const ConfigView = { editor .moveCursorTo(0, 0) .focus(); - } + }, }; -module.exports.init = async () => { +export async function init() { const element = create(); await CloudCmd.View(); await loadFiles(element); -}; +} function create() { const element = createElement('div', { - style: - 'width : 100%;' + - 'height : 100%;' + - 'font-family: "Droid Sans Mono";', - notAppend: true + style: montag` + width: 100%; + height: 100%; + font-family: "Droid Sans Mono"; + `, + notAppend: true, }); Element = element; @@ -51,8 +61,8 @@ function create() { } function checkFn(name, fn) { - if (typeof fn !== 'function') - throw Error(name + ' should be a function!'); + if (!isFn(fn)) + throw Error(`${name} should be a function!`); } function initConfig(options = {}) { @@ -66,49 +76,40 @@ function initConfig(options = {}) { checkFn('options.afterShow', options.afterShow); - const afterShow = {config}; - config.afterShow = () => { - afterShow(); + ConfigView.afterShow(); options.afterShow(); }; return config; } -module.exports.show = (options) => { +export function show(options) { if (Loading) return; - + CloudCmd.View.show(Element, initConfig(options)); - getEditor() - .setOptions({ - fontSize: 16, - }); -}; - -module.exports.getEditor = getEditor; - -function getEditor() { - return editor; + getEditor().setOptions({ + fontSize: 16, + }); } -module.exports.getElement = () => { +export function getElement() { return Element; -}; +} -module.exports.hide = () => { +export function hide() { CloudCmd.View.hide(); -}; +} const loadFiles = async (element) => { - const socketPath = CloudCmd.PREFIX; - const {prefixSocket} = CloudCmd; - const prefix = socketPath + '/' + EditorName; - const url = prefix + '/' + EditorName + '.js'; + const prefix = `${CloudCmd.prefix}/${EditorName}`; + const socketPath = CloudCmd.prefix; + const prefixSocket = `${CloudCmd.prefixSocket}/${EditorName}`; + const url = `${prefix}/${EditorName}.js`; - time(Name + ' load'); + time(`${Name} load`); await loadJS(url); @@ -120,8 +121,7 @@ const loadFiles = async (element) => { socketPath, }); - timeEnd(Name + ' load'); + timeEnd(`${Name} load`); editor = ed; Loading = false; }; - diff --git a/client/modules/help.js b/client/modules/help.js index 5e859115..74657a90 100644 --- a/client/modules/help.js +++ b/client/modules/help.js @@ -1,31 +1,27 @@ -'use strict'; +import * as Images from '#dom/images'; -/* global CloudCmd */ +const {CloudCmd} = globalThis; -CloudCmd.Help = exports; - -const Images = require('../dom/images'); - -module.exports.init = () => { - Images.show.load('top'); +CloudCmd.Help = { + init, + show, + hide, }; -module.exports.show = show; -module.exports.hide = hide; +export function init() { + Images.show.load('top'); +} -function show() { +export function show() { const positionLoad = 'top'; const relative = true; - CloudCmd - .Markdown - .show('/HELP.md', { - positionLoad, - relative, - }); + CloudCmd.Markdown.show('/HELP.md', { + positionLoad, + relative, + }); } -function hide() { +export function hide() { CloudCmd.View.hide(); } - diff --git a/client/modules/konsole.js b/client/modules/konsole.js index 82f4c56c..e9a465af 100644 --- a/client/modules/konsole.js +++ b/client/modules/konsole.js @@ -1,24 +1,21 @@ -'use strict'; - /* global CloudCmd */ /* global Util */ /* global DOM */ /* global Console */ +import exec from 'execon'; +import currify from 'currify'; +import {tryToCatch} from 'try-to-catch'; +import {js as loadJS} from 'load.js'; +import createElement from '@cloudcmd/create-element'; +import * as Images from '#dom/images'; -CloudCmd.Konsole = exports; +CloudCmd.Konsole = { + init, + show, + hide, +}; -const exec = require('execon'); -const {promisify} = require('es6-promisify'); -const currify = require('currify/legacy'); -const tryToCatch = require('try-to-catch/legacy'); -const loadJS = promisify(require('load.js').js); -const createElement = require('@cloudcmd/create-element'); - -const Images = require('../dom/images'); -const { - Dialog, - CurrentInfo:Info, -} = DOM; +const {Dialog, CurrentInfo: Info} = DOM; const rmLastSlash = (a) => a.replace(/\/$/, '') || '/'; @@ -28,12 +25,11 @@ const {config} = CloudCmd; const cd = currify((fn, dir) => fn(`cd ${rmLastSlash(dir)}`)); const Name = 'Konsole'; -const TITLE = 'Console'; let Element; let Loaded; -module.exports.init = async () => { +export async function init() { if (!config('console')) return; @@ -42,42 +38,34 @@ module.exports.init = async () => { await CloudCmd.View(); await load(); await create(); -}; +} -module.exports.hide = () => { +export function hide() { CloudCmd.View.hide(); -}; +} -module.exports.clear = () => { +export const clear = () => { konsole.clear(); }; -function getPrefix() { - return CloudCmd.PREFIX + '/console'; -} +const getPrefix = () => CloudCmd.prefix + '/console'; function getPrefixSocket() { return CloudCmd.prefixSocket + '/console'; } -function getEnv() { - return { - ACTIVE_DIR: DOM.getCurrentDirPath.bind(DOM), - PASSIVE_DIR: DOM.getNotCurrentDirPath.bind(DOM), - CURRENT_NAME: DOM.getCurrentName.bind(DOM), - CURRENT_PATH: () => { - return Info.path; - } - }; -} +const getEnv = () => ({ + ACTIVE_DIR: DOM.getCurrentDirPath.bind(DOM), + PASSIVE_DIR: DOM.getNotCurrentDirPath.bind(DOM), + CURRENT_NAME: DOM.getCurrentName.bind(DOM), + CURRENT_PATH: () => Info.path, +}); -function onPath(path) { +async function onPath(path) { if (Info.dirPath === path) return; - CloudCmd.loadDir({ - path, - }); + await CloudCmd.changeDir(path); } const getDirPath = () => { @@ -91,7 +79,7 @@ const create = async () => { env: getEnv(), prefix: getPrefix(), prefixSocket: getPrefixSocket(), - socketPath: CloudCmd.PREFIX, + socketPath: CloudCmd.prefix, }; Element = createElement('div', { @@ -106,12 +94,12 @@ const create = async () => { CloudCmd.on('active-dir', config.if('syncConsolePath', cd(konsole.handler))); konsole.addShortCuts({ - 'P': () => { + P: () => { const command = konsole.getPromptText(); const path = DOM.getCurrentDirPath(); konsole.setPromptText(command + path); - } + }, }); }; @@ -119,11 +107,11 @@ function authCheck(konsole) { konsole.emit('auth', config('username'), config('password')); konsole.on('reject', () => { - Dialog.alert(TITLE, 'Wrong credentials!'); + Dialog.alert('Wrong credentials!'); }); } -module.exports.show = (callback) => { +export function show(callback) { if (!Loaded) return; @@ -134,23 +122,22 @@ module.exports.show = (callback) => { afterShow: () => { konsole.focus(); exec(callback); - } + }, }); -}; +} const load = async () => { - Util.time(Name + ' load'); + Util.time(`${Name} load`); const prefix = getPrefix(); - const url = prefix + '/console.js'; + const url = `${prefix}/console.js`; const [error] = await tryToCatch(loadJS, url); Loaded = true; - Util.timeEnd(Name + ' load'); + Util.timeEnd(`${Name} load`); if (error) - return Dialog.alert(TITLE, error.message, { - cancel: false + return Dialog.alert(error.message, { + cancel: false, }); }; - diff --git a/client/modules/markdown.js b/client/modules/markdown.js index c83c95c9..c94c64e8 100644 --- a/client/modules/markdown.js +++ b/client/modules/markdown.js @@ -1,50 +1,38 @@ -'use strict'; +import createElement from '@cloudcmd/create-element'; +import * as Images from '#dom/images'; +import {Markdown} from '#dom/rest'; +import {alert} from '#dom/dialog'; -/* global CloudCmd */ +const {CloudCmd} = globalThis; -const {promisify} = require('es6-promisify'); -const tryToCatch = require('try-to-catch/legacy'); +CloudCmd.Markdown = { + init, + show, + hide, +}; -CloudCmd.Markdown = exports; - -const TITLE = 'Cloud Commander'; - -const createElement = require('@cloudcmd/create-element'); - -const Images = require('../dom/images'); -const {Markdown} = require('../dom/rest'); -const {alert} = require('../dom/dialog'); - -const read = promisify(Markdown.read); - -module.exports.init = async () => { +export async function init() { Images.show.load('top'); await CloudCmd.View(); -}; +} -module.exports.show = show; - -module.exports.hide = () => { +export function hide() { CloudCmd.View.hide(); -}; +} -async function show(name, options = {}) { - const relativeQuery = '?relative'; - const { - positionLoad, - relative, - } = options; +export async function show(name, options = {}) { + const {positionLoad, relative} = options; Images.show.load(positionLoad); if (relative) - name += relativeQuery; + name += '?relative'; - const [error, innerHTML] = await tryToCatch(read, name); + const [error, innerHTML] = await Markdown.read(name); Images.hide(); if (error) - return alert(TITLE, error.message, { + return alert(error.message, { cancel: false, }); @@ -57,4 +45,3 @@ async function show(name, options = {}) { CloudCmd.View.show(div); } - diff --git a/client/modules/menu/cloudmenu.js b/client/modules/menu/cloudmenu.js new file mode 100644 index 00000000..8f7c1e68 --- /dev/null +++ b/client/modules/menu/cloudmenu.js @@ -0,0 +1,31 @@ +import {supermenu} from 'supermenu'; + +const noop = () => {}; +const {CloudCmd} = globalThis; + +export const createCloudMenu = async (fm, options, menuData) => { + const createMenu = await loadMenu(); + const menu = await createMenu(fm, options, menuData); + + menu.addContextMenuListener = menu.addContextMenuListener || noop; + + return menu; +}; + +async function loadMenu() { + if (CloudCmd.config('menu') === 'aleman') { + const {prefix} = CloudCmd; + const {host, protocol} = globalThis.location; + const url = `${protocol}//${host}${prefix}/node_modules/aleman/menu/menu.js`; + const {createMenu} = await import(/* webpackIgnore: true */url); + + return createMenu; + } + + return createSupermenu; +} + +function createSupermenu(name, options, menuData) { + const element = document.querySelector('[data-name="js-fm"]'); + return supermenu(element, options, menuData); +} diff --git a/client/modules/menu.js b/client/modules/menu/index.js similarity index 57% rename from client/modules/menu.js rename to client/modules/menu/index.js index c1b88a47..7235591e 100644 --- a/client/modules/menu.js +++ b/client/modules/menu/index.js @@ -1,65 +1,76 @@ -/* global CloudCmd, DOM */ +import exec from 'execon'; +import wrap from 'wraptile'; +import createElement from '@cloudcmd/create-element'; +import {getIdBySrc} from '#dom/load'; +import * as RESTful from '#dom/rest'; +import {FS} from '#common/cloudfunc'; -'use strict'; +const {CloudCmd, DOM} = globalThis; +const {config, Key} = CloudCmd; -const exec = require('execon'); -const wrap = require('wraptile/legacy'); -const supermenu = require('supermenu'); -const createElement = require('@cloudcmd/create-element'); +const { + Buffer, + Events, + Dialog, + Images, +} = DOM; -const {FS} = require('../../common/cloudfunc'); -const {getIdBySrc} = require('../dom/load'); -const RESTful = require('../dom/rest'); - -const config = CloudCmd.config; -const Buffer = DOM.Buffer; const Info = DOM.CurrentInfo; -const Key = CloudCmd.Key; -const Events = DOM.Events; -const Dialog = DOM.Dialog; -const Images = DOM.Images; -const TITLE = 'Cloud Commander'; -const alertNoFiles = wrap(Dialog.alert.noFiles)(TITLE); +const alertNoFiles = Dialog.alert.noFiles; const uploadTo = wrap(_uploadTo); let MenuShowedName; let MenuContext; let MenuContextFile; -module.exports.ENABLED = false; +export const ENABLED = false; -CloudCmd.Menu = exports; - -module.exports.init = () => { - const {isAuth, menuDataFile} = getFileMenuData(); - - const NOT_FILE = true; - const fm = DOM.getFM(); - const menuData = getMenuData(isAuth); - const options = getOptions(NOT_FILE); - const optionsFile = getOptions(); - - MenuContext = supermenu(fm, options, menuData); - MenuContextFile = supermenu(fm, optionsFile, menuDataFile); - - Events.addKey(listener); +CloudCmd.Menu = { + init, + show, + hide, }; -module.exports.hide = hide; +export async function init() { + const {isAuth, menuDataFile} = getFileMenuData(); + + const fm = DOM.getFM(); + const menuData = getMenuData(isAuth); + + const options = getOptions({ + type: 'context', + }); + + const optionsFile = getOptions({ + type: 'file', + }); + + const {createCloudMenu} = await import('./cloudmenu.js'); + + const {name} = fm.dataset; + + MenuContext = await createCloudMenu(name, options, menuData); + MenuContextFile = await createCloudMenu(name, optionsFile, menuDataFile); + + MenuContext.addContextMenuListener(); + MenuContextFile.addContextMenuListener(); + + Events.addKey(listener); +} -function hide() { +export function hide() { MenuContext.hide(); MenuContextFile.hide(); } -module.exports.show = (position) => { +export function show(position) { const {x, y} = getPosition(position); MenuContext.show(x, y); MenuContextFile.show(x, y); Images.hide(); -}; +} function getPosition(position) { if (position) @@ -83,20 +94,23 @@ function getMenuNameByEl(el) { return 'contextFile'; } -function getOptions(notFile) { - let name, func; +function getOptions({type}) { + let name; + let func; - if (notFile) { - name = 'context'; - func = Key.unsetBind; - } else { - name = 'contextFile'; + if (type === 'context') { + name = 'context'; + func = Key.unsetBind; + } else if (type === 'file') { + name = 'contextFile'; } const options = { - icon : true, - beforeClose : Key.setBind, - beforeShow : exec.with(beforeShow, func), + icon: true, + infiniteScroll: false, + beforeClose: Key.setBind, + beforeHide: Key.setBind, + beforeShow: exec.with(beforeShow, func), beforeClick, name, }; @@ -108,14 +122,15 @@ function getMenuData(isAuth) { const menu = { 'Paste': Buffer.paste, 'New': { - 'File': DOM.promptNewFile, - 'Directory': DOM.promptNewDir + File: DOM.promptNewFile, + Directory: DOM.promptNewDir, }, 'Upload': () => { CloudCmd.Upload.show(); }, 'Upload From Cloud': uploadFromCloud, - '(Un)Select All': DOM.toggleAllSelectedFiles + 'Toggle File Selection': DOM.toggleSelectedFile, + '(Un)Select All': DOM.toggleAllSelectedFiles, }; if (isAuth) @@ -126,14 +141,16 @@ function getMenuData(isAuth) { function getFileMenuData() { const isAuth = CloudCmd.config('auth'); - const show = wrap((name) => { - CloudCmd[name].show(); - }); const menuBottom = getMenuData(isAuth); const menuTop = { - 'View': show('View'), - 'Edit': show('EditFile'), + 'View': () => { + CloudCmd.View.show(); + }, + 'Edit': () => { + const name = config('vim') ? 'EditFileVim' : 'EditFile'; + CloudCmd[name].show(); + }, 'Rename': () => { setTimeout(DOM.renameCurrent, 100); }, @@ -183,65 +200,72 @@ function isPath(x, y) { const el = document.elementFromPoint(x, y); const elements = panel.querySelectorAll('[data-name="js-path"] *'); - const is = ~[].indexOf.call(elements, el); - return is; + return !~[].indexOf.call(elements, el); } function beforeShow(callback, params) { - const name = params.name; - let el = DOM.getCurrentByPosition({ - x: params.x, - y: params.y + Key.unsetBind(); + + const { + name, + position = { + x: params.x, + y: params.y, + }, + } = params; + + const {x, y} = position; + + const el = DOM.getCurrentByPosition({ + x, + y, }); const menuName = getMenuNameByEl(el); - let notShow = menuName === 'contextFile'; - if (params.name === 'contextFile') { - notShow = !notShow; - } + let isShow = menuName !== 'contextFile'; - if (!notShow) + if (params.name === 'contextFile') + isShow = !isShow; + + if (isShow) MenuShowedName = name; exec(callback); - if (!notShow) - notShow = isPath(params.x, params.y); + if (isShow) + isShow = isPath(x, y); - return notShow; + return isShow; } -function beforeClick(name) { - return MenuShowedName !== name; -} +const beforeClick = (name) => MenuShowedName !== name; -function _uploadTo(nameModule) { - Info.getData((error, data) => { - if (error) - return; - - const name = Info.name; - const execFrom = CloudCmd.execFromModule; - - execFrom(nameModule, 'uploadFile', name, data); - }); +async function _uploadTo(nameModule) { + const [error, data] = await Info.getData(); - CloudCmd.log('Uploading to ' + name + '...'); + if (error) + return; + + const {name} = Info; + + CloudCmd.execFromModule(nameModule, 'uploadFile', name, data); + CloudCmd.log(`Uploading to ${name}...`); } function uploadFromCloud() { Images.show.load('top'); - CloudCmd.execFromModule('Cloud', 'saveFile', (currentName, data) => { + CloudCmd.execFromModule('Cloud', 'saveFile', async (currentName, data) => { const path = DOM.getCurrentDirPath() + currentName; + const [e] = await RESTful.write(path, data); - RESTful.write(path, data, (error) => { - if (error) - return; - - CloudCmd.refresh({currentName}); + if (e) + return; + + await CloudCmd.refresh({ + currentName, }); }); } @@ -252,37 +276,38 @@ function preDownload() { function download(type) { const TIME = 30 * 1000; - const prefixUr = CloudCmd.PREFIX_URL; + const {prefixURL} = CloudCmd; const PACK = '/pack'; const date = Date.now(); const files = DOM.getActiveFiles(); if (!files.length) return alertNoFiles(); - - files.forEach((file) => { + + for (const file of files) { const selected = DOM.isSelected(file); const isDir = DOM.isCurrentIsDir(file); const path = DOM.getCurrentPath(file); - CloudCmd.log('downloading file ' + path + '...'); + CloudCmd.log(`downloading file ${path}...`); + /* * if we send ajax request - * no need in hash so we escape # * and all other characters, like "%" */ - const encodedPath = encodeURI(path).replace(/#/g, '%23'); + const encodedPath = encodeURI(path).replace(/#/g, '#'); const id = getIdBySrc(path); let src; if (isDir) - src = prefixUr + PACK + encodedPath + DOM.getPackerExt(type); + src = prefixURL + PACK + encodedPath + DOM.getPackerExt(type); else - src = prefixUr + FS + encodedPath + '?download'; + src = prefixURL + FS + encodedPath + '?download'; const element = createElement('iframe', { - id : id + '-' + date, + id: id + '-' + date, async: false, className: 'hidden', src, @@ -295,7 +320,7 @@ function download(type) { if (selected) DOM.toggleSelectedFile(file); - }); + } } function getCurrentPosition() { @@ -304,25 +329,24 @@ function getCurrentPosition() { const position = { x: Math.round(rect.left + rect.width / 3), - y: Math.round(rect.top) + y: Math.round(rect.top), }; return position; } function listener(event) { - const F9 = Key.F9; - const ESC = Key.ESC; + const {F9, ESC} = Key; + const key = event.keyCode; const isBind = Key.isBind(); - if (!isBind) - return; - - if (key === ESC) + if (key === ESC) { + Key.setBind(); return hide(); + } - if (key === F9) { + if (isBind && key === F9) { const position = getCurrentPosition(); MenuContext.show(position.x, position.y); diff --git a/client/modules/operation/format.js b/client/modules/operation/format.js new file mode 100644 index 00000000..c639799e --- /dev/null +++ b/client/modules/operation/format.js @@ -0,0 +1,6 @@ +export const format = (operation, from, to) => { + if (!to) + return `${operation} ${from}`; + + return `${operation} ${from} -> ${to}`; +}; diff --git a/client/modules/operation/get-next-current-name.js b/client/modules/operation/get-next-current-name.js index dc2bed5e..63445888 100644 --- a/client/modules/operation/get-next-current-name.js +++ b/client/modules/operation/get-next-current-name.js @@ -1,19 +1,16 @@ -'use strict'; +import currify from 'currify'; -const currify = require('currify/legacy'); - -const not = currify((array, value) => !~array.indexOf(value)); +const not = currify((array, value) => !array.includes(value)); const notOneOf = currify((a, b) => a.filter(not(b))); -module.exports = (currentName, names, removedNames) => { +export const getNextCurrentName = (currentName, names, removedNames) => { const i = names.indexOf(currentName); const nextNames = notOneOf(names, removedNames); - const length = nextNames.length; + const {length} = nextNames; if (nextNames[i]) return nextNames[i]; return nextNames[length - 1]; }; - diff --git a/client/modules/operation/index.js b/client/modules/operation/index.js index f52c395e..f349f7d8 100644 --- a/client/modules/operation/index.js +++ b/client/modules/operation/index.js @@ -1,51 +1,34 @@ -/* global CloudCmd */ -/* global Util */ -/* global DOM */ -/* global fileop */ +import currify from 'currify'; +import wraptile from 'wraptile'; +import {promisify} from 'es6-promisify'; +import exec from 'execon'; +import load from 'load.js'; +import {tryToCatch} from 'try-to-catch'; +import {encode} from '#common/entity'; +import {removeExtension} from './remove-extension.js'; +import {setListeners} from './set-listeners.js'; +import {getNextCurrentName} from './get-next-current-name.js'; -'use strict'; - -const currify = require('currify/legacy'); -const wraptile = require('wraptile/legacy'); -const {promisify} = require('es6-promisify'); -const exec = require('execon'); -const loadJS = require('load.js').js; - -const { - encode, -} = require('../../../common/entity'); - -const RESTful = require('../../dom/rest'); -const removeExtension = require('./remove-extension'); -const setListeners = require('./set-listeners'); -const getNextCurrentName = require('./get-next-current-name'); +const {DOM, CloudCmd} = globalThis; const removeQuery = (a) => a.replace(/\?.*/, ''); const Name = 'Operation'; -CloudCmd[Name] = exports; -const { - TITLE, - config, -} = CloudCmd; +const {config} = CloudCmd; const {Dialog, Images} = DOM; -const initOperations = wraptile(_initOperations); -const authCheck = wraptile(_authCheck); +const authCheck = wraptile(_authCheck); const Operation = {}; let Loaded; -let { - cp: copyFn, - mv: moveFn, - delete: deleteFn, - extract: extractFn, -} = RESTful; - -let packZipFn = RESTful.pack; -let packTarFn = RESTful.pack; +let copyFn; +let moveFn; +let deleteFn; +let extractFn; +let packZipFn; +let packTarFn; const Info = DOM.CurrentInfo; const showLoad = Images.show.load.bind(null, 'top'); @@ -57,27 +40,30 @@ const noFilesCheck = () => { const is = Boolean(!length); if (is) - return Dialog.alert.noFiles(TITLE); + return Dialog.alert.noFiles(); return is; }; - -module.exports.init = promisify((callback) => { + +export const init = promisify((callback) => { showLoad(); exec.series([ DOM.loadSocket, - (callback) => { - if (!config('progress')) + async (callback) => { + if (config('dropbox')) return callback(); - load(initOperations(CloudCmd.PREFIX, callback)); + const {prefix, prefixSocket} = CloudCmd; + + await loadAll(); + await initOperations(prefix, prefixSocket, callback); }, (callback) => { Loaded = true; Images.hide(); callback(); - } + }, ], callback); }); @@ -86,62 +72,117 @@ function _authCheck(spawn, ok) { const alertDialog = wraptile(Dialog.alert); spawn.on('accept', accept(spawn)); - spawn.on('reject', alertDialog (TITLE, 'Wrong credentials!')); + spawn.on('reject', alertDialog('Wrong credentials!')); spawn.emit('auth', config('username'), config('password')); } -function _initOperations(socketPrefix, fn) { - const prefix = `${socketPrefix}/fileop`; - fileop({prefix, socketPrefix}, (e, operator) => { - fn(); - - operator.on('connect', authCheck(operator, onConnect)); - operator.on('disconnect', onDisconnect); +const onConnect = currify((fn, operator) => { + setOperations(operator); + fn(); +}); + +async function initOperations(prefix, socketPrefix, fn) { + socketPrefix = `${socketPrefix}/fileop`; + + const operator = await globalThis.fileop({ + prefix, + socketPrefix, }); + + operator.on('connect', authCheck(operator, onConnect(fn))); } -function onConnect(operator) { - packTarFn = (data, callback) => { - operator.tar(data.from, data.to, data.names) - .then(setListeners({noContinue: true}, callback)); +function setOperations(operator) { + packTarFn = ({from, to, names}, callback) => { + const operation = 'Tar'; + const listen = setListeners({ + operation, + callback, + noContinue: true, + from, + to, + }); + + operator + .tar(from, to, names) + .then(listen); }; - packZipFn = (data, callback) => { - operator.zip(data.from, data.to, data.names) - .then(setListeners({noContinue: true}, callback)); + packZipFn = ({from, to, names}, callback) => { + const operation = 'Zip'; + const listen = setListeners({ + operation, + callback, + noContinue: true, + from, + to, + }); + + operator + .zip(from, to, names) + .then(listen); }; deleteFn = (from, files, callback) => { from = removeQuery(from); - operator.remove(from, files) - .then(setListeners(callback)); + + const operation = 'Delete'; + const listen = setListeners({ + operation, + callback, + from, + }); + + operator + .remove(from, files) + .then(listen); }; - copyFn = (data, callback) => { - operator.copy(data.from, data.to, data.names) - .then(setListeners(callback)); + copyFn = ({from, to, names}, callback) => { + const operation = 'Copy'; + const listen = setListeners({ + operation, + callback, + from, + to, + names, + }); + + operator + .copy(from, to, names) + .then(listen); }; - moveFn = (data, callback) => { - operator.move(data.from, data.to, data.names) - .then(setListeners(callback)); + moveFn = ({from, to, names}, callback) => { + const operation = 'Move'; + const listen = setListeners({ + operation, + callback, + from, + to, + }); + + operator + .move(from, to, names) + .then(listen); }; - extractFn = (data, callback) => { - operator.extract(data.from, data.to) - .then(setListeners({noContinue: true}, callback)); + extractFn = ({from, to}, callback) => { + const operation = 'Extract'; + const listen = setListeners({ + operation, + callback, + noContinue: true, + from, + to, + }); + + operator + .extract(from, to) + .then(listen); }; } -function onDisconnect() { - packZipFn = RESTful.pack; - packTarFn = RESTful.pack; - deleteFn = RESTful.delete; - copyFn = RESTful.cp; - moveFn = RESTful.mv; - extractFn = RESTful.extract; -} - function getPacker(type) { if (type === 'zip') return packZipFn; @@ -149,11 +190,11 @@ function getPacker(type) { return packTarFn; } -module.exports.hide = () => { +export function hide() { CloudCmd.View.hide(); -}; +} -module.exports.show = (operation, data) => { +export function show(operation, data) { if (!Loaded) return; @@ -174,23 +215,19 @@ module.exports.show = (operation, data) => { if (operation === 'extract') return Operation.extract(); -}; +} Operation.copy = processFiles({ type: 'copy', }); Operation.move = processFiles({ - type: 'move' + type: 'move', }); -Operation.delete = () => { - promptDelete(); -}; +Operation.delete = promptDelete; -Operation.deleteSilent = () => { - deleteSilent(); -}; +Operation.deleteSilent = deleteSilent; Operation.pack = () => { const isZip = config('packer') === 'zip'; @@ -206,7 +243,7 @@ Operation.extract = () => { * * @currentFile */ -function promptDelete() { +async function promptDelete() { if (noFilesCheck()) return; @@ -218,6 +255,7 @@ function promptDelete() { const n = names.length; let msg; + if (n) { let name = ''; @@ -231,21 +269,21 @@ function promptDelete() { } else { const current = DOM.getCurrentFile(); const isDir = DOM.isCurrentIsDir(current); - const getType = (isDir) => { - return isDir ? 'directory' : 'file'; - }; + const getType = (isDir) => isDir ? 'directory' : 'file'; const type = getType(isDir) + ' '; const name = DOM.getCurrentName(current); + msg = msgAsk + msgSel + type + name + '?'; } - const cancel = false; + const [cancel] = await Dialog.confirm(msg); - Dialog.confirm(TITLE, msg, {cancel}).then(() => { - deleteSilent(files); - }); + if (cancel) + return; + + deleteSilent(files); } /** @@ -267,15 +305,15 @@ function deleteSilent(files = DOM.getActiveFiles()) { const currentName = DOM.getCurrentName(); const nextCurrentName = getNextCurrentName(currentName, names, removedNames); - deleteFn(path + query, removedNames, () => { - CloudCmd.refresh(() => { - const names = Info.files.map(DOM.getCurrentName); - const isCurrent = names.includes(currentName); - - let name = isCurrent ? currentName : nextCurrentName; - - DOM.setCurrentByName(name); - }); + deleteFn(path + query, removedNames, async () => { + await CloudCmd.refresh(); + + const names = Info.files.map(DOM.getCurrentName); + const isCurrent = names.includes(currentName); + + const name = isCurrent ? currentName : nextCurrentName; + + DOM.setCurrentByName(name); }); } @@ -284,11 +322,11 @@ function deleteSilent(files = DOM.getActiveFiles()) { * @param data * @param operation */ -function _processFiles(options, data) { - let selFiles, files; +async function _processFiles(options, data) { + let selFiles; + let files; let panel; let shouldAsk; - let sameName; let ok; let from = ''; @@ -297,26 +335,29 @@ function _processFiles(options, data) { let names = []; if (data) { - from = data.from; - to = data.to; - names = data.names; - panel = Info.panel; + ({ + from, + to, + names, + } = data); + + ({panel} = Info); } else { - from = Info.dirPath; - to = DOM.getNotCurrentDirPath(); - selFiles = DOM.getSelectedFiles(); - names = DOM.getFilenames(selFiles); - data = {}; - shouldAsk = true; - panel = Info.panelPassive; + from = Info.dirPath; + to = DOM.getNotCurrentDirPath(); + selFiles = DOM.getSelectedFiles(); + names = DOM.getFilenames(selFiles); + data = {}; + shouldAsk = true; + panel = Info.panelPassive; } if (!names.length) names.push(DOM.getCurrentName()); - const name = names[0]; + const [name] = names; - sameName = DOM.getCurrentByName(name, panel); + const sameName = DOM.getCurrentByName(name, panel); if (!data && noFilesCheck()) return; @@ -328,9 +369,14 @@ function _processFiles(options, data) { const title = isCopy ? 'Copy' : 'Rename/Move'; const operation = isCopy ? copyFn : moveFn; - if (shouldAsk && config(option)) - return message(title, to, names.map(encode)) - .then(ask); + if (shouldAsk && config(option)) { + const [cancel, newTo] = await prompt(title, to, names.map(encode)); + + if (!cancel) + ask(newTo); + + return; + } ask(to); @@ -340,39 +386,37 @@ function _processFiles(options, data) { if (ok && !shouldAsk || !sameName) return go(); - const str = `"${ name }" already exist. Overwrite?`; + const str = `"${name}" already exist. Overwrite?`; const cancel = false; - Dialog.confirm(TITLE, str, {cancel}).then(go); + Dialog + .confirm(str, { + cancel, + }) + .then(go); function go() { showLoad(); - + files = { from, to, names, }; - operation(files, () => { - DOM.Storage.remove(from, () => { - const { - panel, - panelPassive, - } = Info; - - const setCurrent = () => { - const currentName = name || data.names[0]; - DOM.setCurrentByName(currentName); - }; - - if (!Info.isOnePanel) - CloudCmd.refresh({ - panel: panelPassive, - noCurrent: true, - }); - - CloudCmd.refresh({panel}, setCurrent); + operation(files, async () => { + await DOM.Storage.remove(from); + + const {panel, panelPassive} = Info; + + if (!Info.isOnePanel) + CloudCmd.refresh({ + panel: panelPassive, + noCurrent: true, + }); + + CloudCmd.refresh({ + panel, }); }); } @@ -381,7 +425,7 @@ function _processFiles(options, data) { function checkEmpty(name, operation) { if (!operation) - throw Error(name + ' could not be empty!'); + throw Error(`${name} could not be empty!`); } function twopack(operation, type) { @@ -389,24 +433,23 @@ function twopack(operation, type) { let fileFrom; let currentName = Info.name; - const Images = DOM.Images; - const path = Info.path; - const dirPath = Info.dirPath; + const {path, dirPath} = Info; + const activeFiles = DOM.getActiveFiles(); const names = DOM.getFilenames(activeFiles); checkEmpty('operation', operation); if (!names.length) - return Dialog.alert.noFiles(TITLE); + return Dialog.alert.noFiles(); switch(operation) { case 'extract': op = extractFn; - fileFrom = { + fileFrom = { from: path, - to: dirPath + to: dirPath, }; currentName = removeExtension(currentName); @@ -417,7 +460,7 @@ function twopack(operation, type) { op = getPacker(type); if (names.length > 1) - currentName = Info.dir; + currentName = Info.dir; currentName += DOM.getPackerExt(type); @@ -429,48 +472,45 @@ function twopack(operation, type) { break; } - Images.show.load('top'); + showLoad(); op(fileFrom, (error) => { !error && CloudCmd.refresh({ - currentName + currentName, }); }); } -function message(msg, to, names) { +async function prompt(msg, to, names) { const n = names.length; - const name = names[0]; + const [name] = names; msg += ' '; if (names.length > 1) - msg += n + ' file(s)'; + msg += `${n} file(s)`; else - msg += '"' + name + '"'; + msg += `"${name}"`; msg += ' to'; - const cancel = false; - - return Dialog.prompt(TITLE, msg, to, {cancel}); + return await Dialog.prompt(msg, to); } -function load(callback) { - const prefix = CloudCmd.PREFIX; +globalThis.CloudCmd[Name] = { + init, + hide, + show, +}; + +async function loadAll() { + const {prefix} = globalThis.CloudCmd; const file = `${prefix}/fileop/fileop.js`; - loadJS(file, (error) => { - if (error) { - Dialog.alert(TITLE, error.message); - return exec(callback); - } - - Loaded = true; - Util.timeEnd(Name + ' load'); - exec(callback); - }); + const [error] = await tryToCatch(load.js, file); - Util.time(Name + ' load'); + if (error) + Dialog.alert(error.message); + + Loaded = true; } - diff --git a/client/modules/operation/remove-extension.js b/client/modules/operation/remove-extension.js index 52772c30..e6ce2c46 100644 --- a/client/modules/operation/remove-extension.js +++ b/client/modules/operation/remove-extension.js @@ -1,20 +1,17 @@ -'use strict'; +import {getExt} from '#common/util'; -const {getExt} = require('../../../common/util'); - -module.exports = (name) => { +export const removeExtension = (name) => { const ext = getExtension(name); return name.replace(ext, ''); }; function getExtension(name) { - if (/\.tar\.gz$/.test(name)) + if (name.endsWith('.tar.gz')) return '.tar.gz'; - if (/\.tar\.bz2$/.test(name)) + if (name.endsWith('.tar.bz2')) return '.tar.bz2'; return getExt(name); } - diff --git a/test/client/modules/operation/remove-extension.js b/client/modules/operation/remove-extension.spec.js similarity index 81% rename from test/client/modules/operation/remove-extension.js rename to client/modules/operation/remove-extension.spec.js index 6491f052..fa11e9e2 100644 --- a/test/client/modules/operation/remove-extension.js +++ b/client/modules/operation/remove-extension.spec.js @@ -1,9 +1,5 @@ -'use strict'; - -const test = require('tape'); -const dir = '../../../../client/modules/operation'; - -const removeExtension = require(`${dir}/remove-extension`); +import test from 'supertape'; +import {removeExtension} from './remove-extension.js'; test('cloudcmd: client: modules: operation: removeExtension: .tar.gz', (t) => { const name = 'hello'; @@ -16,7 +12,7 @@ test('cloudcmd: client: modules: operation: removeExtension: .tar.gz', (t) => { test('cloudcmd: client: modules: operation: removeExtension: .tar.bz2', (t) => { const name = 'hello'; const fullName = `${name}.tar.bz2`; - + t.equal(removeExtension(fullName), name, 'should remove .tar.bz2'); t.end(); }); @@ -24,8 +20,7 @@ test('cloudcmd: client: modules: operation: removeExtension: .tar.bz2', (t) => { test('cloudcmd: client: modules: operation: removeExtension: .bz2', (t) => { const name = 'hello'; const fullName = `${name}.bz2`; - + t.equal(removeExtension(fullName), name, 'should remove .bz2'); t.end(); }); - diff --git a/client/modules/operation/set-listeners.js b/client/modules/operation/set-listeners.js index 33b7d802..e54e7d14 100644 --- a/client/modules/operation/set-listeners.js +++ b/client/modules/operation/set-listeners.js @@ -1,65 +1,75 @@ -'use strict'; - /* global DOM */ -/* global CloudCmd */ +import forEachKey from 'for-each-key'; +import wraptile from 'wraptile'; +import {format} from './format.js'; -const { - Images, - Dialog, -} = DOM; +const {Dialog, Images} = DOM; -const forEachKey = require('for-each-key/legacy'); -const { - TITLE, -} = CloudCmd; - -module.exports = (options, callback) => (emitter) => { - if (!callback) { - callback = options; - options = {}; - } +export const setListeners = (options) => (emitter) => { + const { + operation, + callback, + noContinue, + from, + to, + } = options; let done; - let lastError; + + const onAbort = wraptile(({emitter, operation}) => { + emitter.abort(); + + const msg = `${operation} aborted`; + + Dialog.alert(msg, { + cancel: false, + }); + }); const removeListener = emitter.removeListener.bind(emitter); const on = emitter.on.bind(emitter); + const message = format(operation, from, to); + const progress = Dialog.progress(message); + + progress.catch(onAbort({ + emitter, + operation, + })); + const listeners = { progress: (value) => { done = value === 100; - Images.setProgress(value); + progress.setProgress(value); }, end: () => { - Images - .hide() - .clearProgress(); - + Images.hide(); forEachKey(removeListener, listeners); + progress.remove(); - if (lastError || done) - callback(); + callback(); }, - error: (error) => { - lastError = error; - - if (options.noContinue) { + error: async (error) => { + if (noContinue) { listeners.end(error); - Dialog.alert(TITLE, error); + Dialog.alert(error); + progress.remove(); + return; } - Dialog.confirm(TITLE, error + '\n Continue?') - .then(() => { - emitter.continue(); - }, () => { - emitter.abort(); - }); - } + const [cancel] = await Dialog.confirm(`${error} + Continue?`); + + if (!done && !cancel) + return emitter.continue(); + + emitter.abort(); + progress.remove(); + }, }; forEachKey(on, listeners); }; - diff --git a/client/modules/polyfill.js b/client/modules/polyfill.js index 8d9c121e..90b62689 100644 --- a/client/modules/polyfill.js +++ b/client/modules/polyfill.js @@ -1,11 +1,15 @@ -'use strict'; +import _scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'; -/* global DOM */ +globalThis.DOM = globalThis.DOM || {}; -require('domtokenlist-shim'); - -const scrollIntoViewIfNeeded = require('scroll-into-view-if-needed').default; -DOM.scrollIntoViewIfNeeded = (el) => scrollIntoViewIfNeeded(el, { - block: 'nearest' -}); +export const scrollIntoViewIfNeeded = (el, overrides = {}) => { + const { + scroll = _scrollIntoViewIfNeeded, + } = overrides; + + return scroll(el, { + block: 'nearest', + }); +}; +globalThis.DOM.scrollIntoViewIfNeeded = scrollIntoViewIfNeeded; diff --git a/client/modules/polyfill.spec.js b/client/modules/polyfill.spec.js index 607b0cb2..740947eb 100644 --- a/client/modules/polyfill.spec.js +++ b/client/modules/polyfill.spec.js @@ -1,32 +1,20 @@ -'use stric'; +import {test, stub} from 'supertape'; +import {scrollIntoViewIfNeeded} from './polyfill.js'; -const test = require('tape'); -const mockRequire = require('mock-require'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); - -test('cloudcmd: client: polyfill: scrollIntoViewIfNeaded', (t) => { - const {DOM} = global; - const scroll = sinon.stub(); +test('cloudcmd: client: polyfill: scrollIntoViewIfNeeded', (t) => { + const scroll = stub(); const el = {}; - global.DOM = {}; - - mockRequire('scroll-into-view-if-needed', { - default: scroll + scrollIntoViewIfNeeded(el, { + scroll, }); - mockRequire.reRequire('./polyfill'); - - global.DOM.scrollIntoViewIfNeeded(el); - mockRequire.stop('scroll-into-view-if-neaded'); - global.DOM = DOM; - const args = [ el, { block: 'nearest', - }]; + }, + ]; - t.ok(scroll.calledWith(...args), 'should call scrollIntoViewIfNeaded'); + t.calledWith(scroll, args, 'should call scrollIntoViewIfNeeded'); t.end(); }); diff --git a/client/modules/terminal-run.js b/client/modules/terminal-run.js new file mode 100644 index 00000000..029415ea --- /dev/null +++ b/client/modules/terminal-run.js @@ -0,0 +1,147 @@ +import '../../css/terminal.css'; +import {promisify} from 'es6-promisify'; +import {tryToCatch} from 'try-to-catch'; +import {fullstore} from 'fullstore'; +import exec from 'execon'; +import load from 'load.js'; +import DOM from '#dom'; +import * as Images from '#dom/images'; + +const {Dialog} = DOM; +const {CloudCmd} = globalThis; +const {Key, config} = CloudCmd; + +CloudCmd.TerminalRun = { + init, + show, + hide, +}; + +let Loaded; +let Terminal; +let Socket; + +const exitCodeStore = fullstore(); + +const loadAll = async () => { + const {prefix} = CloudCmd; + + const prefixGritty = getPrefix(); + const js = `${prefixGritty}/gritty.js`; + const css = `${prefix}/dist/terminal.css`; + + const [e] = await tryToCatch(load.parallel, [js, css]); + + if (e) { + const src = e.target.src.replace(globalThis.location.href, ''); + return Dialog.alert(`file ${src} could not be loaded`); + } + + Loaded = true; +}; + +export async function init() { + if (!config('terminal')) + return; + + Images.show.load('top'); + + await CloudCmd.View(); + await loadAll(); +} + +export async function show(options = {}) { + return await runTerminal(options); +} + +const runTerminal = promisify((options, fn) => { + if (!Loaded) + return fn(null, -1); + + if (!config('terminal')) + return; + + create(options); + + CloudCmd.View.show(Terminal.element, { + afterShow: () => { + Terminal.focus(); + }, + afterClose: (/* exec.series args */) => { + fn(null, exitCodeStore()); + }, + }); +}); + +export function hide() { + CloudCmd.View.hide(); +} + +const getPrefix = () => CloudCmd.prefix + '/gritty'; + +function getPrefixSocket() { + return CloudCmd.prefixSocket + '/gritty'; +} + +const getEnv = () => ({ + ACTIVE_DIR: DOM.getCurrentDirPath, + PASSIVE_DIR: DOM.getNotCurrentDirPath, + CURRENT_NAME: DOM.getCurrentName, + CURRENT_PATH: DOM.getCurrentPath, +}); + +function create(createOptions) { + const { + cwd = DOM.getCurrentDirPath(), + command, + autoClose, + closeMessage = 'Press any key to close Terminal...', + } = createOptions; + + const options = { + cwd, + env: getEnv(), + prefix: getPrefixSocket(), + socketPath: CloudCmd.prefix, + fontFamily: 'Droid Sans Mono', + command, + autoRestart: false, + }; + + let commandExit = false; + + const {socket, terminal} = globalThis.gritty(document.body, options); + + Socket = socket; + Terminal = terminal; + + Terminal.onKey(({domEvent}) => { + const {keyCode, shiftKey} = domEvent; + + if (commandExit) + hide(); + + if (shiftKey && keyCode === Key.ESC) + hide(); + }); + + Socket.on('exit', (code) => { + exitCodeStore(code); + + if (autoClose) + return hide(); + + terminal.write(`\n${closeMessage}`); + commandExit = true; + }); + + Socket.on('connect', exec.with(authCheck, socket)); +} + +function authCheck(spawn) { + spawn.emit('auth', config('username'), config('password')); + + spawn.on('reject', () => { + Dialog.alert('Wrong credentials!'); + }); +} diff --git a/client/modules/terminal.js b/client/modules/terminal.js index 77f8e40d..186ee0b2 100644 --- a/client/modules/terminal.js +++ b/client/modules/terminal.js @@ -1,51 +1,45 @@ -'use strict'; +import '#css/terminal.css'; +import {tryToCatch} from 'try-to-catch'; +import exec from 'execon'; +import load from 'load.js'; +import * as Images from '#dom/images'; +import DOM from '#dom'; -/* global CloudCmd, gritty */ +const loadParallel = load.parallel; -const {promisify} = require('es6-promisify'); -const tryToCatch = require('try-to-catch/legacy'); - -require('../../css/terminal.css'); - -const exec = require('execon'); -const load = require('load.js'); -const DOM = require('../dom'); -const Images = require('../dom/images'); - -const loadParallel = promisify(load.parallel); - -const TITLE = 'Terminal'; +const {CloudCmd} = globalThis; const {Dialog} = DOM; -const {Key} = CloudCmd; +const {Key, config} = globalThis.CloudCmd; -CloudCmd.Terminal = exports; +CloudCmd.Terminal = { + init, + show, + hide, +}; let Loaded; let Terminal; - -const {config} = CloudCmd; +let Socket; const loadAll = async () => { - const { - PREFIX, - } = CloudCmd; + const {prefix} = CloudCmd; - const prefix = getPrefix(); - const js = `${prefix}/gritty.js`; - const css = `${PREFIX}/dist/terminal.css`; + const prefixGritty = getPrefix(); + const js = `${prefixGritty}/gritty.js`; + const css = `${prefix}/dist/terminal.css`; const [e] = await tryToCatch(loadParallel, [js, css]); if (e) { - const src = e.target.src.replace(window.location.href, ''); - return Dialog.alert(TITLE, `file ${src} could not be loaded`); + const src = e.target.src.replace(globalThis.location.href, ''); + return Dialog.alert(`file ${src} could not be loaded`); } Loaded = true; }; -module.exports.init = async () => { +export async function init() { if (!config('terminal')) return; @@ -53,63 +47,58 @@ module.exports.init = async () => { await CloudCmd.View(); await loadAll(); - await create(); -}; + create(); +} -module.exports.show = show; -module.exports.hide = hide; - -function hide () { +export function hide() { CloudCmd.View.hide(); } -function getPrefix() { - return CloudCmd.PREFIX + '/gritty'; -} +const getPrefix = () => CloudCmd.prefix + '/gritty'; function getPrefixSocket() { return CloudCmd.prefixSocket + '/gritty'; } -function getEnv() { - return { - ACTIVE_DIR: DOM.getCurrentDirPath, - PASSIVE_DIR: DOM.getNotCurrentDirPath, - CURRENT_NAME: DOM.getCurrentName, - CURRENT_PATH: DOM.getCurrentPath, - }; -} +const getEnv = () => ({ + ACTIVE_DIR: DOM.getCurrentDirPath, + PASSIVE_DIR: DOM.getNotCurrentDirPath, + CURRENT_NAME: DOM.getCurrentName, + CURRENT_PATH: DOM.getCurrentPath, +}); function create() { const options = { env: getEnv(), prefix: getPrefixSocket(), - socketPath: CloudCmd.PREFIX, + socketPath: CloudCmd.prefix, fontFamily: 'Droid Sans Mono', }; - const {socket, terminal} = gritty(document.body, options); + const {socket, terminal} = globalThis.gritty(document.body, options); + Socket = socket; Terminal = terminal; - terminal.on('key', (char, {keyCode, shiftKey}) => { - if (shiftKey && keyCode === Key.ESC) { + Terminal.onKey(({domEvent}) => { + const {keyCode, shiftKey} = domEvent; + + if (shiftKey && keyCode === Key.ESC) hide(); - } }); - socket.on('connect', exec.with(authCheck, socket)); + Socket.on('connect', exec.with(authCheck, socket)); } function authCheck(spawn) { spawn.emit('auth', config('username'), config('password')); spawn.on('reject', () => { - Dialog.alert(TITLE, 'Wrong credentials!'); + Dialog.alert('Wrong credentials!'); }); } -function show(callback) { +export function show() { if (!Loaded) return; @@ -118,11 +107,7 @@ function show(callback) { CloudCmd.View.show(Terminal.element, { afterShow: () => { - if (Terminal) - Terminal.focus(); - - exec(callback); - } + Terminal.focus(); + }, }); } - diff --git a/client/modules/upload.js b/client/modules/upload.js index 3397817d..8433fbf5 100644 --- a/client/modules/upload.js +++ b/client/modules/upload.js @@ -1,56 +1,53 @@ /* global CloudCmd, DOM */ +import createElement from '@cloudcmd/create-element'; +import * as Files from '#dom/files'; +import {uploadFiles} from '#dom/upload-files'; +import * as Images from '#dom/images'; -'use strict'; - -CloudCmd.Upload = exports; - -const Files = require('../dom/files'); -const Images = require('../dom/images'); -const uploadFiles = require('../dom/upload-files'); -const createElement = require('@cloudcmd/create-element'); - -module.exports.init = async () => { - Images.show.load('top'); - await CloudCmd.View(); +CloudCmd.Upload = { + init, + show, + hide, }; -module.exports.show = show; -module.exports.hide = hide; +export async function init() { + Images.show.load('top'); + await CloudCmd.View(); +} -function show() { +export async function show() { Images.show.load('top'); - Files.get('upload', (error, innerHTML) => { - const autoSize = true; - - const el = createElement('div', { - innerHTML, - }); - - CloudCmd.View.show(el, { - autoSize, - afterShow, - }); + const innerHTML = await Files.get('upload'); + const autoSize = true; + + const el = createElement('div', { + innerHTML, + }); + + CloudCmd.View.show(el, { + autoSize, + afterShow, }); const fontFamily = [ '"Droid Sans Mono"', '"Ubuntu Mono"', '"Consolas"', - 'monospace' + 'monospace', ].join(', '); createElement('style', { dataName: 'upload-css', - innerText: '[data-name=js-upload-file-button] {' + - `font-family: ${fontFamily};` + - 'font-size: 20px;' + - 'width: 97%' + - '}' + innerText: `[data-name=js-upload-file-button] { + font-family: ${fontFamily}; + font-size: 16px; + margin: 10px 0 10px 0; + }`, }); } -function hide() { +export function hide() { CloudCmd.View.hide(); } @@ -67,4 +64,3 @@ function afterShow() { uploadFiles(files); }); } - diff --git a/client/modules/user-menu/get-user-menu.js b/client/modules/user-menu/get-user-menu.js new file mode 100644 index 00000000..aa3a1076 --- /dev/null +++ b/client/modules/user-menu/get-user-menu.js @@ -0,0 +1,8 @@ +export const getUserMenu = (menuFn) => { + const module = {}; + const fn = Function('module', menuFn); + + fn(module); + + return module.exports; +}; diff --git a/client/modules/user-menu/get-user-menu.spec.js b/client/modules/user-menu/get-user-menu.spec.js new file mode 100644 index 00000000..606eb820 --- /dev/null +++ b/client/modules/user-menu/get-user-menu.spec.js @@ -0,0 +1,18 @@ +import test from 'supertape'; +import {getUserMenu} from './get-user-menu.js'; + +test('user-menu: getUserMenu', (t) => { + const menu = `module.exports = { + 'F2 - Rename file': ({DOM}) => { + const {element} = DOM.CurrentInfo; + DOM.renameCurrent(element); + } + }`; + + const result = getUserMenu(menu); + + const [key] = Object.keys(result); + + t.equal(key, 'F2 - Rename file'); + t.end(); +}); diff --git a/client/modules/user-menu/index.js b/client/modules/user-menu/index.js new file mode 100644 index 00000000..60d32d95 --- /dev/null +++ b/client/modules/user-menu/index.js @@ -0,0 +1,192 @@ +import '../../../css/user-menu.css'; +import currify from 'currify'; +import wraptile from 'wraptile'; +import {fullstore} from 'fullstore'; +import load from 'load.js'; +import createElement from '@cloudcmd/create-element'; +import {tryCatch} from 'try-catch'; +import {tryToCatch} from 'try-to-catch'; +import {codeFrameColumns} from '@babel/code-frame'; +import * as Dialog from '#dom/dialog'; +import * as Images from '#dom/images'; +import {getUserMenu} from './get-user-menu.js'; +import {navigate} from './navigate.js'; +import {parseError} from './parse-error.js'; +import {parseUserMenu} from './parse-user-menu.js'; +import {runSelected} from './run.js'; + +const loadCSS = load.css; +const sourceStore = fullstore(); + +const { + CloudCmd, + DOM, + CloudFunc, +} = globalThis; + +const Name = 'UserMenu'; + +CloudCmd[Name] = { + init, + show, + hide, +}; + +const {Key} = CloudCmd; + +export async function init() { + await Promise.all([ + loadCSS(`${CloudCmd.prefix}/dist/user-menu.css`), + CloudCmd.View(), + ]); +} + +const {CurrentInfo} = DOM; + +export async function show() { + Images.show.load('top'); + + const {dirPath} = CurrentInfo; + const res = await fetch(`${CloudCmd.prefix}/api/v1/user-menu?dir=${dirPath}`); + const source = await res.text(); + const [error, userMenu] = tryCatch(getUserMenu, source); + + Images.hide(); + + if (error) + return Dialog.alert(getCodeFrame({ + error, + source, + })); + + sourceStore(source); + + const { + names, + keys, + items, + settings, + } = parseUserMenu(userMenu); + + if (settings.run) + return runSelected(settings.select, items, runUserMenu); + + const button = createElement('button', { + className: 'cloudcmd-user-menu-button', + innerText: 'User Menu', + notAppend: true, + }); + + const select = createElement('select', { + className: 'cloudcmd-user-menu', + innerHTML: fillTemplate(names), + notAppend: true, + size: 10, + }); + + button.addEventListener('click', onButtonClick(userMenu, select)); + select.addEventListener('dblclick', onDblClick(userMenu)); + select.addEventListener('keydown', onKeyDown({ + keys, + userMenu, + })); + + const afterShow = () => select.focus(); + const autoSize = true; + + CloudCmd.View.show([button, select], { + autoSize, + afterShow, + }); +} + +function fillTemplate(options) { + const result = []; + + for (const option of options) + result.push(``); + + return result.join(''); +} + +export function hide() { + CloudCmd.View.hide(); +} + +const onDblClick = currify(async (items, e) => { + const {value} = e.target; + await runUserMenu(items[value]); +}); + +const onButtonClick = wraptile(async (items, {value}) => { + await runUserMenu(items[value]); +}); + +const onKeyDown = currify(async ({keys, userMenu}, e) => { + const {keyCode, target} = e; + + const keyName = e.key.toUpperCase(); + + e.preventDefault(); + e.stopPropagation(); + + let value; + + if (keyCode === Key.ESC) + return hide(); + + if (keyCode === Key.ENTER) + value = userMenu[target.value]; + else if (keys[keyName]) + value = keys[keyName]; + else + return navigate(target, e); + + await runUserMenu(value); +}); + +const runUserMenu = async (fn) => { + hide(); + + const [error] = await tryToCatch(fn, { + DOM, + CloudCmd, + CloudFunc, + tryToCatch, + }); + + if (!error) + return; + + const source = sourceStore(); + + return Dialog.alert(getCodeFrame({ + error, + source, + })); +}; + +function getCodeFrame({error, source}) { + const {code} = error; + + if (!code || code === 'frame') + return error.message; + + const [line, column] = parseError(error); + + const start = { + line, + column, + }; + + const location = { + start, + }; + + const frame = codeFrameColumns(source, location, { + message: error.message, + highlightCode: false, + }); + + return `
${frame}
`; +} diff --git a/client/modules/user-menu/navigate.js b/client/modules/user-menu/navigate.js new file mode 100644 index 00000000..0fa4d672 --- /dev/null +++ b/client/modules/user-menu/navigate.js @@ -0,0 +1,53 @@ +import {fullstore} from 'fullstore'; +import { + J, + K, + UP, + DOWN, +} from '../../key/key.js'; + +const store = fullstore(1); +const isDigit = (a) => /^\d+$/.test(a); + +export const navigate = (el, {key, keyCode}) => { + if (isDigit(key)) + store(Number(key)); + + if (keyCode === DOWN || keyCode === J) { + const count = store(); + store(1); + + return down(el, count); + } + + if (keyCode === UP || keyCode === K) { + const count = store(); + store(1); + + return up(el, count); + } +}; + +function down(el, count) { + const {length} = el; + + if (el.selectedIndex === length - 1) + el.selectedIndex = 0; + else + el.selectedIndex += count; + + if (el.selectedIndex < 0) + el.selectedIndex = length - 1; +} + +function up(el, count) { + const {length} = el; + + if (!el.selectedIndex) + el.selectedIndex = length - 1; + else + el.selectedIndex -= count; + + if (el.selectedIndex < 0) + el.selectedIndex = 0; +} diff --git a/client/modules/user-menu/navigate.spec.js b/client/modules/user-menu/navigate.spec.js new file mode 100644 index 00000000..6539c8e9 --- /dev/null +++ b/client/modules/user-menu/navigate.spec.js @@ -0,0 +1,163 @@ +import test from 'supertape'; +import {navigate} from './navigate.js'; +import { + UP, + DOWN, + J, + K, +} from '../../key/key.js'; + +test('cloudcmd: user-menu: navigate: DOWN', (t) => { + const el = { + length: 3, + selectedIndex: 0, + }; + + navigate(el, { + keyCode: DOWN, + }); + + t.equal(el.selectedIndex, 1); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: J', (t) => { + const el = { + length: 3, + selectedIndex: 0, + }; + + navigate(el, { + keyCode: J, + }); + + t.equal(el.selectedIndex, 1); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: DOWN: bottom', (t) => { + const el = { + length: 3, + selectedIndex: 2, + }; + + navigate(el, { + keyCode: DOWN, + }); + + t.equal(el.selectedIndex, 0); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: K', (t) => { + const el = { + length: 3, + selectedIndex: 2, + }; + + navigate(el, { + keyCode: K, + }); + + t.equal(el.selectedIndex, 1); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: UP', (t) => { + const el = { + length: 3, + selectedIndex: 2, + }; + + navigate(el, { + keyCode: UP, + }); + + t.equal(el.selectedIndex, 1); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: UP: top', (t) => { + const el = { + length: 3, + selectedIndex: 0, + }; + + navigate(el, { + keyCode: UP, + }); + + t.equal(el.selectedIndex, 2); + t.end(); +}); + +test('cloudcmd: user-menu: navigate', (t) => { + const el = { + length: 3, + selectedIndex: 0, + }; + + navigate(el, { + keyCode: 0, + }); + + t.equal(el.selectedIndex, 0, 'should not change'); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: DOWN: count', (t) => { + const el = { + length: 3, + selectedIndex: 0, + }; + + navigate(el, { + keyCode: 53, + key: '5', + }); + + navigate(el, { + keyCode: DOWN, + }); + + t.equal(el.selectedIndex, 5); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: J: count: to big', (t) => { + const el = { + length: 3, + selectedIndex: -Infinity, + }; + + navigate(el, { + keyCode: 53, + key: '5', + }); + + navigate(el, { + keyCode: J, + }); + + t.equal(el.selectedIndex, 2); + t.end(); +}); + +test('cloudcmd: user-menu: navigate: K: count: to small', (t) => { + const el = { + length: 3, + selectedIndex: -Infinity, + }; + + navigate(el, { + keyCode: 53, + key: '5', + }); + + navigate(el, { + keyCode: K, + }); + + t.equal(el.selectedIndex, 0); + t.end(); +}); diff --git a/client/modules/user-menu/parse-error.js b/client/modules/user-menu/parse-error.js new file mode 100644 index 00000000..23d605e0 --- /dev/null +++ b/client/modules/user-menu/parse-error.js @@ -0,0 +1,21 @@ +const isNumber = (a) => typeof a === 'number'; + +export const parseError = (error) => { + const {lineNumber, columnNumber} = error; + + // thank you firefox + if (isNumber(lineNumber) && isNumber(columnNumber)) + return [lineNumber, columnNumber]; + + const before = error.stack.indexOf('>'); + const str = error.stack.slice(before + 1); + const after = str.indexOf(')'); + const newStr = str.slice(1, after); + + const [line, column] = newStr.split(':'); + + return [ + Number(line), + Number(column), + ]; +}; diff --git a/client/modules/user-menu/parse-error.spec.js b/client/modules/user-menu/parse-error.spec.js new file mode 100644 index 00000000..5ec8da45 --- /dev/null +++ b/client/modules/user-menu/parse-error.spec.js @@ -0,0 +1,33 @@ +import test from 'supertape'; +import {parseError} from './parse-error.js'; + +test('user-menu: parse-error', (t) => { + const result = parseError({ + lineNumber: 1, + columnNumber: 2, + }); + + const expected = [1, 2]; + + t.deepEqual(result, expected); + t.end(); +}); + +test('user-menu: parse-error: stack', (t) => { + const stack = ` + ReferenceError: s is not defined + at eval (eval at module.exports (get-user-menu.js:NaN), :1:2) + at module.exports (get-user-menu.js:6) + at tryCatch (VM12611 try-catch.js:7) + at AsyncFunction.show (index.js:67) + `; + + const result = parseError({ + stack, + }); + + const expected = [1, 2]; + + t.deepEqual(result, expected); + t.end(); +}); diff --git a/client/modules/user-menu/parse-user-menu.js b/client/modules/user-menu/parse-user-menu.js new file mode 100644 index 00000000..e4ad39e3 --- /dev/null +++ b/client/modules/user-menu/parse-user-menu.js @@ -0,0 +1,31 @@ +const {entries, assign} = Object; + +export const parseUserMenu = (userMenu) => { + const names = []; + const keys = {}; + const items = {}; + const settings = {}; + + for (const [str, fn] of entries(userMenu)) { + if (str === '__settings') { + assign(settings, userMenu[str]); + continue; + } + + if (str.startsWith('_')) + continue; + + names.push(str); + const [key, name] = str.split(' - '); + + keys[key] = fn; + items[name] = fn; + } + + return { + names, + keys, + items, + settings, + }; +}; diff --git a/client/modules/user-menu/parse-user-menu.spec.js b/client/modules/user-menu/parse-user-menu.spec.js new file mode 100644 index 00000000..fb763209 --- /dev/null +++ b/client/modules/user-menu/parse-user-menu.spec.js @@ -0,0 +1,35 @@ +import {test, stub} from 'supertape'; +import {parseUserMenu} from './parse-user-menu.js'; + +test('cloudcmd: user menu: parse', (t) => { + const fn = stub(); + const __settings = {}; + + const result = parseUserMenu({ + __settings, + 'F2 - Rename file': fn, + '_f': fn, + }); + + const names = [ + 'F2 - Rename file', + ]; + + const keys = { + F2: fn, + }; + + const items = { + 'Rename file': fn, + }; + + const expected = { + names, + keys, + items, + settings: __settings, + }; + + t.deepEqual(result, expected); + t.end(); +}); diff --git a/client/modules/user-menu/run.js b/client/modules/user-menu/run.js new file mode 100644 index 00000000..51e9fe02 --- /dev/null +++ b/client/modules/user-menu/run.js @@ -0,0 +1,5 @@ +export const runSelected = async (selectedItems, items, runUserMenu) => { + for (const selected of selectedItems) { + await runUserMenu(items[selected]); + } +}; diff --git a/client/modules/user-menu/run.spec.js b/client/modules/user-menu/run.spec.js new file mode 100644 index 00000000..86738712 --- /dev/null +++ b/client/modules/user-menu/run.spec.js @@ -0,0 +1,17 @@ +import {test, stub} from 'supertape'; +import {runSelected} from './run.js'; + +test('cloudcmd: client: user menu: run', async (t) => { + const runUserMenu = stub(); + const fn = stub(); + const selected = ['hello']; + + const items = { + hello: fn, + }; + + await runSelected(selected, items, runUserMenu); + + t.calledWith(runUserMenu, [fn]); + t.end(); +}); diff --git a/client/modules/view.js b/client/modules/view.js deleted file mode 100644 index 6373a4c5..00000000 --- a/client/modules/view.js +++ /dev/null @@ -1,347 +0,0 @@ -'use strict'; - -/* global CloudCmd, DOM */ - -require('../../css/view.css'); - -const itype = require('itype/legacy'); -const rendy = require('rendy/legacy'); -const exec = require('execon'); -const currify = require('currify/legacy'); -const {promisify} = require('es6-promisify'); - -const modal = require('@cloudcmd/modal'); -const createElement = require('@cloudcmd/create-element'); - -const {time} = require('../../common/util'); -const {FS} = require('../../common/cloudfunc'); - -const Files = require('../dom/files'); -const Events = require('../dom/events'); -const load = require('load.js'); -const Images = require('../dom/images'); - -const {encode} = require('../../common/entity'); - -const testRegExp = currify((name, reg) => reg.test(name)); -const lifo = currify((fn, el, cb, name) => fn(name, el, cb)); - -const addEvent = lifo(Events.add); -const getRegExp = (ext) => RegExp(`\\.${ext}$`, 'i'); - -const loadCSS = promisify(load.css); - -module.exports.show = show; -module.exports.hide = hide; - -let Loading = false; - -const Name = 'View'; -CloudCmd[Name] = module.exports; - -const Info = DOM.CurrentInfo; -const Key = CloudCmd.Key; -const basename = (a) => a.split('/').pop(); - -let El, TemplateAudio, Overlay; - -const Config = { - beforeShow: (callback) => { - Images.hide(); - Key.unsetBind(); - exec(callback); - }, - beforeClose: (callback) => { - Events.rmKey(listener); - Key.setBind(); - exec(callback); - }, - afterShow: (callback) => { - El.focus(); - exec(callback); - }, - onOverlayClick, - afterClose : exec, - autoSize : false, - helpers: { - title: {}, - }, -}; - -module.exports.init = async () => { - await loadAll(); - - const events = [ - 'click', - 'contextmenu', - ]; - - events.forEach(addEvent(Overlay, onOverlayClick)); -}; - -function show(data, options) { - const prefixUrl = CloudCmd.PREFIX_URL + FS; - - if (Loading) - return; - - if (!options || options.bindKeys !== false) - Events.addKey(listener); - - El = createElement('div', { - className: 'view', - notAppend: true, - }); - - El.tabIndex = 0; - - if (data) { - El.append(data); - modal.open(El, initConfig(Config, options)); - return; - } - - Images.show.load(); - - const path = prefixUrl + Info.path; - const type = getType(path); - - switch(type) { - default: - return viewFile(); - - case 'image': - return viewImage(path, prefixUrl); - - case 'media': - return viewMedia(path); - } -} - -function viewMedia(path) { - getMediaElement(path, (element) => { - const allConfig = { - ...Config, - ...{ - autoSize: true, - afterShow: () => { - element - .querySelector('audio, video') - .focus(); - } - } - }; - - modal.open(element, allConfig); - }); -} - -function viewFile() { - Info.getData((error, data) => { - if (error) - return Images.hide(); - - const element = document.createTextNode(data); - const options = { - ...Config, - }; - - if (CloudCmd.config('showFileName')) - options.title = Info.name; - - El.append(element); - modal.open(El, options); - }); -} - -function initConfig(Config, options) { - const config = { - ...Config - }; - - if (!options) - return config; - - Object.keys(options).forEach((name) => { - const isConfig = !!config[name]; - const item = options[name]; - const isFunc = itype.function(item); - - if (!isFunc || !isConfig) { - config[name] = options[name]; - return; - } - - const func = config[name]; - config[name] = () => { - exec.series([func, item]); - }; - }); - - return config; -} - -function hide() { - modal.close(); -} - -function viewImage(href, prefixUrl) { - const makeTitle = (path) => { - return { - href: prefixUrl + path, - title: encode(basename(path)), - }; - }; - - const names = Info.files - .map(DOM.getCurrentPath) - .filter(isImage); - - const titles = names - .map(makeTitle); - - const index = names.indexOf(Info.path); - const imageConfig = { - index, - autoSize : true, - arrows : true, - keys : true, - helpers : { - title : {} - } - }; - - const config = { - ...Config, - ...imageConfig, - }; - - modal.open(titles, config); -} - -function isImage(name) { - const images = [ - 'jp(e|g|eg)', - 'gif', - 'png', - 'bmp', - 'webp', - 'svg', - 'ico' - ]; - - return images - .map(getRegExp) - .some(testRegExp(name)); -} - -function isMedia(name) { - return isAudio(name) || isVideo(name); -} - -function isAudio(name) { - return /\.(mp3|ogg|m4a)$/i.test(name); -} - -function isVideo(name) { - return /\.(mp4|avi)$/i.test(name); -} - -function getType(name) { - if (isImage(name)) - return 'image'; - - if (isMedia(name)) - return 'media'; -} - -function getMediaElement(src, callback) { - check(src, callback); - - Files.get('view/media-tmpl', (error, template) => { - const {name} = Info; - - if (error) - return alert(error); - - if (!TemplateAudio) - TemplateAudio = template; - - const is = isAudio(name); - const type = is ? 'audio' : 'video'; - - const innerHTML = rendy(TemplateAudio, { - src, - type, - name, - }); - - const element = createElement('div', { - innerHTML, - }); - - callback(element); - }); -} - -function check(src, callback) { - if (typeof src !== 'string') - throw Error('src should be a string!'); - - if (typeof callback !== 'function') - throw Error('callback should be a function'); -} - -/** - * function loads css and js of FancyBox - * @callback - executes, when everything loaded - */ -async function loadAll() { - const {PREFIX} = CloudCmd; - - time(Name + ' load'); - - Loading = true; - await loadCSS(PREFIX + '/dist/view.css'); - Loading = false; -} - -function onOverlayClick(event) { - const position = { - x: event.clientX, - y: event.clientY - }; - - setCurrentByPosition(position); -} - -function setCurrentByPosition(position) { - const element = DOM.getCurrentByPosition(position); - - if (!element) - return; - - const { - files, - filesPassive, - } = Info; - - const isFiles = ~files.indexOf(element); - const isFilesPassive = ~filesPassive.indexOf(element); - - if (!isFiles && !isFilesPassive) - return; - - const isCurrent = DOM.isCurrentFile(element); - - if (isCurrent) - return; - - DOM.setCurrentFile(element); -} - -function listener({keyCode}) { - if (keyCode === Key.ESC) - hide(); -} - diff --git a/client/modules/view/get-type.js b/client/modules/view/get-type.js new file mode 100644 index 00000000..a061399f --- /dev/null +++ b/client/modules/view/get-type.js @@ -0,0 +1,51 @@ +import currify from 'currify'; + +const testRegExp = currify((name, reg) => reg.test(name)); +const getRegExp = (ext) => RegExp(`\\.${ext}$`, 'i'); + +const isPDF = (a) => /\.pdf$/i.test(a); +const isHTML = (a) => a.endsWith('.html'); +const isMarkdown = (a) => /.\.md$/.test(a); + +export default (name) => { + if (isPDF(name)) + return 'pdf'; + + if (isImage(name)) + return 'image'; + + if (isMedia(name)) + return 'media'; + + if (isHTML(name)) + return 'html'; + + if (isMarkdown(name)) + return 'markdown'; +}; + +function isImage(name) { + const images = [ + 'jp(e|g|eg)', + 'gif', + 'png', + 'bmp', + 'webp', + 'svg', + 'ico', + ]; + + return images + .map(getRegExp) + .some(testRegExp(name)); +} + +function isMedia(name) { + return isAudio(name) || isVideo(name); +} + +const isAudio = (name) => /\.(mp3|ogg|m4a)$/i.test(name); + +function isVideo(name) { + return /\.(mp4|avi|webm)$/i.test(name); +} diff --git a/client/modules/view/index.js b/client/modules/view/index.js new file mode 100644 index 00000000..6626f1aa --- /dev/null +++ b/client/modules/view/index.js @@ -0,0 +1,372 @@ +import '#css/view.css'; +import {rendy} from 'rendy'; +import currify from 'currify'; +import wraptile from 'wraptile'; +import {tryToCatch} from 'try-to-catch'; +import load from 'load.js'; +import * as _modal from '@cloudcmd/modal'; +import _createElement from '@cloudcmd/create-element'; +import {time} from '#common/util'; +import * as Files from '#dom/files'; +import * as Events from '#dom/events'; +import {FS} from '#common/cloudfunc'; +import * as Images from '#dom/images'; +import {encode} from '#common/entity'; +import { + isImage, + isAudio, + getType, +} from './types.js'; + +const CloudCmd = globalThis.CloudCmd || {}; +const DOM = globalThis.DOM || {}; +const isString = (a) => typeof a === 'string'; +const {assign} = Object; +const {isArray} = Array; + +const lifo = currify((fn, el, cb, name) => fn(name, el, cb)); +const series = wraptile((...a) => { + for (const f of a) + f(); +}); + +const isFn = (a) => typeof a === 'function'; + +const noop = () => {}; +const addEvent = lifo(Events.add); + +const loadCSS = load.css; + +let Loading = false; + +const Name = 'View'; + +CloudCmd[Name] = { + init, + show, + hide, +}; + +const Info = DOM.CurrentInfo; +const {Key} = CloudCmd; + +const basename = (a) => a + .split('/') + .pop(); + +let El; +let TemplateAudio; +let Overlay; + +const Config = { + beforeShow: () => { + Images.hide(); + Key.unsetBind(); + }, + + beforeClose: () => { + Events.rmKey(listener); + Key.setBind(); + }, + + afterShow: () => { + El.focus(); + }, + + onOverlayClick, + afterClose: noop, + autoSize: false, + + helpers: { + title: {}, + }, +}; + +export const _Config = Config; + +export async function init() { + await loadAll(); + + const events = [ + 'click', + 'contextmenu', + ]; + + events.forEach(addEvent( + Overlay, + onOverlayClick, + )); +} + +export async function show(data, options = {}) { + const prefixURL = CloudCmd.prefixURL + FS; + + if (Loading) + return; + + if (!options || options.bindKeys !== false) + Events.addKey(listener); + + El = _createElement('div', { + className: 'view', + notAppend: true, + }); + + El.tabIndex = 0; + + if (data) { + if (isArray(data)) + El.append(...data); + else + El.append(data); + + _modal.open(El, initConfig(options)); + return; + } + + Images.show.load(); + + const path = prefixURL + Info.path; + const type = options.raw ? '' : await getType(path); + + switch(type) { + default: + return await viewFile(); + + case 'markdown': + return await CloudCmd.Markdown.show(Info.path); + + case 'html': + return viewHtml(path); + + case 'image': + return viewImage(Info.path, prefixURL); + + case 'media': + return await viewMedia(path); + + case 'pdf': + return viewPDF(path); + } +} + +export const _createIframe = createIframe; + +function createIframe(src, overrides = {}) { + const { + createElement = _createElement, + } = overrides; + + const element = createElement('iframe', { + src, + width: '100%', + height: '100%', + }); + + element.addEventListener('load', () => { + element.contentWindow.addEventListener('keydown', listener); + }); + + return element; +} + +export const _viewHtml = viewHtml; + +function viewHtml(src, overrides = {}) { + const {modal = _modal} = overrides; + modal.open(createIframe(src), Config); +} + +function viewPDF(src) { + const element = createIframe(src); + + const options = assign({}, Config); + + if (CloudCmd.config('showFileName')) + options.title = Info.name; + + _modal.open(element, options); +} + +async function viewMedia(path) { + const [e, element] = await getMediaElement(path); + + if (e) + return alert(e); + + const allConfig = { + ...Config, + ...{ + autoSize: true, + afterShow: () => { + element + .querySelector('audio, video') + .focus(); + }, + }, + }; + + _modal.open(element, allConfig); +} + +async function viewFile() { + const [error, data] = await Info.getData(); + + if (error) + return Images.hide(); + + const element = document.createTextNode(data); + const options = Config; + + if (CloudCmd.config('showFileName')) + options.title = Info.name; + + El.append(element); + _modal.open(El, options); +} + +const copy = (a) => assign({}, a); + +export const _initConfig = initConfig; + +function initConfig(options) { + const config = copy(Config); + + if (!options) + return config; + + const names = Object.keys(options); + + for (const name of names) { + const isConfig = Boolean(config[name]); + const item = options[name]; + + if (!isFn(item) || !isConfig) { + config[name] = options[name]; + continue; + } + + const fn = config[name]; + + config[name] = series(fn, item); + } + + return config; +} + +export function hide() { + _modal.close(); +} + +function viewImage(path, prefixURL) { + const isSupportedImage = (a) => isImage(a) || a === path; + const makeTitle = (path) => ({ + href: `${prefixURL}${path}`, + title: encode(basename(path)), + }); + + const names = Info.files + .map(DOM.getCurrentPath) + .filter(isSupportedImage); + + const titles = names.map(makeTitle); + + const index = names.indexOf(Info.path); + + const imageConfig = { + index, + autoSize: true, + arrows: true, + keys: true, + helpers: { + title: {}, + }, + }; + + const config = { + ...Config, + ...imageConfig, + }; + + _modal.open(titles, config); +} + +async function getMediaElement(src) { + check(src); + + const [error, template] = await tryToCatch(Files.get, 'view/media-tmpl'); + + if (error) + return [error]; + + const {name} = Info; + + if (!TemplateAudio) + TemplateAudio = template; + + const is = isAudio(name); + const type = is ? 'audio' : 'video'; + + const innerHTML = rendy(TemplateAudio, { + src, + type, + name, + }); + + const element = _createElement('div', { + innerHTML, + }); + + return [null, element]; +} + +function check(src) { + if (!isString(src)) + throw Error('src should be a string!'); +} + +async function loadAll() { + const {DIR_DIST} = CloudCmd; + + time(`${Name} load`); + + Loading = true; + await loadCSS(`${DIR_DIST}/view.css`); + Loading = false; +} + +function onOverlayClick(event) { + const position = { + x: event.clientX, + y: event.clientY, + }; + + setCurrentByPosition(position); +} + +function setCurrentByPosition(position) { + const element = DOM.getCurrentByPosition(position); + + if (!element) + return; + + const {files, filesPassive} = Info; + + const isFiles = files.includes(element); + const isFilesPassive = filesPassive.includes(element); + + if (!isFiles && !isFilesPassive) + return; + + const isCurrent = DOM.isCurrentFile(element); + + if (isCurrent) + return; + + DOM.setCurrentFile(element); +} + +function listener({keyCode}) { + if (keyCode === Key.ESC) + hide(); +} diff --git a/client/modules/view/index.spec.js b/client/modules/view/index.spec.js new file mode 100644 index 00000000..abfbe3f4 --- /dev/null +++ b/client/modules/view/index.spec.js @@ -0,0 +1,98 @@ +import autoGlobals from 'auto-globals'; +import {stub} from '@cloudcmd/stub'; +import {test as tape} from 'supertape'; +import { + _initConfig, + _viewHtml, + _Config, + _createIframe, +} from './index.js'; + +const test = autoGlobals(tape); + +test('cloudcmd: client: view: initConfig', (t) => { + let config; + let i = 0; + + const afterClose = () => ++i; + const options = { + afterClose, + }; + + config = _initConfig(options); + config.afterClose(); + + config = _initConfig(options); + config.afterClose(); + + t.equal(i, 2, 'should not change default config'); + t.end(); +}); + +test('cloudcmd: client: view: initConfig: no options', (t) => { + const config = _initConfig(); + const result = typeof config; + const expected = 'object'; + + t.equal(result, expected); + t.end(); +}); + +test('cloudcmd: client: view: html', (t) => { + const open = stub(); + const modal = { + open, + }; + + const src = '/hello.html'; + + _viewHtml(src, { + modal, + }); + + const [first] = open.args; + const [arg] = first; + + t.deepEqual(first, [arg, _Config]); + t.end(); +}); + +test('cloudcmd: client: view: createIframe', (t) => { + const addEventListener = stub(); + const el = { + addEventListener, + }; + + const createElement = stub().returns(el); + const src = '/hello.html'; + + _createIframe(src, { + createElement, + }); + + const expected = { + src, + height: '100%', + width: '100%', + }; + + t.calledWith(createElement, ['iframe', expected]); + t.end(); +}); + +test('cloudcmd: client: view: createIframe: returns', (t) => { + const addEventListener = stub(); + const el = { + addEventListener, + }; + + const createElement = stub().returns(el); + + const src = '/hello.html'; + const result = _createIframe(src, { + createElement, + }); + + t.equal(result, el); + t.end(); +}); diff --git a/client/modules/view/types.js b/client/modules/view/types.js new file mode 100644 index 00000000..320a4bc8 --- /dev/null +++ b/client/modules/view/types.js @@ -0,0 +1,74 @@ +import {extname} from 'node:path'; +import currify from 'currify'; + +export const isAudio = (name) => /\.(mp3|ogg|m4a|flac)$/i.test(name); + +const testRegExp = currify((name, reg) => reg.test(name)); +const getRegExp = (ext) => RegExp(`\\.${ext}$`, 'i'); + +const isPDF = (a) => /\.pdf$/i.test(a); +const isHTML = (a) => a.endsWith('.html'); +const isMarkdown = (a) => /.\.md$/.test(a); + +export const getType = async (path) => { + const ext = extname(path); + + if (!ext) + path = await detectType(path); + + if (isPDF(path)) + return 'pdf'; + + if (isImage(path)) + return 'image'; + + if (isMedia(path)) + return 'media'; + + if (isHTML(path)) + return 'html'; + + if (isMarkdown(path)) + return 'markdown'; +}; + +export function isImage(name) { + const images = [ + 'jp(e|g|eg)', + 'gif', + 'png', + 'bmp', + 'webp', + 'svg', + 'ico', + ]; + + return images + .map(getRegExp) + .some(testRegExp(name)); +} + +function isMedia(name) { + return isAudio(name) || isVideo(name); +} + +function isVideo(name) { + return /\.(mp4|avi|webm)$/i.test(name); +} + +export const _detectType = detectType; + +async function detectType(path) { + const {headers} = await fetch(path, { + method: 'HEAD', + }); + + for (const [name, value] of headers) { + if (name === 'content-type') + return `.${value + .split('/') + .pop()}`; + } + + return ''; +} diff --git a/client/modules/view/types.spec.js b/client/modules/view/types.spec.js new file mode 100644 index 00000000..f0542c18 --- /dev/null +++ b/client/modules/view/types.spec.js @@ -0,0 +1,51 @@ +import {test, stub} from 'supertape'; +import {isAudio, _detectType} from './types.js'; + +test('cloudcmd: client: view: types: isAudio', (t) => { + const result = isAudio('hello.mp3'); + + t.ok(result); + t.end(); +}); + +test('cloudcmd: client: view: types: isAudio: flac', (t) => { + const result = isAudio('hello.flac'); + + t.ok(result); + t.end(); +}); + +test('cloudcmd: client: view: types: isAudio: no', (t) => { + const result = isAudio('hello'); + + t.notOk(result); + t.end(); +}); + +test('cloudcmd: client: view: types: detectType', async (t) => { + const fetch = stub().returns({ + headers: [], + }); + + globalThis.fetch = fetch; + await _detectType('/hello'); + + const expected = ['/hello', { + method: 'HEAD', + }]; + + t.calledWith(fetch, expected); + t.end(); +}); + +test('cloudcmd: client: view: types: detectType: found', async (t) => { + globalThis.fetch = stub().returns({ + headers: [ + ['content-type', 'image/png'], + ], + }); + const result = await _detectType('/hello'); + + t.equal(result, '.png'); + t.end(); +}); diff --git a/client/sort.js b/client/sort.js index adf769c4..ed0971f3 100644 --- a/client/sort.js +++ b/client/sort.js @@ -1,35 +1,32 @@ -'use strict'; - /* global CloudCmd */ -const DOM = require('./dom'); +import {fullstore} from 'fullstore'; +import DOM from '#dom'; -const Info = DOM.CurrentInfo; -const sort = CloudCmd.sort; -const order = CloudCmd.order; -const position = DOM.getPanelPosition(); - -let sortPrevious = sort[position]; +const sortPrevious = fullstore(); const {getPanel} = DOM; -CloudCmd.sortPanel = (name, panel = getPanel()) => { - const position = panel - .dataset - .name - .replace('js-', ''); +export const initSortPanel = () => { + const {sort} = CloudCmd; + const position = DOM.getPanelPosition(); - if (name !== sortPrevious) { + sortPrevious(sort[position]); +}; + +export const sortPanel = (name, panel = getPanel()) => { + const {sort, order} = CloudCmd; + const Info = DOM.CurrentInfo; + const position = panel.dataset.name.replace('js-', ''); + + if (name !== sortPrevious()) + order[position] = 'asc'; + else if (order[position] === 'asc') + order[position] = 'desc'; + else order[position] = 'asc'; - } else { - if (order[position] === 'asc') - order[position] = 'desc'; - else - order[position] = 'asc'; - } - sortPrevious = + sortPrevious(name); sort[position] = name; - const noCurrent = position !== Info.panelPosition; CloudCmd.refresh({ @@ -37,4 +34,3 @@ CloudCmd.sortPanel = (name, panel = getPanel()) => { noCurrent, }); }; - diff --git a/client/sw/register.js b/client/sw/register.js index 0f295891..928d63c9 100644 --- a/client/sw/register.js +++ b/client/sw/register.js @@ -1,11 +1,10 @@ -'use strict'; +import {tryToCatch} from 'try-to-catch'; -module.exports.registerSW = registerSW; -module.exports.unregisterSW = unregisterSW; +export const listenSW = (sw, ...args) => { + sw?.addEventListener(...args); +}; -const noop = () => {}; - -async function registerSW(prefix) { +export async function registerSW(prefix) { if (!navigator.serviceWorker) return; @@ -13,15 +12,19 @@ async function registerSW(prefix) { const isLocalhost = location.hostname === 'localhost'; if (!isHTTPS && !isLocalhost) - return { - addEventListener: noop, - }; + return; - return navigator.serviceWorker.register(`${prefix}/sw.js`); + const {serviceWorker} = navigator; + const register = serviceWorker.register.bind(serviceWorker); + const [e, sw] = await tryToCatch(register, `${prefix}/sw.js`); + + if (e) + return null; + + return sw; } -async function unregisterSW() { - const reg = await registerSW(); - return reg.unregister(); +export async function unregisterSW(prefix) { + const reg = await registerSW(prefix); + reg?.unregister(prefix); } - diff --git a/client/sw/register.spec.js b/client/sw/register.spec.js index 5b42ad0a..52699f0b 100644 --- a/client/sw/register.spec.js +++ b/client/sw/register.spec.js @@ -1,155 +1,103 @@ -'use strict'; +import autoGlobals from 'auto-globals'; +import tape from 'supertape'; +import {stub} from '@cloudcmd/stub'; +import {tryCatch} from 'try-catch'; +import { + listenSW, + registerSW, + unregisterSW, +} from './register.js'; -const test = require('tape'); -const sinon = require('sinon'); -const mock = require('mock-require'); +const test = autoGlobals(tape); -test('sw: register: registerSW: no serviceWorker', async (t) => { - const {navigator} = global; - global.navigator = {}; +test('sw: listen', (t) => { + const addEventListener = stub(); + const sw = { + addEventListener, + }; - const { - registerSW, - } = mock.reRequire('./register'); + listenSW(sw, 'hello', 'world'); + + t.calledWith(addEventListener, ['hello', 'world'], 'should call addEventListener'); + t.end(); +}); + +test('sw: lesten: no sw', (t) => { + const [e] = tryCatch(listenSW, null, 'hello', 'world'); + + t.notOk(e, 'should not throw'); + t.end(); +}); + +test('sw: register: registerSW: no serviceWorker', async (t, {navigator}) => { + delete navigator.serviceWorker; await registerSW(); - global.navigator = navigator; - t.pass('should not call register'); t.end(); }); -test('sw: register: registerSW: no https', async (t) => { - const { - navigator, - location, - } = global; +test('sw: register: registerSW: no https', async (t, {location, navigator}) => { + const {register} = navigator.serviceWorker; - const register = sinon.stub(); - - global.navigator = getNavigator({ - register, - }); - - global.location = { - protocol: 'http:' - }; - - const { - registerSW, - } = mock.reRequire('./register'); + location.protocol = 'http:'; await registerSW(); - global.location = location; - global.navigator = navigator; - - t.notOk(register.called, 'should not call register'); + t.notCalled(register, 'should not call register'); t.end(); }); -test('sw: register: registerSW: no localhost', async (t) => { - const { - navigator, - location, - } = global; - - global.location = { +test('sw: register: registerSW: http', async (t, {location, navigator}) => { + Object.assign(location, { protocol: 'http:', hostname: 'cloudcmd.io', - }; - - const register = sinon.stub(); - - global.navigator = getNavigator({ - register, }); - const { - registerSW, - } = mock.reRequire('./register'); + const {register} = navigator.serviceWorker; await registerSW(); - global.location = location; - global.navigator = navigator; - - t.notOk(register.called, 'should not call register'); + t.notCalled(register, 'should not call register'); t.end(); }); -test('sw: register: registerSW', async (t) => { - const { - navigator, - location, - } = global; - - global.location = { - hostname: 'localhost', - }; - - const register = sinon.stub(); - - global.navigator = getNavigator({ - register, +test('sw: register: registerSW: https self-signed', async (t, {location, navigator}) => { + Object.assign(location, { + protocol: 'https:', + hostname: 'self-signed.badssl.com', }); - const { - registerSW, - } = mock.reRequire('./register'); + const {register} = navigator.serviceWorker; + register.throws(Error('Cannot register service worker!')); + const result = await registerSW(); + + t.notOk(result, 'should not throw'); + t.end(); +}); + +test('sw: register: registerSW', async (t, {location, navigator}) => { + location.hostname = 'localhost'; + + const {register} = navigator.serviceWorker; await registerSW('/hello'); - global.location = location; - global.navigator = navigator; - - t.ok(register.calledWith('/hello/sw.js'), 'should call register'); + t.calledWith(register, ['/hello/sw.js'], 'should call register'); t.end(); }); -test('sw: register: unregisterSW', async (t) => { - const { - navigator, - location, - } = global; +test('sw: register: unregisterSW', async (t, {location, navigator}) => { + location.hostname = 'localhost'; - global.location = { - hostname: 'localhost', - }; + const {serviceWorker} = navigator; + const {register} = serviceWorker; - const reg = { - unregister: sinon.stub() - }; + register.returns(serviceWorker); - const register = sinon.stub() - .returns(Promise.resolve(reg)); + await unregisterSW('/hello'); - global.navigator = getNavigator({ - register, - }); - - const { - unregisterSW, - } = mock.reRequire('./register'); - - await unregisterSW(); - - global.location = location; - global.navigator = navigator; - - t.ok(register.calledWith(), 'should call register'); + t.calledWith(register, ['/hello/sw.js'], 'should call register'); t.end(); }); - - -function getNavigator({register, unregister}) { - unregister = unregister || sinon.stub(); - - return { - serviceWorker: { - register, - unregister, - } - }; -} diff --git a/client/sw/sw.js b/client/sw/sw.js index db2f0b47..5b5643a3 100644 --- a/client/sw/sw.js +++ b/client/sw/sw.js @@ -1,8 +1,7 @@ -'use strict'; - -const codegen = require('codegen.macro'); -const tryToCatch = require('try-to-catch/legacy'); -const currify = require('currify/legacy'); +import process from 'node:process'; +import codegen from 'codegen.macro'; +import {tryToCatch} from 'try-to-catch'; +import currify from 'currify'; const isDev = process.env.NODE_ENV === 'development'; @@ -15,7 +14,7 @@ const respondWith = currify((f, e) => { const {url} = request; const pathname = getPathName(url); - if (/\/$/.test(url) || /\^\/fs/.test(pathname)) + if (url.endsWith('/') || /\^\/fs/.test(pathname)) return; if (!isGet(request)) @@ -24,7 +23,7 @@ const respondWith = currify((f, e) => { if (!isBasic(request)) return; - if (/^\/api/.test(pathname)) + if (pathname.startsWith('/api')) return; if (/^socket.io/.test(pathname)) @@ -39,7 +38,7 @@ const date = codegen`module.exports = '"' + Date() + '"'`; const NAME = `cloudcmd: ${date}`; const createRequest = (a) => new Request(a, { - credentials: 'same-origin' + credentials: 'same-origin', }); const getRequest = (a, request) => { @@ -49,14 +48,14 @@ const getRequest = (a, request) => { return createRequest('/'); }; -self.addEventListener('install', wait(onInstall)); -self.addEventListener('fetch', respondWith(onFetch)); -self.addEventListener('activate', wait(onActivate)); +globalThis.addEventListener('install', wait(onInstall)); +globalThis.addEventListener('fetch', respondWith(onFetch)); +globalThis.addEventListener('activate', wait(onActivate)); async function onActivate() { console.info(`cloudcmd: sw: activate: ${NAME}`); - await self.clients.claim(); + await globalThis.clients.claim(); const keys = await caches.keys(); const deleteCache = caches.delete.bind(caches); @@ -66,7 +65,7 @@ async function onActivate() { async function onInstall() { console.info(`cloudcmd: sw: install: ${NAME}`); - await self.skipWaiting(); + await globalThis.skipWaiting(); } async function onFetch(event) { @@ -80,16 +79,16 @@ async function onFetch(event) { if (!isDev && response) return response; - + const [e, resp] = await tryToCatch(fetch, newRequest, { - credentials: 'same-origin' + credentials: 'same-origin', }); if (e) return new Response(e.message); await addToCache(request, resp.clone()); - + return resp; } @@ -97,4 +96,3 @@ async function addToCache(request, response) { const cache = await caches.open(NAME); return cache.put(request, response); } - diff --git a/common/btoa.js b/common/btoa.js deleted file mode 100644 index 0293ebbc..00000000 --- a/common/btoa.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -/* global btoa */ - -module.exports = (str) => { - if (typeof btoa === 'function') - return btoa(str); - - return Buffer - .from(str) - .toString('base64'); -}; - diff --git a/common/callbackify.js b/common/callbackify.js new file mode 100644 index 00000000..71160ac7 --- /dev/null +++ b/common/callbackify.js @@ -0,0 +1,9 @@ +const success = (f) => (data) => f(null, data); + +export default (promise) => (...a) => { + const fn = a.pop(); + + promise(...a) + .then(success(fn)) + .catch(fn); +}; diff --git a/common/callbackify.spec.js b/common/callbackify.spec.js new file mode 100644 index 00000000..d1586d5a --- /dev/null +++ b/common/callbackify.spec.js @@ -0,0 +1,26 @@ +import {promisify} from 'node:util'; +import {tryToCatch} from 'try-to-catch'; +import {test, stub} from 'supertape'; +import callbackify from './callbackify.js'; + +test('cloudcmd: common: callbackify: error', async (t) => { + const promise = stub().rejects(Error('hello')); + + const fn = callbackify(promise); + const newPromise = promisify(fn); + const [error] = await tryToCatch(newPromise); + + t.equal(error.message, 'hello'); + t.end(); +}); + +test('cloudcmd: common: callbackify', async (t) => { + const promise = stub().resolves('hi'); + + const fn = callbackify(promise); + const promiseAgain = promisify(fn); + const data = await promiseAgain(); + + t.equal(data, 'hi'); + t.end(); +}); diff --git a/common/cloudfunc.js b/common/cloudfunc.js index 254d46f3..7884d069 100644 --- a/common/cloudfunc.js +++ b/common/cloudfunc.js @@ -1,48 +1,47 @@ -'use strict'; +import {rendy} from 'rendy'; +import currify from 'currify'; +import {fullstore} from 'fullstore'; +import {encode} from '#common/entity'; -const rendy = require('rendy/legacy'); -const currify = require('currify/legacy'); -const store = require('fullstore/legacy'); -const encode = require('./entity').encode; -const btoa = require('./btoa'); - -const getHeaderField = currify(_getHeaderField); - -/* КОНСТАНТЫ (общие для клиента и сервера)*/ - -/* название программы */ +const id = (a) => a; const NAME = 'Cloud Commander'; -const FS = '/fs'; -const Path = store(); + +export const dateFormatter = fullstore(id); +export const getHeaderField = currify(_getHeaderField); +export const FS = '/fs'; + +const Path = fullstore(); Path('/'); -module.exports.FS = FS; -module.exports.apiURL = '/api/v1'; -module.exports.MAX_FILE_SIZE = 500 * 1024; -module.exports.getHeaderField = getHeaderField; -module.exports.getPathLink = getPathLink; -module.exports.getDotDot = getDotDot; +const filterOutDotFiles = ({showDotFiles}) => ({name}) => { + if (showDotFiles) + return true; + + return !name.startsWith('.'); +}; -module.exports.formatMsg = (msg, name, status) => { +export const apiURL = '/api/v1'; +export const MAX_FILE_SIZE = 500 * 1024; + +export const formatMsg = (msg, name, status) => { status = status || 'ok'; name = name || ''; if (name) - name = '("' + name + '")'; + name = `("${name}")`; - return msg + ': ' + status + name; + return `${msg}: ${status}${name}`; }; /** * Функция возвращает заголовок веб страницы * @path */ -module.exports.getTitle = (options) => { +export const getTitle = (options) => { options = options || {}; - const path = options.path || Path(); - const name = options.name; + const {path = Path(), name} = options; const array = [ name || NAME, @@ -58,7 +57,7 @@ module.exports.getTitle = (options) => { * возвращаеться массив каталогов * @param url - адрес каталога */ -function getPathLink(url, prefix, template) { +export function getPathLink(url, prefix, template) { if (!url) throw Error('url could not be empty!'); @@ -69,55 +68,68 @@ function getPathLink(url, prefix, template) { .split('/') .slice(1, -1); - const allNames = ['/'].concat(names); - const length = allNames.length - 1; + const allNames = [ + '/', + ...names, + ]; + + const lines = []; + const n = allNames.length; let path = '/'; - const pathHTML = allNames.map((name, index) => { - const isLast = index === length; + for (let i = 0; i < n; i++) { + const name = allNames[i]; + const isLast = i === n - 1; - if (index) - path += name + '/'; + if (i) + path += `${name}/`; - if (index && isLast) - return name + '/'; + if (i && isLast) { + lines.push(`${name}/`); + continue; + } - const slash = index ? '/' : ''; + const slash = i ? '/' : ''; - return rendy(template, { + lines.push(rendy(template, { path, name, slash, prefix, - }); - }).join(''); + })); + } - return pathHTML; + return lines.join(''); } -const getDataName = (name) => { +export function _getDataName(name) { const encoded = btoa(encodeURI(name)); return `data-name="js-file-${encoded}" `; -}; +} /** * Функция строит таблицу файлв из JSON-информации о файлах * @param params - информация о файлах * */ -module.exports.buildFromJSON = (params) => { - const prefix = params.prefix; - const template = params.template; +export const buildFromJSON = (params) => { + const { + prefix, + template, + sort = 'name', + order = 'asc', + showDotFiles, + } = params; + + const formatDate = dateFormatter(); + const templateFile = template.file; const templateLink = template.link; const json = params.data; const path = encode(json.path); - const files = json.files; - - const sort = params.sort || 'name'; - const order = params.order || 'asc'; + const {files} = json; /* * Строим путь каталога в котором мы находимся @@ -126,9 +138,9 @@ module.exports.buildFromJSON = (params) => { const htmlPath = getPathLink(path, prefix, template.pathLink); let fileTable = rendy(template.path, { - link : prefix + FS + path, - fullPath : path, - path : htmlPath, + link: prefix + FS + path, + fullPath: path, + path: htmlPath, }); const owner = 'owner'; @@ -139,15 +151,17 @@ module.exports.buildFromJSON = (params) => { const name = getFieldName('name'); const size = getFieldName('size'); const date = getFieldName('date'); + const time = getFieldName('time'); const header = rendy(templateFile, { - tag : 'div', - attribute : 'data-name="js-fm-header" ', - className : 'fm-header', - type : '', + tag: 'div', + attribute: 'data-name="js-fm-header" ', + className: 'fm-header', + type: '', name, size, date, + time, owner, mode, }); @@ -155,7 +169,8 @@ module.exports.buildFromJSON = (params) => { /* сохраняем путь */ Path(path); - fileTable += header + '
    '; + fileTable += `${header}
      `; + /* Если мы не в корне */ if (path !== '/') { const dotDot = getDotDot(path); @@ -163,66 +178,84 @@ module.exports.buildFromJSON = (params) => { const linkResult = rendy(template.link, { link, - title : '..', - name : '..' + title: '..', + name: '..', }); - const dataName = 'data-name="js-file-.." '; - const attribute = 'draggable="true" ' + dataName; + const dataName = _getDataName('..'); + const attribute = `draggable="true" ${dataName}`; /* Сохраняем путь к каталогу верхнего уровня*/ fileTable += rendy(template.file, { - tag : 'li', - attribute, - className : '', - type : 'directory', - name : linkResult, - size : '<dir>', - date : '--.--.----', - owner : '.', - mode : '--- --- ---' - }); - } - - fileTable += files.map((file) => { - const name = encode(file.name); - const link = prefix + FS + path + name; - - const {type} = file; - const size = getSize(file); - - const date = file.date || '--.--.----'; - const owner = file.owner || 'root'; - const mode = file.mode; - - const linkResult = rendy(templateLink, { - link, - title: name, - name, - attribute: getAttribute(file.type) - }); - - const dataName = getDataName(file.name); - const attribute = `draggable="true" ${dataName}`; - - return rendy(templateFile, { tag: 'li', attribute, className: '', - type, + type: 'directory', name: linkResult, - size, - date, - owner, - mode, + size: '<dir>', + date: '--.--.----', + time: '--:--:--', + owner: '.', + mode: '--- --- ---', }); - }).join(''); + } + + fileTable += files + .filter(filterOutDotFiles({ + showDotFiles, + })) + .map(updateField) + .map((file) => { + const name = encode(file.name); + const link = prefix + FS + path + name; + + const { + type, + mode, + date, + time, + owner, + size, + } = file; + + const linkResult = rendy(templateLink, { + link, + title: name, + name, + attribute: getAttribute(file.type), + }); + + const dataName = _getDataName(file.name); + const attribute = `draggable="true" ${dataName}`; + + return rendy(templateFile, { + tag: 'li', + attribute, + className: '', + type, + name: linkResult, + size, + date: formatDate(date), + time, + owner, + mode, + }); + }) + .join(''); fileTable += '
    '; return fileTable; }; +const updateField = (file) => ({ + ...file, + date: file.date || '--.--.----', + time: file.time || '--:--:--', + owner: file.owner || 'root', + size: getSize(file), +}); + function getAttribute(type) { if (type === 'directory') return ''; @@ -230,13 +263,9 @@ function getAttribute(type) { return 'target="_blank" '; } -module.exports._getSize = getSize; -function getSize(file) { - const { - size, - type, - } = file; - +export const _getSize = getSize; + +function getSize({size, type}) { if (type === 'directory') return '<dir>'; @@ -247,7 +276,7 @@ function getSize(file) { } function _getHeaderField(sort, order, name) { - const arrow = order === 'asc' ? '↑' : '↓'; + const arrow = order === 'asc' ? '↑' : '↓'; if (sort !== name) return name; @@ -258,7 +287,7 @@ function _getHeaderField(sort, order, name) { return `${name}${arrow}`; } -function getDotDot(path) { +export function getDotDot(path) { // убираем последний слеш и каталог в котором мы сейчас находимся const lastSlash = path.substr(path, path.lastIndexOf('/')); const dotDot = lastSlash.substr(lastSlash, lastSlash.lastIndexOf('/')); @@ -268,4 +297,3 @@ function getDotDot(path) { return dotDot; } - diff --git a/common/cloudfunc.spec.js b/common/cloudfunc.spec.js index e25d93d5..b679feeb 100644 --- a/common/cloudfunc.spec.js +++ b/common/cloudfunc.spec.js @@ -1,14 +1,101 @@ -'use strict'; - -const test = require('tape'); -const cloudfunc = require('./cloudfunc'); -const { +import {readFileSync} from 'node:fs'; +import test from 'supertape'; +import {montag} from 'montag'; +import * as cheerio from 'cheerio'; +import {tryCatch} from 'try-catch'; +import { _getSize, -} = cloudfunc; + getPathLink, + buildFromJSON, + _getDataName, + dateFormatter, + formatMsg, + getTitle, + getDotDot, + getHeaderField, +} from '#common/cloudfunc'; + +const templatePath = new URL('../tmpl/fs', import.meta.url).pathname; + +const template = { + pathLink: readFileSync(`${templatePath}/pathLink.hbs`, 'utf8'), + path: readFileSync(`${templatePath}/path.hbs`, 'utf8'), + file: readFileSync(`${templatePath}/file.hbs`, 'utf8'), + link: readFileSync(`${templatePath}/link.hbs`, 'utf8'), +}; + +test('cloudfunc: buildFromJSON: ..', (t) => { + const data = { + path: '/media/', + files: [{ + date: '30.08.2016', + mode: 'rwx rwx rwx', + name: 'floppy', + owner: 'root', + size: '7b', + type: 'directory-link', + }], + }; + + const html = buildFromJSON({ + prefix: '', + template, + data, + }); + + const $ = cheerio.load(html); + const el = $('[data-name="js-file-Li4="]'); + + const result = el + .find('[data-name="js-name"]') + .text(); + + const expected = '..'; + + t.equal(result, expected); + t.end(); +}); + +test('cloudfunc: getPathLink: /', (t) => { + const {pathLink} = template; + const result = getPathLink('/', '', pathLink); + + const expected = montag` + / + `; + + t.equal(result, expected); + t.end(); +}); + +test('cloudfunc: getPathLink: /hello/world', (t) => { + const {pathLink} = template; + const result = getPathLink('/hello/world', '', pathLink); + + const expected = montag` + /hello/ + `; + + t.equal(result, expected); + t.end(); +}); + +test('cloudfunc: getPathLink: prefix', (t) => { + const {pathLink} = template; + const result = getPathLink('/hello/world', '/cloudcmd', pathLink); + + const expected = montag` + /hello/ + `; + + t.equal(result, expected); + t.end(); +}); test('cloudfunc: getSize: dir', (t) => { const type = 'directory'; const size = 0; + const result = _getSize({ type, size, @@ -16,13 +103,14 @@ test('cloudfunc: getSize: dir', (t) => { const expected = '<dir>'; - t.equal(result, expected, 'should equal'); + t.equal(result, expected); t.end(); }); test('cloudfunc: getSize: link: dir', (t) => { const type = 'directory-link'; const size = 0; + const result = _getSize({ type, size, @@ -30,13 +118,14 @@ test('cloudfunc: getSize: link: dir', (t) => { const expected = '<link>'; - t.equal(result, expected, 'should equal'); + t.equal(result, expected); t.end(); }); test('cloudfunc: getSize: link: file', (t) => { const type = 'file-link'; const size = 0; + const result = _getSize({ type, size, @@ -44,13 +133,14 @@ test('cloudfunc: getSize: link: file', (t) => { const expected = '<link>'; - t.equal(result, expected, 'should equal'); + t.equal(result, expected); t.end(); }); test('cloudfunc: getSize: file', (t) => { const type = 'file'; const size = '100.00kb'; + const result = _getSize({ type, size, @@ -58,6 +148,217 @@ test('cloudfunc: getSize: file', (t) => { const expected = '100.00kb'; - t.equal(result, expected, 'should equal'); + t.equal(result, expected); + t.end(); +}); + +test('cloudfunc: buildFromJSON: showDotFiles: false', (t) => { + const data = { + path: '/media/', + files: [{ + date: '30.08.2016', + mode: 'rwx rwx rwx', + name: '.floppy', + owner: 'root', + size: '7b', + type: 'directory-link', + }], + }; + + const html = buildFromJSON({ + prefix: '', + template, + data, + showDotFiles: false, + }); + + const $ = cheerio.load(html); + const el = $('[data-name="js-file-LmZsb3BweQ=="]'); + + const result = el + .find('[data-name="js-name"]') + .text(); + + const expected = ''; + + t.equal(result, expected); + t.end(); +}); + +test('cloudfunc: buildFromJSON: name: {{ }}', (t) => { + const data = { + path: '/media/', + files: [{ + date: '30.08.2016', + mode: 'rwx rwx rwx', + name: '{{}}', + owner: 'root', + size: '7b', + type: 'file', + }], + }; + + const html = buildFromJSON({ + prefix: '', + template, + data, + showDotFiles: false, + }); + + const $ = cheerio.load(html); + const el = $('[data-name="js-file-JTdCJTdCJTdEJTdE"]'); + + const result = el + .find('[data-name="js-name"]') + .text(); + + const expected = '{{}}'; + + t.equal(result, expected); + t.end(); +}); + +test('cloudfunc: _getDataName', (t) => { + const result = _getDataName('s'); + const expected = 'data-name="js-file-cw==" '; + + t.equal(result, expected); + t.end(); +}); + +test('cloudfunc: formatMsg: name', (t) => { + const result = formatMsg('hello', 'world'); + const expected = 'hello: ok("world")'; + + t.equal(result, expected, 'should format message with name'); + t.end(); +}); + +test('cloudfunc: formatMsg: no name', (t) => { + const result = formatMsg('hello'); + const expected = 'hello: ok'; + + t.equal(result, expected, 'should format message without name'); + t.end(); +}); + +test('cloudfunc: getTitle: no options', (t) => { + const result = getTitle(); + + t.ok(result, 'should return a title string even without options'); + t.end(); +}); + +test('cloudfunc: getTitle: with name', (t) => { + const result = getTitle({ + name: 'MyName', + }); + + t.match(result, 'MyName', 'should return title with name'); + t.end(); +}); + +test('cloudfunc: getHeaderField: sort not name', (t) => { + const result = getHeaderField('size', 'asc', 'name'); + + t.equal(result, 'name', 'should return plain name when sort does not match'); + t.end(); +}); + +test('cloudfunc: getHeaderField: sort name asc', (t) => { + const result = getHeaderField('name', 'asc', 'name'); + + t.equal(result, 'name', 'should return plain name when name asc'); + t.end(); +}); + +test('cloudfunc: getDotDot: root', (t) => { + const result = getDotDot('/'); + + t.equal(result, '/', 'should return / for root path'); + t.end(); +}); + +test('cloudfunc: getPathLink: /a/b/c', (t) => { + const {pathLink} = template; + const result = getPathLink('/a/b/c/', '', pathLink); + + t.ok(result, 'should build path link for 3-segment path'); + t.end(); +}); + +test('cloudfunc: getPathLink: no url', (t) => { + const [error] = tryCatch(getPathLink); + + t.equal(error.message, 'url could not be empty!', 'should throw when url is empty'); + t.end(); +}); + +test('cloudfunc: getPathLink: no template', (t) => { + const [error] = tryCatch(getPathLink, '/'); + + t.equal(error.message, 'template could not be empty!', 'should throw when template is empty'); + t.end(); +}); + +test('cloudfunc: getHeaderField: sort name desc', (t) => { + const result = getHeaderField('name', 'desc', 'name'); + const expected = 'name↓'; + + t.equal(result, expected, 'should return name with down arrow'); + t.end(); +}); + +test('cloudfunc: getDotDot: normal path', (t) => { + const result = getDotDot('/hello/world/'); + const expected = '/hello'; + + t.equal(result, expected, 'should return parent directory'); + t.end(); +}); + +test('cloudfunc: buildFromJSON: formatDate', (t) => { + const data = { + path: '/media/', + files: [{ + date: '30.08.2016', + mode: 'rwx rwx rwx', + name: '{{}}', + owner: 'root', + size: '7b', + type: 'file', + }], + }; + + const oldFormatter = dateFormatter(); + + const formatDate = (str) => { + const [day, month, year] = str.split('.'); + const date = new Date(year, month - 1, day); + + return date.toLocaleDateString('en-US'); + }; + + dateFormatter(formatDate); + + const html = buildFromJSON({ + prefix: '', + template, + data, + showDotFiles: false, + }); + + dateFormatter(oldFormatter); + + const $ = cheerio.load(html); + const el = $('[data-name="js-file-JTdCJTdCJTdEJTdE"]'); + + const result = el + .find('[data-name="js-date"]') + .text(); + + const expected = '8/30/2016'; + + t.equal(result, expected); t.end(); }); diff --git a/common/datetime.js b/common/datetime.js index 131c27fb..d7982ab4 100644 --- a/common/datetime.js +++ b/common/datetime.js @@ -1,8 +1,6 @@ -'use strict'; +import shortdate from 'shortdate'; -const shortdate = require('shortdate'); - -module.exports = (date) => { +export default (date) => { date = date || new Date(); check(date); diff --git a/common/datetime.spec.js b/common/datetime.spec.js index 25e17c39..e3edb2ef 100644 --- a/common/datetime.spec.js +++ b/common/datetime.spec.js @@ -1,9 +1,6 @@ -'use strict'; - -const test = require('tape'); -const sinon = require('sinon'); - -const datetime = require('./datetime'); +import {test} from 'supertape'; +import {tryCatch} from 'try-catch'; +import datetime from './datetime.js'; test('common: datetime', (t) => { const dateStr = 'Fri, 17 Aug 2018 10:56:48'; @@ -11,26 +8,26 @@ test('common: datetime', (t) => { const expected = '2018.08.17 10:56:48'; - t.equals(result, expected, 'should equal'); + t.equal(result, expected); t.end(); }); test('common: datetime: no arg', (t) => { - const {Date} = global; + const {Date} = globalThis; let called = false; - const myDate = class extends Date { + + globalThis.Date = class extends Date { constructor() { super(); called = true; } }; - global.Date = myDate; - datetime(); - global.Date = Date; + globalThis.Date = Date; + t.ok(called, 'should call new Date'); t.end(); }); @@ -41,14 +38,13 @@ test('common: 0 before number', (t) => { const expected = '2018.08.17 10:56:08'; - t.equals(result, expected, 'should equal'); + t.equal(result, expected); t.end(); }); test('common: datetime: wrong args', (t) => { - const fn = () => datetime({}); + const [error] = tryCatch(datetime, {}); - t.throws(fn, /date should be instanceof Date!/, 'should throw'); + t.equal(error.message, 'date should be instanceof Date!', 'should throw'); t.end(); }); - diff --git a/common/entity.js b/common/entity.js index c3c718c4..690bbd7a 100644 --- a/common/entity.js +++ b/common/entity.js @@ -1,33 +1,31 @@ -'use strict'; - const Entities = { - ' ': ' ', '<': '<', '>': '>', '"': '"', + '{': '{', + '}': '}', }; const keys = Object.keys(Entities); -module.exports.encode = (str) => { - keys.forEach((code) => { +export const encode = (str) => { + for (const code of keys) { const char = Entities[code]; const reg = RegExp(char, 'g'); str = str.replace(reg, code); - }); + } return str; }; -module.exports.decode = (str) => { - keys.forEach((code) => { +export const decode = (str) => { + for (const code of keys) { const char = Entities[code]; const reg = RegExp(code, 'g'); str = str.replace(reg, char); - }); + } return str; }; - diff --git a/test/common/entity.js b/common/entity.spec.js similarity index 53% rename from test/common/entity.js rename to common/entity.spec.js index 43b54d48..79313f7c 100644 --- a/test/common/entity.js +++ b/common/entity.spec.js @@ -1,29 +1,34 @@ -'use strict'; - -const test = require('tape'); -const entity = require('../../common/entity'); +import {test} from 'supertape'; +import * as entity from '#common/entity'; test('cloudcmd: entity: encode', (t) => { const result = entity.encode(' '); - const expected = '<hello> '; + const expected = '<hello> '; + + t.equal(result, expected, 'should encode entity'); + t.end(); +}); + +test('cloudcmd: entity: {{}}', (t) => { + const result = entity.encode('{{}}'); + const expected = '{{}}'; t.equal(result, expected, 'should encode entity'); t.end(); }); test('cloudcmd: entity: decode', (t) => { - const result = entity.decode('<hello> '); + const result = entity.decode('<hello> '); const expected = ' '; t.equal(result, expected, 'should decode entity'); t.end(); }); -test('cloudcmd: entity: encode', (t) => { +test('cloudcmd: entity: encode quote', (t) => { const result = entity.encode('"hello"'); const expected = '"hello"'; t.equal(result, expected, 'should encode entity'); t.end(); }); - diff --git a/common/omit.js b/common/omit.js new file mode 100644 index 00000000..284c2f5b --- /dev/null +++ b/common/omit.js @@ -0,0 +1,12 @@ +const difference = (a, b) => new Set(a).difference(new Set(b)); +const {keys} = Object; + +export const omit = (a, list) => { + const result = {}; + + for (const key of difference(keys(a), list)) { + result[key] = a[key]; + } + + return result; +}; diff --git a/common/omit.spec.js b/common/omit.spec.js new file mode 100644 index 00000000..ff70541c --- /dev/null +++ b/common/omit.spec.js @@ -0,0 +1,18 @@ +import {test} from 'supertape'; +import {omit} from '#common/omit'; + +test('cloudcmd: common: omit', (t) => { + const a = { + hello: 1, + world: 2, + }; + + const result = omit(a, ['world']); + + const expected = { + hello: 1, + }; + + t.deepEqual(result, expected); + t.end(); +}); diff --git a/common/try-to-promise-all.js b/common/try-to-promise-all.js new file mode 100644 index 00000000..1dcfa3a8 --- /dev/null +++ b/common/try-to-promise-all.js @@ -0,0 +1,12 @@ +import {tryToCatch} from 'try-to-catch'; + +const all = Promise.all.bind(Promise); + +export default async (a) => { + const [e, result = []] = await tryToCatch(all, a); + + return [ + e, + ...result, + ]; +}; diff --git a/common/try-to-promise-all.spec.js b/common/try-to-promise-all.spec.js new file mode 100644 index 00000000..eafb036c --- /dev/null +++ b/common/try-to-promise-all.spec.js @@ -0,0 +1,29 @@ +import {test} from 'supertape'; +import tryToPromiseAll from './try-to-promise-all.js'; + +const resolve = Promise.resolve.bind(Promise); +const reject = Promise.reject.bind(Promise); + +test('commons: try-to-promise-all', async (t) => { + const [, ...result] = await tryToPromiseAll([ + resolve('a'), + resolve('b'), + ]); + + const expected = [ + 'a', + 'b', + ]; + + t.deepEqual(result, expected); + t.end(); +}); + +test('commons: try-to-promise-all: error', async (t) => { + const [e] = await tryToPromiseAll([ + reject('a'), + ]); + + t.equal(e, 'a'); + t.end(); +}); diff --git a/common/util.js b/common/util.js index 3580b685..422b3c22 100644 --- a/common/util.js +++ b/common/util.js @@ -1,12 +1,9 @@ -'use strict'; +import exec from 'execon'; -const exec = require('execon'); +const isString = (a) => typeof a === 'string'; -module.exports.getStrBigFirst = getStrBigFirst; -module.exports.kebabToCamelCase = kebabToCamelCase; - -module.exports.escapeRegExp = (str) => { - const isStr = typeof str === 'string'; +export const escapeRegExp = (str) => { + const isStr = isString(str); if (isStr) str = str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); @@ -17,27 +14,24 @@ module.exports.escapeRegExp = (str) => { /** * get regexp from wild card */ -module.exports.getRegExp = (wildcard) => { - wildcard = wildcard || '*'; - - const escaped = '^' + wildcard // search from start of line - .replace('.', '\\.') - .replace('*', '.*') - .replace('?', '.?') + '$'; // search to end of line +export const getRegExp = (wildcard) => { + const escaped = `^${wildcard // search from start of line + .replace(/\./g, '\\.') + .replace(/\*/g, '.*') + .replace('?', '.?')}$`; + // search to end of line return RegExp(escaped); }; -module.exports.exec = exec; - /** * function gets file extension * * @param name * @return ext */ -module.exports.getExt = (name) => { - const isStr = typeof name === 'string'; +export const getExt = (name) => { + const isStr = isString(name); if (!isStr) return ''; @@ -51,22 +45,22 @@ module.exports.getExt = (name) => { }; /** - * find object by name in arrray + * find object by name in array * * @param array * @param name */ -module.exports.findObjByNameInArr = (array, name) => { +export const findObjByNameInArr = (array, name) => { let ret; if (!Array.isArray(array)) throw Error('array should be array!'); - - if (typeof name !== 'string') + + if (!isString(name)) throw Error('name should be string!'); array.some((item) => { - let is = item.name === name; + const is = item.name === name; const isArray = Array.isArray(item); if (is) { @@ -94,7 +88,7 @@ module.exports.findObjByNameInArr = (array, name) => { * start timer * @param name */ -module.exports.time = (name) => { +export const time = (name) => { exec.ifExist(console, 'time', [name]); }; @@ -102,27 +96,6 @@ module.exports.time = (name) => { * stop timer * @param name */ -module.exports.timeEnd = (name) => { +export const timeEnd = (name) => { exec.ifExist(console, 'timeEnd', [name]); }; - -function getStrBigFirst(str) { - if (!str) - throw Error('str could not be empty!'); - - const first = str[0].toUpperCase(); - - return first + str.slice(1); -} - -function kebabToCamelCase(str) { - if (!str) - throw Error('str could not be empty!'); - - return str - .split('-') - .map(getStrBigFirst) - .join('') - .replace(/.js$/, ''); -} - diff --git a/common/util.spec.js b/common/util.spec.js new file mode 100644 index 00000000..5a19a8be --- /dev/null +++ b/common/util.spec.js @@ -0,0 +1,138 @@ +import test from 'supertape'; +import {tryCatch} from 'try-catch'; +import { + findObjByNameInArr, + getRegExp, + escapeRegExp, + getExt, + time, + timeEnd, +} from '#common/util'; + +test('getExt: no extension', (t) => { + const EXT = ''; + const name = 'file-without-extension'; + const ext = getExt(name); + + t.equal(ext, EXT, 'should return "" when extension is none'); + t.end(); +}); + +test('getExt: return extension', (t) => { + const EXT = '.png'; + const name = 'picture.png'; + const ext = getExt(name); + + t.equal(ext, EXT, 'should return ".png" in files "picture.png"'); + t.end(); +}); + +test('util: getExt: no name', (t) => { + const ext = getExt(); + + t.equal(ext, '', 'should return empty string'); + t.end(); +}); + +test('util: findObjByNameInArr: no array', (t) => { + const [error] = tryCatch(findObjByNameInArr); + + t.equal(error.message, 'array should be array!', 'should throw when no array'); + t.end(); +}); + +test('util: findObjByNameInArr: no name', (t) => { + const [error] = tryCatch(findObjByNameInArr, []); + + t.equal(error.message, 'name should be string!', 'should throw when no array'); + t.end(); +}); + +test('util: findObjByNameInArr: object', (t) => { + const name = 'hello'; + const obj = { + name, + }; + + const array = [obj]; + + const result = findObjByNameInArr(array, name); + + t.equal(result, obj, 'should return obj'); + t.end(); +}); + +test('util: findObjByNameInArr: array', (t) => { + const name = 'hello'; + const data = 'abc'; + + const item = { + name, + data, + }; + + const obj = { + name: 'world', + }; + + const array = [ + name, + [obj, item], + ]; + + const result = findObjByNameInArr(array, name); + + t.equal(result, data, 'should return data'); + t.end(); +}); + +test('util: getRegExp', (t) => { + const reg = getRegExp('help?o.*'); + + t.deepEqual(reg, /^help.?o\..*$/, 'should return regexp'); + t.end(); +}); + +test('util: getRegExp: dots', (t) => { + const reg = getRegExp('h.*el?o.*'); + + t.deepEqual(reg, /^h\..*el.?o\..*$/, 'should return regexp'); + t.end(); +}); + +test('util: getRegExp: no', (t) => { + const reg = getRegExp(''); + + t.deepEqual(reg, /^$/, 'should return regexp'); + t.end(); +}); + +test('util: escapeRegExp: no str', (t) => { + const result = escapeRegExp(1); + const expected = 1; + + t.equal(result, expected); + t.end(); +}); + +test('util: escapeRegExp', (t) => { + const result = escapeRegExp('#hello'); + const expected = '\\#hello'; + + t.equal(result, expected); + t.end(); +}); + +test('util: time', (t) => { + const [error] = tryCatch(time, 'test'); + + t.notOk(error, 'should not throw'); + t.end(); +}); + +test('util: timeEnd', (t) => { + const [error] = tryCatch(timeEnd, 'test'); + + t.notOk(error, 'should not throw'); + t.end(); +}); diff --git a/css/columns/name-size-date-time.css b/css/columns/name-size-date-time.css new file mode 100644 index 00000000..f46e63f8 --- /dev/null +++ b/css/columns/name-size-date-time.css @@ -0,0 +1,26 @@ +.name { + width: 35%; +} + +.size { + float: none; +} + +.owner { + display: none; +} + +.mode { + display: none; +} + +.date { + float: right; + width: 19%; +} + +.time { + display: inline; + float: right; + width: 20%; +} diff --git a/css/columns/name-size-date.css b/css/columns/name-size-date.css index 196a2b7f..9248f700 100644 --- a/css/columns/name-size-date.css +++ b/css/columns/name-size-date.css @@ -19,3 +19,7 @@ width: 19%; } +.time { + display: none; +} + diff --git a/css/columns/name-size-time.css b/css/columns/name-size-time.css new file mode 100644 index 00000000..1bbd59de --- /dev/null +++ b/css/columns/name-size-time.css @@ -0,0 +1,24 @@ +.name { + width: 55%; +} + +.size { + float: none; +} + +.owner { + display: none; +} + +.mode { + display: none; +} + +.date { + display: none; +} + +.time { + float: right; + width: 19%; +} diff --git a/css/columns/name-size.css b/css/columns/name-size.css index e58d1844..c02472a5 100644 --- a/css/columns/name-size.css +++ b/css/columns/name-size.css @@ -18,3 +18,8 @@ .date { display: none; } + +.time { + display: none; +} + diff --git a/css/config.css b/css/config.css index ab456d97..4804374a 100644 --- a/css/config.css +++ b/css/config.css @@ -1,7 +1,7 @@ .config { white-space: normal; overflow: hidden; - width : 250px; + width: 250px; } .list li { @@ -18,15 +18,24 @@ padding: 0 12px; font-size: 16px; line-height: 1.5; - color: #555; + color: var(--column-color); + background: var(--internal-background); border: 1px solid #ccc; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); - -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; - -moz-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; - -o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; - transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; + -webkit-box-shadow: inset 0 1px 1px rgb(0 0 0 / 7.5%); + -moz-box-shadow: inset 0 1px 1px rgb(0 0 0 / 7.5%); + box-shadow: inset 0 1px 1px rgb(0 0 0 / 7.5%); + -webkit-transition: + border-color ease-in-out 0.15s, + box-shadow ease-in-out 0.15s; + -moz-transition: + border-color ease-in-out 0.15s, + box-shadow ease-in-out 0.15s; + -o-transition: + border-color ease-in-out 0.15s, + box-shadow ease-in-out 0.15s; + transition: + border-color ease-in-out 0.15s, + box-shadow ease-in-out 0.15s; } .config .form-control::-moz-placeholder { @@ -44,9 +53,15 @@ .config .form-control:focus { border-color: #66afe9; outline: 0; - -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 1px rgba(102, 175, 233, 0.6); - -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 1px rgba(102, 175, 233, 0.6); - box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 1px rgba(102, 175, 233, 0.6); + -webkit-box-shadow: + inset 0 1px 1px rgb(0 0 0 / 7.5%), + 0 0 1px rgb(102 175 233 / 60%); + -moz-box-shadow: + inset 0 1px 1px rgb(0 0 0 / 7.5%), + 0 0 1px rgb(102 175 233 / 60%); + box-shadow: + inset 0 1px 1px rgb(0 0 0 / 7.5%), + 0 0 1px rgb(102 175 233 / 60%); } .config .form-control:focus:invalid:focus { @@ -57,8 +72,8 @@ } .config .list { - padding : 0; - margin : 5%; + padding: 0; + margin: 5%; } .config .full-width { diff --git a/css/help.css b/css/help.css index 42602618..6728c589 100644 --- a/css/help.css +++ b/css/help.css @@ -1,12 +1,12 @@ .help { - margin : 25px; - white-space : normal; + margin: 25px; + white-space: normal; } .help li { - list-style-type : disc; + list-style-type: disc; } .help img { - max-width : 100%; + max-width: 100%; } diff --git a/css/icons.css b/css/icons.css index 4f979db7..ca4a1181 100644 --- a/css/icons.css +++ b/css/icons.css @@ -1,134 +1,144 @@ .icon-help::before { - font-family : 'Fontello'; - content : '\e801 '; + font-family: 'Fontello'; + content: '\e801 '; } .icon-rename::before { - font-family : 'Fontello'; - content : '\e802 '; + font-family: 'Fontello'; + content: '\e802 '; } .icon-view::before { - font-family : 'Fontello'; - content : '\e803 '; + font-family: 'Fontello'; + content: '\e803 '; } .icon-edit::before { - font-family : 'Fontello'; - content : '\e804 '; + font-family: 'Fontello'; + content: '\e804 '; } .icon-copy::before { - font-family : 'Fontello'; - content : '\e805 '; + font-family: 'Fontello'; + content: '\e805 '; } .icon-move::before { - font-family : 'Fontello'; - content : '\e806 '; + font-family: 'Fontello'; + content: '\e806 '; } .icon-directory::before { - font-family : 'Fontello'; - content : '\e807 '; + font-family: 'Fontello'; + content: '\e807 '; } .icon-delete::before { - font-family : 'Fontello'; - content : '\e808 '; + font-family: 'Fontello'; + content: '\e808 '; } .icon-menu::before { - font-family : 'Fontello'; - content : '\e809 '; + font-family: 'Fontello'; + content: '\e809 '; } .icon-config::before { - font-family : 'Fontello'; - content : '\e80a '; + font-family: 'Fontello'; + content: '\e80a '; } .icon-console::before { - font-family : 'Fontello'; - content : '\e80b '; + font-family: 'Fontello'; + content: '\e80b '; } .icon-contact::before { - font-family : 'Fontello'; - content : '\e80c '; + font-family: 'Fontello'; + content: '\e80c '; } .icon-file::before { - font-family : 'Fontello'; - content : '\e80d '; + font-family: 'Fontello'; + content: '\e80d '; } .icon-upload-to-cloud::before { - font-family : 'Fontello'; - content : '\e80e '; + font-family: 'Fontello'; + content: '\e80e '; } .icon-upload-from-cloud::before { - font-family : 'Fontello'; - content : '\e80f '; + font-family: 'Fontello'; + content: '\e80f '; } .icon-download::before { - font-family : 'Fontello'; - content : '\e810 '; + font-family: 'Fontello'; + content: '\e810 '; } .icon-new::before { - font-family : 'Fontello'; - content : '\e811 '; + font-family: 'Fontello'; + content: '\e811 '; +} + +.icon-toggle-file-selection::before { + font-family: 'Fontello'; + content: '\e81f '; } .icon-unselect-all::before { - font-family : 'Fontello'; - content : '\e812 '; + font-family: 'Fontello'; + content: '\e812 '; } .icon-pack::before { - font-family : 'Fontello'; - content : '\e813 '; + font-family: 'Fontello'; + content: '\e813 '; } .icon-extract::before { - font-family : 'Fontello'; - content : '\e814 '; + font-family: 'Fontello'; + content: '\e814 '; } .icon-copy-to-clipboard::before { - font-family : 'Fontello'; - content : '\e815 '; + font-family: 'Fontello'; + content: '\e815 '; } .icon-refresh::before { - font-family : 'Fontello'; - content : '\e816 '; + font-family: 'Fontello'; + content: '\e816 '; } .icon-cut::before { - font-family : 'Fontello'; - content : '\e817 '; + font-family: 'Fontello'; + content: '\e817 '; } .icon-paste::before { - font-family : 'Fontello'; - content : '\e818 '; + font-family: 'Fontello'; + content: '\e818 '; } .icon-upload::before { - font-family : 'Fontello'; - content : '\e819 '; + font-family: 'Fontello'; + content: '\e819 '; } .icon-log-out::before { - font-family : 'Fontello'; - content : '\e81a '; + font-family: 'Fontello'; + content: '\e81a '; } .icon-terminal::before { - font-family : 'Fontello'; - content : '\e81b '; + font-family: 'Fontello'; + content: '\e81b '; +} + +.icon-user-menu::before { + font-family: 'Fontello'; + content: '\e81c '; } diff --git a/css/main.css b/css/main.css index 6008c2a9..6b901a8e 100644 --- a/css/main.css +++ b/css/main.css @@ -1,8 +1,7 @@ -@import './urls.css'; -@import './reset.css'; -@import './style.css'; -@import './icons.css'; -@import './help.css'; -@import './query.css'; -@import './supports.css'; - +@import url(./reset.css); +@import url(./urls.css); +@import url(./style.css); +@import url(./icons.css); +@import url(./help.css); +@import url(./query.css); +@import url(./supports.css); diff --git a/css/nojs.css b/css/nojs.css index 1df4bd12..350ac4e6 100644 --- a/css/nojs.css +++ b/css/nojs.css @@ -1,4 +1,5 @@ -.path-icon, .keyspanel { +.path-icon, +.keyspanel { display: none; } diff --git a/css/query.css b/css/query.css index 0765b652..509f1b45 100644 --- a/css/query.css +++ b/css/query.css @@ -1,4 +1,31 @@ -@media only screen and (max-height: 900px) and (max-width: 600px) { +@media only screen and (width >= 1600px) { + .name { + width: 40%; + } + + .size { + width: 10%; + } + + .date { + width: 15%; + } + + .owner { + width: 12%; + } + + .mode { + width: 15%; + } +} + +:root { + --min-one-panel-width: 1155px; + --is-mobile: 0; +} + +@media only screen and (height <= 900px) and (width <= 600px) { .fm { height: 85%; } @@ -8,7 +35,7 @@ } } -@media only screen and (min-height: 550px) and (max-width: 600px) { +@media only screen and (height >= 550px) and (width <= 600px) { .fm { height: 80%; } @@ -18,43 +45,49 @@ } } -@media only screen and (max-height: 750px) and (max-width: 600px) { +@media only screen and (height <= 750px) and (width <= 600px) { .fm { height: 75%; } } -@media only screen and (max-height: 450px) and (max-width: 600px) { +@media only screen and (height <= 450px) and (width <= 600px) { .fm { height: 75%; } } -@media only screen and (max-height: 550px) and (max-width: 600px) { +@media only screen and (width <= 600px) { + :root { + --is-mobile: 1; + } +} + +@media only screen and (height <= 550px) and (width <= 600px) { .fm { height: 65%; } } -@media only screen and (max-height: 550px) and (max-width: 550px) { +@media only screen and (height <= 550px) and (width <= 550px) { .fm { height: 70%; } } -@media only screen and (min-height: 850px) and (min-width: 650px) { +@media only screen and (height >= 850px) and (width >= 650px) { .fm { height: 95%; } } -@media only screen and (max-height: 850px) { +@media only screen and (height <= 850px) { .files { height: 90%; } } -@media only screen and (max-height: 700px) and (min-width: 600px) { +@media only screen and (height <= 700px) and (width >= 600px) { .fm { height: 85%; } @@ -64,13 +97,13 @@ } } -@media only screen and (max-height: 450px) { +@media only screen and (height <= 450px) { .fm { height: 65%; } } -@media only screen and (max-height: 640px) and (max-width: 360px) { +@media only screen and (height <= 640px) and (width <= 360px) { .fm { height: 75%; } @@ -81,8 +114,8 @@ } /* iphone 6 landscape */ -@media only screen and (min-device-width: 375px) and (max-device-width: 667px) and (orientation: landscape), - @media only screen and (max-height: 360px) and (max-width: 640px) { +@media only screen and (device-width >= 375px) and (device-width <= 667px) and (orientation: landscape), + only screen and (height <= 360px) and (width <= 640px) { .fm { height: 55%; } @@ -92,14 +125,14 @@ } } -@media only screen and (max-width: 600px) { +@media only screen and (width <= 600px) { .panel { font-size: 26px; } /* текущий файл под курсором */ .current-file { - background-color: rgba(49, 123, 249, .40); + background-color: var(--border-color); color: white; } /* делаем иконки под курсом белыми */ @@ -107,25 +140,30 @@ color: white; } - .file::before, .file-link::before { - color: rgba(26, 224, 124, 0.56); + .file::before { + color: rgb(26 224 124 / 56%); content: '\e80d'; } - .current-file .file::before, .file-link::before { - color: white; + .file-link::before { + color: rgb(26 224 124 / 56%); + content: '\e81d'; } /* меняем иконки на шрифтовые */ .mini-icon { - color : rgba(246, 224, 124, 0.56); - font : 16px 'Fontello'; + color: rgb(246 224 124 / 56%); + font: 16px 'Fontello'; background-image: none; - padding : 1%; + padding: 1%; } - .size, .date, .owner, .mode { - display: none; + .size, + .date, + .owner, + .time, + .mode { + display: none !important; } .name { @@ -133,14 +171,30 @@ display: inline-block; } - .directory::before, .directory-link::before { + .directory::before { content: '\e807'; } - .file, .file-link { + .directory-link::before { + content: '\e81e'; + } + + .file, + .file-link { background-image: none; } + .archive, + .archive-link { + background-image: none; + } + + .archive::before, + .archive-link { + color: rgb(26 224 124 / 56%); + content: '\e81d'; + } + /* убираем заголовок */ .fm-header { display: none; @@ -152,24 +206,26 @@ } } -@media only screen and (min-width: 601px) and (max-width: 785px) { +@media only screen and (width >= 601px) and (width <= 785px) { .cmd-button { width: 13%; } } -@media only screen and (min-width: 786px) and (max-width: 1155px) { +@media only screen and (width >= 786px) and (width <= 1155px) { .cmd-button { width: 10%; } } -@media only screen and (max-width: 1155px) { +@media only screen and (width <= 1155px) { .panel { width: 98%; } /* если правая панель не помещаеться - прячем её */ - .panel-right, .cmd-button#f5, .cmd-button#f6 { + .panel-right, + .cmd-button#f5, + .cmd-button#f6 { display: none; } } @@ -182,7 +238,8 @@ border: none; } - .keyspanel, .panel-right { + .keyspanel, + .panel-right { display: none; } diff --git a/css/style.css b/css/style.css index 9e762a37..10820444 100644 --- a/css/style.css +++ b/css/style.css @@ -1,17 +1,19 @@ html { - height : 94%; + height: 94%; } body { - width : 100%; - height : 95%; - overflow : hidden; - background-color : white; + width: 100%; + height: 95%; + overflow: hidden; + background-color: var(--background); } -body, pre, code { - font-family : 'Droid Sans Mono', 'Ubuntu Mono', 'Consolas', monospace; - font-size : 16px; +body, +pre, +code { + font-family: 'Droid Sans Mono', 'Ubuntu Mono', 'Consolas', monospace; + font-size: 16px; } .hidden { @@ -22,31 +24,34 @@ body, pre, code { display: none; } -.fm, .keyspanel { - cursor : default; - -webkit-tap-highlight-color: rgba(0, 0, 0, 0); - -webkit-user-select : none; - -moz-user-select : none; - -ms-user-select : none; - -o-user-select : none; - user-select : none; +.fm, +.keyspanel { + cursor: default; + -webkit-tap-highlight-color: rgb(0 0 0 / 0%); + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + -o-user-select: none; + user-select: none; } .links { - -webkit-user-select : initial; - -moz-user-select : initial; - -ms-user-select : initial; - -o-user-select : initial; - user-select : text; + -webkit-user-select: initial; + -moz-user-select: initial; + -ms-user-select: initial; + -o-user-select: initial; + user-select: text; + color: var(--column-color); } -.panel, .cmd-button { +.panel, +.cmd-button { border: 1px solid; - border-color: rgba(49, 123, 249, 0.4); + border-color: var(--border-color); } .icon { - margin-left : 0.5%; + margin-left: 0.5%; cursor: default; } @@ -56,7 +61,7 @@ body, pre, code { .path-icon { position: relative; - color: #222; + color: var(--icon-color); } .path-icon:active { @@ -64,41 +69,41 @@ body, pre, code { } .path-icon:hover { - color : #06e; + color: #06e; cursor: pointer; } .error::before { - font-family : 'Fontello'; - font-size : 14px; - color : rgb(222, 41, 41); - cursor : default; - content : '\e800'; + font-family: 'Fontello'; + font-size: 14px; + color: rgb(222 41 41); + cursor: default; + content: '\e800'; } .loading { - position : relative; - display : inline-block; - width : 16px; - height : 16px; - vertical-align : middle; + position: relative; + display: inline-block; + width: 16px; + height: 16px; + vertical-align: middle; } .loading::after { - position : relative; - bottom : 5px; - left : 16px; - font-size : 10px; - color : rgb(49, 123, 249); - content : attr(data-progress); + position: relative; + bottom: 5px; + left: 16px; + font-size: 10px; + color: var(--link-color); + content: attr(data-progress); } .cmd-button { width: 5%; height: 30px; margin: 20px 2px 0; - color: #222; - background-color: white; + color: var(--icon-color); + background-color: var(--button-background); transition: ease 0.1s; } @@ -109,7 +114,7 @@ body, pre, code { .cmd-button:active { color: white; - background-color: rgb(49, 123, 249); + background-color: var(--link-color); transition: ease 0.1s; } @@ -121,7 +126,8 @@ a { text-decoration: none; } -a:hover, a:active { +a:hover, +a:active { color: #06e; text-decoration: none; } @@ -145,13 +151,14 @@ a:hover, a:active { } .fm { - width : 98%; + width: 98%; height: 90%; margin: 26px auto 0; } .fm-header { font-weight: bold; + color: var(--column-color); } .panel-left { @@ -159,15 +166,30 @@ a:hover, a:active { } .current-file { - box-shadow: 0 0 0 1px rgba(49, 123, 249, 0.4) inset; + box-shadow: 0 0 0 1px var(--border-color) inset; } .cut-file { opacity: 0.7; } -.selected-file, .selected-file .name > a { - color: rgb(254, 159, 224); +.name { + float: left; + width: 26%; +} + +.name a { + color: var(--link-color); +} + +.name a:hover { + cursor: default; +} + +.selected-file, +.selected-file > span, +.selected-file .name > a { + color: rgb(254 159 224); } .panel-right { @@ -185,54 +207,55 @@ a:hover, a:active { } .selected-panel { - border-color: rgba(254, 159, 224, .40); + border-color: rgb(254 159 224 / 40%); } .keyspanel { text-align: center; } -.name { - float: left; - width: 26%; -} - -.name a:hover { - cursor: default; -} - .size { float: left; width: 12%; margin-right: 27px; text-align: right; + color: var(--column-color); } .date { float: left; width: 19%; + color: var(--column-color); +} + +.time { + color: var(--column-color); + display: none; } .owner { - display : inline-block; - width : 13%; + display: inline-block; + width: 12%; + /* when inline-block * vertical align should be * set top to prevent additional * spaces behind lines */ - vertical-align : top; + vertical-align: top; + color: var(--column-color); } .mode { float: right; - width: 18%; + width: 22%; + color: var(--column-color); } .reduce-text { - overflow : hidden; - text-overflow : ellipsis; - white-space : nowrap; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .files { @@ -247,4 +270,3 @@ a:hover, a:active { .files li { overflow: hidden; } - diff --git a/css/supports.css b/css/supports.css index bf470c2d..ea2084d2 100644 --- a/css/supports.css +++ b/css/supports.css @@ -1,6 +1,6 @@ @supports (overflow: overlay) { .files { - overflow-y: overlay; + overflow-y: auto; } .fm-header { diff --git a/css/terminal.css b/css/terminal.css index 20cf94b4..e7b1fea6 100644 --- a/css/terminal.css +++ b/css/terminal.css @@ -1,4 +1,3 @@ .terminal { height: 100%; } - diff --git a/css/themes/dark.css b/css/themes/dark.css new file mode 100644 index 00000000..311a8093 --- /dev/null +++ b/css/themes/dark.css @@ -0,0 +1,49 @@ +:root { + --link-color: #317bf9; + --border-color: rgb(49 123 249 / 40%); + --background: #22272e; + --column-color: #727e8c; + --icon-color: #478be6; + --button-background: #22272e; + --internal-background: #373e47; +} + +.view { + background: var(--internal-background) !important; + color: var(--column-color) !important; +} +.view a { + color: var(--link-color) !important; +} + +.smalltalk .page, +.smalltalk header, +.smalltalk .button-strip button, +.smalltalk input { + background: var(--internal-background) !important; + color: var(--link-color) !important; + text-shadow: none !important; +} + +.cloudcmd-user-menu, +.cloudcmd-user-menu-button { + background: var(--internal-background) !important; + color: var(--link-color) !important; +} + +.jqconsole { + background: #373e47 !important; +} + +.jqconsole-prompt { + color: var(--column-color) !important; +} + +.log-msg { + color: var(--column-color) !important; +} + +.menu { + color: var(--link-color) !important; + background: var(--internal-background) !important; +} diff --git a/css/themes/light.css b/css/themes/light.css new file mode 100644 index 00000000..e95eb441 --- /dev/null +++ b/css/themes/light.css @@ -0,0 +1,9 @@ +:root { + --link-color: blue; + --selected-menu-item-color: #317bf9; + --border-color: rgb(49 123 249 / 40%); + --background: white; + --column-color: black; + --icon-color: #222; + --button-background: white; +} diff --git a/css/urls.css b/css/urls.css index b53c3626..be90e235 100644 --- a/css/urls.css +++ b/css/urls.css @@ -17,20 +17,23 @@ } @font-face { - font-family : 'Droid Sans Mono'; - src : url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJTwtzT4qNq-faudv5qbO9-U.eot); - src : + font-family: 'Droid Sans Mono'; + src: url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJTwtzT4qNq-faudv5qbO9-U.eot); + src: local('Droid Sans Mono'), local('DroidSansMono'), url(../font/DroidSansMono.eot) format('embedded-opentype'), - url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJTwtzT4qNq-faudv5qbO9-U.eot?#iefix) format('embedded-opentype'), - url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJTwtzT4qNq-faudv5qbO9-U.eot) format('embedded-opentype'), + url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJTwtzT4qNq-faudv5qbO9-U.eot?#iefix) + format('embedded-opentype'), + url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJTwtzT4qNq-faudv5qbO9-U.eot) + format('embedded-opentype'), url(../font/DroidSansMono.woff2) format('woff2'), url(../font/DroidSansMono.woff) format('woff'), - url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff) format('woff'), + url(https://themes.googleusercontent.com/static/fonts/droidsansmono/v5/ns-m2xQYezAtqh7ai59hJUYuTAAIFFn5GTWtryCmBQ4.woff) + format('woff'), local('Consolas'); - font-style : normal; - font-weight : 400; + font-style: normal; + font-weight: 400; } .directory { @@ -49,6 +52,14 @@ background-image: url(../img/file-link.png); } +.archive { + background-image: url(../img/archive.png); +} + +.archive-link { + background-image: url(../img/archive-link.png); +} + .loading-svg { background: url(../img/spinner.svg); } @@ -56,4 +67,3 @@ .loading-gif { background: url(../img/spinner.gif); } - diff --git a/css/user-menu.css b/css/user-menu.css new file mode 100644 index 00000000..792747f4 --- /dev/null +++ b/css/user-menu.css @@ -0,0 +1,23 @@ +.cloudcmd-user-menu { + font-size: 16px; + font-family: 'Droid Sans Mono', 'Ubuntu Mono', 'Consolas', monospace; + border: 0; +} + +.cloudcmd-user-menu:focus { + outline: 0; +} + +.cloudcmd-user-menu > option:checked { + box-shadow: 20px -20px 0 2px var(--selected-menu-item-color) inset; +} + +.cloudcmd-user-menu-button { + display: block; + width: 100%; + font-size: 16px; + padding: 2px; + -webkit-appearance: none; + border: 0; + overflow: auto; +} diff --git a/css/view.css b/css/view.css index 4a02cd15..b6fb20ed 100644 --- a/css/view.css +++ b/css/view.css @@ -15,11 +15,12 @@ } .view-overlay { - display : block; - background : rgba(255, 255, 255, 0.1); + display: block; + background: rgb(255 255 255 / 10%); } -.media, video { +.media, +video { width: 100%; } diff --git a/cssnano.config.js b/cssnano.config.js deleted file mode 100644 index b5b4d7b2..00000000 --- a/cssnano.config.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -// used by OptimizeCssAssetsPlugin - -const defaultPreset = require('cssnano-preset-default'); - -module.exports = defaultPreset({ - svgo: { - plugins: [ - {convertPathData: false}, - {convertShapeToPath: false}, - ] - } -}); - diff --git a/deno.json b/deno.json new file mode 100644 index 00000000..64c1bde2 --- /dev/null +++ b/deno.json @@ -0,0 +1,14 @@ +{ + "tasks": { + "start": "deno run -P=cloudcmd bin/cloudcmd.mjs" + }, + "permissions": { + "cloudcmd": { + "env": true, + "read": true, + "sys": true, + "net": true, + "run": true + } + } +} diff --git a/docker-compose.yml b/docker-compose.yml index e358cb83..0fb72a34 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -version: '2' +version: "2" services: web: ports: @@ -7,4 +7,3 @@ services: - ~:/root - /:/mnt/fs image: coderaiser/cloudcmd - diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 00000000..7c5d7b64 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,29 @@ +FROM node + +LABEL maintainer="Coderaiser" +LABEL org.opencontainers.image.source="https://github.com/coderaiser/cloudcmd" + +RUN mkdir -p /usr/src/cloudcmd + +WORKDIR /usr/src/cloudcmd + +COPY package.json /usr/src/cloudcmd/ + +RUN curl -fsSL https://bun.com/install | bash && \ + ln -s /root/.bun/bin/bun /usr/local/bin/bun && \ + chmod +x /usr/local/bin/bun && \ + bun r gritty --omit dev && \ + bun i gritty --omit dev && \ + bun pm cache rm + +COPY . /usr/src/cloudcmd + +WORKDIR / + +ENV cloudcmd_terminal=true +ENV cloudcmd_terminal_path=gritty +ENV cloudcmd_open=false + +EXPOSE 8000 + +ENTRYPOINT ["/usr/src/cloudcmd/bin/cloudcmd.js"] diff --git a/docker/Dockerfile.alpine b/docker/Dockerfile.alpine new file mode 100644 index 00000000..5e38ab8a --- /dev/null +++ b/docker/Dockerfile.alpine @@ -0,0 +1,34 @@ +FROM node:alpine + +LABEL maintainer="Coderaiser" +LABEL org.opencontainers.image.source="https://github.com/coderaiser/cloudcmd" + +RUN mkdir -p /usr/src/cloudcmd + +WORKDIR /usr/src/cloudcmd + +COPY package.json /usr/src/cloudcmd/ + +RUN apk update && \ + apk add --no-cache curl bash make g++ python3 && \ + curl -fsSL https://bun.sh/install | bash && \ + ln -s ~/.bun/bin/bun /usr/local/bin/bun && \ + chmod +x /usr/local/bin/bun && \ + bun r gritty --omit dev && \ + bun i gritty --omit dev && \ + bun pm cache rm && \ + apk del make g++ python3 && \ + rm -rf /usr/include /tmp/* /var/cache/apk/* + +COPY . /usr/src/cloudcmd + +WORKDIR / + +ENV cloudcmd_terminal=true +ENV cloudcmd_terminal_path=gritty +ENV cloudcmd_open=false +ENV cloudcmd_vim=true + +EXPOSE 8000 + +ENTRYPOINT ["/usr/src/cloudcmd/bin/cloudcmd.js"] diff --git a/docker/Dockerfile.io b/docker/Dockerfile.io new file mode 100644 index 00000000..d5a24459 --- /dev/null +++ b/docker/Dockerfile.io @@ -0,0 +1,113 @@ +FROM ubuntu:resolute + +LABEL maintainer="Coderaiser" +LABEL org.opencontainers.image.source="https://github.com/coderaiser/cloudcmd" + +RUN mkdir -p /usr/local/share/cloudcmd + +WORKDIR /usr/local/share/cloudcmd + +COPY package.json /usr/local/share/cloudcmd/ + +ENV DEBIAN_FRONTEND=noninteractive \ + NVM_DIR=/usr/local/share/nvm \ + npm_config_cache=/tmp/npm-cache \ + GOPATH=/usr/local/share/go \ + PATH=/usr/local/share/bun/bin:$PATH \ + BUN_INSTALL=/usr/local/share/bun \ + NPM_CONFIG_CACHE=/tmp/.npm \ + NPM_CONFIG_PREFIX=/usr/local \ + NPM_CONFIG_PACKAGE_LOCK=false \ + PALABRA_DIR=/usr/local/share \ + XDG_CONFIG_HOME=/usr/local/etc + +ARG UBUNTU_DEPS="libatomic1 curl wget git net-tools iproute2 software-properties-common" +ARG RUST_DEPS="build-essential" +ARG DEPS="pv gcc gdb strace upx-ucl less ffmpeg net-tools netcat-openbsd mc far2l iputils-ping vim bat fzf locales sudo command-not-found ncdu aptitude htop btop hexyl tmux" +ARG PALABRA_DEPS="nvm node rust go deno fasm nvchad rizin yara gdu f4 typos shellcheck gh" +ARG BUN_DEPS="palabra wisdom nupdate version-io redrun superc8 supertape madrun redlint putout renamify-cli runny redfork cline" + +RUN apt-get update && \ + apt-get upgrade -y && \ + apt-get autoremove && \ + apt-get install -y ${UBUNTU_DEPS} ${RUST_DEPES} ${DEPS} && \ + echo "> Install git" && \ + add-apt-repository ppa:git-core/ppa -y && \ + echo "> Update command-not-found database. Run 'sudo apt update' to populate it." && \ + apt-get update && \ + apt-get upgrade -y && \ + apt-get autoremove && \ + apt-get clean && \ + echo "> create user" && \ + useradd -m -s /bin/bash -u 1337 instalador && \ + chown -R instalador /usr/local && \ + chown -R instalador /tmp + +USER instalador + +RUN echo "> install bun" && \ + curl https://bun.sh/install | bash && \ + echo "> install npm globals" && \ + bun i ${BUN_DEPS} -g && \ + echo "> install rust go deno bun fasm nvim" && \ + bun ${BUN_INSTALL}/bin/palabra i ${PALABRA_DEPS} && \ + echo "> install node" && \ + . $NVM_DIR/nvm.sh + +USER root + +RUN echo "> remove user" && \ + userdel -r instalador && \ + echo "> install gritty" && \ + bun r gritty --omit dev && \ + bun i gritty --omit dev && \ + bun pm cache rm && \ + echo "> setup cloudcmd" && \ + ln -s /usr/local/share/cloudcmd/bin/cloudcmd.js /usr/local/bin/cloudcmd && \ + echo "> setup git" && \ + git config --global core.whitespace -trailing-space && \ + git config --global pull.rebase true && \ + git config --global init.defaultBranch master && \ + echo "> configure bash" && \ + echo "alias ls='ls --color=auto'" >> /etc/bash.bashrc && \ + echo "alias buni='bun i --no-save'" >> /etc/bash.bashrc && \ + echo "alias bat='batcat'" >> /etc/bash.bashrc && \ + echo ". /usr/local/share/nvm/nvm.sh" >> /etc/bash.bashrc && \ + echo ". /usr/share/bash-completion/completions/git" >> /etc/bash.bashrc && \ + echo 'PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "' >> /etc/bash.bashrc && \ + echo "> setup inputrc" && \ + echo "set editing-mode vi" >> /etc/inputrc && \ + echo "TAB: menu-complete" >> /etc/inputrc && \ + echo "set UTF-8" && \ + echo " > configure languages" && \ + echo "en_US.UTF-8 UTF-8" > /etc/locale.gen && \ + echo "ru_RU.UTF-8 UTF-8" >> /etc/locale.gen && \ + echo "uk_UA.UTF-8 UTF-8" >> /etc/locale.gen && \ + echo "es_ES.UTF-8 UTF-8" >> /etc/locale.gen && \ + echo "ja_JP.UTF-8 UTF-8" >> /etc/locale.gen && \ + echo "el_GR.UTF-8 UTF-8" >> /etc/locale.gen && \ + locale-gen + +COPY . /usr/local/share/cloudcmd + +WORKDIR / + +ENV cloudcmd_terminal=true \ + cloudcmd_terminal_path=gritty \ + cloudcmd_vim=true \ + cloudcmd_open=false \ + PATH=node_modules/.bin:$PATH \ + PATH=~/.local/bin:$PATH \ + BUN_INSTALL_CACHE_DIR=/tmp/bun-cache \ + DENO_DIR=/tmp/deno-cache \ + LANG=en_US.UTF-8 \ + LANGUAGE=en_US:en \ + LC_ALL=en_US.UTF-8 \ + TERM=xterm-256color \ + XDG_CACHE_HOME=/tmp \ + XDG_DATA_HOME=/usr/local/share \ + XDG_CONFIG_HOME=~/.config + +EXPOSE 8000 + +ENTRYPOINT ["/usr/local/share/cloudcmd/bin/cloudcmd.js"] diff --git a/docker/Dockerfile.slim b/docker/Dockerfile.slim new file mode 100644 index 00000000..c6f273b8 --- /dev/null +++ b/docker/Dockerfile.slim @@ -0,0 +1,39 @@ +FROM node:slim AS build + +RUN mkdir -p /usr/src/cloudcmd/ + +WORKDIR /usr/src/cloudcmd + +COPY package.json /usr/src/cloudcmd/ + +RUN apt-get update && \ + apt-get install -y build-essential python3 libncurses5-dev pkg-config && \ + apt-get install -y --no-install-recommends curl ca-certificates unzip && \ + curl -fsSL https://bun.sh/install | bash && \ + ln -s ~/.bun/bin/bun /usr/local/bin/bun && \ + chmod +x /usr/local/bin/bun && \ + bun r gritty --omit dev && \ + bun i gritty --omit dev && \ + ~/.bun/bin/bun pm cache rm && \ + rm -rf /var/lib/apt/lists/* + +COPY . /usr/src/cloudcmd + +FROM node:slim AS runtime + +COPY --from=build /usr/src/cloudcmd /usr/src/cloudcmd +COPY --from=build /root/.bun /root/.bun + +LABEL maintainer="Coderaiser" +LABEL org.opencontainers.image.source="https://github.com/coderaiser/cloudcmd" + +WORKDIR / + +ENV cloudcmd_terminal=true +ENV cloudcmd_terminal_path=gritty +ENV cloudcmd_open=false +ENV PATH="/root/.bun/bin:$PATH" + +EXPOSE 8000 + +ENTRYPOINT ["/usr/src/cloudcmd/bin/cloudcmd.js"] diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..22add654 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,31 @@ +import {safeAlign} from 'eslint-plugin-putout'; +import {defineConfig} from 'eslint/config'; +import globals from 'globals'; +import {matchToFlat} from '@putout/eslint-flat'; + +export const match = { + 'bin/release.js': { + 'no-console': 'off', + 'n/hashbang': 'off', + }, + 'client/dom/index.*': { + 'no-multi-spaces': 'off', + }, + 'client/**': { + 'n/no-unsupported-features/node-builtins': 'off', + }, +}; +export default defineConfig([ + safeAlign, { + ignores: ['**/fixture'], + rules: { + 'key-spacing': 'off', + }, + }, { + files: ['{client,common,static}/**/*.js'], + languageOptions: { + globals: globals.browser, + }, + }, + ...matchToFlat(match), +]); diff --git a/font/fontello.eot b/font/fontello.eot index 4274ddd2..e144bd82 100644 Binary files a/font/fontello.eot and b/font/fontello.eot differ diff --git a/font/fontello.json b/font/fontello.json index 61c8d00e..c8bad6be 100644 --- a/font/fontello.json +++ b/font/fontello.json @@ -174,6 +174,30 @@ "code": 59413, "src": "entypo" }, + { + "uid": "f805bb95d40c7ef2bc51b3d50d4f2e5c", + "css": "th-list", + "code": 59420, + "src": "fontawesome" + }, + { + "uid": "e15f0d620a7897e2035c18c80142f6d9", + "css": "link-ext", + "code": 59421, + "src": "fontawesome" + }, + { + "uid": "e35de5ea31cd56970498e33efbcb8e36", + "css": "link-ext-alt", + "code": 59422, + "src": "fontawesome" + }, + { + "uid": "12f4ece88e46abd864e40b35e05b11cd", + "css": "ok", + "code": 59423, + "src": "fontawesome" + }, { "uid": "60617c8adc1e7eb3c444a5491dd13f57", "css": "attention-circled-1", diff --git a/font/fontello.svg b/font/fontello.svg index afc5a844..ff664681 100644 --- a/font/fontello.svg +++ b/font/fontello.svg @@ -1,7 +1,7 @@ -Copyright (C) 2018 by original authors @ fontello.com +Copyright (C) 2024 by original authors @ fontello.com @@ -61,6 +61,14 @@ + + + + + + + + - \ No newline at end of file + diff --git a/font/fontello.ttf b/font/fontello.ttf index 1065b0d3..bfec5c43 100644 Binary files a/font/fontello.ttf and b/font/fontello.ttf differ diff --git a/font/fontello.woff b/font/fontello.woff index 9a4a5952..a23a854d 100644 Binary files a/font/fontello.woff and b/font/fontello.woff differ diff --git a/font/fontello.woff2 b/font/fontello.woff2 index b8c98b96..f0210ad6 100644 Binary files a/font/fontello.woff2 and b/font/fontello.woff2 differ diff --git a/html/index.html b/html/index.html index e0fd8595..d366ed1c 100644 --- a/html/index.html +++ b/html/index.html @@ -8,19 +8,22 @@ - + + -
    {{ fm }}
    +
    {{ fm }}
    - + @@ -38,5 +41,15 @@ + diff --git a/img/archive-link.png b/img/archive-link.png new file mode 100644 index 00000000..b134c2b8 Binary files /dev/null and b/img/archive-link.png differ diff --git a/img/archive.png b/img/archive.png new file mode 100644 index 00000000..fd4bbccd Binary files /dev/null and b/img/archive.png differ diff --git a/img/favicon/favicon-256.png b/img/favicon/favicon-256.png new file mode 100644 index 00000000..4e01d43c Binary files /dev/null and b/img/favicon/favicon-256.png differ diff --git a/img/logo/cloudcmd-hq.png b/img/logo/cloudcmd-hq.png new file mode 100644 index 00000000..8e4d1d3b Binary files /dev/null and b/img/logo/cloudcmd-hq.png differ diff --git a/json/config.json b/json/config.json index b925c898..3bbb65f4 100644 --- a/json/config.json +++ b/json/config.json @@ -5,9 +5,10 @@ "password": "2b64f2e3f9fee1942af9ff60d40aa5a719db33b8ba8dd4864bb4f11e25ca2bee00907de32a59429602336cac832c8f2eeff5177cc14c864dd116c8bf6ca5d9a9", "algo": "sha512WithRSAEncryption", "editor": "edward", + "menu": "aleman", "packer": "tar", "diff": true, - "zip" : true, + "zip": true, "buffer": true, "dirStorage": false, "online": false, @@ -18,12 +19,12 @@ "root": "/", "prefix": "", "prefixSocket": "", - "progress": true, "contact": true, "confirmCopy": true, "confirmMove": true, "configDialog": true, "configAuth": true, + "configPort": true, "oneFilePanel": false, "console": true, "syncConsolePath": false, @@ -31,16 +32,19 @@ "terminalPath": "", "terminalCommand": "", "terminalAutoRestart": true, + "showDotFiles": true, "showConfig": false, "showFileName": false, "vim": false, "columns": "name-size-date-owner-mode", + "theme": "light", "export": false, "exportToken": "root", "import": false, "importToken": "root", "importUrl": "http://localhost:8000", "importListen": false, - "log": true + "log": true, + "dropbox": false, + "dropboxToken": "" } - diff --git a/json/help.json b/json/help.json index b984a7b3..44f79248 100644 --- a/json/help.json +++ b/json/help.json @@ -8,6 +8,7 @@ "-p, --password ": "set password", "-c, --config ": "configuration file path", "--show-config ": "show config values", + "--show-dot-files ": "show dot files", "--show-file-name ": "show file name in view and edit", "--editor ": "set editor: \"dword\", \"edward\" or \"deepword\"", "--packer ": "set packer: \"tar\" or \"zip\"", @@ -15,29 +16,34 @@ "--prefix ": "set url prefix", "--prefix-socket ": "set prefix for socket connection", "--port ": "set port number", - "--progress ": "show progress of file operations", "--confirm-copy ": "confirm copy", "--confirm-move ": "confirm move", "--open ": "open web browser when server started", "--name ": "set tab name in web browser", + "--menu ": "set menu: \"supermenu\" or \"aleman\"", "--one-file-panel ": "show one file panel", "--keys-panel ": "show keys panel", "--config-dialog ": "enable config dialog", "--config-auth ": "enable auth change in config dialog", + "--config-port ": "enable port change in config dialog", "--console ": "enable console", "--sync-console-path ": "sync console path", "--contact ": "enable contact", "--terminal ": "enable terminal", "--terminal-path ": "set terminal path", "--terminal-command ": "set command to run in terminal (shell by default)", + "--terminal-auto-restart ": "restart command on exit", "--vim ": "enable vim hot keys", "--columns ": "set visible columns", + "--theme ": "set theme 'light' or 'dark'", "--export ": "enable export of config through a server", "--export-token ": "authorization token used by export server", "--import ": "enable import of config", "--import-url ": "url of an export server", "--import-token ": "authorization token used to connect to export server", "--import-listen ": "enable listen on config updates from import server", + "--dropbox ": "enable dropbox integration", + "--dropbox-token ": "set dropbox token", "--log ": "enable logging", "--no-show-config ": "do not show config values", "--no-server ": "do not start server", @@ -47,22 +53,25 @@ "--no-name ": "set default tab name in web browser", "--no-one-file-panel ": "show two file panels", "--no-keys-panel ": "hide keys panel", - "--no-one-file-panel ": "show two file panels", - "--no-progress ": "do not show progress of file operations", "--no-confirm-copy ": "do not confirm copy", "--no-confirm-move ": "do not confirm move", "--no-config-dialog ": "disable config dialog", "--no-config-auth ": "disable auth change in config dialog", + "--no-config-port ": "disable port change in config dialog", "--no-console ": "disable console", "--no-sync-console-path ": "do not sync console path", "--no-contact ": "disable contact", "--no-terminal ": "disable terminal", "--no-terminal-command ": "set default shell to run in terminal", + "--no-terminal-auto-restart ": "do not restart command on exit", "--no-vim ": "disable vim hot keys", "--no-columns ": "set default visible columns", "--no-export ": "disable export config through a server", "--no-import ": "disable import of config", "--no-import-listen ": "disable listen on config updates from import server", - "--no-log ": "disable logging", - "--no-show-file-name ": "do not show file name in view and edit" + "--no-show-dot-files ": "do not show dot files", + "--no-show-file-name ": "do not show file name in view and edit", + "--no-dropbox ": "disable dropbox integration", + "--no-dropbox-token ": "unset dropbox token", + "--no-log ": "disable logging" } diff --git a/json/modules.json b/json/modules.json index 0c7439d8..6ed586d1 100644 --- a/json/modules.json +++ b/json/modules.json @@ -11,15 +11,18 @@ "markdown", "config", "contact", + "command-line", "upload", "operation", "konsole", "terminal", - "cloud" + "terminal-run", + "cloud", + "user-menu" ], "remote": [{ "name": "socket", - "version": "2.1.1", + "version": "4.0.1", "local": "/socket.io/socket.io.js", "remote": "https://cdnjs.cloudflare.com/ajax/libs/socket.io/{{ version }}/socket.io.js" }], diff --git a/man/cloudcmd.1 b/man/cloudcmd.1 index fd2ca17e..dab36a2c 100644 --- a/man/cloudcmd.1 +++ b/man/cloudcmd.1 @@ -31,14 +31,15 @@ programs in browser from any computer, mobile or tablet device. -p, --password set password -c, --config configuration file path --show-config show config values + --show-dot-files show dot files --show-file-name show file name in view and edit modes - --editor set editor: "dword", "edward" or "deepword" + --editor set editor: "dword", "edward", "deepword" or "qword" + --menu set menu: "supermenu" or "aleman" --packer set packer: "tar" or "zip" --root set root directory --prefix set url prefix --prefix-socket set prefix for socket connection --port set port number - --progress show progress of file operations --confirm-copy confirm copy --confirm-move confirm move --open open web browser when server started @@ -48,6 +49,7 @@ programs in browser from any computer, mobile or tablet device. --contact enable contact --config-dialog enable config dialog --config-auth enable auth change in config dialog + --config-port enable port change in config dialog --console enable console --sync-console-path sync console path --terminal enable terminal @@ -56,14 +58,18 @@ programs in browser from any computer, mobile or tablet device. --terminal-auto-restart restart command on exit --vim enable vim hot keys --columns set visible columns + --theme set theme 'light' or 'dark' --export enable export of config through a server --export-token authorization token used by export server --import enable import of config --import-url url of an import server --import-token authorization token used to connect to export server --import-listen enable listen on config updates from import server + --dropbox enable dropbox integration + --dropbox-token set dropbox token --log enable logging --no-show-config do not show config values + --no-show-dot-files do not show dot files --no-server do not start server --no-auth disable authorization --no-online load scripts from local server @@ -71,12 +77,12 @@ programs in browser from any computer, mobile or tablet device. --no-name set default tab name in web browser --no-one-file-panel show two file panels --no-keys-panel hide keys panel - --no-progress do not show progress of file operations --no-confirm-copy do not confirm copy --no-confirm-move do not confirm move --no-contact disable contact --no-config-dialog disable config dialog --no-config-auth disable auth change in config dialog + --no-config-port disable port change in config dialog --no-console disable console --no-sync-console-path do not sync console path --no-terminal disable terminal @@ -88,8 +94,10 @@ programs in browser from any computer, mobile or tablet device. --no-import disable import of config --no-import-url url of an import server --no-import-listen disable listen on config updates from import server - --no-log disable logging --no-show-file-name do not show file name in view and edit modes + --no-dropbox disable dropbox integration + --no-dropbox-token unset dropbox token + --no-log disable logging .SH RESOURCES AND DOCUMENTATION diff --git a/manifest.yml b/manifest.yml index 97b2810f..c10c360d 100644 --- a/manifest.yml +++ b/manifest.yml @@ -1,4 +1,3 @@ ---- applications: .: name: cloudcmd @@ -7,7 +6,7 @@ applications: info: mem: 512M description: Node.js Application - exec: + exec: null url: ${name}.${target-base} mem: 128M instances: 2 diff --git a/now.json b/now.json deleted file mode 100644 index c6fa74f9..00000000 --- a/now.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "type": "npm", - "alias": "cloudcmd", - "env": { - "cloudcmd_config_dialog": "true", - "cloudcmd_config_auth": "false", - "cloudcmd_terminal": "true", - "cloudcmd_terminal_path": "gritty", - "cloudcmd_import": "true", - "cloudcmd_import_listen": "true", - "cloudcmd_import_token": "hello", - "cloudcmd_import_url": "https://cloudcmd.herokuapp.com", - "cloudcmd_export": "true", - "cloudcmd_export_token": "hello", - "cloudcmd_name": "Cloud Commander - Now", - "cloudcmd_open": "false" - }, - "engines": { - "node": "8" - }, - "files": [ - "bin", - "server", - ".babelrc", - "css", - "font", - "favicon.ico", - "client", - "common", - "html", - "tmpl", - "img", - "man", - "modules", - ".webpack", - "webpack.config.js", - "cssnano.config.js", - "json", - "HELP.md" - ] -} diff --git a/package.json b/package.json index 64f3f462..f680e519 100644 --- a/package.json +++ b/package.json @@ -1,13 +1,16 @@ { "name": "cloudcmd", - "version": "11.7.0", + "version": "19.19.1", + "type": "module", "author": "coderaiser (https://github.com/coderaiser)", "description": "File manager for the web with console and editor", "homepage": "http://cloudcmd.io", + "funding": "https://opencollective.com/cloudcmd", "repository": { "type": "git", - "url": "git://github.com/coderaiser/cloudcmd.git" + "url": "git+https://github.com/coderaiser/cloudcmd.git" }, + "main": "server/cloudcmd.js", "keywords": [ "console", "terminal", @@ -38,195 +41,204 @@ "bin": { "cloudcmd": "bin/cloudcmd.js" }, - "config": { - "dirs": "bin/cloudcmd.js common server", - "dirs_test": "test bin/release.js webpack.config.js cssnano.config.js .webpack" - }, "scripts": { - "start": "node bin/cloudcmd.js", - "start:dev": "NODE_ENV=development node bin/cloudcmd.js", - "build:start": "redrun build:client start", - "build:start:dev": "redrun build:client:dev start:dev", - "lint": "redrun lint:*", - "lint:js": "redrun lint:client lint:server lint:test", - "lint:server": "eslint -c .eslintrc.server $npm_package_config_dirs --ignore-pattern *.spec.js", - "lint:test": "eslint $npm_package_config_dirs_test", - "lint:client": "eslint --env browser client", - "lint:css": "stylelint css/*.css", - "lint:md": "yaspeller .", - "fix:lint:client": "redrun lint:client -- --fix", - "fix:lint:test": "redrun lint:test -- --fix", - "fix:lint:server": "redrun lint:server -- --fix", - "test": "tape 'test/**/*.js' '{client,common,server}/**/*.spec.js'", - "test:client": "tape 'test/client/**/*.js'", - "test:server": "tape 'test/**/*.js' 'server/**/*.spec.js' 'common/**/*.spec.js'", - "wisdom": "redrun lint build test", - "wisdom:type": "bin/release.js", - "docker:pull:node": "docker pull node", - "docker:pull:alpine": "docker pull mhart/alpine-node", - "docker:push": "docker push coderaiser/cloudcmd:`version`", - "docker:push:latest": "docker push coderaiser/cloudcmd:latest", - "docker:push:alpine": "docker push coderaiser/cloudcmd:`version`-alpine", - "docker:push:alpine:latest": "docker push coderaiser/cloudcmd:latest-alpine", - "docker:build": "docker build -t coderaiser/cloudcmd:`version` .", - "docker:build:alpine": "docker build -f Dockerfile.alpine -t coderaiser/cloudcmd:`version`-alpine .", - "docker": "redrun docker:pull* docker:build* docker:tag* docker:push*", - "docker-ci": "redrun build docker-login docker", - "docker-login": "docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD", - "docker:alpine": "redrun docker:pull:alpine docker:build:alpine docker:tag:alpine docker:push:alpine docker:push:alpine:latest", - "docker:tag": "docker tag coderaiser/cloudcmd:`version` coderaiser/cloudcmd:latest", - "docker:tag:alpine": "docker tag coderaiser/cloudcmd:`version`-alpine coderaiser/cloudcmd:latest-alpine", - "docker:rm:version": "docker rmi -f coderaiser/cloudcmd:`version`", - "docker:rm:latest": "docker rmi -f coderaiser/cloudcmd:latest", - "docker:rm:alpine": "docker rmi -f coderaiser/cloudcmd:`version`-alpine", - "docker:rm:latest-alpine": "docker rmi -f coderaiser/cloudcmd:latest-alpine", - "docker:rm-old": "redrun -P docker:rm:*", - "coverage": "nyc npm test", - "report": "nyc report --reporter=text-lcov | coveralls", - "6to5": "webpack --progress", - "6to5:client": "npm run 6to5 -- --mode production", - "6to5:client:dev": "NODE_ENV=development npm run 6to5 -- --progress --mode development", - "pre6to5:client": "rimraf dist", - "pre6to5:client:dev": "rimraf dist-dev", - "watch:client": "redrun 6to5:client -- --watch", - "watch:client:dev": "redrun 6to5:client:dev -- --watch", - "watch:server": "nodemon bin/cloudcmd.js", - "watch:lint": "nodemon -w client -w server -w webpack.config.js -x 'redrun lint:js'", - "watch:lint:client": "nodemon -w client -w webpack.config.js -x 'redrun lint:client'", - "watch:lint:server": "nodemon -w server -w common -x 'redrun lint:server'", - "watch:test": "nodemon -w client -w server -w test -w common -x \"npm test\"", - "watch:test:client": "nodemon -w client -w test/client -x \"npm run test:client\"", - "watch:test:server": "nodemon -w client -w test/client -x \"npm run test:server\"", - "watch:coverage": "nodemon -w server -w test -w common -x \"npm run coverage\"", - "w:c": "redrun watch:client", - "w:c:d": "redrun watch:client:dev", - "build": "redrun 6to5:*", - "build:client": "redrun 6to5:client", - "build:client:dev": "redrun 6to5:client:dev", - "heroku-postbuild": "redrun 6to5:client" + "start": "madrun start", + "start:dev": "madrun start:dev", + "build:start": "madrun build:start", + "build:start:dev": "madrun build:start:dev", + "lint:all": "madrun lint:all", + "lint": "madrun lint", + "lint:progress": "madrun lint:progress", + "watch:lint": "madrun watch:lint", + "fresh:lint": "madrun fresh:lint", + "lint:fresh": "madrun lint:fresh", + "fix:lint": "madrun fix:lint", + "lint:stream": "madrun lint:stream", + "test": "madrun test", + "test:e2e": "madrun test:e2e", + "test:client": "madrun test:client", + "test:server": "madrun test:server", + "wisdom": "madrun wisdom", + "wisdom:type": "madrun wisdom:type", + "coverage": "madrun coverage", + "coverage:report": "madrun coverage:report", + "report": "madrun report", + "6to5": "madrun 6to5", + "6to5:client": "madrun 6to5:client", + "6to5:client:dev": "madrun 6to5:client:dev", + "watch:client": "madrun watch:client", + "watch:client:dev": "madrun watch:client:dev", + "watch:server": "madrun watch:server", + "watch:test": "madrun watch:test", + "watch:test:client": "madrun watch:test:client", + "watch:test:server": "madrun watch:test:server", + "watch:coverage": "madrun watch:coverage", + "watch:fix:lint": "madrun watch:fix:lint", + "build": "madrun build", + "build:dev": "madrun build:dev", + "build:client": "madrun build:client", + "build:client:dev": "madrun build:client:dev", + "heroku-postbuild": "madrun heroku-postbuild" }, "directories": { "man": "man" }, "subdomain": "cloudcmd", "dependencies": { - "@cloudcmd/fileop": "^2.0.0", - "@cloudcmd/move-files": "^2.0.1", + "@cloudcmd/dropbox": "^5.0.1", + "@cloudcmd/fileop": "^9.0.7", + "@cloudcmd/move-files": "^8.0.0", "@cloudcmd/read-files-sync": "^2.0.0", + "@putout/cli-validate-args": "^2.0.0", + "@putout/plugin-cloudcmd": "^5.2.0", + "aleman": "^2.0.1", "apart": "^2.0.0", - "chalk": "^2.0.1", - "console-io": "^10.0.0", - "copymitter": "^4.0.2", - "criton": "^1.0.0", - "currify": "^3.0.0", - "deepmerge": "^2.0.0", - "deepword": "^5.0.0", - "dword": "^9.0.0", - "edward": "^9.0.0", + "chalk": "^5.3.0", + "compression": "^1.7.4", + "console-io": "^15.0.1", + "copymitter": "^10.3.0", + "criton": "^2.0.0", + "currify": "^4.0.0", + "deepmerge": "^4.0.0", + "deepword": "^11.0.0", + "dword": "^16.0.0", + "edward": "^16.0.0", + "es6-promisify": "^7.0.0", "execon": "^1.2.0", - "express": "^4.13.0", - "files-io": "^3.0.0", - "flop": "^6.0.0", - "for-each-key": "^1.0.1", - "format-io": "^1.0.0", - "fullstore": "^1.0.0", - "http-auth": "^3.2.3", - "inly": "^3.0.0", - "jaguar": "^5.0.0", + "express": "^5.1.0", + "express-rate-limit": "^8.5.2", + "files-io": "^4.0.0", + "find-up": "^8.0.0", + "for-each-key": "^2.0.0", + "format-io": "^2.0.0", + "fullstore": "^4.0.0", + "http-auth": "^4.2.1", + "inly": "^5.0.0", + "jaguar": "^6.0.0", "jju": "^1.3.0", - "jonny": "^2.0.3", - "markdown-it": "^8.0.0", - "mellow": "^2.0.0", - "minimist": "^1.2.0", - "nomine": "^3.0.0", - "object.omit": "^3.0.0", - "onezip": "^3.0.0", - "opn": "^5.1.0", - "package-json": "^5.0.0", - "ponse": "^3.0.0", - "pullout": "^2.0.0", - "rendy": "^2.0.0", - "restafary": "^5.0.0", - "shortdate": "^1.2.0", - "socket.io": "^2.0.3", - "socket.io-client": "^2.1.1", + "jonny": "^3.0.0", + "just-snake-case": "^3.2.0", + "markdown-it": "^14.0.0", + "mellow": "^3.0.0", + "mime-types": "^3.0.1", + "montag": "^2.0.1", + "nano-memoize": "^3.0.16", + "nomine": "^4.0.0", + "once": "^1.4.0", + "onezip": "^7.0.0", + "open": "^11.0.0", + "package-json": "^10.0.0", + "pipe-io": "^4.0.1", + "ponse": "^8.0.0", + "pullout": "^5.0.0", + "putout": "^42.0.5", + "qword": "^1.0.0", + "redzip": "^4.6.1", + "rendy": "^5.0.0", + "restafary": "^13.0.1", + "restbox": "^4.0.0", + "shortdate": "^2.0.0", + "socket.io": "^4.0.0", + "socket.io-client": "^4.0.1", "squad": "^3.0.0", - "table": "^5.0.2", - "try-catch": "^2.0.0", - "try-to-catch": "^1.0.2", - "tryrequire": "^2.0.1", - "wraptile": "^2.0.0", - "writejson": "^2.0.0" + "table": "^6.0.1", + "try-catch": "^4.0.4", + "try-to-catch": "^4.0.0", + "tryrequire": "^3.0.0", + "win32": "^8.0.0", + "wraptile": "^3.0.0", + "writejson": "^3.0.0", + "yargs-parser": "^22.0.0" }, "devDependencies": { - "@babel/core": "^7.0.0", - "@babel/plugin-proposal-object-rest-spread": "^7.0.0", - "@babel/plugin-syntax-dynamic-import": "^7.0.0", - "@babel/plugin-transform-object-assign": "^7.0.0", - "@babel/preset-env": "^7.0.0", - "@cloudcmd/clipboard": "^1.0.2", - "@cloudcmd/create-element": "^1.0.0", - "@cloudcmd/modal": "^1.0.0", - "@cloudcmd/olark": "^2.0.1", - "babel-loader": "^8.0.0", - "babel-plugin-macros": "^2.2.1", - "clean-css-loader": "^1.0.1", - "clear-module": "^3.0.0", - "codegen.macro": "^3.0.0", - "coveralls": "^3.0.0", - "css-loader": "^1.0.0", + "@babel/code-frame": "^8.0.0", + "@babel/core": "^8.0.1", + "@babel/plugin-transform-optional-chaining": "^8.0.1", + "@babel/preset-env": "^8.0.2", + "@cloudcmd/clipboard": "^2.0.0", + "@cloudcmd/create-element": "^2.0.0", + "@cloudcmd/modal": "^4.0.0", + "@cloudcmd/olark": "^3.0.2", + "@cloudcmd/stub": "^5.0.0", + "@iocmd/wait": "^2.1.0", + "@putout/eslint-flat": "^4.0.0", + "@rspack/cli": "^2.1.4", + "@rspack/core": "^2.1.4", + "@supertape/loader-css": "^1.0.0", + "@types/node-fetch": "^2.6.11", + "auto-globals": "^4.0.0", + "babel-loader": "^10.0.0", + "babel-plugin-macros": "^3.0.0", + "cheerio": "^1.0.0-rc.5", + "clean-css-loader": "^4.2.1", + "codegen.macro": "^4.0.0", + "css-loader": "^7.1.2", + "css-modules-require-hook": "^4.2.3", + "cssnano-preset-default": "^8.0.1", "domtokenlist-shim": "^1.2.0", - "emitify": "^3.0.2", - "es6-promise": "^4.0.5", - "es6-promisify": "^6.0.0", - "eslint": "^5.0.0", - "eslint-plugin-node": "^7.0.0", - "extract-text-webpack-plugin": "^4.0.0-alpha.0", - "fast-async": "^7.0.6", - "file-loader": "^2.0.0", - "gritty": "^4.0.0", + "emitify": "^4.0.1", + "eslint": "^10.0.0", + "eslint-plugin-putout": "^31.0.0", + "globals": "^17.0.0", + "gritty": "^10.2.0", "gunzip-maybe": "^1.3.1", - "html-looks-like": "^1.0.2", - "html-webpack-plugin": "^3.0.7", + "html-webpack-plugin": "^5.6.3", "inherits": "^2.0.3", - "limier": "^2.0.0", - "load.js": "^2.0.0", - "memfs": "^2.9.0", + "itype": "^3.0.1", + "just-capitalize": "^3.2.0", + "just-pascal-case": "^3.2.0", + "limier": "^3.0.0", + "load.js": "^3.0.0", + "madrun": "^13.0.0", + "memfs": "^4.2.0", "minor": "^1.2.2", - "mkdirp": "^0.5.1", - "mock-require": "^3.0.1", "morgan": "^1.6.1", - "nodemon": "^1.9.1", - "nyc": "^13.0.1", - "optimize-css-assets-webpack-plugin": "^5.0.0", - "philip": "^2.0.0", + "multi-rename": "^3.0.0", + "nodemon": "^3.0.1", + "path-browserify": "^1.0.1", + "philip": "^3.0.0", "place": "^1.1.4", - "readjson": "^1.1.3", - "redrun": "^7.0.0", + "postcss": "^8.5.3", + "process": "^0.11.10", + "readjson": "^2.0.1", + "redlint": "^6.0.0", "request": "^2.76.0", - "rimraf": "^2.5.4", - "scroll-into-view-if-needed": "^2.2.5", - "serviceworker-webpack-plugin": "^1.0.1", - "sinon": "^7.0.0", - "sinon-called-with-diff": "^2.0.0", - "smalltalk": "^3.1.0", - "style-loader": "^0.23.0", - "stylelint": "^9.0.0", - "stylelint-config-standard": "^18.0.0", - "supermenu": "^2.1.2", - "tape": "^4.4.0", - "tar-stream": "^1.5.2", - "unionfs": "^3.0.2", - "url-loader": "^1.0.1", - "version-io": "^2.0.1", - "webpack": "^4.0.0", - "webpack-cli": "^3.0.1", - "webpack-merge": "^4.1.2", - "yaspeller": "^5.0.0" + "rimraf": "^6.0.1", + "scroll-into-view-if-needed": "^3.0.4", + "serve-once": "^4.0.1", + "smalltalk": "^5.0.0", + "style-loader": "^4.0.0", + "superc8": "^12.6.0", + "supermenu": "^5.0.0", + "supertape": "^13.0.0", + "tar-stream": "^3.0.0", + "unionfs": "^4.0.0", + "url-loader": "^4.0.0", + "util": "^0.12.5", + "webpack-merge": "^6.0.1" + }, + "imports": { + "#css/": "./css/", + "#dom": "./client/dom/index.js", + "#dom/events": "./client/dom/events/index.js", + "#dom/load": "./client/dom/load.js", + "#dom/dialog": "./client/dom/dialog.js", + "#dom/images": "./client/dom/images.js", + "#dom/files": "./client/dom/files.js", + "#dom/upload-files": "./client/dom/upload-files.js", + "#dom/storage": "./client/dom/storage.js", + "#dom/rest": "./client/dom/rest.js", + "#common/util": "./common/util.js", + "#common/omit": "./common/omit.js", + "#common/cloudfunc": "./common/cloudfunc.js", + "#common/entity": "./common/entity.js", + "#server/cloudcmd": "./server/cloudcmd.js" }, "engines": { - "node": ">=8.3.0" + "node": ">=22" }, "license": "MIT", - "main": "server/cloudcmd.js" + "publishConfig": { + "access": "public" + } } diff --git a/robots.txt b/robots.txt new file mode 100644 index 00000000..1f53798b --- /dev/null +++ b/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: / diff --git a/rspack.config.js b/rspack.config.js new file mode 100644 index 00000000..5dcb033d --- /dev/null +++ b/rspack.config.js @@ -0,0 +1,10 @@ +import {merge} from 'webpack-merge'; +import * as htmlConfig from './.rspack/html.js'; +import cssConfig from './.rspack/css.js'; +import jsConfig from './.rspack/js.js'; + +export default merge([ + jsConfig, + htmlConfig, + cssConfig, +]); diff --git a/rules/split-autoglobals-with-tape.js b/rules/split-autoglobals-with-tape.js new file mode 100644 index 00000000..5c3c3eb2 --- /dev/null +++ b/rules/split-autoglobals-with-tape.js @@ -0,0 +1,8 @@ +export const report = () => `Use 'if condition' instead of 'ternary expression'`; + +export const replace = () => ({ + 'const test = autoGlobals(require("supertape"))': `{ + const {test: tape} = require('supertape'); + const test = autoGlobals(tape); + }`, +}); diff --git a/server/auth.js b/server/auth.js index 39e30d73..09da0c2a 100644 --- a/server/auth.js +++ b/server/auth.js @@ -1,31 +1,31 @@ -'use strict'; +import httpAuth from 'http-auth'; +import criton from 'criton'; +import currify from 'currify'; -const httpAuth = require('http-auth'); -const criton = require('criton'); -const currify = require('currify'); const middle = currify(_middle); +const check = currify(_check); -const config = require('./config'); - -module.exports = () => { +export default (config) => { const auth = httpAuth.basic({ - realm: 'Cloud Commander' - }, check); + realm: 'Cloud Commander', + }, check(config)); - return middle(auth); + return middle(config, auth); }; -function _middle(authentication, req, res, next) { +function _middle(config, authentication, req, res, next) { const is = config('auth'); + const {originalUrl} = req; - if (!is) + if (!is || originalUrl.startsWith('/public/')) return next(); - const success = () => next(/* success */); - authentication.check(req, res, success); + const success = () => next(); + + return authentication.check(success)(req, res); } -function check(username, password, callback) { +function _check(config, username, password, callback) { const BAD_CREDENTIALS = false; const name = config('username'); const pass = config('password'); @@ -39,4 +39,3 @@ function check(username, password, callback) { callback(sameName && samePass); } - diff --git a/server/cloudcmd.js b/server/cloudcmd.js index a05da3f5..2e751520 100644 --- a/server/cloudcmd.js +++ b/server/cloudcmd.js @@ -1,105 +1,127 @@ -'use strict'; +import path, {dirname, join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import process from 'node:process'; +import fs from 'node:fs'; +import {fullstore} from 'fullstore'; +import currify from 'currify'; +import apart from 'apart'; +import * as ponse from 'ponse'; +import {restafary} from 'restafary'; +import restbox from 'restbox'; +import {konsole} from 'console-io'; +import {edward} from 'edward'; +import {dword} from 'dword'; +import {deepword} from 'deepword'; +import {qword} from 'qword'; +import nomine from 'nomine'; +import {fileop} from '@cloudcmd/fileop'; +import * as cloudfunc from '#common/cloudfunc'; +import authentication from './auth.js'; +import {createConfig, configPath} from './config.js'; +import modulas from './modulas.js'; +import {userMenu} from './user-menu.js'; +import rest from './rest/index.js'; +import route from './route.js'; +import * as validate from './validate.js'; +import prefixer from './prefixer.js'; +import terminal from './terminal.js'; +import {distributeExport} from './distribute/export.js'; +import {createDepStore} from './depstore.js'; -const DIR = __dirname + '/'; -const DIR_ROOT = DIR + '../'; -const DIR_COMMON = DIR + '../common/'; - -const path = require('path'); -const fs = require('fs'); - -const cloudfunc = require(DIR_COMMON + 'cloudfunc'); -const authentication = require(DIR + 'auth'); -const config = require(DIR + 'config'); -const modulas = require(DIR + 'modulas'); -const rest = require(DIR + 'rest'); -const route = require(DIR + 'route'); -const validate = require(DIR + 'validate'); -const prefixer = require(DIR + 'prefixer'); -const pluginer = require(DIR + 'plugins'); -const terminal = require(DIR + 'terminal'); -const distribute = require(DIR + 'distribute'); - -const currify = require('currify'); -const apart = require('apart'); -const ponse = require('ponse'); -const restafary = require('restafary'); -const konsole = require('console-io'); -const edward = require('edward'); -const dword = require('dword'); -const deepword = require('deepword'); -const nomine = require('nomine'); -const fileop = require('@cloudcmd/fileop'); - -const isDev = process.env.NODE_ENV === 'development'; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const {assign} = Object; +const DIR = `${__dirname}/`; +const DIR_ROOT = join(DIR, '..'); const getDist = (isDev) => isDev ? 'dist-dev' : 'dist'; +const isDev = fullstore(process.env.NODE_ENV === 'development'); + const getIndexPath = (isDev) => path.join(DIR, '..', `${getDist(isDev)}/index.html`); -const defaultHtml = fs.readFileSync(getIndexPath(isDev), 'utf8'); - -const auth = currify(_auth); -const root = () => config('root'); +const html = fs.readFileSync(getIndexPath(isDev()), 'utf8'); +const initAuth = currify(_initAuth); const notEmpty = (a) => a; const clean = (a) => a.filter(notEmpty); -module.exports = (params) => { +const isUndefined = (a) => typeof a === 'undefined'; +const isFn = (a) => typeof a === 'function'; + +export default cloudcmd; + +export function cloudcmd(params) { const p = params || {}; const options = p.config || {}; - const { - modules, - plugins, - } = p; + const config = p.configManager || createConfig({ + configPath, + }); + + const {modules} = p; const keys = Object.keys(options); - checkPlugins(plugins); - - keys.forEach((name) => { + for (const name of keys) { let value = options[name]; - if (/root|editor|packer|columns/.test(name)) + if (/root/.test(name)) + validate.root(value, config); + + if (/editor|packer|themes|menu/.test(name)) validate[name](value); - + if (/prefix/.test(name)) value = prefixer(value); config(name, value); - }); + } - config('console', defaultValue('console', options)); - config('configDialog', defaultValue('configDialog', options)); + config('console', defaultValue(config, 'console', options)); + config('configDialog', defaultValue(config, 'configDialog', options)); - const {prefix} = prefixer(options.prefix); - const prefixSocket = prefixer(options.prefixSocket) || prefix; // MAJOR: remove condition on v12 + const prefixSocket = prefixer(options.prefixSocket); if (p.socket) - listen(prefixSocket, p.socket); + listen({ + prefixSocket, + config, + socket: p.socket, + }); - return cloudcmd(prefix, plugins, modules); + return cloudcmdMiddle({ + modules, + config, + }); +} + +const depStore = createDepStore(); + +export const createConfigManager = createConfig; +export { + configPath, }; -module.exports._getIndexPath = getIndexPath; +export const _getIndexPath = getIndexPath; -function defaultValue(name, options) { +function defaultValue(config, name, options) { const value = options[name]; const previous = config(name); - if (typeof value === 'undefined') + if (isUndefined(value)) return previous; return value; } -module.exports._getPrefix = getPrefix; +export const _getPrefix = getPrefix; + function getPrefix(prefix) { - if (typeof prefix === 'function') + if (isFn(prefix)) return prefix() || ''; return prefix || ''; } -module.exports._auth = _auth; -function _auth(accept, reject, username, password) { +export function _initAuth(config, accept, reject, username, password) { if (!config('auth')) return accept(); @@ -112,111 +134,141 @@ function _auth(accept, reject, username, password) { reject(); } -function listen(prefixSocket, socket) { - prefixSocket = getPrefix(prefixSocket); +function listen({prefixSocket, socket, config}) { + const root = apart(config, 'root'); + const auth = initAuth(config); + prefixSocket = getPrefix(prefixSocket); config.listen(socket, auth); edward.listen(socket, { root, auth, - prefixSocket: prefixSocket + '/edward', + prefixSocket: `${prefixSocket}/edward`, }); dword.listen(socket, { root, auth, - prefixSocket: prefixSocket + '/dword', + prefixSocket: `${prefixSocket}/dword`, + }); + + qword.listen(socket, { + root, + auth, + prefixSocket: `${prefixSocket}/qword`, }); deepword.listen(socket, { root, auth, - prefixSocket: prefixSocket + '/deepword', + prefixSocket: `${prefixSocket}/deepword`, }); config('console') && konsole.listen(socket, { auth, - prefixSocket: prefixSocket + '/console', + prefixSocket: `${prefixSocket}/console`, }); fileop.listen(socket, { root, auth, - prefix: prefixSocket + '/fileop', + prefix: `${prefixSocket}/fileop`, }); - config('terminal') && terminal().listen(socket, { + config('terminal') && terminal(config).listen(socket, { auth, - prefix: prefixSocket + '/gritty', + prefix: `${prefixSocket}/gritty`, command: config('terminalCommand'), autoRestart: config('terminalAutoRestart'), }); - distribute.export(socket); + distributeExport(config, socket); } -function cloudcmd(prefix, plugins, modules) { +function cloudcmdMiddle({modules, config}) { const online = apart(config, 'online'); const cache = false; const diff = apart(config, 'diff'); const zip = apart(config, 'zip'); - const dir = DIR_ROOT; + const root = apart(config, 'root'); + + const ponseStatic = ponse.createStatic({ + cache, + root: DIR_ROOT, + }); + + const dropbox = config('dropbox'); + const dropboxToken = config('dropboxToken'); - const ponseStatic = ponse.static(dir, {cache}); - const funcs = clean([ config('console') && konsole({ online, }), - - config('terminal') && terminal({ - }), - + config('terminal') && terminal(config, {}), edward({ + root, online, diff, zip, + dropbox, + dropboxToken, }), - dword({ + root, online, diff, zip, + dropbox, + dropboxToken, + }), + qword({ + root, + online, + diff, + zip, + dropbox, + dropboxToken, }), - deepword({ + root, online, diff, zip, + dropbox, + dropboxToken, }), - - fileop({ - }), - - nomine({ - }), - + fileop(), + nomine(), setUrl, setSW, logout, - authentication(), + authentication(config), config.middle, - modules && modulas(modules), - + config('dropbox') && restbox({ + prefix: cloudfunc.apiURL, + root, + token: dropboxToken, + }), restafary({ prefix: cloudfunc.apiURL + '/fs', - root + root, }), - - rest, - route({ - html: defaultHtml + userMenu({ + menuName: '.cloudcmd.menu.js', + config, }), - - pluginer(plugins), - ponseStatic + rest({ + config, + fs: depStore('fs'), + moveFiles: depStore('moveFiles'), + }), + route(config, { + html, + win32: depStore('win32'), + }), + ponseStatic, ]); return funcs; @@ -229,9 +281,11 @@ function logout(req, res, next) { res.sendStatus(401); } -module.exports._replaceDist = replaceDist; +export const _isDev = isDev; +export const _replaceDist = replaceDist; + function replaceDist(url) { - if (!isDev) + if (!isDev()) return url; return url.replace(/^\/dist\//, '/dist-dev/'); @@ -248,19 +302,17 @@ function setUrl(req, res, next) { function setSW(req, res, next) { const {url} = req; - const isSW = /^\/sw\.js(\.map)?$/.test(url); + const isSW = /^\/sw\.[mc]?js(\.map)?$/.test(url); - if (isSW) + if (isSW) { + const url = req.url.replace(/[cm]js/, 'js'); req.url = replaceDist(`/dist${url}`); + } next(); } -function checkPlugins(plugins) { - if (typeof plugins === 'undefined') - return; - - if (!Array.isArray(plugins)) - throw Error('plugins should be an array!'); -} - +assign(cloudcmd, { + depStore, + createConfigManager, +}); diff --git a/server/cloudcmd.spec.js b/server/cloudcmd.spec.js new file mode 100644 index 00000000..d79aa4c1 --- /dev/null +++ b/server/cloudcmd.spec.js @@ -0,0 +1,247 @@ +import path, {dirname} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {serveOnce} from 'serve-once'; +import {test, stub} from 'supertape'; +import cloudcmd, { + _isDev, + _replaceDist, + createConfigManager, + _getPrefix, + _initAuth, + _getIndexPath, +} from '#server/cloudcmd'; +import {connect} from '../test/before.js'; + +const noop = () => {}; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const {request} = serveOnce(cloudcmd, { + config: { + auth: false, + dropbox: false, + }, +}); + +test('cloudcmd: defaults: config', (t) => { + const configManager = createConfigManager(); + + configManager('configDialog', false); + + cloudcmd({ + configManager, + }); + + t.notOk(configManager('configDialog'), 'should not override config with defaults'); + t.end(); +}); + +test('cloudcmd: defaults: console', (t) => { + const configManager = createConfigManager(); + configManager('console', false); + + cloudcmd({ + configManager, + }); + + t.notOk(configManager('console'), 'should not override config with defaults'); + t.end(); +}); + +test('cloudcmd: getPrefix', (t) => { + const value = 'hello'; + const result = _getPrefix(value); + + t.equal(result, value); + t.end(); +}); + +test('cloudcmd: getPrefix: function', (t) => { + const value = 'hello'; + const fn = () => value; + const result = _getPrefix(fn); + + t.equal(result, value); + t.end(); +}); + +test('cloudcmd: getPrefix: function: empty', (t) => { + const value = null; + const fn = () => value; + const result = _getPrefix(fn); + + t.equal(result, ''); + t.end(); +}); + +test('cloudcmd: replaceDist', (t) => { + const currentIsDev = _isDev(); + + _isDev(true); + const url = '/dist/hello'; + const result = _replaceDist(url); + const expected = '/dist-dev/hello'; + + _isDev(currentIsDev); + + t.equal(result, expected); + t.end(); +}); + +test('cloudcmd: replaceDist: !isDev', (t) => { + const url = '/dist/hello'; + + const currentIsDev = _isDev(); + _isDev(false); + const result = _replaceDist(url); + + _isDev(currentIsDev); + + t.equal(result, url); + t.end(); +}); + +test('cloudcmd: auth: reject', (t) => { + const accept = stub(); + const reject = stub(); + + const config = createConfigManager(); + + const username = 'root'; + const password = 'toor'; + + config('auth', true); + config('username', username); + config('password', password); + + _initAuth(config, accept, reject, username, 'abc'); + + t.ok(reject.called, 'should reject'); + t.end(); +}); + +test('cloudcmd: auth: accept', (t) => { + const accept = stub(); + const reject = stub(); + + const username = 'root'; + const password = 'toor'; + const auth = true; + + const config = createConfigManager(); + config('username', username); + config('password', password); + config('auth', auth); + + _initAuth(config, accept, reject, username, password); + + t.ok(accept.called, 'should accept'); + t.end(); +}); + +test('cloudcmd: auth: accept: no auth', (t) => { + const accept = stub(); + const reject = stub(); + + const auth = false; + const username = 'root'; + const password = 'toor'; + + const config = createConfigManager(); + config('username', username); + config('password', password); + config('auth', auth); + + _initAuth(config, accept, reject, username, password); + + t.ok(accept.called, 'should accept'); + t.end(); +}); + +test('cloudcmd: getIndexPath: production', (t) => { + const isDev = false; + + const result = _getIndexPath(isDev); + const expected = path.join(__dirname, '..', 'dist', 'index.html'); + + t.equal(result, expected); + t.end(); +}); + +test('cloudcmd: getIndexPath: development', (t) => { + const isDev = true; + const result = _getIndexPath(isDev); + const expected = path.join(__dirname, '..', 'dist-dev', 'index.html'); + + t.equal(result, expected); + t.end(); +}); + +test('cloudcmd: sw', async (t) => { + const {status} = await request.get('/sw.mjs'); + + t.equal(status, 200, 'should return sw'); + t.end(); +}); + +test('cloudcmd: no params', (t) => { + const middle = cloudcmd(); + + t.ok(Array.isArray(middle), 'should return middleware list when no params passed'); + t.end(); +}); + +test('cloudcmd: listen: terminal', async (t) => { + const {done} = await connect({ + config: { + terminal: true, + }, + }); + + await done(); + + t.pass('should listen with terminal enabled'); + t.end(); +}); + +test('cloudcmd: middle: dropbox', async (t) => { + const {port, done} = await connect({ + config: { + dropbox: true, + dropboxToken: 'hello', + }, + }); + + const response = await fetch(`http://localhost:${port}/api/v1/dropbox/nonexistent`); + + await done(); + + t.ok(response.status, 'should mount dropbox route'); + t.end(); +}); + +test('cloudcmd: logout', async (t) => { + const {status} = await request.get('/logout'); + + t.equal(status, 401, 'should return 401 for /logout'); + t.end(); +}); + +test('cloudcmd: modules', (t) => { + const middle = cloudcmd({ + modules: { + hello: noop, + }, + }); + + t.ok(Array.isArray(middle), 'should return middleware list with modules'); + t.end(); +}); + +test('cloudcmd: setUrl: cloudcmd.js', async (t) => { + const {status} = await request.get('/cloudcmd.js'); + + t.equal(status, 200, 'should serve cloudcmd.js'); + t.end(); +}); diff --git a/server/columns.js b/server/columns.js index d6f2b952..eff63957 100644 --- a/server/columns.js +++ b/server/columns.js @@ -1,9 +1,16 @@ -'use strict'; +import path, {dirname} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import process from 'node:process'; +import fs from 'node:fs'; +import {fullstore} from 'fullstore'; +import * as nanomemoizeDefault from 'nano-memoize'; +import readFilesSync from '@cloudcmd/read-files-sync'; -const path = require('path'); -const fs= require('fs'); -const readFilesSync = require('@cloudcmd/read-files-sync'); -const isMap = (a) => /\.map$/.test(a); +const nanomemoize = nanomemoizeDefault.default.nanomemoize || nanomemoizeDefault.default; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const isMap = (a) => /\.(map|js)$/.test(a); const not = (fn) => (a) => !fn(a); const defaultColumns = { @@ -11,19 +18,27 @@ const defaultColumns = { 'name-size-date-owner-mode': '', }; -const isDev = process.env.NODE_ENV === 'development'; +const _isDev = fullstore(process.env.NODE_ENV === 'development'); const getDist = (isDev) => isDev ? 'dist-dev' : 'dist'; -const dist = getDist(isDev); -const columnsDir = path.join(__dirname, '..', dist, 'columns'); +export const isDev = _isDev; -const names = fs.readdirSync(columnsDir) - .filter(not(isMap)); - -const columns = readFilesSync(columnsDir, names, 'utf8'); - -module.exports = { - ...columns, - ...defaultColumns, +export const getColumns = ({isDev = _isDev()} = {}) => { + const columns = readFilesSyncMemo(isDev); + + return { + ...columns, + ...defaultColumns, + }; }; +const readFilesSyncMemo = nanomemoize((isDev) => { + const dist = getDist(isDev); + const columnsDir = path.join(__dirname, '..', dist, 'columns'); + + const names = fs + .readdirSync(columnsDir) + .filter(not(isMap)); + + return readFilesSync(columnsDir, names, 'utf8'); +}); diff --git a/server/columns.spec.js b/server/columns.spec.js new file mode 100644 index 00000000..533cfe75 --- /dev/null +++ b/server/columns.spec.js @@ -0,0 +1,40 @@ +import {dirname} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import fs from 'node:fs'; +import test from 'supertape'; +import {getColumns, isDev} from './columns.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +test('columns: prod', (t) => { + const columns = getColumns({ + isDev: false, + }); + + t.equal(columns[''], ''); + t.end(); +}); + +test('columns: dev', (t) => { + const columns = getColumns({ + isDev: true, + }); + + const css = fs.readFileSync(`${__dirname}/../css/columns/name-size-date.css`, 'utf8'); + + t.match(columns['name-size-date'], css); + t.end(); +}); + +test('columns: no args', (t) => { + const currentIsDev = isDev(); + isDev(true); + const columns = getColumns(); + + const css = fs.readFileSync(`${__dirname}/../css/columns/name-size-date.css`, 'utf8'); + isDev(currentIsDev); + + t.match(columns['name-size-date'], css); + t.end(); +}); diff --git a/server/config.js b/server/config.js index aae568e9..77c4a6af 100644 --- a/server/config.js +++ b/server/config.js @@ -1,121 +1,123 @@ -'use strict'; +import path from 'node:path'; +import fs from 'node:fs'; +import Emitter from 'node:events'; +import {homedir} from 'node:os'; +import currify from 'currify'; +import wraptile from 'wraptile'; +import {tryToCatch} from 'try-to-catch'; +import pullout from 'pullout'; +import * as ponse from 'ponse'; +import jonny from 'jonny'; +import jju from 'jju'; +import writejson from 'writejson'; +import {tryCatch} from 'try-catch'; +import criton from 'criton'; +import * as CloudFunc from '#common/cloudfunc'; +import exit from './exit.js'; +import rootConfig from '../json/config.json' with { + type: 'json', +}; -const DIR_SERVER = __dirname + '/'; -const DIR_COMMON = '../common/'; -const DIR = DIR_SERVER + '../'; +const isUndefined = (a) => typeof a === 'undefined'; -const path = require('path'); -const fs = require('fs'); -const Emitter = require('events'); -const {promisify} = require('util'); -const {homedir} = require('os'); - -const exit = require(DIR_SERVER + 'exit'); -const CloudFunc = require(DIR_COMMON + 'cloudfunc'); - -const currify = require('currify'); -const wraptile = require('wraptile'); -const squad = require('squad'); -const tryToCatch = require('try-to-catch'); -const pullout = promisify(require('pullout')); -const ponse = require('ponse'); -const jonny = require('jonny'); -const jju = require('jju'); -const writejson = require('writejson'); -const tryCatch = require('try-catch'); -const criton = require('criton'); const HOME = homedir(); -const manageConfig = squad(traverse, cryptoPass); -const save = promisify(_save); +const resolve = Promise.resolve.bind(Promise); const formatMsg = currify((a, b) => CloudFunc.formatMsg(a, b)); -const apiURL = CloudFunc.apiURL; -const changeEmitter = new Emitter(); +const {apiURL} = CloudFunc; -const ConfigPath = path.join(DIR, 'json/config.json'); -const ConfigHome = path.join(HOME, '.cloudcmd.json'); +const key = (a) => Object + .keys(a) + .pop(); + +const connection = currify(_connection); + +const connectionWrapped = wraptile(_connection); + +const middle = currify(_middle); const readjsonSync = (name) => { return jju.parse(fs.readFileSync(name, 'utf8'), { - mode: 'json' + mode: 'json', }); }; -const rootConfig = readjsonSync(ConfigPath); -const key = (a) => Object.keys(a).pop(); - -const [error, configHome] = tryCatch(readjsonSync, ConfigHome); - -if (error && error.code !== 'ENOENT') - exit(`cloudcmd --config ${ConfigHome}: ${error.message}`); - -const config = { - ...rootConfig, - ...configHome, -}; - -const connectionWraped = wraptile(connection); - -module.exports = manage; -module.exports.save = save; -module.exports.middle = middle; -module.exports.subscribe = (fn) => { - changeEmitter.on('change', fn); -}; - -module.exports.unsubscribe = (fn) => { - changeEmitter.removeListener('change', fn); -}; - -module.exports.listen = (socket, auth) => { - check(socket, auth); +function read(filename) { + if (!filename) + return rootConfig; + const [error, configHome] = tryCatch(readjsonSync, filename); + + if (error && error.code !== 'ENOENT') + exit(`cloudcmd --config ${filename}: ${error.message}`); + + return { + ...rootConfig, + ...configHome, + }; +} + +export const configPath = path.join(HOME, '.cloudcmd.json'); + +const manageListen = currify((manage, socket, auth) => { if (!manage('configDialog')) return middle; - listen(socket, auth); + listen(manage, socket, auth); return middle; +}); + +function initWrite(filename, configManager) { + if (filename) + return write.bind(null, filename, configManager); + + return resolve; +} + +export function createConfig({configPath} = {}) { + const config = {}; + const changeEmitter = new Emitter(); + + const configManager = (key, value) => { + if (key === '*') + return config; + + if (isUndefined(value)) + return config[key]; + + config[key] = value; + changeEmitter.emit('change', key, value); + + return `${key} = ${value}`; + }; + + Object.assign(config, read(configPath)); + + configManager.middle = middle(configManager); + configManager.listen = manageListen(configManager); + configManager.write = initWrite(configPath, configManager); + configManager.subscribe = (fn) => { + changeEmitter.on('change', fn); + }; + + configManager.unsubscribe = (fn) => { + changeEmitter.off('change', fn); + }; + + return configManager; +} + +const write = (filename, config) => { + return writejson(filename, config('*'), { + mode: 0o600, + }); }; -function manage(key, value) { - if (!key) - return; - - if (key === '*') - return config; - - if (value === undefined) - return config[key]; - - config[key] = value; - - changeEmitter.emit('change', key, value); - - return `${key} = ${value}`; -} - -function _save(callback) { - writejson(ConfigHome, config, {mode: 0o600}, callback); -} - -function listen(sock, auth) { - const prefix = manage('prefixSocket'); - - sock.of(prefix + '/config') - .on('connection', (socket) => { - if (!manage('auth')) - return connection(socket); - - const reject = () => socket.emit('reject'); - socket.on('auth', auth(connectionWraped(socket), reject)); - }); -} - -function connection(socket) { - socket.emit('config', config); +function _connection(manage, socket) { + socket.emit('config', manage('*')); const emit = currify((socket, name, e) => { return socket.emit(name, e.message); @@ -125,30 +127,44 @@ function connection(socket) { if (typeof json !== 'object') return socket.emit('err', 'Error: Wrong data type!'); - manageConfig(json); + traverse(cryptoPass(manage, json)); const send = () => { const data = CloudFunc.formatMsg('config', key(json)); - socket.broadcast.send(json); socket.send(json); socket.emit('log', data); }; - save() + manage + .write() .then(send) .catch(emit(socket, 'err')); }); } -function middle(req, res, next) { +function listen(manage, sock, auth) { + const prefix = manage('prefixSocket'); + + sock + .of(`${prefix}/config`) + .on('connection', (socket) => { + if (!manage('auth')) + return connection(manage, socket); + + const reject = () => socket.emit('reject'); + socket.on('auth', auth(connectionWrapped(manage, socket), reject)); + }); +} + +async function _middle(manage, req, res, next) { const noConfigDialog = !manage('configDialog'); if (req.url !== `${apiURL}/config`) return next(); - + switch(req.method) { case 'GET': - get(req, res, next); + get(manage, req, res); break; case 'PATCH': @@ -156,8 +172,8 @@ function middle(req, res, next) { return res .status(404) .send('Config is disabled'); - - patch(req, res); + + await patch(manage, req, res); break; default: @@ -165,20 +181,21 @@ function middle(req, res, next) { } } -function get(request, response) { - const data = jonny.stringify(config); +function get(manage, request, response) { + const data = jonny.stringify(manage('*')); ponse.send(data, { - name : 'config.json', + name: 'config.json', request, response, - cache : false + cache: false, }); } -async function patch(request, response) { +async function patch(manage, request, response) { const name = 'config.json'; const cache = false; + const options = { name, request, @@ -186,18 +203,18 @@ async function patch(request, response) { cache, }; - const [e] = await tryToCatch(patchConfig, options); + const [e] = await tryToCatch(patchConfig, manage, options); if (e) ponse.sendError(e, options); } -async function patchConfig({name, request, response, cache}) { - const str = await pullout(request, 'string'); +async function patchConfig(manage, {name, request, response, cache}) { + const str = await pullout(request); const json = jonny.parse(str); - manageConfig(json); - await save(); + traverse(cryptoPass(manage, json)); + await manage.write(); const msg = formatMsg('config', key(json)); ponse.send(msg, { @@ -208,32 +225,26 @@ async function patchConfig({name, request, response, cache}) { }); } -function traverse(json) { - Object.keys(json).forEach((name) => { +function traverse([manage, json]) { + for (const name of Object.keys(json)) { manage(name, json[name]); - }); + } } -module.exports._cryptoPass = cryptoPass; -function cryptoPass(json) { +export const _cryptoPass = cryptoPass; + +function cryptoPass(manage, json) { const algo = manage('algo'); if (!json.password) - return json; + return [manage, json]; const password = criton(json.password, algo); - return { - ...json, - password, - }; + return [ + manage, { + ...json, + password, + }, + ]; } - -function check(socket, auth) { - if (!socket) - throw Error('socket could not be empty!'); - - if (auth && typeof auth !== 'function') - throw Error('auth should be function!'); -} - diff --git a/server/config.spec.js b/server/config.spec.js index bf5343b7..92b0646c 100644 --- a/server/config.spec.js +++ b/server/config.spec.js @@ -1,26 +1,13 @@ -'use strict'; +import {createRequire} from 'node:module'; +import {test, stub} from 'supertape'; +import {apiURL} from '#common/cloudfunc'; +import {createConfig, _cryptoPass} from './config.js'; +import {connect} from '../test/before.js'; -const os = require('os'); -const path = require('path'); +const require = createRequire(import.meta.url); +const fixture = require('./config.fixture.json'); -const test = require('tape'); -const readjson = require('readjson'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); - -const root = '../'; -const dir = './'; -const configPath = './config'; - -const config = require(configPath); -const {_cryptoPass} = config; -const {apiURL} = require(root + 'common/cloudfunc'); - -const pathHomeConfig = path.join(os.homedir(), '.cloudcmd.json'); -const pathConfig = path.join(__dirname, '..', 'json', 'config.json'); - -const fixture = require('./config.fixture'); -const {connect} = require('../test/before'); +const config = createConfig(); test('config: manage', (t) => { t.equal(undefined, config(), 'should return "undefined"'); @@ -29,24 +16,30 @@ test('config: manage', (t) => { test('config: manage: get', async (t) => { const editor = 'deepword'; + const configManager = createConfig(); const {done} = await connect({ - config: {editor} + config: { + editor, + }, + configManager, }); done(); - t.equal(config('editor'), editor, 'should get config'); + t.equal(configManager('editor'), editor, 'should get config'); t.end(); }); -test('config: manage: get', async (t) => { +test('config: manage: get: config', async (t) => { const editor = 'deepword'; const conf = { - editor + editor, }; - const {done} = await connect({config: conf}); + const {done} = await connect({ + config: conf, + }); config('editor', 'dword'); done(); @@ -63,27 +56,15 @@ test('config: manage: get: *', (t) => { t.end(); }); -test('config: listen: no socket', (t) => { - t.throws(config.listen, 'should throw when no socket'); - t.end(); -}); - -test('config: listen: authCheck: not function', (t) => { - const socket = {}; - const fn = () => config.listen(socket, 'hello'); - - t.throws(fn, 'should throw when authCheck not function'); - t.end(); -}); - test('config: cryptoPass: no password', (t) => { const json = { hello: 'world', }; - const result = _cryptoPass(json); + const config = createConfig(); + const result = _cryptoPass(config, json); - t.equal(result, json, 'should not change json'); + t.deepEqual(result, [config, json], 'should not change json'); t.end(); }); @@ -98,25 +79,27 @@ test('config: cryptoPass', (t) => { password, }; - const result = _cryptoPass(json); + const config = createConfig(); + const result = _cryptoPass(config, json); - t.deepEqual(result, expected, 'should crypt password'); + t.deepEqual(result, [config, expected], 'should crypt password'); t.end(); }); test('config: middle: no', (t) => { const {middle} = config; - const next = sinon.stub(); + const next = stub(); const res = null; const url = `${apiURL}/config`; const method = 'POST'; + const req = { url, - method + method, }; middle(req, res, next); - t.ok(next.calledWith(), 'should call next'); + + t.calledWithNoArgs(next, 'should call next'); t.end(); }); - diff --git a/server/depstore.js b/server/depstore.js new file mode 100644 index 00000000..c5fefaa9 --- /dev/null +++ b/server/depstore.js @@ -0,0 +1,13 @@ +export const createDepStore = () => { + const deps = {}; + + return (name, value) => { + if (!name) + return false; + + if (!value) + return deps[name]; + + deps[name] = value; + }; +}; diff --git a/server/distribute/export.js b/server/distribute/export.js index bebe8905..5e1b54d4 100644 --- a/server/distribute/export.js +++ b/server/distribute/export.js @@ -1,22 +1,17 @@ -'use strict'; - -const currify = require('currify'); -const wraptile = require('wraptile'); -const squad = require('squad'); -const omit = require('object.omit'); - -const config = require('../config'); -const log = require('./log'); - -const exportStr = log.exportStr; -const connectedStr = log.connectedStr; -const disconnectedStr = log.disconnectedStr; -const authTryStr = log.authTryStr; - -const makeColor = log.makeColor; -const getMessage = log.getMessage; -const getDescription = log.getDescription; -const logWraped = log.logWraped; +import currify from 'currify'; +import wraptile from 'wraptile'; +import squad from 'squad'; +import {omit} from '#common/omit'; +import log, { + exportStr, + connectedStr, + disconnectedStr, + authTryStr, + makeColor, + getMessage, + getDescription, + logWrapped, +} from './log.js'; const omitList = [ 'auth', @@ -38,22 +33,21 @@ const omitList = [ const omitConfig = (config) => omit(config, omitList); -module.exports = (socket) => { +export const distributeExport = (config, socket) => { if (!config('export')) return; const prefix = config('prefix'); const distributePrefix = `${prefix}/distribute`; + const isLog = config('log'); - const onError = squad( - logWraped(exportStr), - getMessage, - ); + const onError = squad(logWrapped(isLog, exportStr), getMessage); - const onConnectError = squad(logWraped(exportStr), getDescription); + const onConnectError = squad(logWrapped(isLog, exportStr), getDescription); - socket.of(distributePrefix) - .on('connection', onConnection(push)) + socket + .of(distributePrefix) + .on('connection', onConnection(push, config)) .on('error', onError) .on('connect_error', onConnectError); }; @@ -66,10 +60,13 @@ const push = currify((socket, key, value) => { }); function getHost(socket) { - const remoteAddress = socket.request.connection.remoteAddress; - const name = socket.handshake.query.name; - const port = socket.handshake.query.port; - const color = socket.handshake.query.color; + const {remoteAddress} = socket.request.connection; + + const { + name, + port, + color, + } = socket.handshake.query; if (!name) return `${remoteAddress}:${port}`; @@ -79,41 +76,49 @@ function getHost(socket) { return `${colorName} [${remoteAddress}:${port}]`; } -const connectPush = wraptile((push, socket) => { +const connectPush = wraptile((push, config, socket) => { socket.emit('accept'); + const isLog = config('log'); const host = getHost(socket); const subscription = push(socket); - socket.on('disconnect', onDisconnect(subscription, host)); + socket.on('disconnect', onDisconnect( + subscription, + config, + host, + )); - log(exportStr, `${connectedStr} to ${host}`); + log(isLog, exportStr, `${connectedStr} to ${host}`); socket.emit('config', omitConfig(config('*'))); - log(exportStr, `config send to ${host}`); + log(isLog, exportStr, `config send to ${host}`); config.subscribe(subscription); }); -const onConnection = currify((push, socket) => { +const onConnection = currify((push, config, socket) => { const host = getHost(socket); const reject = () => { socket.emit('reject'); socket.disconnect(); }; - log(exportStr, `${authTryStr} from ${host}`); - socket.on('auth', auth(connectPush(push, socket), reject)); + const isLog = config('log'); + + log(isLog, exportStr, `${authTryStr} from ${host}`); + socket.on('auth', auth(config, reject, connectPush(push, config, socket))); }); -const auth = currify((fn, reject, token) => { +const auth = currify((config, reject, fn, token) => { if (token === config('exportToken')) return fn(); reject(); }); -const onDisconnect = wraptile((subscription, host) => { +const onDisconnect = wraptile((subscription, config, host) => { + const isLog = config('log'); + config.unsubscribe(subscription); - log(exportStr, `${disconnectedStr} from ${host}`); + log(isLog, exportStr, `${disconnectedStr} from ${host}`); }); - diff --git a/server/distribute/export.spec.js b/server/distribute/export.spec.js index 0d50061a..ca6155a8 100644 --- a/server/distribute/export.spec.js +++ b/server/distribute/export.spec.js @@ -1,12 +1,10 @@ -'use strict'; +import {once} from 'node:events'; +import test from 'supertape'; +import io from 'socket.io-client'; +import * as Config from '../config.js'; +import {connect} from '../../test/before.js'; -const {promisify} = require('util'); - -const test = require('tape'); -const io = require('socket.io-client'); - -const {connect} = require('../../test/before'); -const config = require('../config'); +const config = Config.createConfig(); test('distribute: export', async (t) => { const defaultConfig = { @@ -14,33 +12,31 @@ test('distribute: export', async (t) => { exportToken: 'a', vim: true, log: false, + prefix: '', }; const {port, done} = await connect({ - config: defaultConfig + config: defaultConfig, + configManager: config, }); - const url = `http://localhost:${port}/distribute?port=${1111}`; + const url = `http://localhost:${port}/distribute?port=1111`; const socket = io.connect(url); - const name = config('name'); + await once(socket, 'connect'); + socket.emit('auth', 'a'); - socket.on('connect', () => { - socket.emit('auth', 'a'); - }); + await once(socket, 'accept'); + config('vim', false); + config('auth', true); - socket.on('accept', () => { - config('vim', false); - config('auth', true); - }); + await once(socket, 'change'); - socket.on('change', async () => { - socket.close(); - await done(); - - t.pass('should emit change'); - t.end(); - }); + socket.close(); + await done(); + + t.pass('should emit change'); + t.end(); }); test('distribute: export: config', async (t) => { @@ -52,24 +48,21 @@ test('distribute: export: config', async (t) => { }; const {port, done} = await connect({ - config: defaultConfig + config: defaultConfig, }); - const url = `http://localhost:${port}/distribute?port=${1111}`; + const url = `http://localhost:${port}/distribute?port=1111`; const socket = io.connect(url); - const name = config('name'); - - socket.on('connect', () => { + socket.once('connect', () => { socket.emit('auth', 'a'); }); - socket.on('config', async (data) => { - socket.close(); - await done(); - - t.equal(typeof data, 'object', 'should emit object'); - t.end(); - }); + const data = await once(socket, 'config'); + + socket.close(); + await done(); + + t.equal(typeof data, 'object', 'should emit object'); + t.end(); }); - diff --git a/server/distribute/import.js b/server/distribute/import.js index 7888d5c5..f6cbe614 100644 --- a/server/distribute/import.js +++ b/server/distribute/import.js @@ -1,30 +1,33 @@ -'use strict'; +import currify from 'currify'; +import wraptile from 'wraptile'; +import squad from 'squad'; +import {fullstore} from 'fullstore'; +import io from 'socket.io-client'; +import _forEachKey from 'for-each-key'; +import log from './log.js'; +import * as env from '../env.js'; -const currify = require('currify'); -const wraptile = require('wraptile'); -const squad = require('squad'); -const fullstore = require('fullstore'); +const isUndefined = (a) => typeof a === 'undefined'; -const io = require('socket.io-client'); -const forEachKey = currify(require('for-each-key')); +const noop = () => {}; +const forEachKey = currify(_forEachKey); -const config = require('../config'); -const log = require('./log'); +const { + importStr, + connectedStr, + disconnectedStr, + tokenRejectedStr, + authTryStr, + getMessage, + getDescription, + logWrapped, +} = log; -const importStr = log.importStr; -const connectedStr = log.connectedStr; -const disconnectedStr = log.disconnectedStr; -const tokenRejectedStr = log.tokenRejectedStr; -const authTryStr = log.authTryStr; - -const makeColor = log.makeColor; -const stringToRGB = log.stringToRGB; -const getMessage = log.getMessage; -const getDescription = log.getDescription; -const logWraped = log.logWraped; +const {entries} = Object; const equal = (a, b) => `${a}=${b}`; const append = currify((obj, a, b) => obj.value += b && equal(a, b) + '&'); + const wrapApply = (f, disconnect) => (status) => () => f(null, { status, disconnect, @@ -33,35 +36,43 @@ const wrapApply = (f, disconnect) => (status) => () => f(null, { const closeIfNot = wraptile((socket, is) => !is && socket.close()); const addUrl = currify((url, a) => `${url}: ${a}`); -const getColorUrl = (url, name) => { - if (!name) - return url; - - return makeColor(url, stringToRGB(name)); -}; - const rmListeners = wraptile((socket, listeners) => { socket.removeListener('connect', listeners.onConnect); + socket.removeListener('accept', listeners.onAccept); socket.removeListener('config', listeners.onConfig); socket.removeListener('error', listeners.onError); - socket.removeListener('connection_error', listeners.onError); + socket.removeListener('connect_error', listeners.onConnectError); + socket.removeListener('reject', listeners.onReject); + + if (listeners.onChange) + socket.removeListener('change', listeners.onChange); }); const canceled = (f) => f(null, { status: 'canceled', - disconnect: () => {}, + disconnect: noop, }); const done = wraptile((fn, store) => fn(null, { - status: store() + status: store(), })); -const emitAuth = wraptile((importUrl, socket) => { - log(importStr, `${authTryStr} to ${importUrl}`); +const emitAuth = wraptile((importUrl, config, socket) => { + const isLog = config('log'); + log(isLog, importStr, `${authTryStr} to ${importUrl}`); socket.emit('auth', config('importToken')); }); -module.exports = (options, fn) => { +const updateConfig = currify((config, data) => { + for (const [key, value] of entries(data)) { + if (!isUndefined(env.parse(key))) + continue; + + config(key, value); + } +}); + +export const distributeImport = (config, options, fn) => { fn = fn || options; if (!config('import')) @@ -71,6 +82,7 @@ module.exports = (options, fn) => { const importListen = config('importListen'); const name = config('name'); const port = config('port'); + const isLog = config('log'); const query = toLine({ name, @@ -78,60 +90,48 @@ module.exports = (options, fn) => { }); const url = `${importUrl}/distribute?${query}`; + const socket = io.connect(url, { ...options, rejectUnauthorized: false, }); const superFn = wrapApply(fn, socket.close.bind(socket)); - const colorUrl = getColorUrl(importUrl, name); + const colorUrl = importUrl; const close = closeIfNot(socket, importListen); const statusStore = fullstore(); - const statusStoreWraped = wraptile(statusStore); + const statusStoreWrapped = wraptile(statusStore); - const onConfig = squad( - close, - logWraped(importStr, `config received from ${colorUrl}`), - statusStoreWraped('received'), - forEachKey(config), - ); + const onConfig = squad(close, logWrapped(isLog, importStr, `config received from ${colorUrl}`), statusStoreWrapped('received'), updateConfig(config)); - const onError = squad( - superFn('error'), - logWraped(importStr), - addUrl(colorUrl), - getMessage, - ); + const onError = squad(superFn('error'), logWrapped(isLog, config, importStr), addUrl(colorUrl), getMessage); - const onConnectError = squad( - superFn('connect_error'), - logWraped(importStr), - addUrl(colorUrl), - getDescription, - ); + const onConnectError = squad(superFn('connect_error'), logWrapped(isLog, importStr), addUrl(colorUrl), getDescription); - const onConnect = emitAuth(importUrl, socket); - const onAccept = logWraped(importStr,`${connectedStr} to ${colorUrl}`); - const onDisconnect = squad( + const onConnect = emitAuth(importUrl, config, socket); + const onAccept = logWrapped(isLog, importStr, `${connectedStr} to ${colorUrl}`); + const onChange = squad(logWrapped(isLog, importStr), config); + + const onReject = squad(superFn('reject'), logWrapped( + isLog, + importStr, + tokenRejectedStr, + )); + + const onDisconnect = squad(...[ done(fn, statusStore), - logWraped(importStr, `${disconnectedStr} from ${colorUrl}`), + logWrapped(isLog, importStr, `${disconnectedStr} from ${colorUrl}`), rmListeners(socket, { - onError, onConnect, + onAccept, onConfig, + onError, + onConnectError, + onReject, + onChange, }), - ); - - const onChange = squad( - logWraped(importStr), - config, - ); - - const onReject = squad( - superFn('reject'), - logWraped(importStr, tokenRejectedStr), - ); + ]); socket.on('connect', onConnect); socket.on('accept', onAccept); @@ -158,4 +158,3 @@ function toLine(obj) { return result.value.slice(start, backward * end); } - diff --git a/server/distribute/import.spec.js b/server/distribute/import.spec.js index f1ff761c..10e246be 100644 --- a/server/distribute/import.spec.js +++ b/server/distribute/import.spec.js @@ -1,33 +1,34 @@ -'use strict'; +import process from 'node:process'; +import {promisify} from 'node:util'; +import test from 'supertape'; +import {tryToCatch} from 'try-to-catch'; +import {createConfigManager} from '#server/cloudcmd'; +import {connect} from '../../test/before.js'; +import {distributeImport} from './import.js'; -const test = require('tape'); -const {promisify} = require('util'); -const tryToCatch = require('try-to-catch'); -const io = require('socket.io-client'); -const mockRequire = require('mock-require'); - -const {connect} = require('../../test/before'); - -const config = require('../config'); const distribute = { - import: promisify(require('./import')), + import: promisify(distributeImport), }; +const config = createConfigManager(); + +process.on('unhandledRejection', console.log); + test('distribute: import: canceled', async (t) => { - const {done, port} = await connect({ + const {done} = await connect({ config: { export: false, import: false, importListen: false, log: false, - } + }, }); - const {status} = await distribute.import(); + const {status} = await distribute.import(config); await done(); - t.equal(status, 'canceled', 'should equal'); + t.equal(status, 'canceled'); t.end(); }); @@ -38,12 +39,12 @@ test('distribute: import: received: no error', async (t) => { importListen: false, export: true, log: false, - } + }, }); config('importUrl', `http://localhost:${port}`); - const [e] = await tryToCatch(distribute.import); + const [e] = await tryToCatch(distribute.import, config); await done(); @@ -52,7 +53,9 @@ test('distribute: import: received: no error', async (t) => { }); test('distribute: import: received', async (t) => { + const configManager = createConfigManager(); const {done, port} = await connect({ + configManager, config: { name: 'bill', import: true, @@ -61,20 +64,22 @@ test('distribute: import: received', async (t) => { export: true, importListen: false, log: false, - } + }, }); - config('importUrl', `http://localhost:${port}`); + configManager('importUrl', `http://localhost:${port}`); - const {status} = await distribute.import(); + const {status} = await distribute.import(configManager); await done(); - t.equal(status, 'received','should equal'); + t.equal(status, 'received'); t.end(); }); test('distribute: import: received: auth: reject', async (t) => { + const configManager = createConfigManager(); const {done, port} = await connect({ + configManager, config: { name: 'bill', import: true, @@ -83,20 +88,22 @@ test('distribute: import: received: auth: reject', async (t) => { export: true, importListen: false, log: false, - } + }, }); - config('importUrl', `http://localhost:${port}`); + configManager('importUrl', `http://localhost:${port}`); - const {status} = await distribute.import(); + const {status} = await distribute.import(configManager); await done(); - t.equal(status, 'reject','should equal'); + t.equal(status, 'reject'); t.end(); }); test('distribute: import: received: auth: accept', async (t) => { + const configManager = createConfigManager(); const {done, port} = await connect({ + configManager, config: { name: 'bill', import: true, @@ -105,79 +112,174 @@ test('distribute: import: received: auth: accept', async (t) => { export: true, importListen: false, log: false, - } + }, }); - config('importUrl', `http://localhost:${port}`); + configManager('importUrl', `http://localhost:${port}`); - const {status} = await distribute.import(); + const {status} = await distribute.import(configManager); await done(); - t.equal(status, 'received','should equal'); + t.equal(status, 'received'); t.end(); }); test('distribute: import: received: no name', async (t) => { + const configManager = createConfigManager(); const {done, port} = await connect({ + configManager, config: { name: '', import: true, export: true, importListen: false, log: false, - } + }, }); - config('importUrl', `http://localhost:${port}`); + configManager('importUrl', `http://localhost:${port}`); - const {status} = await distribute.import(); + const {status} = await distribute.import(configManager); await done(); - t.equal(status, 'received','should equal'); + t.equal(status, 'received'); t.end(); }); test('distribute: import: error', async (t) => { - const {done, port} = await connect({ + const configManager = createConfigManager(); + const {done} = await connect({ + configManager, config: { import: true, export: false, importListen: false, log: false, - } + }, }); - config('importUrl', `http://localhost:0`); + configManager('importUrl', `http://localhost:0`); - const {status} = await distribute.import({ + const {status} = await distribute.import(configManager, { reconnection: false, }); await done(); - t.equal(status, 'connect_error','should equal'); + t.equal(status, 'connect_error'); t.end(); }); test('distribute: import: config:change: no export', async (t) => { - const {done, port} = await connect({ + const configManager = createConfigManager(); + const {done} = await connect({ + configManager, config: { import: true, export: false, importListen: true, log: false, - } + }, }); - const {status} = await distribute.import({ + const {status} = await distribute.import(configManager, { reconnection: false, }); await done(); - t.equal(status, 'connect_error','should equal'); + t.equal(status, 'connect_error'); t.end(); }); -process.on('unhandledRejection', console.log); +test('distribute: import: env', async (t) => { + const configManager = createConfigManager(); + const configManagerImport = createConfigManager(); + + const exporter = await connect({ + configManager, + config: { + name: 'bill', + import: false, + importListen: false, + export: true, + exportToken: 'a', + log: false, + editor: 'edward', + }, + }); + + const importer = await connect({ + configManager: configManagerImport, + config: { + name: 'jack', + import: true, + importToken: 'a', + export: false, + importListen: false, + log: false, + editor: 'deepword', + }, + }); + + process.env.cloudcmd_editor = 'some editor'; + + configManagerImport('importUrl', `http://localhost:${exporter.port}`); + + await distribute.import(configManagerImport); + + await importer.done(); + await exporter.done(); + + delete process.env.cloudcmd_editor; + + const result = configManagerImport('editor'); + const expected = 'deepword'; + + t.equal(result, expected); + t.end(); +}); +test('distribute: import: no env', async (t) => { + const configManager = createConfigManager(); + const configManagerImport = createConfigManager(); + + const exporter = await connect({ + configManager, + config: { + name: 'bill', + import: false, + importListen: false, + export: true, + exportToken: 'a', + log: false, + editor: 'edward', + }, + }); + + const importer = await connect({ + configManager: configManagerImport, + config: { + name: 'jack', + import: true, + importToken: 'a', + export: false, + importListen: false, + log: false, + editor: 'deepword', + }, + }); + + configManagerImport('importUrl', `http://localhost:${exporter.port}`); + + await distribute.import(configManagerImport); + + await importer.done(); + await exporter.done(); + + const result = configManagerImport('editor'); + const expected = 'edward'; + + t.equal(result, expected); + t.end(); +}); diff --git a/server/distribute/index.js b/server/distribute/index.js deleted file mode 100644 index 9fae4b04..00000000 --- a/server/distribute/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -module.exports.import = require('./import'); -module.exports.export = require('./export'); diff --git a/server/distribute/log.js b/server/distribute/log.js index 8968b1b9..acea5759 100644 --- a/server/distribute/log.js +++ b/server/distribute/log.js @@ -1,31 +1,27 @@ -'use strict'; +import wraptile from 'wraptile'; +import chalk from 'chalk'; +import datetime from '../../common/datetime.js'; -const wraptile = require('wraptile'); -const chalk = require('chalk'); +const {assign} = Object; -const config = require('../config'); -const datetime = require('../../common/datetime'); +const log = (isLog, name, msg) => isLog && console.log(`${datetime()} -> ${name}: ${msg}`); -const log = (name, msg) => config('log') && console.log(`${datetime()} -> ${name}: ${msg}`); -const makeColor = (a, color) => chalk.rgb.apply(chalk, color || stringToRGB(a))(a); -const getMessage = (e) => e.message || e; -const getDescription = (e) => `${e.type}: ${e.description}`; +export const makeColor = (a) => chalk.blue(a); +export const getMessage = (e) => e.message || e; +export const getDescription = (e) => e.message; -module.exports = log; -module.exports.logWraped = wraptile(log); -module.exports.stringToRGB = stringToRGB; -module.exports.makeColor = makeColor; -module.exports.getMessage = getMessage; -module.exports.getDescription = getDescription; +export default log; -module.exports.importStr = 'import'; -module.exports.exportStr = 'export'; -module.exports.connectedStr = chalk.green('connected'); -module.exports.disconnectedStr = chalk.red('disconnected'); -module.exports.tokenRejectedStr = chalk.red('token rejected'); -module.exports.authTryStr = chalk.yellow('try to auth'); +export const logWrapped = wraptile(log); -function stringToRGB(a) { +export const importStr = 'import'; +export const exportStr = 'export'; +export const connectedStr = chalk.green('connected'); +export const disconnectedStr = chalk.red('disconnected'); +export const tokenRejectedStr = chalk.red('token rejected'); +export const authTryStr = chalk.yellow('try to auth'); + +export function stringToRGB(a) { return [ a.charCodeAt(0), a.length, @@ -33,9 +29,7 @@ function stringToRGB(a) { ]; } -const add = (a, b) => { - return a + b.charCodeAt(0); -}; +const add = (a, b) => a + b.charCodeAt(0); function crc(a) { return a @@ -43,3 +37,16 @@ function crc(a) { .reduce(add, 0); } +assign(log, { + getMessage, + makeColor, + getDescription, + authTryStr, + stringToRGB, + logWrapped, + importStr, + exportStr, + connectedStr, + disconnectedStr, + tokenRejectedStr, +}); diff --git a/server/distribute/log.spec.js b/server/distribute/log.spec.js index 650de213..1c6d1aa3 100644 --- a/server/distribute/log.spec.js +++ b/server/distribute/log.spec.js @@ -1,32 +1,63 @@ -'use strict'; - -const test = require('tape'); -const log = require('./log'); -const config = require('../config'); +import test from 'supertape'; +import log from './log.js'; +import {createConfig} from '../config.js'; test('distribute: log: getMessage', (t) => { const e = 'hello'; - const result = log.getMessage(e) + const result = log.getMessage(e); - t.equal(e, result, 'should equal'); + t.equal(e, result); t.end(); }); test('distribute: log: getMessage: message', (t) => { const message = 'hello'; const result = log.getMessage({ - message - }) + message, + }); - t.equal(result, message, 'should equal'); + t.equal(result, message); t.end(); }); test('distribute: log: config', (t) => { + const config = createConfig(); const logOriginal = config('log'); + config('log', true); log('log', 'test message'); config('log', logOriginal); + t.end(); +}, { + checkAssertionsCount: false, +}); + +test('distribute: log: stringToRGB', (t) => { + const result = log.stringToRGB('abc'); + + t.deepEqual(result, [97, 3, 294], 'should return [charCode, length, crc]'); + t.end(); +}); + +test('distribute: log: makeColor', (t) => { + const result = log.makeColor('hello'); + + t.match(result, 'hello', 'should return colored string containing the input'); + t.end(); +}); + +test('distribute: log: getDescription', (t) => { + const message = 'some error'; + const result = log.getDescription({ + message, + }); + + t.equal(result, message, 'should return message from error object'); + t.end(); +}); + +test('distribute: log: connectedStr', (t) => { + t.ok(log.connectedStr, 'should have connectedStr'); t.end(); }); diff --git a/server/env.js b/server/env.js index 1baeccc8..86865307 100644 --- a/server/env.js +++ b/server/env.js @@ -1,23 +1,27 @@ -'use strict'; +import {env} from 'node:process'; +import snake from 'just-snake-case'; -const env = process.env; const up = (a) => a.toUpperCase(); -module.exports = parse; -module.exports.bool = (name) => { +export const bool = (name) => { const value = parse(name); if (value === 'true') return true; + if (value === '1') + return true; + if (value === 'false') return false; + + if (value === '0') + return false; }; -function parse(name) { - const small = `cloudcmd_${name}`; +export const parse = (name) => { + const small = `cloudcmd_${snake(name)}`; const big = up(small); - return env[small] || env[big]; -} - + return env[big] || env[small]; +}; diff --git a/server/env.spec.js b/server/env.spec.js new file mode 100644 index 00000000..5a8765f4 --- /dev/null +++ b/server/env.spec.js @@ -0,0 +1,69 @@ +import process from 'node:process'; +import {test} from 'supertape'; +import * as env from './env.js'; + +test('cloudcmd: server: env: bool: upper case first', (t) => { + const { + CLOUDCMD_TERMINAL, + cloudcmd_terminal, + } = process.env; + + process.env.cloudcmd_terminal = 'true'; + process.env.CLOUDCMD_TERMINAL = 'false'; + + const result = env.bool('terminal'); + + process.env.cloudcmd_terminal = cloudcmd_terminal; + process.env.CLOUDCMD_TERMINAL = CLOUDCMD_TERMINAL; + + t.notOk(result); + t.end(); +}); + +test('cloudcmd: server: env: bool: snake_case', (t) => { + process.env.cloudcmd_config_auth = 'true'; + + const result = env.bool('configAuth'); + + t.ok(result); + t.end(); +}); + +test('cloudcmd: server: env: bool: number', (t) => { + const {cloudcmd_terminal} = process.env; + + process.env.CLOUDCMD_TERMINAL = '1'; + + const result = env.bool('terminal'); + + process.env.CLOUDCMD_TERMINAL = cloudcmd_terminal; + + t.ok(result); + t.end(); +}); + +test('cloudcmd: server: env: bool: number: 0', (t) => { + const {cloudcmd_terminal} = process.env; + + process.env.cloudcmd_terminal = '0'; + + const result = env.bool('terminal'); + + process.env.cloudcmd_terminal = cloudcmd_terminal; + + t.notOk(result); + t.end(); +}); + +test('cloudcmd: server: env: bool: zero uppercase', (t) => { + const {CLOUDCMD_TERMINAL} = process.env; + + process.env.CLOUDCMD_TERMINAL = '0'; + + const result = env.bool('terminal'); + + process.env.CLOUDCMD_TERMINAL = CLOUDCMD_TERMINAL; + + t.notOk(result); + t.end(); +}); diff --git a/server/exit.js b/server/exit.js index 698adee0..ebe5ad8f 100644 --- a/server/exit.js +++ b/server/exit.js @@ -1,11 +1,10 @@ -'use strict'; +import process from 'node:process'; -const getMessage = (a) => a && a.message || a; +const getMessage = (a) => a?.message || a; -module.exports= (...args) => { +export default (...args) => { const messages = args.map(getMessage); console.error(...messages); process.exit(1); }; - diff --git a/server/exit.spec.js b/server/exit.spec.js index 49718259..94d627ac 100644 --- a/server/exit.spec.js +++ b/server/exit.spec.js @@ -1,50 +1,49 @@ -'use strict'; - -const test = require('tape'); -const exit = require('./exit'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); +import process from 'node:process'; +import {test, stub} from 'supertape'; +import exit from './exit.js'; test('cloudcmd: exit: process.exit', (t) => { - const {exit:exitOriginal} = process; - process.exit = sinon.stub(); + const {exit: exitOriginal} = process; + const exitStub = stub(); + + process.exit = exitStub; exit(); - t.ok(process.exit.calledWith(1), 'should call process.exit'); process.exit = exitOriginal; + t.calledWith(exitStub, [1], 'should call process.exit'); t.end(); }); test('cloudcmd: exit: console.error', (t) => { - const {exit:exitOriginal} = process; + const {exit: exitOriginal} = process; const {error} = console; + const errorStub = stub(); - console.error = sinon.stub(); - process.exit = sinon.stub(); + console.error = errorStub; + process.exit = stub(); exit('hello world'); - t.ok(console.error.calledWith('hello world'), 'should call console.error'); process.exit = exitOriginal; console.error = error; + t.calledWith(errorStub, ['hello world'], 'should call console.error'); t.end(); }); test('cloudcmd: exit.error: console.error: error', (t) => { - const {exit:exitOriginal} = process; + const {exit: exitOriginal} = process; const {error} = console; + const errorStub = stub(); - console.error = sinon.stub(); - process.exit = sinon.stub(); + console.error = errorStub; + process.exit = stub(); exit(Error('hello world')); - t.ok(console.error.calledWith('hello world'), 'should call console.error'); - process.exit = exitOriginal; console.error = error; + t.calledWith(errorStub, ['hello world'], 'should call console.error'); t.end(); }); - diff --git a/server/fixture-user-menu/io-cp-fix.js b/server/fixture-user-menu/io-cp-fix.js new file mode 100644 index 00000000..52f9c0b0 --- /dev/null +++ b/server/fixture-user-menu/io-cp-fix.js @@ -0,0 +1,3 @@ +async function copy() { + await IO.copy(dirPath, mp3Dir, mp3Names); +} diff --git a/server/fixture-user-menu/io-cp.js b/server/fixture-user-menu/io-cp.js new file mode 100644 index 00000000..0547933c --- /dev/null +++ b/server/fixture-user-menu/io-cp.js @@ -0,0 +1,7 @@ +async function copy() { + await IO.cp({ + from: dirPath, + to: mp3Dir, + names: mp3Names, + }); +} diff --git a/server/fixture-user-menu/io-mv-fix.js b/server/fixture-user-menu/io-mv-fix.js new file mode 100644 index 00000000..d95ccf3f --- /dev/null +++ b/server/fixture-user-menu/io-mv-fix.js @@ -0,0 +1,3 @@ +async function move() { + await IO.move(dirPath, mp3Dir, mp3Names); +} diff --git a/server/fixture-user-menu/io-mv.js b/server/fixture-user-menu/io-mv.js new file mode 100644 index 00000000..56884891 --- /dev/null +++ b/server/fixture-user-menu/io-mv.js @@ -0,0 +1,7 @@ +async function move() { + await IO.mv({ + from: dirPath, + to: mp3Dir, + names: mp3Names, + }); +} diff --git a/test/fixture/cp.txt b/server/fixture/route.js similarity index 100% rename from test/fixture/cp.txt rename to server/fixture/route.js diff --git a/server/markdown.js b/server/markdown.js deleted file mode 100644 index 9d0efff9..00000000 --- a/server/markdown.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -const DIR_ROOT = __dirname + '/../'; -const fs = require('fs'); -const { - callbackify, - promisify, -} = require('util'); - -const pullout = promisify(require('pullout')); -const ponse = require('ponse'); -const markdown = require('markdown-it')(); - -const readFile = promisify(fs.readFile); - -const root = require('./root'); - -module.exports = callbackify(async (name, request) => { - check(name, request); - - const {method} = request; - - switch(method) { - case 'GET': - return onGET(request, name); - - case 'PUT': - return onPUT(request); - } -}); - -function parseName(query, name) { - const shortName = name.replace('/markdown', ''); - - if (query === 'relative') - return DIR_ROOT + shortName; - - return root(shortName); -} - -async function onGET(request, name) { - const query = ponse.getQuery(request); - const fileName = parseName(query, name); - const data = await readFile(fileName, 'utf8'); - - return parse(data); -} - -async function onPUT(request) { - const data = await pullout(request, 'string'); - - return parse(data); -} - -const parse = promisify((data, callback) => { - process.nextTick(() => { - const md = markdown.render(data); - - callback(null, md); - }); -}); - -function check(name, request) { - if (typeof name !== 'string') - throw Error('name should be string!'); - - if (!request) - throw Error('request could not be empty!'); -} - diff --git a/server/markdown.spec.js b/server/markdown.spec.js deleted file mode 100644 index fa2f6852..00000000 --- a/server/markdown.spec.js +++ /dev/null @@ -1,113 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); -const tryToCatch = require('try-to-catch'); - -const markdown = require('./markdown'); -const before = require('../test/before'); -const {connect} = before; - -const _pullout = promisify(pullout); -const _markdown = promisify(markdown); - -const fixtureDir = path.join(__dirname, 'fixture', 'markdown'); - -const get = promisify((url, fn) => { - fn(null, request(url)); -}); - -test('cloudcmd: markdown: error', async (t) => { - const {port, done} = await connect(); - - const [error, data] = await tryToCatch(get, `http://localhost:${port}/api/v1/markdown/not-found`) - const result = await _pullout(data, 'string'); - - await done(); - - t.notOk(error, 'should not be error'); - t.ok(/ENOENT/.test(result), 'should not found'); - t.end(); -}); - -test('cloudcmd: markdown: relative: error', async (t) => { - const {port, done} = await connect(); - const [e, data] = await tryToCatch(get, `http://localhost:${port}/api/v1/markdown/not-found?relative`) - const result = await _pullout(data, 'string'); - - await done(); - t.ok(/ENOENT/.test(result), 'should not found'); - t.end(); -}); - -test('cloudcmd: markdown: relative', async (t) => { - const {port, done} = await connect(); - const data = await get(`http://localhost:${port}/api/v1/markdown/HELP.md?relative`) - const result = await _pullout(data, 'string'); - - await done(); - - t.notOk(/ENOENT/.test(result), 'should not return error'); - t.end(); -}); - -test('cloudcmd: markdown: put', async (t) => { - const md = path.join(fixtureDir, 'markdown.md'); - const html = path.join(fixtureDir, 'markdown.html'); - - const mdStream = fs.createReadStream(md); - const htmlFile = fs.readFileSync(html, 'utf8'); - - const {port, done} = await connect(); - const url = `http://localhost:${port}/api/v1/markdown`; - - const putStream = mdStream - .pipe(request.put(url)); - - const [error, result] = await tryToCatch(_pullout, putStream, 'string'); - - await done(); - - t.notOk(error, 'shoud not be error'); - t.equal(result, htmlFile, 'should render markdown input to html'); - t.end(); -}); - -test('cloudcmd: markdown: put: error', (t) => { - const md = path.join(fixtureDir, 'markdown-not-exist.md'); - - const name = 'hello'; - const mdStream = fs.createReadStream(md); - - mdStream.url = 'http://hello.world'; - mdStream.method = 'PUT'; - - _markdown(name, mdStream) - .then((result) => { - t.fail(`should fail but: ${result}`); - t.end(); - }) - .catch((error) => { - t.ok(error.message.includes('ENOENT: no such file or directory'), 'should emit error'); - t.end(); - }); -}); - -test('cloudcmd: markdown: no name', async (t) => { - const [e] = await tryToCatch(_markdown); - - t.equal(e.message, 'name should be string!', 'should throw when no name'); - t.end(); -}); - -test('cloudcmd: markdown: no request', async (t) => { - const [e] = await tryToCatch(_markdown, 'hello'); - - t.equal(e.message, 'request could not be empty!', 'should throw when no request'); - t.end(); -}); - diff --git a/server/fixture/markdown/markdown.html b/server/markdown/fixture/markdown.html similarity index 100% rename from server/fixture/markdown/markdown.html rename to server/markdown/fixture/markdown.html diff --git a/server/fixture/markdown/markdown.md b/server/markdown/fixture/markdown.md similarity index 100% rename from server/fixture/markdown/markdown.md rename to server/markdown/fixture/markdown.md diff --git a/server/markdown/fixture/markdown.zip b/server/markdown/fixture/markdown.zip new file mode 100644 index 00000000..41e0b976 Binary files /dev/null and b/server/markdown/fixture/markdown.zip differ diff --git a/server/markdown/index.js b/server/markdown/index.js new file mode 100644 index 00000000..3f80ff03 --- /dev/null +++ b/server/markdown/index.js @@ -0,0 +1,62 @@ +import {callbackify} from 'node:util'; +import {fileURLToPath} from 'node:url'; +import {dirname} from 'node:path'; +import pullout from 'pullout'; +import {getQuery} from 'ponse'; +import {read} from 'redzip'; +import root from '../root.js'; +import parse from './worker.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const isString = (a) => typeof a === 'string'; + +// warm up +parse(''); + +const DIR_ROOT = `${__dirname}/../../`; + +export default callbackify(async (name, rootDir, request) => { + check(name, request); + + const {method} = request; + + switch(method) { + case 'GET': + return await onGET(request, name, rootDir); + + case 'PUT': + return await onPUT(request); + } +}); + +function parseName(query, name, rootDir) { + const shortName = name.replace('/markdown', ''); + + if (query === 'relative') + return DIR_ROOT + shortName; + + return root(shortName, rootDir); +} + +async function onGET(request, name, root) { + const query = getQuery(request); + const fileName = parseName(query, name, root); + const stream = await read(fileName); + const data = await pullout(stream); + + return parse(data); +} + +async function onPUT(request) { + const data = await pullout(request); + return parse(data); +} + +function check(name, request) { + if (!isString(name)) + throw Error('name should be string!'); + + if (!request) + throw Error('request could not be empty!'); +} diff --git a/server/markdown/index.spec.js b/server/markdown/index.spec.js new file mode 100644 index 00000000..f705915e --- /dev/null +++ b/server/markdown/index.spec.js @@ -0,0 +1,128 @@ +import fs from 'node:fs'; +import {join} from 'node:path'; +import {promisify} from 'node:util'; +import {tryToCatch} from 'try-to-catch'; +import test from 'supertape'; +import {serveOnce} from 'serve-once'; +import {cloudcmd} from '#server/cloudcmd'; +import markdown from './index.js'; + +const config = { + auth: false, +}; + +const configManager = cloudcmd.createConfigManager(); + +const {request} = serveOnce(cloudcmd, { + config, + configManager, +}); + +const fixtureDir = new URL('fixture', import.meta.url).pathname; + +const _markdown = promisify(markdown); + +test('cloudcmd: markdown: error', async (t) => { + const {body} = await request.get('/api/v1/markdown/not-found'); + + t.match(body, 'ENOENT', 'should not found'); + t.end(); +}); + +test('cloudcmd: markdown: relative: error', async (t) => { + const {body} = await request.get('/api/v1/markdown/not-found?relative'); + + t.match(body, 'ENOENT', 'should not found'); + t.end(); +}); + +test('cloudcmd: markdown: relative', async (t) => { + const {body} = await request.get('/api/v1/markdown/HELP.md?relative'); + + t.notOk(/ENOENT/.test(body), 'should not return error'); + t.end(); +}); + +test('cloudcmd: markdown: put', async (t) => { + const md = join(fixtureDir, 'markdown.md'); + const html = join(fixtureDir, 'markdown.html'); + + const mdStream = fs.createReadStream(md); + const htmlFile = fs.readFileSync(html, 'utf8'); + + const {body} = await request.put('/api/v1/markdown', { + body: mdStream, + }); + + t.equal(body, htmlFile, 'should render markdown input to html'); + t.end(); +}); + +test('cloudcmd: markdown: put: error', async (t) => { + const md = join(fixtureDir, 'markdown-not-exist.md'); + + const name = 'hello'; + const mdStream = fs.createReadStream(md); + + mdStream.url = 'http://hello.world'; + mdStream.method = 'PUT'; + + const [e] = await tryToCatch(_markdown, name, '/', mdStream); + + t.match(e.message, 'ENOENT: no such file or directory', 'should emit error'); + t.end(); +}); + +test('cloudcmd: markdown: no name', async (t) => { + const [e] = await tryToCatch(_markdown); + + t.equal(e.message, 'name should be string!', 'should throw when no name'); + t.end(); +}); + +test('cloudcmd: markdown: no request', async (t) => { + const [e] = await tryToCatch(_markdown, 'hello'); + + t.equal(e.message, 'request could not be empty!', 'should throw when no request'); + t.end(); +}); + +test('cloudcmd: markdown', async (t) => { + const configManager = cloudcmd.createConfigManager(); + const fixtureDir = new URL('fixture', import.meta.url).pathname; + + const config = { + auth: false, + root: fixtureDir, + }; + + const {request} = serveOnce(cloudcmd, { + config, + configManager, + }); + + const {body} = await request.get('/api/v1/markdown/markdown.md'); + + t.equal(body, '

    hello

    \n'); + t.end(); +}); + +test('cloudcmd: markdown: zip', async (t) => { + const configManager = cloudcmd.createConfigManager(); + const fixtureDir = new URL('fixture', import.meta.url).pathname; + + const config = { + auth: false, + root: fixtureDir, + }; + + const {request} = serveOnce(cloudcmd, { + config, + configManager, + }); + + const {body} = await request.get('/api/v1/markdown/markdown.zip/markdown.md'); + + t.equal(body, '

    hello

    \n'); + t.end(); +}); diff --git a/server/markdown/worker.js b/server/markdown/worker.js new file mode 100644 index 00000000..ccac2aee --- /dev/null +++ b/server/markdown/worker.js @@ -0,0 +1,5 @@ +import createMarkdownIt from 'markdown-it'; + +const markdownIt = createMarkdownIt(); + +export default (a) => markdownIt.render(a); diff --git a/server/modulas.js b/server/modulas.js index 1b32dffa..7d38df99 100644 --- a/server/modulas.js +++ b/server/modulas.js @@ -1,9 +1,9 @@ -'use strict'; +import deepmerge from 'deepmerge'; +import originalModules from '../json/modules.json' with { + type: 'json', +}; -const deepmerge = require('deepmerge'); -const originalModules = require('../json/modules'); - -module.exports = (modules) => { +export default (modules) => { const result = deepmerge(originalModules, modules || {}); return (req, res, next) => { @@ -13,4 +13,3 @@ module.exports = (modules) => { res.send(result); }; }; - diff --git a/server/plugins.js b/server/plugins.js deleted file mode 100644 index deb1d0f3..00000000 --- a/server/plugins.js +++ /dev/null @@ -1,17 +0,0 @@ -'use strict'; - -const currify = require('currify'); -const files = require('files-io'); - -module.exports = currify((plugins, req, res, next) => { - if (req.url !== '/plugins.js') - return next(); - - if (!plugins || !plugins.length) - return res.send(''); - - files.readPipe(plugins, res).catch((e) => { - res.end(e.message); - }); -}); - diff --git a/server/prefixer.js b/server/prefixer.js index 3b5f3a95..87a83411 100644 --- a/server/prefixer.js +++ b/server/prefixer.js @@ -1,15 +1,14 @@ -'use strict'; +const isString = (a) => typeof a === 'string'; -module.exports = (value) => { - if (typeof value !== 'string') +export default (value) => { + if (!isString(value)) return ''; if (value.length === 1) return ''; - if (value && !~value.indexOf('/')) - return '/' + value; + if (value && !value.includes('/')) + return `/${value}`; return value; }; - diff --git a/test/server/prefixer.js b/server/prefixer.spec.js similarity index 79% rename from test/server/prefixer.js rename to server/prefixer.spec.js index a7c7e824..3ea77dfb 100644 --- a/test/server/prefixer.js +++ b/server/prefixer.spec.js @@ -1,9 +1,5 @@ -'use strict'; - -const test = require('tape'); - -const dir = '../../server/'; -const prefixer = require(dir + 'prefixer'); +import {test} from 'supertape'; +import prefixer from './prefixer.js'; test('prefixer: prefix without a slash', (t) => { t.equal(prefixer('hello'), '/hello', 'should add slash'); diff --git a/server/repl.js b/server/repl.js index a24c7d0b..46d58a15 100644 --- a/server/repl.js +++ b/server/repl.js @@ -1,25 +1,25 @@ -'use strict'; - -const net = require('net'); -const repl = require('repl'); - -module.exports = net.createServer((socket) => { - const pid = process.pid; - const addr = socket.remoteAddress; - const port = socket.remotePort; - - const r = repl.start({ - prompt: `[${pid} ${addr}:${port}>`, - input: socket, - output: socket, - terminal: true, - useGlobal: false - }); - - r.on('exit', () => { - socket.end(); - }); - - r.context.socket = socket; -}).listen(1337); +import process from 'node:process'; +import net from 'node:net'; +import repl from 'node:repl'; +export default net + .createServer((socket) => { + const {pid} = process; + const addr = socket.remoteAddress; + const port = socket.remotePort; + + const r = repl.start({ + prompt: `[${pid} ${addr}:${port}>`, + input: socket, + output: socket, + terminal: true, + useGlobal: false, + }); + + r.on('exit', () => { + socket.end(); + }); + + r.context.socket = socket; + }) + .listen(1337); diff --git a/server/rest/index.js b/server/rest/index.js index edfe303d..c3a3eda0 100644 --- a/server/rest/index.js +++ b/server/rest/index.js @@ -1,54 +1,59 @@ -'use strict'; - -const DIR = '../'; -const DIR_COMMON = DIR + '../common/'; - -const path = require('path'); -const fs = require('fs'); - -const root = require(DIR + 'root'); -const config = require(DIR + 'config'); -const CloudFunc = require(DIR_COMMON + 'cloudfunc'); -const markdown = require(DIR + 'markdown'); -const info = require('./info'); - -const jaguar = require('jaguar'); -const onezip = require('onezip'); -const inly = require('inly'); -const wraptile = require('wraptile'); -const pullout = require('pullout'); -const json = require('jonny'); -const ponse = require('ponse'); - -const copymitter = require('copymitter'); -const moveFiles = require('@cloudcmd/move-files'); +import path from 'node:path'; +import _fs from 'node:fs'; +import process from 'node:process'; +import jaguar from 'jaguar'; +import {onezip} from 'onezip'; +import inly from 'inly'; +import wraptile from 'wraptile'; +import currify from 'currify'; +import pullout from 'pullout'; +import json from 'jonny'; +import * as ponse from 'ponse'; +import {copymitter} from 'copymitter'; +import _moveFiles from '@cloudcmd/move-files'; +import * as CloudFunc from '#common/cloudfunc'; +import root from '../root.js'; +import markdown from '../markdown/index.js'; +import info from './info.js'; +const isUndefined = (a) => typeof a === 'undefined'; +const isRootAll = (root, names) => names.some(isRootWin32(root)); +const isString = (a) => typeof a === 'string'; +const isFn = (a) => typeof a === 'function'; const swap = wraptile((fn, a, b) => fn(b, a)); const isWin32 = process.platform === 'win32'; const {apiURL} = CloudFunc; -module.exports = (request, response, next) => { - check(request, response, next); +const UserError = (msg) => { + const error = Error(msg); + error.code = 'EUSER'; + + return error; +}; + +export const _UserError = UserError; + +export default currify(({config, fs = _fs, moveFiles = _moveFiles}, request, response, next) => { const name = ponse.getPathName(request); - const regExp = RegExp('^' + apiURL); + const regExp = RegExp(`^${apiURL}`); const is = regExp.test(name); if (!is) return next(); - rest(request,response); -}; + rest({fs, config, moveFiles}, request, response); +}); -function rest(request, response) { +function rest({fs, config, moveFiles}, request, response) { const name = ponse.getPathName(request); - const params = { + const params = { request, response, name: name.replace(apiURL, '') || '/', }; - sendData(params, (error, options, data) => { + sendData(params, {fs, config, moveFiles}, (error, options, data) => { params.gzip = !error; if (!data) { @@ -59,12 +64,15 @@ function rest(request, response) { if (options.name) params.name = options.name; - if (options.gzip !== undefined) + if (!isUndefined(options.gzip)) params.gzip = options.gzip; if (options.query) params.query = options.query; + if (error?.code) + return ponse.sendError(error, params); + if (error) return ponse.sendError(error, params); @@ -75,75 +83,90 @@ function rest(request, response) { /** * getting data on method and command * - * @param params {name, method, body, requrest, response} + * @param params {name, method, body, request, response} + * @param config {} + * @param callback */ -function sendData(params, callback) { +function sendData(params, {fs, config, moveFiles}, callback) { const p = params; - const isMD = RegExp('^/markdown').test(p.name); + const isMD = p.name.startsWith('/markdown'); + const rootDir = config('root'); if (isMD) - return markdown(p.name, p.request, callback); + return markdown(p.name, rootDir, p.request, callback); - const method = p.request.method; + const {method} = p.request; switch(method) { case 'GET': - return onGET(params, callback); + return onGET(params, config, callback); case 'PUT': - return pullout(p.request, 'string', (error, body) => { - if (error) - return callback(error); - - onPUT(p.name, body, callback); - }); + return pullout(p.request) + .then((body) => { + onPUT({ + name: p.name, + fs, + moveFiles, + config, + body, + }, callback); + }) + .catch(callback); } } -function onGET(params, callback) { +function onGET(params, config, callback) { let cmd; const p = params; + const packer = config('packer'); + const prefix = config('prefix'); + const rootDir = config('root'); if (p.name[0] === '/') cmd = p.name.replace('/', ''); - if (/^pack/.test(cmd)) { + if (cmd.startsWith('pack')) { cmd = cmd.replace(/^pack/, ''); - streamPack(root(cmd), p.response); + streamPack(root(cmd, rootDir), p.response, packer); + return; } switch(cmd) { case '': - p.data = json.stringify(info()); + p.data = json.stringify(info(prefix)); callback(null, {name: 'api.json'}, p.data); break; default: callback({ - message: 'Not Found' + message: 'Not Found', }); break; } } -function getPackReg() { - if (config('packer') === 'zip') +function getPackReg(packer) { + if (packer === 'zip') return /\.zip$/; return /\.tar\.gz$/; } -function streamPack(cmd, response) { +export const _getPackReg = getPackReg; + +function streamPack(cmd, response, packer) { const noop = () => {}; - const filename = cmd.replace(getPackReg(), ''); + const filename = cmd.replace(getPackReg(packer), ''); const dir = path.dirname(filename); + const names = [ - path.basename(filename) + path.basename(filename), ]; - operation('pack', dir, response, names, noop); + operation('pack', packer, dir, response, names, noop); } function getCMD(cmd) { @@ -153,50 +176,68 @@ function getCMD(cmd) { return cmd; } -const getMoveMsg = (files) => { - const data = !files.names ? files : files.names.slice(); - const msg = formatMsg('move', data); +export const _getCMD = getCMD; + +const getMoveMsg = (names) => formatMsg('move', names); + +const getRenameMsg = (from, to) => { + const msg = formatMsg('rename', { + from, + to, + }); return msg; }; -module.exports._onPUT = onPUT; -function onPUT(name, body, callback) { +export const _onPUT = onPUT; + +function onPUT({name, fs, moveFiles, config, body}, callback) { checkPut(name, body, callback); const cmd = getCMD(name); const files = json.parse(body); + const rootDir = config('root'); switch(cmd) { - case 'mv': { - if (!files.from || !files.to) - return callback(body); + case 'move': { + const { + from, + to, + names, + } = files; - if (isRootAll([files.to, files.from])) + if (!from) + return callback(UserError('"from" should be filled')); + + if (!to) + return callback(UserError('"to" should be filled')); + + if (isRootAll(rootDir, [to, from])) return callback(getWin32RootMsg()); - const msg = getMoveMsg(files); + const msg = getMoveMsg(names); const fn = swap(callback, msg); - const from = root(files.from); - const to = root(files.to); - const names = files.names; + const fromRooted = root(from, rootDir); + const toRooted = root(to, rootDir); - if (!names) - return fs.rename(from, to, fn); - - return moveFiles(from, to, names) + return moveFiles(fromRooted, toRooted, names) .on('error', fn) .on('end', fn); - } case 'cp': + } + + case 'rename': + return rename(rootDir, files.from, files.to, fs, callback); + + case 'copy': if (!files.from || !files.names || !files.to) return callback(body); - if (isRootAll([files.to, files.from])) + if (isRootAll(rootDir, [files.to, files.from])) return callback(getWin32RootMsg()); - - files.from = root(files.from); - files.to = root(files.to); + + files.from = root(files.from, rootDir); + files.to = root(files.to, rootDir); copy(files.from, files.to, files.names, (error) => { const msg = formatMsg('copy', files.names); @@ -208,14 +249,14 @@ function onPUT(name, body, callback) { if (!files.from) return callback(body); - pack(files.from, files.to, files.names, callback); + pack(files.from, files.to, files.names, config, callback); break; case 'extract': if (!files.from) return callback(body); - extract(files.from, files.to, callback); + extract(files.from, files.to, config, callback); break; @@ -225,58 +266,87 @@ function onPUT(name, body, callback) { } } -function pack(from, to, names, fn) { - from = root(from); - to = root(to); +function rename(rootDir, from, to, fs, callback) { + if (!from) + return callback(UserError('"from" should be filled')); + + if (!to) + return callback(UserError('"to" should be filled')); + + const msg = getRenameMsg(from, to); + const fn = swap(callback, msg); + + const fromRooted = root(from, rootDir); + const toRooted = root(to, rootDir); + + return fs.rename(fromRooted, toRooted, fn); +} + +export const _rename = rename; + +function pack(from, to, names, config, fn) { + const rootDir = config('root'); + const packer = config('packer'); + + from = root(from, rootDir); + to = root(to, rootDir); if (!names) { names = [ - path.basename(from) + path.basename(from), ]; from = path.dirname(from); } - operation('pack', from, to, names, fn); + operation('pack', packer, from, to, names, fn); } -function extract(from, to, fn) { - from = root(from); +export const _pack = pack; + +function extract(from, to, config, fn) { + const rootDir = config('root'); + + from = root(from, rootDir); if (to) - to = root(to); + to = root(to, rootDir); else to = from.replace(/\.tar\.gz$/, ''); - operation('extract', from, to, fn); + operation('extract', config('packer'), from, to, fn); } -function getPacker(operation) { +export const _extract = extract; + +function getPacker(operation, packer) { if (operation === 'extract') return inly; - if (config('packer') === 'zip') + if (packer === 'zip') return onezip.pack; return jaguar.pack; } -function operation(op, from, to, names, fn) { +export const _getPacker = getPacker; + +function operation(op, packer, from, to, names, fn) { if (!fn) { - fn = names; - names = [ - path.basename(from) + fn = names; + names = [ + path.basename(from), ]; } - const packer = getPacker(op); - const pack = packer(from, to, names); + const packerFn = getPacker(op, packer); + const pack = packerFn(from, to, names); pack.on('error', fn); const [name] = names; pack.on('progress', (count) => { - process.stdout.write(`\r${ op } "${ name }": ${ count }%`); + process.stdout.write(`\r${op} "${name}": ${count}%`); }); pack.on('end', () => { @@ -289,6 +359,8 @@ function operation(op, from, to, names, fn) { }); } +export const _operation = operation; + function copy(from, to, names, fn) { copymitter(from, to, names) .on('error', fn) @@ -301,26 +373,22 @@ function copy(from, to, names, fn) { }); } -module.exports._isRootWin32 = isRootWin32; -function isRootWin32(path) { +const isRootWin32 = currify((root, path) => { const isRoot = path === '/'; - const isConfig = config('root') === '/'; + const isConfig = root === '/'; return isWin32 && isRoot && isConfig; -} +}); -module.exports._isRootAll = isRootAll; -function isRootAll(names) { - return names.some(isRootWin32); -} +export const _isRootWin32 = isRootWin32; +export const _isRootAll = isRootAll; -module.exports._getWin32RootMsg = getWin32RootMsg; +export const _getWin32RootMsg = getWin32RootMsg; function getWin32RootMsg() { const message = 'Could not copy from/to root on windows!'; - const error = Error(message); - return error; + return Error(message); } function parseData(data) { @@ -332,33 +400,20 @@ function parseData(data) { return json.stringify(data); } -module.exports._formatMsg = formatMsg; +export const _formatMsg = formatMsg; function formatMsg(msg, data, status) { const value = parseData(data); - return CloudFunc.formatMsg(msg, value, status); } -function check(request, response, next) { - if (typeof request !== 'object') - throw Error('request should be an object!'); - - if (typeof response !== 'object') - throw Error('response should be an object!'); - - if (typeof next !== 'function') - throw Error('next should be a function!'); -} - function checkPut(name, body, callback) { - if (typeof name !== 'string') + if (!isString(name)) throw Error('name should be a string!'); - if (typeof body !== 'string') + if (!isString(body)) throw Error('body should be a string!'); - if (typeof callback !== 'function') + if (!isFn(callback)) throw Error('callback should be a function!'); } - diff --git a/server/rest/index.spec.js b/server/rest/index.spec.js index b47344aa..9c672095 100644 --- a/server/rest/index.spec.js +++ b/server/rest/index.spec.js @@ -1,14 +1,17 @@ -'use strict'; - -const test = require('tape'); -const rest = require('.'); -const { +import {test, stub} from 'supertape'; +import {tryToCatch} from 'try-to-catch'; +import { _formatMsg, _getWin32RootMsg, _isRootWin32, _isRootAll, _onPUT, -} = rest; + _UserError, + _getPackReg, + _getCMD, + _rename, + _getPacker, +} from './index.js'; test('rest: formatMsg', (t) => { const result = _formatMsg('hello', 'world'); @@ -29,55 +32,147 @@ test('rest: formatMsg: json', (t) => { test('rest: getWin32RootMsg', (t) => { const {message} = _getWin32RootMsg(); - t.equal(message,'Could not copy from/to root on windows!', 'should return error'); + t.equal(message, 'Could not copy from/to root on windows!', 'should return error'); t.end(); }); test('rest: isRootWin32', (t) => { - const result = _isRootWin32('/'); + const result = _isRootWin32('/', '/'); t.notOk(result, 'should equal'); t.end(); }); test('rest: isRootAll', (t) => { - const result = _isRootAll(['/', '/h']); + const result = _isRootAll('/', ['/', '/h']); t.notOk(result, 'should equal'); t.end(); }); -test('rest: onPUT: no args', (t) => { - t.throws(_onPUT, /name should be a string!/, 'should throw when no args'); +test('rest: onPUT: no args', async (t) => { + const [e] = await tryToCatch(_onPUT, {}); + + t.equal(e.message, 'name should be a string!', 'should throw when no args'); t.end(); }); -test('rest: onPUT: no body', (t) => { - const fn = () => _onPUT('hello'); - t.throws(fn, /body should be a string!/, 'should throw when no body'); +test('rest: onPUT: no body', async (t) => { + const [e] = await tryToCatch(_onPUT, { + name: 'hello', + }); + + t.equal(e.message, 'body should be a string!', 'should throw when no body'); t.end(); }); -test('rest: onPUT: no callback', (t) => { - const fn = () => _onPUT('hello', 'world'); - t.throws(fn, /callback should be a function!/, 'should throw when no callback'); +test('rest: onPUT: no callback', async (t) => { + const [e] = await tryToCatch(_onPUT, { + name: 'hello', + body: 'world', + }); + + t.equal(e.message, 'callback should be a function!', 'should throw when no callback'); t.end(); }); -test('rest: no args', (t) => { - t.throws(rest, /request should be an object!/, 'should throw when no args'); +test('rest: UserError: message', (t) => { + const result = _UserError('hello'); + + t.equal(result.message, 'hello', 'should set message'); t.end(); }); -test('rest: no response', (t) => { - const fn = () => rest({}); - t.throws(fn, /response should be an object!/, 'should throw when no response'); +test('rest: UserError: code', (t) => { + const result = _UserError('hello'); + + t.equal(result.code, 'EUSER', 'should set code'); t.end(); }); -test('rest: no next', (t) => { - const fn = () => rest({}, {}); - t.throws(fn, /next should be a function!/, 'should throw when no response'); +test('rest: getPackReg: zip', (t) => { + const result = _getPackReg('zip'); + + t.match('file.zip', result, 'should match .zip'); t.end(); }); +test('rest: getPackReg: tar', (t) => { + const result = _getPackReg('tar'); + + t.match('file.tar.gz', result, 'should match .tar.gz'); + t.end(); +}); + +test('rest: getCMD: with slash', (t) => { + const result = _getCMD('/move'); + + t.equal(result, 'move', 'should strip leading slash'); + t.end(); +}); + +test('rest: getCMD: no slash', (t) => { + const result = _getCMD('move'); + + t.equal(result, 'move', 'should return as is'); + t.end(); +}); + +test('rest: rename: no from', (t) => { + const callback = stub(); + + _rename('/', null, 'to', null, callback); + + const msg = '"from" should be filled'; + + t.calledWith(callback, [ + _UserError(msg), + ], 'should return UserError'); + t.end(); +}); + +test('rest: rename: no to', (t) => { + const callback = stub(); + + _rename('/', 'from', null, null, callback); + + const msg = '"to" should be filled'; + + t.calledWith(callback, [ + _UserError(msg), + ], 'should return UserError'); + t.end(); +}); + +test('rest: rename: success', (t) => { + const callback = stub(); + const fs = { + rename: stub(), + }; + + _rename('/root', 'from', 'to', fs, callback); + + t.calledWith(fs.rename, ['/root/from', '/root/to', callback], 'should call fs.rename'); + t.end(); +}); + +test('rest: getPacker: extract', (t) => { + const result = _getPacker('extract', 'zip'); + + t.equal(typeof result, 'function', 'should return function'); + t.end(); +}); + +test('rest: getPacker: pack zip', (t) => { + const result = _getPacker('pack', 'zip'); + + t.equal(typeof result, 'function', 'should return function'); + t.end(); +}); + +test('rest: getPacker: pack tar', (t) => { + const result = _getPacker('pack', 'tar'); + + t.equal(typeof result, 'function', 'should return function'); + t.end(); +}); diff --git a/server/rest/info.js b/server/rest/info.js index 11da857c..8cf0e1d7 100644 --- a/server/rest/info.js +++ b/server/rest/info.js @@ -1,18 +1,18 @@ -'use strict'; +import process from 'node:process'; +import format from 'format-io'; +import info from '../../package.json' with { + type: 'json', +}; -const format = require('format-io'); - -const version = require('../../package').version; -const config = require('../config'); +const {version} = info; const getMemory = () => { - const rss = process.memoryUsage().rss; + const {rss} = process.memoryUsage(); return format.size(rss); }; -module.exports = () => ({ +export default (prefix) => ({ version, + prefix, memory: getMemory(), - prefix: config('prefix'), }); - diff --git a/server/rest/info.spec.js b/server/rest/info.spec.js index a5bbf34a..cac19e53 100644 --- a/server/rest/info.spec.js +++ b/server/rest/info.spec.js @@ -1,15 +1,11 @@ -'use strict'; - -const test = require('tape'); -const info = require('./info'); -const sinon = require('sinon'); +import process from 'node:process'; +import {test, stub} from 'supertape'; +import info from './info.js'; test('cloudcmd: rest: info', (t) => { const {memoryUsage} = process; - const _memoryUsage = sinon - .stub() - .returns({}); + const _memoryUsage = stub().returns({}); process.memoryUsage = _memoryUsage; @@ -17,7 +13,6 @@ test('cloudcmd: rest: info', (t) => { process.memoryUsage = memoryUsage; - t.ok(_memoryUsage.calledWith(), 'should call memoryUsage'); + t.calledWithNoArgs(_memoryUsage, 'should call memoryUsage'); t.end(); }); - diff --git a/server/root.js b/server/root.js index 5c3ea26b..b563d77d 100644 --- a/server/root.js +++ b/server/root.js @@ -1,11 +1,5 @@ -'use strict'; +import mellow from 'mellow'; -const config = require('./config'); -const mellow = require('mellow'); - -module.exports = (dir) => { - const root = config('root') || '/'; - - return mellow.pathToWin(dir, root); +export default (dir, root, {webToWin = mellow.webToWin} = {}) => { + return webToWin(dir, root || '/'); }; - diff --git a/server/root.spec.js b/server/root.spec.js new file mode 100644 index 00000000..2d9dd768 --- /dev/null +++ b/server/root.spec.js @@ -0,0 +1,16 @@ +import {test, stub} from 'supertape'; +import root from './root.js'; + +test('cloudcmd: root: mellow', (t) => { + const webToWin = stub(); + + const dir = 'hello'; + const dirRoot = '/'; + + root(dir, '', { + webToWin, + }); + + t.calledWith(webToWin, [dir, dirRoot], 'should call mellow'); + t.end(); +}); diff --git a/server/route.js b/server/route.js index 85a271b8..7844ce09 100644 --- a/server/route.js +++ b/server/route.js @@ -1,63 +1,71 @@ -'use strict'; +import {createRequire} from 'node:module'; +import {extname} from 'node:path'; +import * as _win32 from 'win32'; +import * as ponse from 'ponse'; +import {rendy} from 'rendy'; +import format from 'format-io'; +import currify from 'currify'; +import wraptile from 'wraptile'; +import {tryToCatch} from 'try-to-catch'; +import once from 'once'; +import pipe from 'pipe-io'; +import {contentType} from 'mime-types'; +import * as CloudFunc from '#common/cloudfunc'; +import root from './root.js'; +import prefixer from './prefixer.js'; +import Template from './template.js'; +import {getColumns} from './columns.js'; +import {getThemes} from './theme.js'; -const DIR_SERVER = './'; -const DIR_COMMON = '../common/'; - -const fs = require('fs'); -const { - promisify, -} = require('util'); - -const flop = require('flop'); -const ponse = require('ponse'); -const rendy = require('rendy'); -const format = require('format-io'); -const squad = require('squad'); -const apart = require('apart'); -const currify = require('currify'); -const tryToCatch = require('try-to-catch'); - -const config = require(DIR_SERVER + 'config'); -const root = require(DIR_SERVER + 'root'); -const prefixer = require(DIR_SERVER + 'prefixer'); -const CloudFunc = require(DIR_COMMON + 'cloudfunc'); - -const prefix = squad(prefixer, apart(config, 'prefix')); +const require = createRequire(import.meta.url); +const {stringify} = JSON; +const {FS} = CloudFunc; const sendIndex = (params, data) => { const ponseParams = { ...params, - name: 'index.html' + name: 'index.html', }; ponse.send(data, ponseParams); }; -const {FS} = CloudFunc; +const onceRequire = once(require); +const getPrefix = (config) => prefixer(config('prefix')); -const Columns = require('./columns'); -const Template = require('./template'); - -const read = promisify(flop.read); -const realpath = promisify(fs.realpath); +const getReadDir = (config, {win32 = _win32} = {}) => { + if (!config('dropbox')) + return win32.read; + + const {readDir} = onceRequire('@cloudcmd/dropbox'); + + return wraptile(readDir, config('dropboxToken')); +}; /** * routing of server queries */ -module.exports = currify((options, request, response, next) => { +export default currify((config, options, request, response, next) => { const name = ponse.getPathName(request); - const isFS = RegExp('^/$|^' + FS).test(name); + const isFS = RegExp(`^/$|^${FS}`).test(name); if (!isFS) return next(); - route(options, request, response) - .catch(next); + route({ + config, + options, + request, + response, + }).catch(next); }); -async function route(options, request, response) { +export const _getReadDir = getReadDir; + +async function route({config, options, request, response}) { const name = ponse.getPathName(request); const gzip = true; + const p = { request, response, @@ -68,42 +76,54 @@ async function route(options, request, response) { config('prefix', prefixer(request.baseUrl)); const rootName = name.replace(CloudFunc.FS, '') || '/'; - const fullPath = root(rootName); + const fullPath = root(rootName, config('root')); - const [error, dir] = await tryToCatch(read, fullPath); - const {html} = options; + if (fullPath.indexOf(config('root'))) + return ponse.sendError(Error(`Path '${fullPath}' beyond root '${config('root')}'`), p); - if (!error) - return sendIndex(p, buildIndex(html, { - ...dir, - path: format.addSlashToEnd(rootName), - })); + const {html, win32} = options; - if (error.code !== 'ENOTDIR') + const read = getReadDir(config, { + win32, + }); + + const [error, stream] = await tryToCatch(read, fullPath, { + root: config('root'), + }); + + if (error) return ponse.sendError(error, p); - const [realPathError, pathReal] = await tryToCatch(realpath, fullPath); + if (stream.type === 'directory') { + const {files} = stream; + + return sendIndex(p, buildIndex(config, html, { + files, + path: format.addSlashToEnd(rootName), + })); + } - ponse.sendFile({ - ...p, - name: realPathError ? name : pathReal, - gzip: false - }); + const {contentLength} = stream; + + response.setHeader('Content-Length', contentLength); + response.setHeader('Content-Type', contentType(extname(fullPath))); + + await pipe([stream, response]); } /** * additional processing of index file */ -function indexProcessing(options) { +function indexProcessing(config, options) { const oneFilePanel = config('oneFilePanel'); const noKeysPanel = !config('keysPanel'); const noContact = !config('contact'); const noConfig = !config('configDialog'); const noConsole = !config('console'); const noTerminal = !config('terminal'); - const panel = options.panel; + const {panel} = options; - let data = options.data; + let {data} = options; if (noKeysPanel) data = hideKeysPanel(data); @@ -114,33 +134,30 @@ function indexProcessing(options) { .replace('icon-copy', 'icon-copy none'); if (noContact) - data = data - .replace('icon-contact', 'icon-contact none'); + data = data.replace('icon-contact', 'icon-contact none'); if (noConfig) - data = data - .replace('icon-config', 'icon-config none'); + data = data.replace('icon-config', 'icon-config none'); if (noConsole) - data = data - .replace('icon-console', 'icon-console none'); + data = data.replace('icon-console', 'icon-console none'); if (noTerminal) - data = data - .replace('icon-terminal', 'icon-terminal none'); + data = data.replace('icon-terminal', 'icon-terminal none'); const left = rendy(Template.panel, { - side : 'left', - content : panel, - className : !oneFilePanel ? '' : 'panel-single' + side: 'left', + content: panel, + className: !oneFilePanel ? '' : 'panel-single', }); let right = ''; + if (!oneFilePanel) right = rendy(Template.panel, { - side : 'right', - content : panel, - className : '' + side: 'right', + content: panel, + className: '', }); const name = config('name'); @@ -150,40 +167,42 @@ function indexProcessing(options) { name, }), fm: left + right, - prefix: prefix(), - config: JSON.stringify(config('*')), - columns: Columns[config('columns')], + prefix: getPrefix(config), + config: stringify(config('*')), + columns: getColumns()[config('columns')], + themes: getThemes()[config('theme')], }); return data; } -function buildIndex(html, json) { +function buildIndex(config, html, data) { const panel = CloudFunc.buildFromJSON({ - data: json, - prefix: prefix(), + data, + prefix: getPrefix(config), template: Template, + showDotFiles: config('showDotFiles'), }); - return indexProcessing({ + return indexProcessing(config, { panel, data: html, }); } -module.exports._hideKeysPanel = hideKeysPanel; +export const _hideKeysPanel = hideKeysPanel; + function hideKeysPanel(html) { const keysPanel = '
    (...b) => fn(...b, ...a); -const _pullout = promisify(pullout); - -const get = promisify((url, fn) => { - fn(null, request(url)); -}); - -const getStr = (url) => { - return get(url) - .then(warp(_pullout, 'string')) - .catch(console.error); +const defaultConfig = { + auth: false, + dropbox: false, }; +const {request} = serveOnce(cloudcmd, { + config: defaultConfig, +}); + +const {stringify} = JSON; +const {assign} = Object; + test('cloudcmd: route: buttons: no console', async (t) => { - const config = { - console: false + const options = { + config: { + console: false, + }, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const {body} = await request.get('/', { + options, + }); - t.ok(/icon-console none/.test(result), 'should hide console'); + t.match(body, 'icon-console none', 'should hide console'); t.end(); - - await done(); }); test('cloudcmd: route: buttons: console', async (t) => { @@ -52,147 +45,143 @@ test('cloudcmd: route: buttons: console', async (t) => { console: true, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const options = { + config, + }; - t.notOk(/icon-console none/.test(result), 'should not hide console'); + const {body} = await request.get('/', { + options, + }); + + t.notOk(/icon-console none/.test(body), 'should not hide console'); t.end(); - - await done(); }); test('cloudcmd: route: buttons: no config', async (t) => { const config = { - configDialog: false + configDialog: false, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const options = { + config, + }; - t.ok(/icon-config none/.test(result), 'should hide config'); + const {body} = await request.get('/', { + options, + }); + + t.match(body, 'icon-config none', 'should hide config'); t.end(); - - await done(); }); test('cloudcmd: route: buttons: no contact', async (t) => { const config = { - contact: false + contact: false, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const options = { + config, + }; - t.ok(/icon-contact none/.test(result), 'should hide contact'); + const {body} = await request.get('/', { + options, + }); + + t.match(body, 'icon-contact none', 'should hide contact'); t.end(); - - await done(); }); test('cloudcmd: route: buttons: one file panel: move', async (t) => { const config = { - oneFilePanel: true + oneFilePanel: true, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const options = { + config, + }; - t.ok(/icon-move none/.test(result), 'should hide move button'); + const {body} = await request.get('/', { + options, + }); + + t.match(body, 'icon-move none', 'should hide move button'); t.end(); - - await done(); }); -test('cloudcmd: route: buttons: no one file panel: move', async (t) => { +test('cloudcmd: route: buttons: one file panel: copy', async (t) => { const config = { - oneFilePanel: false + oneFilePanel: true, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); - - t.notOk(/icon-move none/.test(result), 'should not hide move button'); - t.end(); - - await done(); -}); - -test('cloudcmd: route: buttons: one file panel: move', async (t) => { - const config = { - oneFilePanel: true + const options = { + config, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const {body} = await request.get('/', { + options, + }); - t.ok(/icon-copy none/.test(result), 'should hide copy button'); + t.match(body, 'icon-copy none', 'should hide copy button'); t.end(); - - await done(); }); test('cloudcmd: route: keys panel: hide', async (t) => { const config = { - keysPanel: false + keysPanel: false, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const options = { + config, + }; - t.ok(/keyspanel hidden/.test(result), 'should hide keyspanel'); + const {body} = await request.get('/', { + options, + }); + + t.match(body, 'keyspanel hidden', 'should hide keyspanel'); t.end(); - - await done(); }); test('cloudcmd: route: keys panel', async (t) => { const config = { - keysPanel: true + keysPanel: true, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); - - t.notOk(/keyspanel hidden/.test(result), 'should show keyspanel'); - t.end(); - - await done(); -}); - -test('cloudcmd: route: file: fs', async (t) => { - const root = path.join(fixtureDir, 'empty-file'); - const config = { - root, + const options = { + config, }; - const {port, done} = await connect({config}); - const empty = await getStr(`http://localhost:${port}/fs`); + const {body} = await request.get('/', { + options, + }); - t.equal(empty, '', 'should equal'); + t.notOk(/keyspanel hidden/.test(body), 'should show keyspanel'); t.end(); - - await done(); }); test('cloudcmd: route: symlink', async (t) => { const emptyDir = path.join(fixtureDir, 'empty-dir'); - const root = fixtureDir + const root = fixtureDir; const symlink = path.join(root, 'symlink-dir'); const config = { root, }; + const options = { + config, + }; + fs.symlinkSync(emptyDir, symlink); - const {port, done} = await connect({config}); - const data = await getStr(`http://localhost:${port}/fs/symlink-dir`); + const {body} = await request.get('/fs/symlink-dir', { + options, + }); - t.ok(data.length, 'should return html document'); fs.unlinkSync(symlink); - t.end(); - await done(); + t.ok(body.length, 'should return html document'); + t.end(); }); test('cloudcmd: route: not found', async (t) => { @@ -201,154 +190,178 @@ test('cloudcmd: route: not found', async (t) => { root, }; - const {port, done} = await connect({config}); - const data = await getStr(`http://localhost:${port}/fs/file-not-found`); - - t.ok(~data.indexOf('ENOENT: no such file or directory'), 'should return error'); - t.end(); - - await done(); -}); - -test('cloudcmd: route: realpath: error', async (t) => { - const error = 'realpath error'; - const {realpath} = fs; - - fs.realpath = (name, fn) => { - fn(error); - fs.realpath = realpath; + const options = { + config, }; - const config = { - root: fixtureDir, - }; + const {body} = await request.get('/fs/file-not-found', { + options, + }); - reRequire('./route'); - reRequire('./cloudcmd'); - - const {connect} = reRequire(beforePath); - const {port, done} = await connect({config}); - const data = await getStr(`http://localhost:${port}/fs/empty-file`); - - fs.realpath = realpath; - - t.ok(/^ENOENT/.test(data), 'should return error'); + t.match(body, 'ENOENT: no such file or directory', 'should return error'); t.end(); - - await done(); }); test('cloudcmd: route: sendIndex: encode', async (t) => { const name = '">'; - const nameEncoded = '"><svg onload=alert(3);>'; + const nameEncoded = '"><svg onload=alert(3);>'; + const path = '/'; + const files = [{ name, }]; - const read = (path, fn) => fn(null, { + const stream = Readable.from(stringify({ path, files, + })); + + assign(stream, { + path, + files, + type: 'directory', }); - mockRequire('flop', { - read + const read = stub().resolves(stream); + + cloudcmd.depStore('win32', { + read, }); - reRequire(routePath); - reRequire(cloudcmdPath); + const {request} = serveOnce(cloudcmd, { + configManager: createConfigManager(), + }); - const {connect} = reRequire(beforePath); - const {port, done} = await connect(); - const data = await getStr(`http://localhost:${port}`); + const {body} = await request.get('/'); - t.ok(data.includes(nameEncoded), 'should encode name'); + cloudcmd.depStore(); - mockRequire.stop('flop'); - - await done(); + t.match(body, nameEncoded, 'should encode name'); t.end(); }); test('cloudcmd: route: sendIndex: encode: not encoded', async (t) => { const name = '">'; + const path = '/'; + const files = [{ name, }]; - const read = (path, fn) => fn(null, { + const stream = Readable.from(stringify({ path, files, + })); + + assign(stream, { + path, + files, + type: 'directory', }); - mockRequire('flop', { - read + const read = stub().resolves(stream); + + cloudcmd.depStore('win32', { + read, }); - clear(routePath); - clear(cloudcmdPath); - clear(beforePath); + const {request} = serveOnce(cloudcmd); + const {body} = await request.get('/'); - const {connect} = require(beforePath); - const {port, done} = await connect(); - const data = await getStr(`http://localhost:${port}`); + cloudcmd.depStore(); - t.notOk(data.includes(name), 'should not put not encoded name'); - - mockRequire.stop('flop'); - clear(routePath); - clear(cloudcmdPath); - clear(beforePath); - - await done(); + t.notOk(body.includes(name), 'should not put not encoded name'); t.end(); }); test('cloudcmd: route: sendIndex: ddos: render', async (t) => { - const name = '$$$\'"'; + const name = `$$$'"`; + const path = '/'; + const files = [{ name, }]; - const read = (path, fn) => fn(null, { + const stream = Readable.from(stringify({ path, files, + })); + + assign(stream, { + path, + files, + type: 'directory', }); - mockRequire('flop', { - read + const read = stub().resolves(stream); + + cloudcmd.depStore('win32', { + read, + }); + const {request} = serveOnce(cloudcmd, { + config: defaultConfig, }); - clear(routePath); - clear(cloudcmdPath); - clear(beforePath); + const {status} = await request.get('/'); - const {connect} = require(beforePath); - const {port, done} = await connect(); + cloudcmd.depStore(); - await getStr(`http://localhost:${port}`); - - t.pass('should not hang up'); - - mockRequire.stop('flo'); - clear(routePath); - clear(cloudcmdPath); - clear(beforePath); - - await done(); + t.equal(status, 200, 'should not hang up'); t.end(); }); test('cloudcmd: route: buttons: no terminal', async (t) => { const config = { - terminal: false + terminal: false, }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const options = { + config, + }; - t.ok(/icon-terminal none/.test(result), 'should hide terminal'); + const {body} = await request.get('/', { + options, + }); - await done(); + t.match(body, 'icon-terminal none', 'should hide terminal'); + t.end(); +}); + +test('cloudcmd: route: no terminal: /fs', async (t) => { + const config = { + terminal: false, + }; + + const options = { + config, + configManager: createConfigManager(), + }; + + const {request} = serveOnce(cloudcmd); + + const {body} = await request.get('/fs', { + options, + }); + + t.match(body, 'icon-terminal none', 'should hide terminal'); + t.end(); +}); + +test('cloudcmd: route: buttons: terminal: can not load', async (t) => { + const config = { + terminal: true, + terminalPath: 'xxxxxxxxxxxx', + }; + + const options = { + config, + }; + + const {body} = await request.get('/', { + options, + }); + + t.match(body, 'icon-terminal none', 'should not enable terminal'); t.end(); }); @@ -358,12 +371,90 @@ test('cloudcmd: route: buttons: terminal', async (t) => { terminalPath: 'gritty', }; - const {port, done} = await connect({config}); - const result = await getStr(`http://localhost:${port}`); + const options = { + config, + }; - t.notOk(/icon-terminal none/.test(result), 'should enable terminal'); + const {body} = await request.get('/', { + options, + }); - await done(); + t.notOk(/icon-terminal none/.test(body), 'should not enable terminal'); t.end(); }); +test('cloudcmd: route: buttons: contact', async (t) => { + const config = { + contact: true, + }; + + const options = { + config, + }; + + const {request} = serveOnce(cloudcmd); + + const {body} = await request.get('/', { + options, + }); + + t.notOk(/icon-contact none/.test(body), 'should enable terminal'); + t.end(); +}); + +test('cloudcmd: route: dropbox', async (t) => { + const config = createConfigManager(); + config('dropbox', true); + config('dropboxToken', ''); + + const readdir = _getReadDir(config); + const [e] = await tryToCatch(readdir, '/root'); + + t.match(e.message, 'API', 'should contain word token in message'); + t.end(); +}); + +test('cloudcmd: route: content length', async (t) => { + const options = { + root: fixtureDir, + }; + + const {headers} = await request.get('/route.js', { + options, + }); + + const result = headers.get('content-length'); + + t.ok(result); + t.end(); +}); + +test('cloudcmd: route: read: root', async (t) => { + const stream = Readable.from('hello'); + + stream.contentLength = 5; + + const read = stub().returns(stream); + cloudcmd.depStore('win32', { + read, + }); + + const configManager = createConfigManager(); + const root = '/hello'; + + configManager('root', root); + + const {request} = serveOnce(cloudcmd, { + configManager, + }); + + await request.get('/fs/route.js'); + cloudcmd.depStore(); + + const expected = ['/hello/route.js', { + root, + }]; + + t.calledWith(read, expected); + t.end(); +}); diff --git a/server/server.js b/server/server.js index 061cd3d6..06b6464a 100644 --- a/server/server.js +++ b/server/server.js @@ -1,67 +1,94 @@ -'use strict'; +import http from 'node:http'; +import {promisify} from 'node:util'; +import process from 'node:process'; +import {rateLimit} from 'express-rate-limit'; +import currify from 'currify'; +import squad from 'squad'; +import {tryToCatch} from 'try-to-catch'; +import opn from 'open'; +import express from 'express'; +import {Server} from 'socket.io'; +import wraptile from 'wraptile'; +import compression from 'compression'; +import tryRequire from 'tryrequire'; +import {cloudcmd} from '#server/cloudcmd'; +import exit from './exit.js'; -const DIR_SERVER = './'; -const cloudcmd = require(DIR_SERVER + 'cloudcmd'); +const RATE_LIMIT = 1000; +const RATE_WINDOW = 15 * 60 * 1000; -const http = require('http'); -const {promisify} = require('util'); -const currify = require('currify'); -const squad = require('squad'); -const tryToCatch = require('try-to-catch'); - -const config = require(DIR_SERVER + 'config'); +const bind = (f, self) => f.bind(self); const two = currify((f, a, b) => f(a, b)); -const exit = require(DIR_SERVER + 'exit'); +const shutdown = wraptile(async (config, promises) => { + if (config('log')) + console.log('closing cloudcmd...'); + + await Promise.all(promises); + process.exit(0); +}); -const exitPort = two(exit, 'cloudcmd --port: %s'); -const bind = (f, self) => f.bind(self); const promisifySelf = squad(promisify, bind); -const opn = require('opn'); -const express = require('express'); -const io = require('socket.io'); +const exitPort = two(exit, 'cloudcmd --port: %s'); -const tryRequire = require('tryrequire'); const logger = tryRequire('morgan'); -module.exports = async (options) => { +export default async (options, config) => { const prefix = config('prefix'); - const port = process.env.PORT || /* c9 */ - config('port'); + const port = process.env.PORT /* c9 */ || config('port'); - const ip = process.env.IP || /* c9 */ - config('ip') || - '0.0.0.0'; + const ip = process.env.IP /* c9 */ || config('ip') || '0.0.0.0'; const app = express(); const server = http.createServer(app); - if (logger) + if (config('log') && logger) app.use(logger('dev')); if (prefix) - app.get('/', (req, res) => res.redirect(prefix + '/')); + app.get('/', (req, res) => res.redirect(`${prefix}/`)); + const socketServer = new Server(server, { + path: `${prefix}/socket.io`, + }); + + const limiter = rateLimit({ + windowMs: RATE_WINDOW, + limit: RATE_LIMIT, + }); + + app.set('trust proxy', 1); + + app.use(compression()); + app.use(limiter); app.use(prefix, cloudcmd({ config: options, - socket: io(server, { - path: `${prefix}/socket.io`, - }), + socket: socketServer, + configManager: config, })); - if (port < 0 || port > 65535) + if (port < 0 || port > 65_535) return exitPort('port number could be 1..65535, 0 means any available port'); const listen = promisifySelf(server.listen, server); + const closeServer = promisifySelf(server.close, server); + const closeSocket = promisifySelf(socketServer.close, socketServer); server.on('error', exitPort); await listen(port, ip); + const close = shutdown(config, [closeServer, closeSocket]); + + process.on('SIGINT', close); + process.on('SIGUSR1', close); + const host = config('ip') || 'localhost'; const port0 = port || server.address().port; const url = `http://${host}:${port0}${prefix}/`; - console.log('url:', url); + + if (config('log')) + console.log(`url: ${url}`); if (!config('open')) return; @@ -71,4 +98,3 @@ module.exports = async (options) => { if (openError) console.error('cloudcmd --open:', openError.message); }; - diff --git a/server/show-config.js b/server/show-config.js index 10f8a8c5..f151dd10 100644 --- a/server/show-config.js +++ b/server/show-config.js @@ -1,16 +1,17 @@ -'use strict'; - -const { +import { table, getBorderCharacters, -} = require('table'); +} from 'table'; -module.exports = (config) => { +export const showConfig = (config) => { check(config); - const data = Object.keys(config).map((name) => { - return [name, config[name]]; - }); + const data = Object + .keys(config) + .map((name) => [ + name, + config[name], + ]); if (!data.length) return ''; @@ -20,7 +21,7 @@ module.exports = (config) => { 1: { width: 30, truncate: 30, - } + }, }, border: getBorderCharacters('ramac'), }); @@ -33,4 +34,3 @@ function check(config) { if (typeof config !== 'object') throw Error('config should be an object!'); } - diff --git a/test/server/show-config.js b/server/show-config.spec.js similarity index 55% rename from test/server/show-config.js rename to server/show-config.spec.js index d2d597db..b25e56a2 100644 --- a/test/server/show-config.js +++ b/server/show-config.spec.js @@ -1,27 +1,29 @@ -'use strict'; - -const test = require('tape'); -const showConfig = require('../../server/show-config'); +import {test} from 'supertape'; +import {tryCatch} from 'try-catch'; +import {showConfig} from './show-config.js'; test('cloudcmd: show-config: no arguments', (t) => { - t.throws(showConfig, /config could not be empty!/, 'should throw when no config'); + const [error] = tryCatch(showConfig); + + t.equal(error.message, 'config could not be empty!', 'should throw when no config'); t.end(); }); test('cloudcmd: show-config: bad arguments', (t) => { - const fn = () => showConfig('hello'); - t.throws(fn, /config should be an object!/, 'should throw when config not object'); + const [error] = tryCatch(showConfig, 'hello'); + + t.equal(error.message, 'config should be an object!', 'should throw when config not object'); t.end(); }); -test('cloudcmd: show-config: return', (t) => { +test('cloudcmd: show-config: empty: return', (t) => { t.equal(showConfig({}), '', 'should return string'); t.end(); }); test('cloudcmd: show-config: return', (t) => { const config = { - hello: 'world' + hello: 'world', }; const result = [ @@ -33,4 +35,3 @@ test('cloudcmd: show-config: return', (t) => { t.equal(showConfig(config), result, 'should return table'); t.end(); }); - diff --git a/server/template.js b/server/template.js index 150b63fd..0e705e79 100644 --- a/server/template.js +++ b/server/template.js @@ -1,8 +1,9 @@ -'use strict'; +import path, {dirname} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import readFilesSync from '@cloudcmd/read-files-sync'; -const path = require('path'); -const readFilesSync = require('@cloudcmd/read-files-sync'); +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); const templatePath = path.join(__dirname, '..', 'tmpl/fs'); -module.exports = readFilesSync(templatePath, 'utf8'); - +export default readFilesSync(templatePath, 'utf8'); diff --git a/server/terminal.js b/server/terminal.js index af40d224..c6d80df9 100644 --- a/server/terminal.js +++ b/server/terminal.js @@ -1,18 +1,26 @@ -'use strict'; +import {createRequire} from 'node:module'; +import {tryCatch} from 'try-catch'; -const tryCatch = require('try-catch'); -const config = require('./config'); +const require = createRequire(import.meta.url); + +const noop = (req, res, next) => { + next && next(); +}; -const noop = () => {}; noop.listen = noop; -module.exports = (arg) => getTerminal(config('terminal'), arg); +const parseDefault = (a) => a.default || a; +const _getModule = (a) => parseDefault(require(a)); -function getTerminal(term, arg) { - if (!term) +export default (config, arg, overrides = {}) => { + const { + getModule = _getModule, + } = overrides; + + if (!config('terminal')) return noop; - const [e, terminalModule] = tryCatch(require, config('terminalPath')); + const [e, terminalModule] = tryCatch(getModule, config('terminalPath')); if (!e && !arg) return terminalModule; @@ -24,5 +32,4 @@ function getTerminal(term, arg) { console.log(`cloudcmd --terminal: ${e.message}`); return noop; -} - +}; diff --git a/server/terminal.spec.js b/server/terminal.spec.js new file mode 100644 index 00000000..22f20282 --- /dev/null +++ b/server/terminal.spec.js @@ -0,0 +1,73 @@ +import {test, stub} from 'supertape'; +import {createConfigManager} from '#server/cloudcmd'; +import terminal from './terminal.js'; + +test('cloudcmd: terminal: disabled', (t) => { + const config = createConfigManager(); + config('terminal', false); + + const fn = terminal(config); + + t.notOk(fn(), 'should return noop'); + t.end(); +}); + +test('cloudcmd: terminal: disabled: listen', (t) => { + const config = createConfigManager(); + config('terminal', false); + + const fn = terminal(config).listen(); + + t.notOk(fn, 'should return noop'); + t.end(); +}); + +test('cloudcmd: terminal: enabled', (t) => { + const term = stub(); + const arg = 'hello'; + const config = stub().returns(true); + const getModule = stub().returns(term); + + terminal(config, arg, { + getModule, + }); + + t.calledWith(term, [arg], 'should call terminal'); + t.end(); +}); + +test('cloudcmd: terminal: enabled: no string', (t) => { + const {log: originalLog} = console; + const log = stub(); + + console.log = log; + const config = createConfigManager(); + + config('terminal', true); + config('terminalPath', 'hello'); + terminal(config); + + console.log = originalLog; + + const msg = `cloudcmd --terminal: Cannot find module 'hello'`; + const [arg] = log.args[0]; + + t.match(arg, RegExp(msg), 'should call with msg'); + t.end(); +}); + +test('cloudcmd: terminal: no arg', (t) => { + const gritty = {}; + const getModule = stub().returns(gritty); + const config = createConfigManager(); + + config('terminal', true); + config('terminalPath', 'gritty'); + + const result = terminal(config, '', { + getModule, + }); + + t.equal(result, gritty); + t.end(); +}); diff --git a/server/theme.js b/server/theme.js new file mode 100644 index 00000000..d66623b5 --- /dev/null +++ b/server/theme.js @@ -0,0 +1,33 @@ +import path, {dirname} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import process from 'node:process'; +import fs from 'node:fs'; +import {fullstore} from 'fullstore'; +import * as nanomemoizeDefault from 'nano-memoize'; +import readFilesSync from '@cloudcmd/read-files-sync'; + +const nanomemoize = nanomemoizeDefault.default.nanomemoize || nanomemoizeDefault.default; +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const isMap = (a) => /\.(map|js)$/.test(a); +const not = (fn) => (a) => !fn(a); + +const _isDev = fullstore(process.env.NODE_ENV === 'development'); +const getDist = (isDev) => isDev ? 'dist-dev' : 'dist'; + +export const isDev = _isDev; + +export const getThemes = ({isDev = _isDev()} = {}) => { + return readFilesSyncMemo(isDev); +}; + +const readFilesSyncMemo = nanomemoize((isDev) => { + const dist = getDist(isDev); + const themesDir = path.join(__dirname, '..', dist, 'themes'); + + const names = fs + .readdirSync(themesDir) + .filter(not(isMap)); + + return readFilesSync(themesDir, names, 'utf8'); +}); diff --git a/server/themes.spec.js b/server/themes.spec.js new file mode 100644 index 00000000..709896e8 --- /dev/null +++ b/server/themes.spec.js @@ -0,0 +1,50 @@ +import {dirname} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import fs from 'node:fs'; +import test from 'supertape'; +import {getThemes, isDev} from './theme.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +test('themes: dev', (t) => { + const themes = getThemes({ + isDev: true, + }); + + const css = fs.readFileSync(`${__dirname}/../css/themes/dark.css`, 'utf8'); + const result = themes.dark.includes(css); + + t.ok(result); + t.end(); +}); + +test('themes: no args', (t) => { + const currentIsDev = isDev(); + isDev(true); + const themes = getThemes(); + + const css = fs.readFileSync(`${__dirname}/../css/themes/light.css`, 'utf8'); + isDev(currentIsDev); + + t.match(themes.light, css); + t.end(); +}); + +test('themes: production', (t) => { + const themes = getThemes({ + isDev: false, + }); + + t.ok(themes.dark, 'should have dark theme'); + t.end(); +}); + +test('themes: production: light', (t) => { + const themes = getThemes({ + isDev: false, + }); + + t.ok(themes.light, 'should have light theme'); + t.end(); +}); diff --git a/server/user-menu.js b/server/user-menu.js new file mode 100644 index 00000000..53599553 --- /dev/null +++ b/server/user-menu.js @@ -0,0 +1,125 @@ +import {homedir} from 'node:os'; +import {readFile as _readFile} from 'node:fs/promises'; +import {join} from 'node:path'; +// warm up worker cache +import {montag} from 'montag'; +import {tryToCatch} from 'try-to-catch'; +import currify from 'currify'; +import {putout, codeframe} from 'putout'; + +// warm up worker cache +transpile(''); + +const PREFIX = '/api/v1/user-menu'; + +export const userMenu = currify(async ({menuName, readFile = _readFile, config}, req, res, next) => { + if (!req.url.startsWith(PREFIX)) + return next(); + + const {method} = req; + + if (method === 'GET') + return await onGET({ + req, + res, + menuName, + readFile, + config, + }); + + next(); +}); + +async function onGET({req, res, menuName, readFile, config}) { + const {dir} = req.query; + const url = req.url.replace(PREFIX, ''); + + if (url === '/default') + return await sendDefaultMenu(res, { + readFile, + }); + + const {findUp} = await import('find-up'); + + const cwd = join(config('root'), dir); + const [errorFind, currentMenuPath] = await tryToCatch(findUp, [menuName], { + cwd, + }); + + if (errorFind && errorFind.code !== 'ENOENT') + return res + .status(404) + .send(errorFind.message); + + const homeMenuPath = join(homedir(), menuName); + const menuPath = currentMenuPath || homeMenuPath; + const [e, source] = await tryToCatch(readFile, menuPath, 'utf8'); + + if (e && e.code !== 'ENOENT') + return res + .status(404) + .send(e.message); + + if (e) + return await sendDefaultMenu(res, { + readFile, + }); + + const [parseError, result] = await transpile(source); + + if (parseError) + return res + .type('js') + .send(getError(parseError, source)); + + res + .type('js') + .send(result.code); +} + +function getError(error, source) { + return montag` + const e = Error(\`
    ${codeframe({
    +            error,
    +            source,
    +            highlightCode: false,
    +        })}
    \`); + + e.code = 'frame'; + + throw e; + `; +} + +async function sendDefaultMenu(res, {readFile}) { + const menu = await getDefaultMenu({ + readFile, + }); + + res + .type('js') + .send(menu); +} + +async function transpile(source) { + return await tryToCatch(putout, source, { + rules: { + 'nodejs/convert-esm-to-commonjs': 'on', + }, + plugins: [ + 'nodejs', + 'cloudcmd', + ], + }); +} + +async function getDefaultMenu({readFile}) { + const DEFAULT_MENU_PATH = new URL('../static/user-menu.js', import.meta.url).pathname; + const menu = await readFile(DEFAULT_MENU_PATH, 'utf8'); + const [error, result] = await transpile(menu); + + if (error) + return String(error); + + return result.code; +} diff --git a/server/user-menu.spec.js b/server/user-menu.spec.js new file mode 100644 index 00000000..7c5fcf2c --- /dev/null +++ b/server/user-menu.spec.js @@ -0,0 +1,129 @@ +import {dirname, join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {readFileSync} from 'node:fs'; +import {test, stub} from 'supertape'; +import {serveOnce} from 'serve-once'; +import {putout} from 'putout'; +import {userMenu} from './user-menu.js'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const {request} = serveOnce(userMenu); +const userMenuPath = join(__dirname, '..', '.cloudcmd.menu.js'); + +const fixtureDir = new URL('fixture-user-menu', import.meta.url).pathname; +const fixtureMoveName = join(fixtureDir, 'io-mv.js'); +const fixtureMoveFixName = join(fixtureDir, 'io-mv-fix.js'); +const fixtureCopyName = join(fixtureDir, 'io-cp.js'); +const fixtureCopyFixName = join(fixtureDir, 'io-cp-fix.js'); + +const fixtureMove = readFileSync(fixtureMoveName, 'utf8'); +const fixtureMoveFix = readFileSync(fixtureMoveFixName, 'utf8'); +const fixtureCopy = readFileSync(fixtureCopyName, 'utf8'); +const fixtureCopyFix = readFileSync(fixtureCopyFixName, 'utf8'); + +test('cloudcmd: user menu', async (t) => { + const config = stub().returns(''); + const userMenuFile = getUserMenuFile(); + + const options = { + config, + menuName: '.cloudcmd.menu.js', + }; + + const {body} = await request.get(`/api/v1/user-menu?dir=${__dirname}`, { + options, + }); + + t.equal(userMenuFile, body); + t.end(); +}); + +test('cloudcmd: user menu: io.mv', async (t) => { + const config = stub().returns(''); + const readFile = stub().returns(fixtureMove); + + const options = { + menuName: '.cloudcmd.menu.js', + readFile, + config, + }; + + const {request} = serveOnce(userMenu); + + const {body} = await request.get(`/api/v1/user-menu?dir=${__dirname}`, { + options, + }); + + t.equal(body, fixtureMoveFix); + t.end(); +}); + +test('cloudcmd: user menu: default menu', async (t) => { + const config = stub().returns(''); + const options = { + menuName: '111.cloudcmd.menu.js', + config, + }; + + const {request} = serveOnce(userMenu); + + const {body} = await request.get(`/api/v1/user-menu?dir=abcd`, { + options, + }); + + t.match(body, 'module.exports'); + t.end(); +}); + +test('cloudcmd: user menu: io.cp', async (t) => { + const config = stub().returns(''); + const readFile = stub().returns(fixtureCopy); + + const options = { + menuName: '.cloudcmd.menu.js', + readFile, + config, + }; + + const {request} = serveOnce(userMenu); + + const {body} = await request.get(`/api/v1/user-menu?dir=${__dirname}`, { + options, + }); + + t.equal(body, fixtureCopyFix); + t.end(); +}); + +test('cloudcmd: user menu: broken file', async (t) => { + const readFile = stub().returns('sdfsdf /; s'); + const options = { + menuName: '.cloudcmd.menu.js', + readFile, + }; + + const {request} = serveOnce(userMenu); + + const {body} = await request.get(`/api/v1/user-menu/default`, { + options, + }); + + const expected = 'SyntaxError: Unexpected token (1:8)'; + + t.equal(body, expected); + t.end(); +}); + +function getUserMenuFile() { + const userMenuFile = readFileSync(userMenuPath, 'utf8'); + const {code} = putout(userMenuFile, { + rules: { + 'nodejs/convert-esm-to-commonjs': 'on', + }, + plugins: ['nodejs'], + }); + + return code; +} diff --git a/server/validate.js b/server/validate.js index 9280b606..e01d0505 100644 --- a/server/validate.js +++ b/server/validate.js @@ -1,44 +1,63 @@ -'use strict'; +import {statSync as _statSync} from 'node:fs'; +import {tryCatch} from 'try-catch'; +import _exit from './exit.js'; +import {getColumns as _getColumns} from './columns.js'; +import {getThemes as _getThemes} from './theme.js'; -const exit = require('./exit'); -const columns = require('./columns'); +const isString = (a) => typeof a === 'string'; -module.exports.root = (dir, fn) => { - if (typeof dir !== 'string') +export const root = (dir, config, overrides = {}) => { + const { + exit = _exit, + statSync = _statSync, + } = overrides; + + if (!isString(dir)) throw Error('dir should be a string'); if (dir === '/') return; - const fs = require('fs'); + if (config('dropbox')) + return; - fs.stat(dir, (error) => { - if (error) - return exit('cloudcmd --root: %s', error.message); - - if (typeof fn === 'function') - fn('root:', dir); - }); + const [error] = tryCatch(statSync, dir); + + if (error) + return exit('cloudcmd --root: %s', error.message); }; -module.exports.editor = (name) => { - const reg = /^(dword|edward|deepword)$/; +export const editor = (name, {exit = _exit} = {}) => { + const reg = /^(dword|edward|deepword|qword)$/; if (!reg.test(name)) - exit('cloudcmd --editor: could be "dword", "edward" or "deepword" only'); + exit(`cloudcmd --editor: could be "dword", "edward", "deepword" or "qword" only, received: "${name}"`); }; -module.exports.packer = (name) => { +export const menu = (name, {exit = _exit} = {}) => { + const reg = /^(supermenu|aleman)$/; + + if (!reg.test(name)) + exit('cloudcmd --menu: could be "supermenu" or "aleman" only'); +}; + +export const packer = (name, {exit = _exit} = {}) => { const reg = /^(tar|zip)$/; if (!reg.test(name)) exit('cloudcmd --packer: could be "tar" or "zip" only'); }; -module.exports.columns = (type) => { +export const columns = (type, overrides = {}) => { + const { + exit = _exit, + getColumns = _getColumns, + } = overrides; + const addQuotes = (a) => `"${a}"`; + const all = Object - .keys(columns) + .keys(getColumns()) .concat(''); const names = all @@ -46,7 +65,27 @@ module.exports.columns = (type) => { .map(addQuotes) .join(', '); - if (!~all.indexOf(type)) + if (!all.includes(type)) exit(`cloudcmd --columns: can be only one of: ${names}`); }; +export const theme = (type, overrides = {}) => { + const { + exit = _exit, + getThemes = _getThemes, + } = overrides; + + const addQuotes = (a) => `"${a}"`; + + const all = Object + .keys(getThemes()) + .concat(''); + + const names = all + .filter(Boolean) + .map(addQuotes) + .join(', '); + + if (!all.includes(type)) + exit(`cloudcmd --theme: can be only one of: ${names}`); +}; diff --git a/server/validate.spec.js b/server/validate.spec.js new file mode 100644 index 00000000..639f185c --- /dev/null +++ b/server/validate.spec.js @@ -0,0 +1,156 @@ +import {test, stub} from 'supertape'; +import {tryCatch} from 'try-catch'; +import {cloudcmd} from '#server/cloudcmd'; +import * as validate from './validate.js'; + +test('validate: root: bad', (t) => { + const config = { + root: Math.random(), + }; + + const [e] = tryCatch(cloudcmd, { + config, + }); + + t.equal(e.message, 'dir should be a string', 'should throw'); + t.end(); +}); + +test('validate: root: config', (t) => { + const config = stub().returns(true); + + validate.root('/hello', config); + + t.calledWith(config, ['dropbox'], 'should call config'); + t.end(); +}); + +test('validate: root: /', (t) => { + const fn = stub(); + validate.root('/', fn); + + t.notCalled(fn, 'should not call fn'); + t.end(); +}); + +test('validate: root: stat', (t) => { + const config = stub(); + const error = 'ENOENT'; + const statSync = stub().throws(Error(error)); + const exit = stub(); + + validate.root('hello', config, { + statSync, + exit, + }); + + const msg = 'cloudcmd --root: %s'; + + t.calledWith(exit, [msg, error], 'should call fn'); + t.end(); +}); + +test('validate: packer: not valid', (t) => { + const exit = stub(); + const msg = 'cloudcmd --packer: could be "tar" or "zip" only'; + + validate.packer('hello', { + exit, + }); + + t.calledWith(exit, [msg], 'should call fn'); + t.end(); +}); + +test('validate: editor: not valid', (t) => { + const exit = stub(); + const msg = 'cloudcmd --editor: could be "dword", "edward", "deepword" or "qword" only, received: "hello"'; + + validate.editor('hello', { + exit, + }); + + t.calledWith(exit, [msg], 'should call fn'); + t.end(); +}); + +test('validate: columns', (t) => { + const exit = stub(); + + validate.columns('name-size-date', { + exit, + }); + + t.notCalled(exit, 'should not call exit'); + t.end(); +}); + +test('validate: columns: wrong', (t) => { + const getColumns = stub().returns({ + 'name-size-date': '', + 'name-size': '', + }); + + const exit = stub(); + const msg = 'cloudcmd --columns: can be only one of: "name-size-date", "name-size"'; + + validate.columns('hello', { + exit, + getColumns, + }); + + t.calledWith(exit, [msg], 'should call exit'); + t.end(); +}); + +test('validate: theme', (t) => { + const exit = stub(); + + validate.theme('dark', { + exit, + }); + + t.notCalled(exit, 'should not call exit'); + t.end(); +}); + +test('validate: theme: wrong', (t) => { + const getThemes = stub().returns({ + light: '', + dark: '', + }); + + const exit = stub(); + const msg = 'cloudcmd --theme: can be only one of: "light", "dark"'; + + validate.theme('hello', { + exit, + getThemes, + }); + + t.calledWith(exit, [msg], 'should call exit'); + t.end(); +}); + +test('validate: menu: not valid', (t) => { + const exit = stub(); + const msg = 'cloudcmd --menu: could be "supermenu" or "aleman" only'; + + validate.menu('hello', { + exit, + }); + + t.calledWith(exit, [msg], 'should call fn'); + t.end(); +}); + +test('validate: menu: valid', (t) => { + const exit = stub(); + + validate.menu('supermenu', { + exit, + }); + + t.notCalled(exit, 'should not call fn'); + t.end(); +}); diff --git a/static/user-menu.js b/static/user-menu.js new file mode 100644 index 00000000..1252aca9 --- /dev/null +++ b/static/user-menu.js @@ -0,0 +1,168 @@ +const RENAME_FILE = 'Rename file'; +const CDN = 'https://cdn.jsdelivr.net'; +const CDN_GH = `${CDN}/gh/cloudcmd/user-menu@1.2.4`; + +export default { + '__settings': { + select: [RENAME_FILE], + run: false, + }, + [`F2 - ${RENAME_FILE}`]: async ({DOM}) => { + await DOM.renameCurrent(); + }, + + 'F6 - Copy URL to current file': runFromCDN('copy-url-to-current-file'), + + 'R - cd /': async ({CloudCmd}) => { + await CloudCmd.changeDir('/'); + }, + 'Y - Convert YouTube to MP3': async ({CloudCmd, DOM}) => { + const {convertYouTubeToMp3} = await import(`${CDN}/menu/convert-youtube-to-mp3.js`); + + await convertYouTubeToMp3({ + CloudCmd, + DOM, + }); + }, + + 'F - Convert flac to mp3 [ffmpeg]': async ({CloudCmd, DOM}) => { + const {convertFlacToMp3} = await import(`${CDN}/menu/ffmpeg.js`); + + await convertFlacToMp3({ + CloudCmd, + DOM, + }); + }, + 'M - Convert mp4 to mp3 [ffmpeg]': async ({CloudCmd, DOM}) => { + const {convertMp4ToMp3} = await import(`${CDN}/menu/ffmpeg.js`); + + await convertMp4ToMp3({ + CloudCmd, + DOM, + }); + }, + + 'O - Convert mov to mp3 [ffmpeg]': async ({CloudCmd, DOM}) => { + const {convertMovToMp3} = await import(`${CDN}/menu/ffmpeg.js`); + + await convertMovToMp3({ + CloudCmd, + DOM, + }); + }, + + 'C - Create User Menu File': async ({DOM, CloudCmd}) => { + const {Dialog, CurrentInfo} = DOM; + + const currentFile = DOM.getCurrentByName('.cloudcmd.menu.js'); + + if (currentFile) { + const [cancel] = await Dialog.confirm(`Looks like file '.cloudcmd.menu.js' already exists. Overwrite?`); + + if (cancel) + return; + } + + const {dirPath} = CurrentInfo; + const path = `${dirPath}.cloudcmd.menu.js`; + const {prefix} = CloudCmd; + + const data = await readDefaultMenu({ + prefix, + }); + + await createDefaultMenu({ + path, + data, + DOM, + CloudCmd, + }); + }, + 'D - Compare directories': ({DOM}) => { + const { + CurrentInfo, + getFilenames, + getCurrentByName, + selectFile, + } = DOM; + + const { + files, + filesPassive, + panel, + panelPassive, + } = CurrentInfo; + + const names = getFilenames(files); + const namesPassive = getFilenames(filesPassive); + + const selectedNames = compare(names, namesPassive); + const selectedNamesPassive = compare(namesPassive, names); + + selectNames(selectedNames, panel, { + selectFile, + getCurrentByName, + }); + + selectNames(selectedNamesPassive, panelPassive, { + selectFile, + getCurrentByName, + }); + }, +}; + +async function createDefaultMenu({path, data, DOM, CloudCmd}) { + const {IO} = DOM; + + await IO.write(path, data); + await CloudCmd.refresh(); + + DOM.setCurrentByName('.cloudcmd.menu.js'); + + await CloudCmd.EditFile.show(); +} + +async function readDefaultMenu({prefix}) { + const res = await fetch(`${prefix}/api/v1/user-menu/default`); + + return await res.text(); +} + +export const _selectNames = selectNames; + +function selectNames(names, panel, {selectFile, getCurrentByName}) { + for (const name of names) { + const file = getCurrentByName(name, panel); + selectFile(file); + } +} + +export const _compare = compare; + +function compare(a, b) { + const result = []; + + for (const el of a) { + if (b.includes(el)) + continue; + + result.push(el); + } + + return result; +} + +const MAP = { + 'copy-url-to-current-file': 'copyURLToCurrentFile', +}; + +function runFromCDN(name) { + return async (...a) => { + const fnName = MAP[name]; + const { + [fnName]: fn, + } = await import(`${CDN_GH}/menu/${name}.js`); + + await fn(...a); + }; +} diff --git a/static/user-menu.spec.js b/static/user-menu.spec.js new file mode 100644 index 00000000..76f3a517 --- /dev/null +++ b/static/user-menu.spec.js @@ -0,0 +1,343 @@ +import {stub} from '@cloudcmd/stub'; +import {tryToCatch} from 'try-to-catch'; +import wraptile from 'wraptile'; +import {test as tape} from 'supertape'; +import autoGlobals from 'auto-globals'; +import defaultMenu, {_selectNames, _compare} from './user-menu.js'; + +const test = autoGlobals(tape); +const {create} = autoGlobals; +const {_data} = defaultMenu; + +const reject = wraptile(async (a) => { + throw Error(a); +}); + +test('cloudcmd: static: user menu: Rename', async (t) => { + const name = 'F2 - Rename file'; + const DOM = getDOM(); + + const {renameCurrent} = DOM; + + await defaultMenu[name]({ + DOM, + }); + + t.ok(renameCurrent.called, 'should call renameCurrent'); + t.end(); +}); + +test('cloudcmd: static: user menu: R', (t) => { + const name = 'R - cd /'; + const changeDir = stub(); + + const CloudCmd = { + changeDir, + }; + + const fn = defaultMenu[name]; + + fn({ + CloudCmd, + }); + + t.calledWith(changeDir, ['/']); + t.end(); +}); + +test('cloudcmd: static: user menu: F6', async (t) => { + const name = 'F6 - Copy URL to current file'; + const DOM = {}; + + const fn = defaultMenu[name]; + const [error] = await tryToCatch(fn, { + DOM, + }); + + t.equal(error.code, 'ERR_UNSUPPORTED_ESM_URL_SCHEME'); + t.end(); +}); + +test('cloudcmd: static: user menu: Y', async (t) => { + const name = 'Y - Convert YouTube to MP3'; + const DOM = {}; + + const fn = defaultMenu[name]; + const [error] = await tryToCatch(fn, { + DOM, + }); + + t.equal(error.code, 'ERR_UNSUPPORTED_ESM_URL_SCHEME'); + t.end(); +}); + +test('cloudcmd: static: user menu: F', async (t) => { + const name = 'F - Convert flac to mp3 [ffmpeg]'; + const DOM = {}; + + const fn = defaultMenu[name]; + const [error] = await tryToCatch(fn, { + DOM, + }); + + t.equal(error.code, 'ERR_UNSUPPORTED_ESM_URL_SCHEME'); + t.end(); +}); + +test('cloudcmd: static: user menu: M', async (t) => { + const name = 'M - Convert mp4 to mp3 [ffmpeg]'; + const DOM = {}; + + const fn = defaultMenu[name]; + const [error] = await tryToCatch(fn, { + DOM, + }); + + t.equal(error.code, 'ERR_UNSUPPORTED_ESM_URL_SCHEME'); + t.end(); +}); + +test('cloudcmd: static: user menu: O', async (t) => { + const name = 'O - Convert mov to mp3 [ffmpeg]'; + const DOM = {}; + + const fn = defaultMenu[name]; + const [error] = await tryToCatch(fn, { + DOM, + }); + + t.equal(error.code, 'ERR_UNSUPPORTED_ESM_URL_SCHEME'); + t.end(); +}); + +test('cloudcmd: static: user menu: IO.write', async (t) => { + const name = 'C - Create User Menu File'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + const {write} = DOM.IO; + + await defaultMenu[name]({ + DOM, + CloudCmd, + }); + + const path = '/.cloudcmd.menu.js'; + + t.calledWith(write, [path, _data], 'should call IO.write'); + t.end(); +}); + +test('cloudcmd: static: user menu: C: exists: ok', async (t) => { + const name = 'C - Create User Menu File'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + + const { + Dialog, + getCurrentByName, + } = DOM; + + const {confirm} = Dialog; + const {write} = DOM.IO; + + getCurrentByName.returns({}); + confirm.resolves([]); + + await defaultMenu[name]({ + DOM, + CloudCmd, + }); + + const path = '/.cloudcmd.menu.js'; + + t.calledWith(write, [path, _data], 'should call IO.write'); + t.end(); +}); + +test('cloudcmd: static: user menu: C: exists: cancel', async (t) => { + const name = 'C - Create User Menu File'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + + const { + Dialog, + getCurrentByName, + } = DOM; + + const {confirm} = Dialog; + const {write} = DOM.IO; + + getCurrentByName.returns({}); + confirm.resolves([ + Error('cancel'), + ]); + + await defaultMenu[name]({ + DOM, + CloudCmd, + }); + + t.notCalled(write); + t.end(); +}); + +test('cloudcmd: static: user menu: refresh', async (t) => { + const name = 'C - Create User Menu File'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + const {refresh} = CloudCmd; + + await defaultMenu[name]({ + DOM, + CloudCmd, + }); + + t.calledWithNoArgs(refresh, 'should call CloudCmd.refresh'); + t.end(); +}); + +test('cloudcmd: static: user menu: setCurrentByName', async (t) => { + const name = 'C - Create User Menu File'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + const {setCurrentByName} = DOM; + + await defaultMenu[name]({ + DOM, + CloudCmd, + }); + + const fileName = '.cloudcmd.menu.js'; + + t.calledWith(setCurrentByName, [fileName], 'should call DOM.setCurrentByName'); + t.end(); +}); + +test('cloudcmd: static: user menu: EditFile.show', async (t) => { + const name = 'C - Create User Menu File'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + const {EditFile} = CloudCmd; + + await defaultMenu[name]({ + DOM, + CloudCmd, + }); + + t.ok(EditFile.show.called, 'should call EditFile.show'); + t.end(); +}); + +test('cloudcmd: static: user menu: no EditFile.show', async (t) => { + const name = 'C - Create User Menu File'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + const {IO} = DOM; + const {EditFile} = CloudCmd; + + IO.write = stub(reject('Error')); + + await tryToCatch(defaultMenu[name], { + DOM, + CloudCmd, + }); + + t.notCalled(EditFile.show, 'should not call EditFile.show'); + t.end(); +}); + +test('cloudcmd: static: user menu: compare directories', (t) => { + const name = 'D - Compare directories'; + const DOM = getDOM(); + const CloudCmd = getCloudCmd(); + + defaultMenu[name]({ + DOM, + CloudCmd, + }); + + const {files} = DOM.CurrentInfo; + + t.calledWith(DOM.getFilenames, [files], 'should call getFilenames'); + t.end(); +}); + +test('cloudcmd: static: user menu: compare directories: select names', (t) => { + const selectFile = stub(); + const file = {}; + const getCurrentByName = stub().returns(file); + + const names = ['hi']; + const panel = {}; + + _selectNames(names, panel, { + selectFile, + getCurrentByName, + }); + + t.calledWith(selectFile, [file], 'should call selectFile'); + t.end(); +}); + +test('cloudcmd: static: user menu: compare directories: select names: getCurrentByName', (t) => { + const selectFile = stub(); + const getCurrentByName = stub(); + + const name = 'hi'; + const names = [name]; + const panel = {}; + + _selectNames(names, panel, { + selectFile, + getCurrentByName, + }); + + t.calledWith(getCurrentByName, [name, panel], 'should call selectFile'); + t.end(); +}); + +test('cloudcmd: static: user menu: compare directories: select names: compare', (t) => { + const a = [1, 2]; + const b = [1, 3]; + + const result = _compare(a, b); + const expected = [2]; + + t.deepEqual(result, expected); + t.end(); +}); + +function getDOM() { + const IO = { + write: stub(), + }; + + const Dialog = { + confirm: stub(), + }; + + const CurrentInfo = { + dirPath: '/', + files: [], + filesPassive: [], + panel: create(), + panelPassive: create(), + }; + + return { + IO, + Dialog, + CurrentInfo, + setCurrentByName: stub(), + getFilenames: stub().returns([]), + getCurrentByName: stub(), + renameCurrent: stub(), + }; +} + +const getCloudCmd = () => ({ + refresh: stub(), + EditFile: { + show: stub(), + }, +}); diff --git a/test-e2e/ratelimit.js b/test-e2e/ratelimit.js new file mode 100644 index 00000000..54cdbca8 --- /dev/null +++ b/test-e2e/ratelimit.js @@ -0,0 +1,55 @@ +import process from 'node:process'; +import {spawn} from 'node:child_process'; +import {test} from 'supertape'; + +test('cloudcmd: server: ratelimit: x-forwarded-for', async (t) => { + const PORT = 3000; + const child = await run(PORT); + + const {status} = await fetch(`http://localhost:${PORT}`, { + headers: { + 'X-Forwarded-For': '127.0.0.1', + }, + }); + + child.kill(); + + t.notEqual(status, 500); + t.end(); +}); + +test('cloudcmd: server: ratelimit', async (t) => { + const PORT = 3001; + const STATUS = 429; + + const child = await run(PORT); + + for (let i = 0; i < 1000; i++) { + await fetch(`http://localhost:${PORT}`); + } + + const {status} = await fetch(`http://localhost:${PORT}`); + child.kill(); + + t.equal(status, STATUS); + t.end(); +}); + +function run(port) { + return new Promise((resolve, reject) => { + const child = spawn(new URL('../bin/cloudcmd.js', import.meta.url).pathname, [], { + env: { + ...process.env, + PORT: port, + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + + child.stdout.on('data', (a) => { + if (a.toString().includes('url')) + resolve(child); + }); + + child.on('error', reject); + }); +} diff --git a/test/before.js b/test/before.js index 416ca8f3..08a50f04 100644 --- a/test/before.js +++ b/test/before.js @@ -1,33 +1,37 @@ -'use strict'; +import process from 'node:process'; +import http from 'node:http'; +import os from 'node:os'; +import {promisify} from 'node:util'; +import {fileURLToPath} from 'node:url'; +import {dirname} from 'node:path'; +import express from 'express'; +import {Server} from 'socket.io'; +import writejson from 'writejson'; +import readjson from 'readjson'; +import {cloudcmd} from '#server/cloudcmd'; -const http = require('http'); -const os = require('os'); - -const express = require('express'); -const io = require('socket.io'); -const writejson = require('writejson'); -const readjson = require('readjson'); -const {promisify} = require('util'); +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); process.env.NODE_ENV = 'development'; - -const cloudcmd = require('../server/cloudcmd'); const {assign} = Object; const pathConfig = os.homedir() + '/.cloudcmd.json'; const currentConfig = readjson.sync.try(pathConfig); -module.exports = before; +export default before; function before(options, fn = options) { - if (fn === options) { - options = {}; - } - - const {config, plugins, modules} = options; + const { + config, + plugins, + modules, + configManager, + } = options; const app = express(); const server = http.createServer(app); + const after = (cb) => { if (currentConfig) writejson.sync(pathConfig, currentConfig); @@ -35,12 +39,13 @@ function before(options, fn = options) { server.close(cb); }; - const socket = io.listen(server); + const socket = new Server(server); app.use(cloudcmd({ socket, plugins, config: assign(defaultConfig(), config), + configManager, modules, })); @@ -49,16 +54,16 @@ function before(options, fn = options) { }); } -module.exports.connect = promisify((options, fn = options) => { +export const connect = promisify((options, fn = options) => { before(options, (port, done) => { - fn(null, {port, done}); + fn(null, { + port, + done, + }); }); }); -function defaultConfig() { - return { - auth: false, - root: __dirname - }; -} - +const defaultConfig = () => ({ + auth: false, + root: __dirname, +}); diff --git a/test/client/listeners/get-range.js b/test/client/listeners/get-range.js deleted file mode 100644 index 9b431de0..00000000 --- a/test/client/listeners/get-range.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const test = require('tape'); - -const dir = '../../../client/listeners'; -const getRange = require(`${dir}/get-range`); - -test('cloudcmd: client: listeners: getRange: direct', (t) => { - const expected = ['hello', 'world']; - const files = [...expected, 'how', 'come']; - const result = getRange(0, 1, files); - - t.deepEqual(expected, result, 'should return range'); - t.end(); -}); - -test('cloudcmd: client: listeners: getRange: reverse', (t) => { - const expected = ['hello', 'world']; - const files = [...expected, 'how', 'come']; - const result = getRange(1, 0, files); - - t.deepEqual(expected, result, 'should return range'); - t.end(); -}); - -test('cloudcmd: client: listeners: getRange: one', (t) => { - const expected = ['hello']; - const files = [...expected, 'how', 'come']; - const result = getRange(0, 0, files); - - t.deepEqual(expected, result, 'should return range'); - t.end(); -}); - diff --git a/test/common/btoa.js b/test/common/btoa.js deleted file mode 100644 index 4d4bbe46..00000000 --- a/test/common/btoa.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -const test = require('tape'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); - -const btoa = require('../../common/btoa'); - -test('btoa: browser', (t) => { - const btoaOriginal = global.btoa; - const str = 'hello'; - - global.btoa = sinon.stub(); - - btoa(str); - - t.ok(global.btoa.calledWith(str), 'should call global.btoa'); - t.end(); - - global.btoa = btoaOriginal; -}); - -test('btoa: node', (t) => { - const str = 'hello'; - const expected = 'aGVsbG8='; - - const result = btoa(str); - - t.equal(result, expected, 'should encode base64'); - t.end(); -}); - diff --git a/test/common/cloudfunc.html b/test/common/cloudfunc.html index c5f9a5b2..a032b107 100644 --- a/test/common/cloudfunc.html +++ b/test/common/cloudfunc.html @@ -2,13 +2,15 @@ name size + time date owner mode -
    • +
    • .. <dir> + --:--:-- --.--.---- . --- --- --- @@ -16,6 +18,7 @@ applnk <dir> + --:--:-- 21.02.2016 root rwx r-x r-x @@ -23,7 +26,8 @@ ай 1.30kb + --:--:-- --.--.---- root rwx r-x r-x -
    \ No newline at end of file +
diff --git a/test/common/cloudfunc.js b/test/common/cloudfunc.js index 79eae79d..86f93908 100644 --- a/test/common/cloudfunc.js +++ b/test/common/cloudfunc.js @@ -1,28 +1,21 @@ -'use strict'; +import fs from 'node:fs'; +import {fileURLToPath} from 'node:url'; +import {dirname} from 'node:path'; +import {tryCatch} from 'try-catch'; +import {test} from 'supertape'; +import readFilesSync from '@cloudcmd/read-files-sync'; +import * as CloudFunc from '#common/cloudfunc'; +import {time, timeEnd} from '#common/util'; -const fs = require('fs'); +const __filename = fileURLToPath(import.meta.url); -const DIR = __dirname + '/../../'; -const COMMONDIR = DIR + 'common/'; -const TMPLDIR = DIR + 'tmpl/'; +const __dirname = dirname(__filename); +const DIR = `${__dirname}/../../`; -const { - time, - timeEnd, -} = require(COMMONDIR + 'util'); +const TMPLDIR = `${DIR}tmpl/`; -const CloudFuncPath = COMMONDIR + 'cloudfunc'; - -const CloudFunc = require(CloudFuncPath); - -const test = require('tape'); -const {reRequire} = require('mock-require'); - -const htmlLooksLike = require('html-looks-like'); -const readFilesSync = require('@cloudcmd/read-files-sync'); - -const FS_DIR = TMPLDIR + 'fs/'; -const EXPECT_PATH = __dirname + '/cloudfunc.html'; +const FS_DIR = `${TMPLDIR}fs/`; +const EXPECT_PATH = `${__dirname}/cloudfunc.html`; const addHBS = (a) => `${a}.hbs`; const TMPL = [ @@ -32,62 +25,62 @@ const TMPL = [ 'link', ].map(addHBS); -const JSON_FILES = { - path : '/etc/X11/', - files : [{ +const data = { + path: '/etc/X11/', + files: [{ name: 'applnk', size: '4.0.0kb', date: '21.02.2016', - uid : 0, + uid: 0, mode: 'rwx r-x r-x', type: 'directory', }, { name: 'ай', size: '1.30kb', date: 0, - uid : 0, + uid: 0, mode: 'rwx r-x r-x', type: 'file', - }] + }], }; -let Expect = - '
' + - '' + - '' + - '' + - '' + - '/' + - '' + - 'etc' + - '/X11/' + - '' + +let Expect = '
' + + '' + + '' + + '' + + '' + + '/' + + '' + + 'etc' + + '/X11/' + + '' + '
'; test('cloudfunc: render', (t) => { const template = readFilesSync(FS_DIR, TMPL, 'utf8'); - const expect = fs.readFileSync(EXPECT_PATH, 'utf8'); time('CloudFunc.buildFromJSON'); const result = CloudFunc.buildFromJSON({ - prefix : '', - data : JSON_FILES, - template: template + prefix: '', + data, + template, }); - Expect += expect; + Expect += fs + .readFileSync(EXPECT_PATH, 'utf8') + .slice(0, -1); let i; + const isNotOk = Expect .split('') .some((item, number) => { const ret = result[number] !== item; - if (ret) { + if (ret) i = number; - } return ret; }); @@ -95,19 +88,11 @@ test('cloudfunc: render', (t) => { timeEnd('CloudFunc.buildFromJSON'); if (isNotOk) { - console.log( - `Error in char number: ${i}\n`, - `Expect: ${Expect.substr(i)}\n`, - `Result: ${result.substr(i)}` - ); - + console.log(`Error in char number: ${i}\n`, `Expect: ${Expect.substr(i)}\n`, `Result: ${result.substr(i)}`); console.log('buildFromJSON: Not OK'); } - t.equal(Expect, result, 'should be equal rendered json data'); - - htmlLooksLike(Expect, result); - + t.equal(result, Expect, 'should be equal rendered json data'); t.end(); }); @@ -122,7 +107,7 @@ test('cloudfunc: formatMsg', (t) => { t.end(); }); -test('cloudfunc: formatMsg', (t) => { +test('cloudfunc: formatMsg: no name', (t) => { const msg = 'hello'; const name = null; const status = 'ok'; @@ -134,20 +119,19 @@ test('cloudfunc: formatMsg', (t) => { }); test('cloudfunc: getTitle', (t) => { - const CloudFunc = reRequire(CloudFuncPath); - - const result = CloudFunc.getTitle(); + const result = CloudFunc.getTitle({ + path: '/', + }); t.equal(result, 'Cloud Commander - /'); t.end(); }); test('cloudfunc: getTitle: no name', (t) => { - const CloudFunc = reRequire(CloudFuncPath); const path = '/hello/world'; const result = CloudFunc.getTitle({ - path + path, }); t.equal(result, 'Cloud Commander - /hello/world'); @@ -155,7 +139,6 @@ test('cloudfunc: getTitle: no name', (t) => { }); test('cloudfunc: getTitle: name, path', (t) => { - const CloudFunc = reRequire(CloudFuncPath); const name = 'hello'; const path = '/hello/world'; @@ -181,16 +164,18 @@ test('cloudfunc: getHeaderField', (t) => { }); test('cloudfunc: getPathLink: no url', (t) => { - t.throws(CloudFunc.getPathLink, 'should throw when no url'); + const [error] = tryCatch(CloudFunc.getPathLink); + + t.ok(error, 'should throw when no url'); t.end(); }); test('cloudfunc: getPathLink: no template', (t) => { const url = 'http://abc.com'; const prefix = ''; - const fn = () => CloudFunc.getPathLink(url, prefix); + const [error] = tryCatch(CloudFunc.getPathLink, url, prefix); - t.throws(fn, 'should throw when no template'); + t.ok(error, 'should throw when no template'); t.end(); }); @@ -207,4 +192,3 @@ test('cloudfunc: getDotDot: two levels deep', (t) => { t.equal(dotDot, '/home', 'should return up level'); t.end(); }); - diff --git a/test/common/util.js b/test/common/util.js deleted file mode 100644 index 2d60a5ee..00000000 --- a/test/common/util.js +++ /dev/null @@ -1,149 +0,0 @@ -'use strict'; - -const test = require('tape'); -const clean = require('clear-module'); -const DIR = '../../'; -const UtilPath = DIR + 'common/util'; -const Util = require(UtilPath); -const { - getStrBigFirst, - kebabToCamelCase, - findObjByNameInArr, - getRegExp, - escapeRegExp, -} = Util; - -test('getExt: no extension', (t) => { - const EXT = ''; - const name = 'file-withot-extension'; - const ext = Util.getExt(name); - - t.equal(ext, EXT, 'should return "" when extension is none'); - t.end(); -}); - -test('getExt: return extension', (t) => { - const EXT = '.png'; - const name = 'picture.png'; - const ext = Util.getExt(name); - - t.equal(ext, EXT, 'should return ".png" in files "picture.png"'); - t.end(); -}); - -test('util: getExt: no name', (t) => { - const ext = Util.getExt(); - - t.equal(ext, '', 'should return empty string'); - t.end(); -}); - -test('getStrBigFirst: args', (t) => { - t.throws(getStrBigFirst, /str could not be empty!/, 'should throw when no str'); - t.end(); -}); - -test('getStrBigFirst', (t) => { - t.equal(getStrBigFirst('hello'), 'Hello', 'should return str'); - t.end(); -}); - -test('kebabToCamelCase: args', (t) => { - t.throws(kebabToCamelCase, /str could not be empty!/, 'should throw when no str'); - t.end(); -}); - -test('kebabToCamelCase', (t) => { - t.equal(kebabToCamelCase('hello-world'), 'HelloWorld', 'should convert kebab to camel case'); - t.end(); -}); - -test('util: findObjByNameInArr: no array', (t) => { - t.throws(findObjByNameInArr, /array should be array!/, 'should throw when no array'); - t.end(); -}); - -test('util: findObjByNameInArr: no name', (t) => { - const fn = () => findObjByNameInArr([]); - t.throws(fn, /name should be string!/, 'should throw when no name'); - t.end(); -}); - -test('util: findObjByNameInArr: object', (t) => { - const name = 'hello'; - const obj = { - name, - }; - - const array = [ - obj, - ]; - - const result = findObjByNameInArr(array, name); - - t.equal(result, obj, 'should return obj'); - t.end(); -}); - -test('util: findObjByNameInArr: array', (t) => { - const name = 'hello'; - const data = 'abc'; - const item = { - name, - data, - }; - - const obj = { - name: 'world', - }; - - const array = [ - name, [ - obj, - item, - ] - ]; - - const result = findObjByNameInArr(array, name); - - t.equal(result, data, 'should return data'); - t.end(); -}); - -test('util: getRegExp', (t) => { - const reg = getRegExp('hel?o.*'); - - t.deepEqual(reg, RegExp('^hel.?\\..*$'), 'should return regexp'); - t.end(); -}); - -test('util: getRegExp: no', (t) => { - const reg = getRegExp(''); - - t.deepEqual(reg, RegExp('^.*$'), 'should return regexp'); - t.end(); -}); - -test('util: escapeRegExp: no str', (t) => { - t.equal(escapeRegExp(1), 1, 'should equal'); - t.end(); -}); - -test('util: escapeRegExp', (t) => { - t.equal(escapeRegExp('#hello'), '\\#hello', 'should equal'); - t.end(); -}); - -test('util: scope', (t) => { - global.window = {}; - clean(UtilPath); - - require(UtilPath); - - t.pass('should set window in scope'); - - delete global.window; - - t.end(); -}); - diff --git a/test/fixture/copy.txt b/test/fixture/copy.txt new file mode 100644 index 00000000..ce013625 --- /dev/null +++ b/test/fixture/copy.txt @@ -0,0 +1 @@ +hello diff --git a/test/plugins.js b/test/plugins.js deleted file mode 100644 index 43efd6af..00000000 --- a/test/plugins.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); - -const before = require('./before'); - -const warp = (fn, ...a) => (...b) => fn(...b, ...a); - -const _pullout = promisify(pullout); - -const get = promisify((url, fn) => { - fn(null, request(url)); -}); - -test('cloudcmd: plugins', (t) => { - const plugins = []; - - before({plugins}, (port, after) => { - get(`http://localhost:${port}/plugins.js`) - .then(warp(_pullout, 'string')) - .then((content) => { - t.equal(content, '', 'should content be empty'); - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: plugins', (t) => { - const plugins = [ - __filename - ]; - - before({plugins}, (port, after) => { - get(`http://localhost:${port}/plugins.js`) - .then(warp(_pullout, 'string')) - .then((content) => { - const file = fs.readFileSync(__filename, 'utf8'); - t.equal(content, file, 'should return file plugin content'); - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: plugins: load error', (t) => { - const noEntry = __filename + Math.random(); - const plugins = [ - __filename, - noEntry - ]; - - const msg = `ENOENT: no such file or directory, open '${noEntry}'`; - - before({plugins}, (port, after) => { - get(`http://localhost:${port}/plugins.js`) - .then(warp(_pullout, 'string')) - .then((content) => { - const file = fs.readFileSync(__filename, 'utf8') + msg; - t.equal(content, file, 'should return file plugin content'); - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - diff --git a/test/rest/config.js b/test/rest/config.js index 57a993b6..b45a0d18 100644 --- a/test/rest/config.js +++ b/test/rest/config.js @@ -1,43 +1,21 @@ -'use strict'; +import {serveOnce} from 'serve-once'; +import test from 'supertape'; +import {cloudcmd} from '#server/cloudcmd'; -const path = require('path'); -const os = require('os'); - -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); -const readjson = require('readjson'); -const writejson = require('writejson'); - -const manageConfig = require('../../server/config'); -const {connect} = require('../before'); - -const warp = (fn, ...a) => (...b) => fn(...b, ...a); - -const _pullout = promisify(pullout); - -const pathConfig = path.join(os.homedir(), '.cloudcmd.json'); - -const get = promisify((url, fn) => { - fn(null, request(url)); -}); - -const patch = promisify((url, json, fn) => { - fn(null, request.patch({url, json})); +const configManager = cloudcmd.createConfigManager(); +const {request} = serveOnce(cloudcmd, { + config: { + auth: false, + }, + configManager, }); test('cloudcmd: rest: config: get', async (t) => { - const {port, done} = await connect(); + const {body} = await request.get('/api/v1/config', { + type: 'json', + }); - const config = await get(`http://localhost:${port}/api/v1/config`) - .then(warp(_pullout, 'string')) - .then(JSON.parse) - .catch(console.error); - - await done(); - - t.notOk(config.auth, 'should config.auth to be false'); + t.notOk(body.auth, 'should config.auth to be false'); t.end(); }); @@ -47,16 +25,20 @@ test('cloudcmd: rest: config: patch', async (t) => { configDialog, }; - const {port, done} = await connect({config}); - const json = { + const options = { + config, + }; + + const body = { auth: false, }; - const result = await patch(`http://localhost:${port}/api/v1/config`, json) - .then(warp(_pullout, 'string')) - .catch(console.error); + const res = await request.patch('/api/v1/config', { + options, + body, + }); - await done(); + const result = res.body; t.equal(result, 'config: ok("auth")', 'should patch config'); t.end(); @@ -64,68 +46,59 @@ test('cloudcmd: rest: config: patch', async (t) => { test('cloudcmd: rest: config: patch: no configDialog', async (t) => { const config = { - configDialog: false + configDialog: false, }; - const {port, done} = await connect({config}); - const json = { - ip: null + const options = { + config, }; - - const result = await patch(`http://localhost:${port}/api/v1/config`, json) - .then(warp(_pullout, 'string')) - .catch(console.error); - await done(); + const body = { + ip: null, + }; - t.equal(result, 'Config is disabled', 'should return error'); + const result = await request.patch(`/api/v1/config`, { + body, + options, + }); + + t.equal(result.body, 'Config is disabled', 'should return error'); t.end(); }); test('cloudcmd: rest: config: patch: no configDialog: statusCode', async (t) => { const config = { - configDialog: false + configDialog: false, }; - const {port, done} = await connect({config}); - const json = { + const options = { + config, + }; + + const body = { ip: null, }; - const result = await patch(`http://localhost:${port}/api/v1/config`, json) - .catch((error) => { - console.log(error); - }); - - result.on('response', async (response) => { - manageConfig('configDialog', true); - - await done(); - t.equal(response.statusCode, 404); - t.end(); + const response = await request.patch(`/api/v1/config`, { + body, + options, }); + + configManager('configDialog', true); + + t.equal(response.status, 404); + t.end(); }); test('cloudcmd: rest: config: patch: save config', async (t) => { - const {port, done} = await connect(); - const json = { + const body = { editor: 'dword', }; - const originalConfig = readjson.sync.try(pathConfig); + await request.patch(`/api/v1/config`, { + body, + }); - await patch(`http://localhost:${port}/api/v1/config`, json) - .then(warp(_pullout, 'string')) - .catch(console.error); - - const config = readjson.sync(pathConfig); - - await done(); - - t.equal(config.editor, 'dword', 'should change config file on patch'); + t.equal(configManager('editor'), 'dword', 'should change config file on patch'); t.end(); - - if (originalConfig) - writejson.sync(pathConfig, originalConfig); }); - diff --git a/test/rest/copy.js b/test/rest/copy.js new file mode 100644 index 00000000..e6d8a03f --- /dev/null +++ b/test/rest/copy.js @@ -0,0 +1,44 @@ +import {dirname, join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {mkdirSync} from 'node:fs'; +import {serveOnce} from 'serve-once'; +import test from 'supertape'; +import {rimraf} from 'rimraf'; +import {cloudcmd} from '#server/cloudcmd'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +const config = { + root: new URL('..', import.meta.url).pathname, +}; + +const configManager = cloudcmd.createConfigManager(); + +configManager('auth', false); +const {request} = serveOnce(cloudcmd, { + config, + configManager, +}); + +const fixtureDir = join(__dirname, '..', 'fixture') + '/'; + +test('cloudcmd: rest: copy', async (t) => { + const tmp = join(fixtureDir, 'tmp'); + const files = { + from: '/fixture/', + to: '/fixture/tmp', + names: ['copy.txt'], + }; + + mkdirSync(tmp); + + const {body} = await request.put(`/api/v1/copy`, { + body: files, + }); + + rimraf.sync(tmp); + + t.equal(body, 'copy: ok("["copy.txt"]")', 'should return result'); + t.end(); +}); diff --git a/test/rest/cp.js b/test/rest/cp.js deleted file mode 100644 index 21948ecc..00000000 --- a/test/rest/cp.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const { - join, -} = require('path'); -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); -const before = require('../before'); -const rimraf = require('rimraf'); -const mkdirp = require('mkdirp'); - -const fixtureDir = join(__dirname, '..', 'fixture') + '/'; - -const warp = (fn, ...a) => (...b) => fn(...b, ...a); -const _pullout = promisify(pullout); - -const put = promisify((url, json, fn) => { - fn(null, request.put(url, { - json, - })); -}); - -test('cloudcmd: rest: cp', (t) => { - before({}, (port, after) => { - const tmp = join(fixtureDir, 'tmp'); - const files = { - from: '/fixture/', - to: '/fixture/tmp', - names: [ - 'cp.txt' - ] - }; - - mkdirp.sync(tmp); - - const rmTmp = () => rimraf.sync(tmp); - - put(`http://localhost:${port}/api/v1/cp`, files) - .then(warp(_pullout, 'string')) - .then((body) => { - t.equal(body, 'copy: ok("["cp.txt"]")', 'should return result'); - t.end(); - - after(); - }) - .catch(console.error) - .then(rmTmp); - }); -}); - diff --git a/test/rest/fs.js b/test/rest/fs.js index 08c599df..db438a71 100644 --- a/test/rest/fs.js +++ b/test/rest/fs.js @@ -1,29 +1,27 @@ -'use strict'; +import {serveOnce} from 'serve-once'; +import test from 'supertape'; +import {cloudcmd} from '#server/cloudcmd'; -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); -const before = require('../before'); - -const warp = (fn, ...a) => (...b) => fn(...b, ...a); -const _pullout = promisify(pullout); - -const get = promisify((url, fn) => { - fn(null, request(url)); +const {request} = serveOnce(cloudcmd, { + config: { + auth: false, + }, }); -test('cloudcmd: rest: fs: path', (t) => { - before((port, after) => { - get(`http://localhost:${port}/api/v1/fs`) - .then(warp(_pullout, 'string')) - .then(JSON.parse) - .then((dir) => { - t.equal('/', dir.path, 'should dir path be "/"'); - t.end(); - after(); - }) - .catch(console.error); +test('cloudcmd: rest: fs: path', async (t) => { + const {body} = await request.get(`/api/v1/fs`, { + type: 'json', }); + + const {path} = body; + + t.equal(path, '/', 'should dir path be "/"'); + t.end(); }); +test('cloudcmd: path traversal beyond root', async (t) => { + const {body} = await request.get('/fs..%2f..%2fetc/passwd'); + + t.match(body, 'beyond root', 'should return beyond root message'); + t.end(); +}); diff --git a/test/rest/move.js b/test/rest/move.js new file mode 100644 index 00000000..073c520f --- /dev/null +++ b/test/rest/move.js @@ -0,0 +1,87 @@ +import {EventEmitter} from 'node:events'; +import wait from '@iocmd/wait'; +import {test, stub} from 'supertape'; +import {serveOnce} from 'serve-once'; +import {cloudcmd} from '#server/cloudcmd'; + +test('cloudcmd: rest: move', async (t) => { + const move = new EventEmitter(); + const moveFiles = stub().returns(move); + + const {createConfigManager} = cloudcmd; + cloudcmd.depStore('moveFiles', moveFiles); + + const configManager = createConfigManager(); + configManager('auth', false); + configManager('root', '/'); + + const {request} = serveOnce(cloudcmd, { + configManager, + }); + + const files = { + from: '/fixture/', + to: '/fixture/tmp/', + names: ['move.txt'], + }; + + const emit = move.emit.bind(move); + + const [{body}] = await Promise.all([ + request.put(`/api/v1/move`, { + body: files, + }), + wait(1000, emit, 'end'), + ]); + + t.equal(body, 'move: ok("["move.txt"]")', 'should move'); + t.end(); +}); + +test('cloudcmd: rest: move: no from', async (t) => { + const {createConfigManager} = cloudcmd; + + const configManager = createConfigManager(); + configManager('auth', false); + configManager('root', '/'); + + const {request} = serveOnce(cloudcmd, { + configManager, + }); + + const files = {}; + + const {body} = await request.put(`/api/v1/move`, { + body: files, + }); + + const expected = '"from" should be filled'; + + t.equal(body, expected); + t.end(); +}); + +test('cloudcmd: rest: move: no to', async (t) => { + const {createConfigManager} = cloudcmd; + + const configManager = createConfigManager(); + configManager('auth', false); + configManager('root', '/'); + + const {request} = serveOnce(cloudcmd, { + configManager, + }); + + const files = { + from: '/', + }; + + const {body} = await request.put(`/api/v1/move`, { + body: files, + }); + + const expected = '"to" should be filled'; + + t.equal(body, expected); + t.end(); +}); diff --git a/test/rest/mv.js b/test/rest/mv.js deleted file mode 100644 index 18009b81..00000000 --- a/test/rest/mv.js +++ /dev/null @@ -1,116 +0,0 @@ -'use strict'; - -const fs = require('fs'); - -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); -const {Volume} = require('memfs'); -const {ufs} = require('unionfs'); -const tryToCatch = require('try-to-catch'); -const mockRequire = require('mock-require'); -const clean = require('clear-module'); - -const root = '../../'; -const dir = root + 'server/'; -const cloudcmdPath = dir + 'cloudcmd'; -const restPath = dir + 'rest'; -const beforePath = '../before'; - -const _pullout = promisify(pullout); - -const put = promisify((url, json, fn) => { - fn(null, request.put(url, { - json, - })); -}); - -test('cloudcmd: rest: mv', async (t) => { - const volume = { - '/fixture/mv.txt': 'hello', - '/fixture/tmp/a.txt': 'a', - }; - - const vol = Volume.fromJSON(volume, '/'); - - const unionFS = ufs - .use(vol) - .use(fs); - - clean(beforePath); - clean(cloudcmdPath); - clean(restPath); - clean('@cloudcmd/move-files'); - clean('@cloudcmd/rename-files'); - - mockRequire('fs', unionFS); - - const {connect} = require(beforePath); - const {port, done} = await connect({ - config: { - root: '/' - } - }); - - const files = { - from: '/fixture/', - to: '/fixture/tmp/', - names: [ - 'mv.txt' - ] - }; - - - const [, result] = await tryToCatch(put, `http://localhost:${port}/api/v1/mv`, files); - const body = await _pullout(result, 'string'); - - done(); - mockRequire.stop('fs'); - - t.equal(body, 'move: ok("["mv.txt"]")', 'should move'); - t.end(); -}); - -test('cloudcmd: rest: mv: rename', async (t) => { - const volume = { - '/fixture/mv.txt': 'hello', - '/fixture/tmp/a.txt': 'a', - }; - - const vol = Volume.fromJSON(volume, '/'); - - const unionFS = ufs - .use(vol) - .use(fs); - - clean(beforePath); - clean(cloudcmdPath); - clean(restPath); - - mockRequire('fs', unionFS); - - const {connect} = require(beforePath); - const {port, done} = await connect({ - config: { - root: '/' - } - }); - - const files = { - from: '/fixture/mv.txt', - to: '/fixture/tmp/mv.txt', - }; - - const [, result] = await tryToCatch(put, `http://localhost:${port}/api/v1/mv`, files); - const body = await _pullout(result, 'string'); - - done(); - mockRequire.stop('fs'); - - const expected = 'move: ok("{"from":"/fixture/mv.txt","to":"/fixture/tmp/mv.txt"}")'; - - t.equal(body, expected, 'should move'); - t.end(); -}); - diff --git a/test/rest/pack.js b/test/rest/pack.js index ebc01c2e..4c7a49ed 100644 --- a/test/rest/pack.js +++ b/test/rest/pack.js @@ -1,230 +1,231 @@ -'use strict'; +import fs from 'node:fs'; +import {join, dirname} from 'node:path'; +import {promisify} from 'node:util'; +import {fileURLToPath} from 'node:url'; +import test from 'supertape'; +import tar from 'tar-stream'; +import gunzip from 'gunzip-maybe'; +import pullout from 'pullout'; +import {serveOnce} from 'serve-once'; +import {cloudcmd} from '#server/cloudcmd'; -const fs = require('fs'); -const path = require('path'); +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const pathZipFixture = join(__dirname, '..', 'fixture/pack.zip'); -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); -const tar = require('tar-stream'); -const gunzip = require('gunzip-maybe'); +const pathTarFixture = join(__dirname, '..', 'fixture/pack.tar.gz'); -const before = require('../before'); - -const warp = (fn, ...a) => (...b) => fn(...b, ...a); - -const _pullout = promisify(pullout); - -const pathTarFixture = path.join(__dirname, '..', 'fixture/pack.tar.gz'); -const pathZipFixture = path.join(__dirname, '..', 'fixture/pack.zip'); +const defaultOptions = { + config: { + auth: false, + root: new URL('..', import.meta.url).pathname, + }, +}; const fixture = { tar: fs.readFileSync(pathTarFixture), zip: fs.readFileSync(pathZipFixture), }; -const get = promisify((url, fn) => { - fn(null, request(url)); -}); +const {request} = serveOnce(cloudcmd, defaultOptions); -const put = promisify((options, fn) => { - fn(null, request.put(options)); -}); - -test('cloudcmd: rest: pack: tar: get', (t) => { - const config = {packer: 'tar'}; - - before({config}, (port, after) => { - get(`http://localhost:${port}/api/v1/pack/fixture/pack`) - .then((pack) => { - const extract = tar.extract(); - - pack.pipe(gunzip()).pipe(extract); - - extract.on('entry', (header, stream) => { - pullout(stream, 'string', (e, data) => { - const file = fs.readFileSync(__dirname + '/../fixture/pack', 'utf8'); - t.equal(file, data, 'should pack data'); - t.end(); - after(); - }); - }); - }) - .catch((error) => { - console.log(error); - }); +const once = promisify((name, extract, fn) => { + extract.once(name, (header, stream) => { + fn(null, [header, stream]); }); }); -test('cloudcmd: rest: pack: tar: put: file', (t) => { - const config = {packer: 'tar'}; - - before({config}, (port, after) => { - const name = String(Math.random()) + '.tar.gz'; - const options = getPackOptions(port, name); - - put(options) - .then(_pullout) - .then(() => { - const file = fs.createReadStream(__dirname + '/../' + name); - const extract = tar.extract(); - - file.pipe(gunzip()).pipe(extract); - - extract.on('entry', (header, stream) => { - pullout(stream, 'string', (e, data) => { - const file = fs.readFileSync(__dirname + '/../fixture/pack', 'utf8'); - fs.unlinkSync(`${__dirname}/../${name}`); - - t.equal(file, data, 'should create archive'); - t.end(); - after(); - }); - }); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: rest: pack: tar: put: response', (t) => { - const options = {packer: 'tar'}; - before(options, (port, after) => { - const name = String(Math.random()) + '.tar.gz'; - const options = getPackOptions(port, name); - - put(options) - .then(warp(_pullout, 'string')) - .then((msg) => { - t.equal(msg, 'pack: ok("fixture")', 'should return result message'); - - fs.unlinkSync(`${__dirname}/../${name}`); - - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: rest: pack: tar: put: error', (t) => { - const config = {packer: 'tar'}; - - before({config}, (port, after) => { - const options = getPackOptions(port, 'name', [ - 'not found' - ]); - - put(options) - .then(warp(_pullout, 'string')) - .then((msg) => { - t.ok(/^ENOENT: no such file or directory/.test(msg), 'should return error'); - - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: rest: pack: zip: get', (t) => { - const config = {packer: 'zip'}; - before({config}, (port, after) => { - get(`http://localhost:${port}/api/v1/pack/fixture/pack`) - .then(_pullout) - .then((pack) => { - t.equal(pack.length, fixture.zip.length, 'should pack data'); - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: rest: pack: zip: put: file', (t) => { - const config = {packer: 'zip'}; - - before({config}, (port, after) => { - const name = String(Math.random()) + '.zip'; - const options = getPackOptions(port, name); - - put(options) - .then(warp(_pullout, 'string')) - .then(() => { - const file = fs.readFileSync(__dirname + '/../' + name); - - fs.unlinkSync(`${__dirname}/../${name}`); - t.equal(fixture.zip.length, file.length, 'should create archive'); - - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: rest: pack: zip: put: response', (t) => { - const config = {packer: 'zip'}; - - before({config}, (port, after) => { - const name = String(Math.random()) + '.zip'; - const options = getPackOptions(port, name); - - put(options) - .then(warp(_pullout, 'string')) - .then((msg) => { - t.equal(msg, 'pack: ok("fixture")', 'should return result message'); - - fs.unlinkSync(`${__dirname}/../${name}`); - - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -test('cloudcmd: rest: pack: zip: put: error', (t) => { - const config = {packer: 'zip'}; - before({config}, (port, after) => { - const options = getPackOptions(port, 'name', [ - 'not found' - ]); - - put(options) - .then(warp(_pullout, 'string')) - .then((msg) => { - t.ok(/^ENOENT: no such file or directory/.test(msg), 'should return error'); - - t.end(); - after(); - }) - .catch((error) => { - console.log(error); - }); - }); -}); - -function getPackOptions(port, to, names = ['pack']) { - return { - url: `http://localhost:${port}/api/v1/pack`, - json: { - to, - names, - from: '/fixture', - } +test('cloudcmd: rest: pack: tar: get', async (t) => { + const config = { + packer: 'tar', + auth: false, }; -} + + const options = { + config, + }; + + const {request} = serveOnce(cloudcmd, defaultOptions); + + const {body} = await request.get(`/api/v1/pack/fixture/pack`, { + options, + type: 'stream', + }); + + const extract = tar.extract(); + + body + .pipe(gunzip()) + .pipe(extract); + + const [, stream] = await once('entry', extract); + const data = await pullout(stream); + const file = fs.readFileSync(`${__dirname}/../fixture/pack`, 'utf8'); + + t.equal(file, data, 'should pack data'); + t.end(); +}, { + timeout: 7000, +}); +test('cloudcmd: rest: pack: tar: put: file', async (t) => { + const config = { + packer: 'tar', + }; + + const options = { + config, + }; + + const name = `${Math.random()}.tar.gz`; + + const {request} = serveOnce(cloudcmd, defaultOptions); + + await request.put(`/api/v1/pack`, { + options, + body: getPackOptions(name), + }); + + const file = fs.createReadStream(join(__dirname, '..', name)); + const extract = tar.extract(); + + file + .pipe(gunzip()) + .pipe(extract); + + const [, stream] = await once('entry', extract); + const data = await pullout(stream, 'buffer'); + const result = fs.readFileSync(`${__dirname}/../fixture/pack`); + + fs.unlinkSync(`${__dirname}/../${name}`); + + t.deepEqual(result, data, 'should create archive'); + t.end(); +}); + +test('cloudcmd: rest: pack: tar: put: response', async (t) => { + const config = { + packer: 'tar', + }; + + const options = { + config, + }; + + const name = `${Math.random()}.tar.gz`; + + const {body} = await request.put(`/api/v1/pack`, { + options, + body: getPackOptions(name), + }); + + fs.unlinkSync(`${__dirname}/../${name}`); + + t.equal(body, 'pack: ok("fixture")', 'should return result message'); + t.end(); +}); + +test('cloudcmd: rest: pack: tar: put: error', async (t) => { + const config = { + packer: 'tar', + }; + + const options = { + config, + }; + + const {body} = await request.put(`/api/v1/pack`, { + options, + body: getPackOptions('name', ['not found']), + }); + + t.match(body, /^ENOENT: no such file or directory/, 'should return error'); + t.end(); +}); + +test('cloudcmd: rest: pack: zip: get', async (t) => { + const config = { + packer: 'zip', + }; + + const options = { + config, + }; + + const {body} = await request.get(`/api/v1/pack/fixture/pack`, { + options, + type: 'buffer', + }); + + t.equal(body.length, 145, 'should pack data'); + t.end(); +}); + +test('cloudcmd: rest: pack: zip: put: file', async (t) => { + const config = { + packer: 'zip', + }; + + const options = { + config, + }; + + const name = `${Math.random()}.zip`; + + await request.put(`/api/v1/pack`, { + options, + body: getPackOptions(name), + }); + + fs.unlinkSync(`${__dirname}/../${name}`); + + t.equal(fixture.zip.length, 136, 'should create archive'); + t.end(); +}); + +test('cloudcmd: rest: pack: zip: put: response', async (t) => { + const config = { + packer: 'zip', + }; + + const options = { + config, + }; + + const name = `${Math.random()}.zip`; + + const {body} = await request.put(`/api/v1/pack`, { + options, + body: getPackOptions(name), + }); + + fs.unlinkSync(`${__dirname}/../${name}`); + + t.equal(body, 'pack: ok("fixture")', 'should return result message'); + t.end(); +}); + +test('cloudcmd: rest: pack: zip: put: error', async (t) => { + const config = { + packer: 'zip', + auth: false, + }; + + const options = { + config, + }; + + const {body} = await request.put(`/api/v1/pack`, { + options, + body: getPackOptions('name', ['not found']), + }); + + t.match(body, /^ENOENT: no such file or directory/, 'should return error'); + t.end(); +}); + +const getPackOptions = (to, names = ['pack']) => ({ + to, + names, + from: '/fixture', +}); diff --git a/test/rest/rename.js b/test/rest/rename.js new file mode 100644 index 00000000..eb773dba --- /dev/null +++ b/test/rest/rename.js @@ -0,0 +1,94 @@ +import fs from 'node:fs'; +import test from 'supertape'; +import {Volume} from 'memfs'; +import {ufs} from 'unionfs'; +import {serveOnce} from 'serve-once'; +import {cloudcmd} from '#server/cloudcmd'; + +test('cloudcmd: rest: rename', async (t) => { + const volume = { + '/fixture/mv.txt': 'hello', + '/fixture/tmp/a.txt': 'a', + }; + + const vol = Volume.fromJSON(volume, '/'); + + const unionFS = ufs + .use(vol) + .use(fs); + + const {createConfigManager} = cloudcmd; + const configManager = createConfigManager(); + + configManager('auth', false); + configManager('root', '/'); + + cloudcmd.depStore('fs', unionFS); + const {request} = serveOnce(cloudcmd, { + configManager, + }); + + const files = { + from: '/fixture/mv.txt', + to: '/fixture/tmp/mv.txt', + }; + + const {body} = await request.put(`/api/v1/rename`, { + body: files, + }); + + cloudcmd.depStore(); + + const expected = 'rename: ok("{"from":"/fixture/mv.txt","to":"/fixture/tmp/mv.txt"}")'; + + t.equal(body, expected, 'should move'); + t.end(); +}); + +test('cloudcmd: rest: rename: no from', async (t) => { + const {createConfigManager} = cloudcmd; + + const configManager = createConfigManager(); + configManager('auth', false); + configManager('root', '/'); + + const {request} = serveOnce(cloudcmd, { + configManager, + }); + + const files = {}; + + const {body} = await request.put(`/api/v1/rename`, { + body: files, + }); + + const expected = '"from" should be filled'; + + t.equal(body, expected); + t.end(); +}); + +test('cloudcmd: rest: rename: no to', async (t) => { + const {createConfigManager} = cloudcmd; + + const configManager = createConfigManager(); + configManager('auth', false); + configManager('root', '/'); + + const {request} = serveOnce(cloudcmd, { + configManager, + }); + + const files = { + from: '/', + }; + + const {body} = await request.put(`/api/v1/rename`, { + body: files, + }); + + const expected = '"to" should be filled'; + + t.equal(body, expected); + t.end(); +}); diff --git a/test/rest/rest.js b/test/rest/rest.js deleted file mode 100644 index 947bbb64..00000000 --- a/test/rest/rest.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -const test = require('tape'); -const rest = require('../../server/rest'); - -const { - _formatMsg, - _getWin32RootMsg, - _isRootWin32, - _isRootAll, -} = rest; - -test('rest: formatMsg', (t) => { - const result = _formatMsg('hello', 'world'); - - t.equal(result, 'hello: ok("world")', 'should be equal'); - t.end(); -}); - -test('rest: formatMsg: json', (t) => { - const result = _formatMsg('hello', { - name: 'world', - }); - - t.equal(result, 'hello: ok("{"name":"world"}")', 'should parse json'); - t.end(); -}); - -test('rest: getWin32RootMsg', (t) => { - const {message} = _getWin32RootMsg(); - - t.equal(message,'Could not copy from/to root on windows!', 'should return error'); - t.end(); -}); - -test('rest: isRootWin32', (t) => { - const result = _isRootWin32('/'); - - t.notOk(result, 'should equal'); - t.end(); -}); - -test('rest: isRootAll', (t) => { - const result = _isRootAll(['/', '/h']); - - t.notOk(result, 'should equal'); - t.end(); -}); - diff --git a/test/server/cloudcmd.js b/test/server/cloudcmd.js deleted file mode 100644 index 96c97a96..00000000 --- a/test/server/cloudcmd.js +++ /dev/null @@ -1,238 +0,0 @@ -'use strict'; - -const path = require('path'); - -const test = require('tape'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); -const currify = require('currify'); -const clean = require('clear-module'); -const request = require('request'); -const {promisify} = require('es6-promisify'); - -const DIR = '../../server/'; -const cloudcmdPath = DIR + 'cloudcmd'; -const beforePath = '../before'; - -const config = require(DIR + 'config'); -const cloudcmd = require(cloudcmdPath); -const {connect} = require(beforePath); -const { - _getPrefix, - _auth, -} = cloudcmd; - -const get = promisify(request); - -test('cloudcmd: args: no', (t) => { - const fn = () => cloudcmd(); - - t.doesNotThrow(fn, /plugins should be an array!/, 'should throw when plugins not an array'); - t.end(); -}); - -test('cloudcmd: args: plugins: error', (t) => { - const fn = () => cloudcmd({ - plugins: '' - }); - - t.throws(fn, /plugins should be an array!/, 'should throw when plugins not an array'); - t.end(); -}); - -test('cloudcmd: defaults: config', (t) => { - const configDialog = config('configDialog'); - - config('configDialog', false); - cloudcmd(); - t.notOk(config('configDialog'), 'should not override config with defaults'); - - config('configDialog', configDialog); - - t.end(); -}); - -test('cloudcmd: defaults: console', (t) => { - const console = config('console'); - config('console', false); - cloudcmd(); - t.notOk(config('console'), 'should not override config with defaults'); - - config('console', console); - - t.end(); -}); - -test('cloudcmd: getPrefix', (t) => { - const value = 'hello'; - const result = _getPrefix(value); - - t.equal(result, value, 'should equal'); - t.end(); -}); - -test('cloudcmd: getPrefix: function', (t) => { - const value = 'hello'; - const fn = () => value; - const result = _getPrefix(fn); - - t.equal(result, value, 'should equal'); - t.end(); -}); - -test('cloudcmd: getPrefix: function: empty', (t) => { - const value = null; - const fn = () => value; - const result = _getPrefix(fn); - - t.equal(result, '', 'should equal'); - t.end(); -}); - -test('cloudcmd: replaceDist', (t) => { - const {NODE_ENV} = process.env; - process.env.NODE_ENV = 'development'; - - clean(cloudcmdPath); - - const {_replaceDist} = require(cloudcmdPath); - - const url = '/dist/hello'; - const result = _replaceDist(url); - const expected = '/dist-dev/hello'; - - process.env.NODE_ENV = NODE_ENV; - - t.equal(result, expected, 'should equal'); - t.end(); -}); - -test('cloudcmd: replaceDist: !isDev', (t) => { - const url = '/dist/hello'; - const cloudcmdPath = DIR + 'cloudcmd'; - - const reset = cleanNodeEnv(); - - clean(cloudcmdPath); - const {_replaceDist} = require(cloudcmdPath); - - const result = _replaceDist(url); - const expected = url; - - reset(); - - t.equal(result, expected, 'should equal'); - t.end(); -}); - -test('cloudcmd: auth: reject', (t) => { - const auth = config('auth'); - const accept = sinon.stub(); - const reject = sinon.stub(); - const username = 'root'; - const password = 'toor'; - - const set = credentials(); - const reset = set('hello', 'world'); - config('auth', true); - - _auth(accept, reject, username, password); - - config('auth', auth); - reset(); - - t.ok(reject.called, 'should accept'); - t.end(); -}); - -test('cloudcmd: auth: accept', (t) => { - const auth = config('auth'); - const accept = sinon.stub(); - const reject = sinon.stub(); - const username = 'root'; - const password = 'toor'; - - const set = credentials(); - const reset = set(username, password); - config('auth', true); - - _auth(accept, reject, username, password); - - config('auth', auth); - reset(); - - t.ok(accept.called, 'should accept'); - t.end(); -}); - -test('cloudcmd: auth: accept: no auth', (t) => { - const auth = config('auth'); - const accept = sinon.stub(); - const reject = sinon.stub(); - const username = 'root'; - const password = 'toor'; - - config('auth', false); - _auth(accept, reject, username, password); - config('auth', auth); - - t.ok(accept.called, 'should accept'); - t.end(); -}); - -function credentials() { - const username = config('username'); - const password = config('password'); - - const reset = () => { - config('username', username); - config('password', password); - }; - - const set = currify((fn, a, b) => { - config('username', a); - config('password', b); - - return fn; - }); - - return set(reset); -} - -test('cloudcmd: getIndexPath: production', (t) => { - const isDev = false; - const name = path.join(__dirname, '..', '..', 'dist', 'index.html'); - - t.equal(cloudcmd._getIndexPath(isDev), name); - t.end(); -}); - -test('cloudcmd: getIndexPath: development', (t) => { - const isDev = true; - const name = path.join(__dirname, '..', '..', 'dist-dev', 'index.html'); - - t.equal(cloudcmd._getIndexPath(isDev), name); - t.end(); -}); - -test('cloudcmd: sw', async (t) => { - const {port, done} = await connect(); - const {statusCode}= await get(`http://localhost:${port}/sw.js`); - - await done(); - - t.equal(statusCode, 200, 'should return sw'); - t.end(); -}); - -function cleanNodeEnv() { - const {NODE_ENV} = process.env; - process.env.NODE_ENV = ''; - - const reset = () => { - process.env.NODE_ENV = NODE_ENV; - }; - - return reset; -} - diff --git a/test/server/columns.js b/test/server/columns.js deleted file mode 100644 index 9248d585..00000000 --- a/test/server/columns.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const test = require('tape'); -const fs = require('fs'); -const clean = require('clear-module'); -const columnsPath = '../../server/columns'; - -test('columns', (t) => { - clean(columnsPath); - - const {NODE_ENV} = process.env; - process.env.NODE_ENV = ''; - const columns = require(columnsPath); - - t.equal(columns[''], '', 'should equal'); - process.env.NODE_ENV = NODE_ENV; - - t.end(); -}); - -test('columns: dev', (t) => { - clean(columnsPath); - const {NODE_ENV} = process.env; - process.env.NODE_ENV = 'development'; - - const columns = require(columnsPath); - const css = fs.readFileSync(`${__dirname}/../../css/columns/name-size-date.css`, 'utf8'); - - t.equal(columns['name-size-date'], css, 'should equal'); - process.env.NODE_ENV = NODE_ENV; - - t.end(); -}); - diff --git a/test/server/console.js b/test/server/console.js index 858bdd89..56d35a3c 100644 --- a/test/server/console.js +++ b/test/server/console.js @@ -1,30 +1,31 @@ -'use strict'; +import {once} from 'node:events'; +import test from 'supertape'; +import io from 'socket.io-client'; +import {connect} from '../before.js'; +import {createConfig} from '../../server/config.js'; -const path = require('path'); - -const test = require('tape'); -const io = require('socket.io-client'); - -const configPath = path.join(__dirname, '../..', 'server', 'config'); -const {connect} = require('../before'); -const configFn = require(configPath); +const configFn = createConfig(); test('cloudcmd: console: enabled', async (t) => { const config = { console: true, }; - const {port, done} = await connect({config}); + const {port, done} = await connect({ + config, + }); + const socket = io(`http://localhost:${port}/console`); socket.emit('auth', configFn('username'), configFn('password')); - socket.once('data', (data) => { - done(); - socket.close(); - - t.equal(data, 'client #1 console connected\n', 'should emit data event'); - t.end(); - }); + + const [data] = await once(socket, 'data'); + + socket.close(); + await done(); + + t.equal(data, 'client #1 console connected\n', 'should emit data event'); + t.end(); }); test('cloudcmd: console: disabled', async (t) => { @@ -32,15 +33,17 @@ test('cloudcmd: console: disabled', async (t) => { console: false, }; - const {port, done} = await connect({config}); + const {port, done} = await connect({ + config, + }); + const socket = io(`http://localhost:${port}/console`); - socket.on('error', (error) => { - socket.close(); - done(); - - t.equal(error, 'Invalid namespace', 'should emit error'); - t.end(); - }); + const [error] = await once(socket, 'connect_error'); + + socket.close(); + await done(); + + t.equal(error.message, 'Invalid namespace', 'should emit error'); + t.end(); }); - diff --git a/test/server/env.js b/test/server/env.js index 7d0fad6e..34bc8959 100644 --- a/test/server/env.js +++ b/test/server/env.js @@ -1,48 +1,51 @@ -'use strict'; - -const test = require('tape'); -const env = require('../../server/env'); +import process from 'node:process'; +import {test} from 'supertape'; +import * as env from '../../server/env.js'; test('env: small', (t) => { process.env.cloudcmd_hello = 'world'; - t.equal(env('hello'), 'world', 'should parse string from env'); delete process.env.cloudcmd_hello; + + t.equal(env.parse('hello'), 'world', 'should parse string from env'); t.end(); }); test('env: big', (t) => { process.env.CLOUDCMD_HELLO = 'world'; - t.equal(env('hello'), 'world', 'should parse string from env'); delete process.env.CLOUDCMD_HELLO; + + t.equal(env.parse('hello'), 'world', 'should parse string from env'); t.end(); }); test('env: bool: false', (t) => { process.env.cloudcmd_terminal = 'false'; - t.equal(env.bool('terminal'), false, 'should return false'); delete process.env.cloudcmd_terminal; + + t.notOk(env.bool('terminal'), 'should return false'); t.end(); }); test('env: bool: true', (t) => { process.env.cloudcmd_terminal = 'true'; - t.equal(env.bool('terminal'), true, 'should be true'); - delete process.env.cloudcmd_terminal; + + t.ok(env.bool('terminal'), 'should be true'); t.end(); }); test('env: bool: undefined', (t) => { const {cloudcmd_terminal} = process.env; + process.env.cloudcmd_terminal = undefined; - - t.equal(env.bool('terminal'), undefined, 'should be undefined'); - process.env.cloudcmd_terminal = cloudcmd_terminal; + + const result = env.bool('terminal'); + + t.notOk(result); t.end(); }); - diff --git a/test/server/modulas.js b/test/server/modulas.js index 829c2cfa..0085449e 100644 --- a/test/server/modulas.js +++ b/test/server/modulas.js @@ -1,61 +1,59 @@ -'use strict'; +import {createRequire} from 'node:module'; +import {dirname, join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {serveOnce} from 'serve-once'; +import {test, stub} from 'supertape'; +import {cloudcmd} from '#server/cloudcmd'; +import modulas from '../../server/modulas.js'; -const path = require('path'); -const test = require('tape'); +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); +const require = createRequire(import.meta.url); +const cloudcmdPath = join(__dirname, '..', '..'); +const modulesPath = join(cloudcmdPath, 'json', 'modules.json'); +const localModules = require(modulesPath); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); - -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); - -const dir = path.join(__dirname, '..', '..'); -const modulesPath = path.join(dir, 'json', 'modules.json'); - -const localModules = require(modulesPath); -const modulas = require(`${dir}/server/modulas`); - -const warp = (fn, ...a) => (...b) => fn(...b, ...a); -const _pullout = promisify(pullout); - -const get = promisify((url, fn) => { - fn(null, request(url)); +const {request} = serveOnce(cloudcmd, { + config: { + auth: false, + dropbox: false, + }, }); -const getJSON = (url) => { - return get(url) - .then(warp(_pullout, 'string')) - .then(JSON.parse); -}; - -const {connect} = require('../before'); - test('cloudcmd: modules', async (t) => { const modules = { data: { FilePicker: { - key: 'hello' - } - } + key: 'hello', + }, + }, + }; + + const options = { + modules, }; const expected = { ...localModules, ...modules, }; - const {port, done} = await connect({modules}); - const result = await getJSON(`http://localhost:${port}/json/modules.json`); - t.deepEqual(result, expected, 'should equal'); + const {body} = await request.get(`/json/modules.json`, { + type: 'json', + options, + }); + + t.deepEqual(body, expected); t.end(); - - await done(); }); test('cloudcmd: modules: wrong route', async (t) => { const modules = { - hello: 'world' + hello: 'world', + }; + + const options = { + modules, }; const expected = { @@ -63,23 +61,24 @@ test('cloudcmd: modules: wrong route', async (t) => { ...modules, }; - const {port, done} = await connect({modules}); - const result = await getJSON(`http://localhost:${port}/package.json`); + const {body} = await request.get(`/package.json`, { + type: 'json', + options, + }); - t.notDeepEqual(result, expected, 'should not be equal'); + t.notDeepEqual(body, expected, 'should not be equal'); t.end(); - - await done(); }); test('cloudcmd: modules: no', (t) => { const fn = modulas(); const url = '/json/modules.json'; - const send = sinon.stub(); + const send = stub(); - fn({url}, {send}); + fn({url}, { + send, + }); - t.ok(send.calledWith(localModules), 'should have been called with modules'); + t.calledWith(send, [localModules], 'should have been called with modules'); t.end(); }); - diff --git a/test/server/root.js b/test/server/root.js deleted file mode 100644 index e3dcbeb5..00000000 --- a/test/server/root.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -const path = require('path'); -const test = require('tape'); - -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); - -const dir = path.join(__dirname, '..', '..', 'server'); - -const pathConfig = path.join(dir, 'config'); -const pathRoot = `${dir}/root`; - -const clean = require('clear-module'); - -const {cache, resolve} = require; -const stub = (name, exports) => { - require(name); - - const resolved = resolve(name); - cache[resolved].exports = exports; -}; - -test('cloudcmd: root: config', (t) => { - clean(pathRoot); - - const config = sinon.stub().returns(false); - - stub(pathConfig, config); - - const root = require(pathRoot); - - root('hello'); - - t.ok(config.calledWith('root'), 'should call config'); - - clean(pathConfig); - clean(pathRoot); - - t.end(); -}); - -test('cloudcmd: root: mellow', (t) => { - clean(pathRoot); - - const config = sinon.stub().returns(''); - const pathToWin = sinon.stub(); - - const mellow = { - pathToWin - }; - - stub('mellow', mellow); - stub(pathConfig, config); - - const root = require(pathRoot); - const dir = 'hello'; - const dirRoot = '/'; - - root(dir); - - t.ok(pathToWin.calledWith(dir, dirRoot), 'should call mellow'); - - clean('mellow'); - clean(pathConfig); - clean(pathRoot); - - t.end(); -}); - diff --git a/test/server/terminal.js b/test/server/terminal.js deleted file mode 100644 index 5557d1a6..00000000 --- a/test/server/terminal.js +++ /dev/null @@ -1,107 +0,0 @@ -'use strict'; - -const test = require('tape'); -const mock = require('mock-require'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); - -const stub = require('mock-require'); -const clean = require('clear-module'); - -const configPath = '../../server/config'; -const terminalPath = '../../server/terminal'; - -test('cloudcmd: terminal: disabled', (t) => { - clean(terminalPath); - stub(configPath, () => { - return false; - }); - - const terminal = require('../../server/terminal'); - - const fn = terminal(); - - t.notOk(fn(), 'should return noop'); - - clean(configPath); - require(configPath); - - t.end(); -}); - -test('cloudcmd: terminal: disabled: listen', (t) => { - clean(terminalPath); - stub(configPath, () => false); - - const terminal = require(terminalPath); - - const fn = terminal().listen(); - - t.notOk(fn, 'should return noop'); - - clean(configPath); - require(configPath); - - t.end(); -}); - -test('cloudcmd: terminal: enabled', (t) => { - const term = sinon.stub(); - const arg = 'hello'; - - clean(terminalPath); - stub(configPath, () => '/terminal'); - stub('/terminal', term); - - const terminal = require(terminalPath); - terminal(arg); - - t.ok(term.calledWith(arg), 'should call terminal'); - t.end(); -}); - -test('cloudcmd: terminal: enabled: no string', (t) => { - const {log:originalLog} = console; - const log = sinon.stub(); - - clean(terminalPath); - stub(configPath, () => 'hello'); - - console.log = log; - const terminal = require(terminalPath); - terminal(); - console.log = originalLog; - - const msg = 'cloudcmd --terminal: Cannot find module \'hello\''; - - t.ok(log.calledWith(msg), 'should call exit'); - - t.end(); -}); - -test('cloudcmd: terminal: no arg', (t) => { - const gritty = {}; - - mock('gritty', gritty); - - clean(terminalPath); - stub(configPath, (a) => { - if (a === 'terminal') - return true; - - return 'gritty'; - }); - - const terminal = require(terminalPath); - const result = terminal(); - - t.equal(result, gritty, 'should equal'); - - mock.stop('gritty'); - - clean(configPath); - require(configPath); - - t.end(); -}); - diff --git a/test/server/validate.js b/test/server/validate.js deleted file mode 100644 index 2f32fcbb..00000000 --- a/test/server/validate.js +++ /dev/null @@ -1,164 +0,0 @@ -'use strict'; - -const fs = require('fs'); - -const test = require('tape'); -const diff = require('sinon-called-with-diff'); -const sinon = diff(require('sinon')); - -const before = require('../before'); -const {connect} = before; -const dir = '../..'; - -const validatePath = `${dir}/server/validate`; -const exitPath = `${dir}/server/exit`; -const columnsPath = `${dir}/server/columns`; - -const validate = require(validatePath); -const clear = require('clear-module'); - -const {cache, resolve} = require; -const stub = (name, exports) => { - require(name); - - const resolved = resolve(name); - cache[resolved].exports = exports; -}; - -test('validate: root: bad', (t) => { - const config = { - root: Math.random() - }; - - const success = ({done}) => { - t.fail('should not create server'); - t.end(); - done(); - }; - - const error = (e) => { - t.equal(e.message, 'dir should be a string', 'should throw'); - t.end(); - }; - - connect({config}) - .then(success) - .catch(error); -}); - -test('validate: root: /', (t) => { - const fn = sinon.stub(); - validate.root('/', fn); - - t.notOk(fn.called, 'should not call fn'); - t.end(); -}); - -test('validate: root: /home', (t) => { - const fn = sinon.stub(); - - validate.root('/home', (...args) => { - fn(...args); - - t.ok(fn.calledWith('root:', '/home'), 'should not call fn'); - t.end(); - }); -}); - -test('validate: root: stat', (t) => { - const fn = sinon.stub(); - const {stat} = fs; - - const error = 'ENOENT'; - fs.stat = (dir, fn) => fn(Error(error)); - - clean(); - require(exitPath); - stub(exitPath, fn); - - const {root} = require(validatePath); - - root('hello', fn); - - const msg = 'cloudcmd --root: %s'; - t.ok(fn.calledWith(msg, error), 'should call fn'); - - fs.stat = stat; - t.end(); -}); - -test('validate: packer: not valid', (t) => { - const fn = sinon.stub(); - - clean(); - require(exitPath); - stub(exitPath, fn); - - const {packer} = require(validatePath); - const msg = 'cloudcmd --packer: could be "tar" or "zip" only'; - - packer('hello'); - - t.ok(fn.calledWith(msg), 'should call fn'); - - t.end(); -}); - -test('validate: editor: not valid', (t) => { - const fn = sinon.stub(); - - clean(); - require(exitPath); - stub(exitPath, fn); - - const {editor} = require(validatePath); - const msg = 'cloudcmd --editor: could be "dword", "edward" or "deepword" only'; - - editor('hello'); - - t.ok(fn.calledWith(msg), 'should call fn'); - - t.end(); -}); - -test('validate: columns', (t) => { - const fn = sinon.stub(); - - clean(); - require(exitPath); - stub(exitPath, fn); - - const {columns} = require(validatePath); - - columns('name-size-date'); - - t.notOk(fn.called, 'should not call exit'); - t.end(); -}); - -test('validate: columns: wrong', (t) => { - const fn = sinon.stub(); - - clean(); - clear(columnsPath); - require(exitPath); - stub(exitPath, fn); - stub(columnsPath, { - 'name-size-date': '', - 'name-size': '', - }); - - const {columns} = require(validatePath); - const msg = 'cloudcmd --columns: can be only one of: "name-size-date", "name-size"'; - - columns('hello'); - - t.ok(fn.calledWith(msg), 'should call exit'); - t.end(); -}); - -function clean() { - clear(validatePath); - clear(exitPath); -} - diff --git a/test/static.js b/test/static.js index ddc0f7e7..0f0da5cb 100644 --- a/test/static.js +++ b/test/static.js @@ -1,173 +1,152 @@ -'use strict'; +import {Buffer} from 'node:buffer'; +import {serveOnce} from 'serve-once'; +import test from 'supertape'; +import criton from 'criton'; +import {cloudcmd} from '#server/cloudcmd'; -const test = require('tape'); -const {promisify} = require('es6-promisify'); -const pullout = require('pullout'); -const request = require('request'); +const config = { + auth: false, +}; -const configFn = require('../server/config'); -const {connect} = require('./before'); - -const warp = (fn, ...a) => (...b) => fn(...b, ...a); - -const _pullout = promisify(pullout); - -const get = promisify((url, options, fn) => { - if (!fn) { - fn = options; - options = {}; - } - - fn(null, request(url, options)); +const {request} = serveOnce(cloudcmd, { + config, }); +const configFn = cloudcmd.createConfigManager(); + test('cloudcmd: static', async (t) => { - const {port, done} = await connect(); const name = 'package.json'; + const {body} = await request.get(`/${name}`, { + type: 'json', + }); - get(`http://localhost:${port}/${name}`) - .then(warp(_pullout, 'string')) - .then(JSON.parse) - .then((json) => { - t.equal(json.name, 'cloudcmd', 'should download file'); - t.end(); - }) - .catch(console.error) - .then(done); + t.equal(body.name, 'cloudcmd', 'should download file'); + t.end(); }); test('cloudcmd: static: not found', async (t) => { const name = Math.random(); + const {status} = await request.get(`/${name}`); - const {port, done} = await connect({}); - const res = await get(`http://localhost:${port}/${name}`); - - res.on('response', (res) => { - t.equal(res.statusCode, 404, 'should return 404'); - }); - - res.on('error', console.error); - res.on('end', async () => { - await done(); - t.end(); - }); + t.equal(status, 404, 'should return 404'); + t.end(); }); test('cloudcmd: prefix: wrong', async (t) => { const originalPrefix = configFn('prefix'); + const config = { + prefix: '/hello', + }; - const {port, done} = await connect({ - config: { - prefix: '/hello' - } - }); + const options = { + config, + }; const name = Math.random(); - const res = await get(`http://localhost:${port}/${name}`); - res.on('response', async ({statusCode}) => { - await done(); - configFn('prefix', originalPrefix); - - console.log(require('../server/config')('prefix')); - - t.equal(statusCode, 404, 'should return 404'); - t.end(); + const {status} = await request.get(`/${name}`, { + options, }); + + configFn('prefix', originalPrefix); + + t.equal(status, 404, 'should return 404'); + t.end(); }); test('cloudcmd: /cloudcmd.js', async (t) => { const name = 'cloudcmd.js'; + const {status} = await request.get(`/${name}`); - const {port, done} = await connect(); - const res = await get(`http://localhost:${port}/${name}`); - - res.on('response', ({statusCode}) => { - t.equal(statusCode, 200, 'should return OK'); - }); - - res.on('end', async () => { - await done(); - t.end(); - }); + t.equal(status, 200, 'should return OK'); + t.end(); }); test('cloudcmd: /cloudcmd.js: auth: access denied', async (t) => { const name = 'cloudcmd.js'; const config = { - auth: true + auth: true, }; - const {port, done} = await connect({config}); - const res = await get(`http://localhost:${port}/${name}`); + const options = { + config, + }; - res.on('response', ({statusCode}) => { - t.equal(statusCode, 401, 'should return auth'); + const {status} = await request.get(`/${name}`, { + options, }); - res.on('end', async () => { - await done(); - t.end(); - }); + t.equal(status, 401, 'should return auth'); + t.end(); }); test('cloudcmd: /cloudcmd.js: auth: no password', async (t) => { const name = 'cloudcmd.js'; + const username = 'hello'; const config = { - auth: true + auth: true, + username, }; - const auth = { - username: configFn('username'), + const options = { + config, }; - const {port, done} = await connect({config}); - const res = await get(`http://localhost:${port}/${name}`, {auth}); + const encoded = Buffer + .from(`${username}:`) + .toString('base64'); - res.on('response', ({statusCode}) => { - t.equal(statusCode, 401, 'should return auth'); - }); - res.on('end', async () => { - await done(); - t.end(); + const authorization = `Basic ${encoded}`; + + const {status} = await request.get(`/${name}`, { + headers: { + authorization, + }, + options, }); + + t.equal(status, 401, 'should return auth'); + t.end(); }); test('cloudcmd: /cloudcmd.js: auth: access granted', async (t) => { const name = 'cloudcmd.js'; + const username = 'hello'; + const password = 'world'; + const algo = configFn('algo'); + const config = { - auth: true - }; - const auth = { - username: configFn('username'), - password: configFn('password'), + auth: true, + username, + password: criton(password, algo), }; - const {port, done} = await connect({config}); - const res = await get(`http://localhost:${port}/${name}`, {auth}); + const options = { + config, + }; - res.on('response', ({statusCode}) => { - t.equal(statusCode, 401, 'should return auth'); + const encoded = Buffer + .from(`${username}:${password}`) + .toString('base64'); + + const authorization = `Basic ${encoded}`; + + const {status} = await request.get(`/${name}`, { + headers: { + authorization, + }, + options, }); - res.on('end', async () => { - await done(); - t.end(); - }); + t.equal(status, 200, 'should return auth'); + t.end(); }); test('cloudcmd: /logout', async (t) => { const name = 'logout'; - const {port, done} = await connect(); - const res = await get(`http://localhost:${port}/${name}`); + const {status} = await request.get(`/${name}`); - res.on('response', ({statusCode}) => { - t.equal(statusCode, 401, 'should return 401'); - }); - res.on('end', async () => { - await done(); - t.end(); - }); + t.equal(status, 401, 'should return 401'); + t.end(); }); - diff --git a/tmpl/config.hbs b/tmpl/config.hbs index 742c2b24..6002cd8b 100644 --- a/tmpl/config.hbs +++ b/tmpl/config.hbs @@ -1,5 +1,5 @@
    -
  • +
  • -
  • +
  • -
  • +
  • -
  • - + + + +
  • +
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • + +
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • -
  • +
  • + +
  • +
  • -
  • +
  • -
  • +
  • -
  • - -
  • -
  • +
  • -
+ \ No newline at end of file diff --git a/tmpl/fs/file.hbs b/tmpl/fs/file.hbs index 0eaa6887..8b50494f 100644 --- a/tmpl/fs/file.hbs +++ b/tmpl/fs/file.hbs @@ -2,6 +2,7 @@ {{ name }} {{ size }} + {{ time }} {{ date }} {{ owner }} {{ mode }} diff --git a/webpack.config.js b/webpack.config.js index b663db21..5d684391 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,14 +1,10 @@ -'use strict'; +import {merge} from 'webpack-merge'; +import * as htmlConfig from './.webpack/html.js'; +import cssConfig from './.webpack/css.js'; +import jsConfig from './.webpack/js.js'; -const merge = require('webpack-merge'); - -const htmlConfig = require('./.webpack/html'); -const cssConfig = require('./.webpack/css'); -const jsConfig = require('./.webpack/js'); - -module.exports = merge([ +export default merge([ jsConfig, htmlConfig, cssConfig, ]); -