npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

oro-functions

v2.3.3

Published

The Class Ofn extends Ofn-client and includes additional static helper functions for: URLs, Files, Operating System.

Downloads

29

Readme

Oro Functions

Overview

Ofn contains utility static methods (helpers).

This package ( oro-functions ) is divided from oro-functions-client to allow using that functions in js-client frameworks like Vuejs or React.

Class oro-functions is extended from oro-functions-client.

If you want to know all fns, read oro-functions-client.

Functions could be divided in groups: ⇢ (Extended) · URLs · Crypto · Files · Operating System · Ports · Console ⇢ (Client) · General · Numbers · String · Crypto · Functions · Classes · Objects · Arrays · Dates · URLs · Files · PHP Serialize · Response

Installation

npm install oro-functions

Example:

// cjs
const { Ofn } = require( 'oro-functions' );

// mjs, ts
import { Ofn } from 'oro-functions';

Ofn.type( [ 1, 2, 3 ] ); // -> 'array'

also every method could be called individually:

// cjs
const { type } = require( 'oro-functions' );

// mjs, ts
import { type } from 'oro-functions';

type( [ 1, 2, 3 ] ); // -> 'array'

Methods

Oro Functions Client

In Ofn there are all functions of Oro Functions Client.

Extended Functions

URLs

Ofn.jwkTokenDecode()

jwkTokenDecode( token: string ) => string;
Ofn.jwkTokenDecode(
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoib3JvcGVzYSIsImlhdCI6MTYyOTcxMzM2MywiZXhwIjoxNjI5NzIwNTYzfQ.2zL8FzvFQCtuqi0fFoby4QVCXSi2pWNS3bzCU53Vd4M',
);
// -> '{"user":"oropesa","iat":1629713363,"exp":1629720563}'

Crypto

Ofn.cryptoGenerateKeyPair()

Ofn.cryptoGenerateKeyPair(
  passphrase?: string,
  options?: CryptoKeyPairOptions
) => Promise<CryptoKeyPairResponse>

interface CryptoKeyPairOptions {
  type?: string;
  modulusLength?: number;
  publicKeyEncodingType?: string;
  publicKeyEncodingFormat?: string;
  privateKeyEncodingType?: string;
  privateKeyEncodingFormat?: string;
  privateKeyEncodingCipher?: string;
}

type CryptoKeyPairResponse = SResponse<
  CryptoKeyPairObject,  // as SResponseOK
  CryptoKeyPairError    // as SResponseKO
>;

interface SResponseOK {
  status: true,
  passphrase: string;
  publicKey: string;
  privateKey: string;
}

interface SResponseKO {
  status: false,
  error: {
    msg: string;
    err: Error;
  }
}

interface CryptoKeyPairObject {
  passphrase: string;
  publicKey: string;
  privateKey: string;
}

interface CryptoKeyPairError {
  msg: string;
  err: Error;
}
await Ofn.cryptoGenerateKeyPair('example');
// {
//   passphrase: 'example',
//   publicKey: '-----BEGIN RSA PUBLIC KEY-----',
//   privateKey: '-----BEGIN RSA PRIVATE KEY-----'
// }
  • Default options
options = {
  type: 'rsa', // 'rsa', 'rsa-pss', 'dsa', 'ec', 'ed25519', 'ed448', 'x25519', 'x448', 'dh'.
  modulusLength: 4096,
  publicKeyEncodingType: 'spki', // 'pkcs1' (RSA only) or 'spki'.
  publicKeyEncodingFormat: 'pem', // 'pem', 'der', or 'jwk'.
  privateKeyEncodingType: 'pkcs8', // 'pkcs1' (RSA only), 'pkcs8' or 'sec1' (EC only).
  privateKeyEncodingFormat: 'pem', // 'pem', 'der', or 'jwk'.
  privateKeyEncodingCipher: 'aes-256-cbc', // 'aes-256-cbc', 'des-cbc-sha', 'rc4-128-md5', ...
};

Files

await Ofn.obtainOConfig()

Ofn.obtainOConfigSync()

await Ofn.obtainOConfig<T extends object = OConfigDefaultParams>
    ( args?: OConfigArgs ) => Promise<OConfigResponse<T>>;

Ofn.obtainOConfigSync<T extends object = OConfigDefaultParams>
    ( args?: OConfigArgs ) => OConfigResponse<T>;

interface OConfigArgs {
  file?: string;
  deep?: number;
  defaultParams?: string[];
  extraParams?: string[];
}

interface OConfigDefaultParams {
  environment: string;
  projectname: string;
  projectserver: string;
}

type OConfigResponse<T extends object = OConfigDefaultParams> =
    SResponse<
      OConfigObject<T>, // as SResponseOK
      OConfigError      // as SResponseKO
    >;

interface SResponseOK {
  status: true,
  config: T;
}

interface SResponseKO {
  status: false,
  error: {
    msg: string;
    args?: OConfigArgs;
  }
}

interface OConfigObject<T extends object = OConfigDefaultParams> {
  config: T;
}

interface OConfigError {
  msg: string;
  args?: OConfigArgs;
}

Put yourself in this situation, you work with Git and you create modules or projects that need the common file .env to use custom variables, with data about, i.e., connect to dbs, users-passwords, dev-pro or other envs, custom configs.

Then, you have something like:

- parent-folder/
  ├─ project-1/  #git-project-1
  │   └...
  ├─ project-2/  #git-project-2
  │   └...
  └...

Instead of create global variables in the system, or duplicate the file .env, you can centralize all data in oro-config.json.

This file, oro-config.json, could be in the same project and in the parent folders too, in such a way that the final json is merged and overwritten from the parent folders to the project.

So, using this example, you have:

- parent-folder/
  ├─ project-1/
  │   ├─ oro-config.json #json of project 1
  │   └...
  ├─ project-2/
  │   ├─ oro-config.json #json of project 2
  │   └...
  ├─ oro-config.json #json of parent-folder
  └...

Continuing, the oro-config.json files have the next data:

// oro-config.json of Parent Folder
{
  "environment": "dev",
  "projectserver": "laptop-dev",
  "nuxt": {
    "server": "localhost",
    "defaultRole": "default"
  }
}

// oro-config.json of Project 1
{
  "projectname": "project-1"
}

// oro-config.json of Project 2
{
  "projectname": "project-2",
  "nuxt": {
    "pageName": "The Project 2",
    "defaultRole": "client"
  }
}

Finally, the json result is:

/* Inside project 1 */

let obtainConfig = await Ofn.obtainOConfig( { deep: 1 } );
// {
//   status: true,
//   config: {
//     environment: 'dev',
//     projectserver: 'laptop-dev',
//     projectname: 'project-1',
//     nuxt: {
//       server: 'localhost',
//       defaultRole: 'default'
//     }
//   }
// }

/* Inside project 2 */

let obtainConfig = await Ofn.obtainOConfig( { deep: 1 } );
// {
//   status: true,
//   config: {
//     environment: 'dev',
//     projectserver: 'laptop-dev',
//     projectname: 'project-2',
//     nuxt: {
//       server: 'localhost',
//       pageName: 'The Project 2',
//       defaultRole: 'client'
//     }
//   }
// }
  • Default args
let args = {
  file: 'oro-config.json',
  deep: 0,
  defaultParams: ['environment', 'projectname', 'projectserver'],
  extraParams: [],
};

By default, there are 3 params that are required in json: environment, projectname, projectserver.

So, if there are missing, the response of Ofn.obtainOConfig() is { status: false, ... }.

Alternatively, you can change defaultParams, or you can add extraParams to be required.

On the other hand, you can change de file name to search, so instead of oro-config.json, you can use custom.json.

Finally, you choose the deep from parents to look for.

await Ofn.getFileJsonRecursively()

Ofn.getFileJsonRecursivelySync()

await Ofn.getFileJsonRecursively<T>
    ( filenameOrPath: string, parentDeep?: number ) => Promise<T>;

Ofn.getFileJsonRecursivelySync<T>
    ( filenameOrPath: string, parentDeep?: number ) => T;

Having this case:

- main/
  ├─ folder/
  │   ├─ subfolder/
  │   │   ├─ index.js
  │   │   └─ custom.json
  │   └ custom.json
  └ custom.json

The final json is merged and overwritten from the parents to the project file.

// in index.js
let custom = await Ofn.getFileJsonRecursively('custom.json', 2);
// { ... }

await Ofn.globFiles()

await Ofn.globFiles = (
  folderPath: string | string[],
  globArgs?: GlobFilesOptions,
) => Promise<string[]>;
await Ofn.globFiles(`folder/*`);
// [
//   `folder/example.txt`,
//   ...
// ]
// default
globArgs = {
  dot: true,
  unique: true,
  onlyFiles: true,
  ignore: ['node_modules/**', '.zero/**'],
};

await Ofn.folderIsEmpty()

await Ofn.folderIsEmpty = (
  folderPath: string,
  globArgs?: GlobFilesOptions,
) => Promise<boolean>;
await Ofn.folderIsEmpty(`folder/`); // false
  • Default args

This function is a wrapper of fast-glob with default args. so GlobFilesOptions are the same as fast-glob Options

// default
globArgs = {
  dot: true,
  unique: true,
  onlyFiles: true,
  ignore: ['node_modules/**', '.zero/**'],
};

await Ofn.pathIsFolder()

await Ofn.pathIsFolder = ( folderPath: string ) => Promise<boolean>;
await Ofn.pathIsFolder(`folder`);
// -> true

await Ofn.zipFolder()

await Ofn.zipFolder = ( folderPath: string, zipPath?: string ) => Promise<ZipFolderResponse>;

type ZipFolderResponse = SResponse<
  ZipFolderObject, // as SResponseOK
  ZipFolderError   // as SResponseKO
>;

interface SResponseOK {
  status: true,
  zipPath: string;
}

interface SResponseKO {
  status: false,
  error: {
    msg: string;
    folderPath?: string;
    zipPath?: string;
  }
}

interface ZipFolderObject {
  zipPath: string;
}

interface ZipFolderError {
  msg: string;
  folderPath?: string;
  zipPath?: string;
}
await Ofn.zipFolder(`folder`, 'folder.zip');
// -> { status: true, zipPath: 'folder.zip' }

Operating System

Ofn.osPlatform()

Ofn.osPlatform = () => NodeJS.Platform;
Ofn.osPlatform();
// -> 'win32' || 'darwin' || 'linux' || ...

Ofn.osIsWindows()

Ofn.osIsWindows = () => boolean;
Ofn.osIsWindows();
// -> true

Ofn.osIsMac()

Ofn.osIsMac = () => boolean;
Ofn.osIsMac();
// -> false

Ofn.osIsLinux()

Ofn.osIsLinux = () => boolean;
Ofn.osIsLinux();
// -> true

Ofn.osIsAndroid()

Ofn.osIsAndroid = () => boolean;
Ofn.osIsAndroid();
// -> true

Ports

await Ofn.isPortFree()

await Ofn.isPortFree = ( port: number ) => Promise<IsPortFreeResponse>;

type IsPortFreeResponse = SResponse<
  PortFreeObject, // as SResponseOK
  IsPortFreeError // as SResponseKO
>;

interface SResponseOK {
  status: true,
  port: number;
}

interface SResponseKO {
  status: false,
  error: {
    msg: string;
    port: number;
  }
}

interface PortFreeObject {
  port: number;
}

interface IsPortFreeError {
  msg: string;
  port: number;
}
await Ofn.isPortFree(3000);
// -> { status: true, port: 3000 }

await Ofn.getPortFree()

await Ofn.getPortFree = ( portStart?: number | number[], portEnd?: number )
    => Promise<GetPortFreeResponse>;

type GetPortFreeResponse = SResponse<
  PortFreeObject,  // as SResponseOK
  GetPortFreeError // as SResponseKO
>;

interface SResponseOK {
  status: true,
  port: number;
}

interface SResponseKO {
  status: false,
  error: {
    msg: string;
    port?: number;
    opts?: {
      random?: boolean;
      port?: number;
      ports?: number[];
      portRange?: number[];
    };
    err?: any;
  }
}

interface PortFreeObject {
  port: number;
}

interface GetPortFreeError {
  msg: string;
  port?: number;
  opts?: {
    random?: boolean;
    port?: number;
    ports?: number[];
    portRange?: number[];
  };
  err?: any;
}
await Ofn.getPortFree();
// -> { status: true, port: 60247 } #random

await Ofn.getPortFree(3000);
// -> { status: true, port: 3000 } #if not allowed, return random

await Ofn.getPortFree([3000, 3001, 3002]);
// -> { status: true, port: 3000 }
// -> { status: false, error: { msg: 'No available ports in array [ 3000, 3001, 3002 ]' } }

await Ofn.getPortFree(3000, 3100);
// -> { status: true, port: 3000 }
// -> { status: false, error: { msg: 'No available ports in range 3000-3100' } }

Console

Ofn.processWrite()

Ofn.processWrite(
  strOrObject: string | ProcessWriteObject,
  color?: string,
  bg?: string
) => string;

type ProcessWriteObject =
    | { s?: string, c?: string, b?: string }
    | { str?: string, cl?: string, bg?: string }
    | { string?: string, color?: string, background?: string }
Ofn.processWrite('info', 'blue');
Ofn.processWrite(' Doing some stuff... ');

Ofn.processWrite({ s: 'Error!', c: 'red', b: 'redlight' });
Ofn.processWrite('\n');
  • Example:

Example Console - Process Write

Note: first param could be a string or an object

  • Allowed Object:

    • s, str, or string
    • c, cl, or color
    • b, bg, or background
  • Allowed Colors and Background:

    • gray
    • red
    • green
    • white
    • yellow
    • blue
    • redlight
    • bluelight

Ofn.processWrites()

Ofn.processWrites( arr: Array<string | ProcessWriteObject> ) => string;

type ProcessWriteObject =
    | { s?: string, c?: string, b?: string }
    | { str?: string, cl?: string, bg?: string }
    | { string?: string, color?: string, background?: string }
Ofn.processWrites([
  { s: ' info ', c: 'blue', b: 'bluelight' },
  ' Doing some stuff... ',
  { s: 'Error!', c: 'red', b: 'redlight' },
  '\n',
]);
  • Example:

Example Console - Process Writes