@fullstackunicorn/initialize 1.0.2 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +33 -13
  2. package/package.json +10 -8
  3. package/readme.md +0 -190
package/index.js CHANGED
@@ -4,10 +4,13 @@ String.prototype.low = function () { return this.toLowerCase() }
4
4
  String.prototype.cut = function (n = 1) { return this.slice(0, -n) }
5
5
 
6
6
  class F3Error extends Error {
7
- constructor(service, message, params = {}) {
7
+ constructor(service, message, params, cause) {
8
8
  super(message)
9
+ this.name = 'F3Error'
9
10
  this.service = service
10
- this.params = params
11
+ if (params) this.params = params
12
+ if (cause) this.cause = cause
13
+ if (Error.captureStackTrace) Error.captureStackTrace(this, F3Error)
11
14
  }
12
15
  }
13
16
 
@@ -15,6 +18,7 @@ globalThis.F3 = {}
15
18
 
16
19
  globalThis.F3.service = ''
17
20
 
21
+ globalThis.F3.isErr = value => value instanceof Error
18
22
  globalThis.F3.isArr = value => Array.isArray(value)
19
23
  globalThis.F3.isNil = value => value === undefined || value === null
20
24
  globalThis.F3.isFnc = value => typeof value === 'function'
@@ -42,7 +46,7 @@ globalThis.F3.obj.isGood = obj => !!obj && typeof obj === 'object' && Object.key
42
46
  globalThis.F3.obj.safe = obj => (typeof obj === 'object' && obj !== null) ? obj : {}
43
47
  globalThis.F3.obj.isPlain = obj => obj !== null && typeof obj === 'object' && Object.getPrototypeOf(obj) === Object.prototype
44
48
  globalThis.F3.obj.inKb = obj => new TextEncoder().encode(JSON.stringify(obj)).length / 1000
45
- globalThis.F3.obj.string = obj => {
49
+ globalThis.F3.obj.toStr = obj => {
46
50
  if (typeof obj === 'string') return obj
47
51
  try { return JSON.stringify(obj, null, 2) } catch { return String(obj) }
48
52
  }
@@ -90,25 +94,41 @@ globalThis.F3.log.obj = (object = {}, ...rest) => {
90
94
  const result = []
91
95
  for (const item of rest) result.push(String(item))
92
96
  for (const key of Object.keys(object)) {
93
- try { result.push(`\n${key}:\n${F3.obj.string(object[key])}\n`) }
97
+ try { result.push(`\n${key}:\n${F3.obj.toStr(object[key])}\n`) }
94
98
  catch { result.push(`\n${key}: [Error serializing value]\n`) }
95
99
  }
96
100
  console.log(result.join('\n'))
97
101
  }
98
102
 
103
+ globalThis.F3.throw = (...args) => { throw new F3Error(F3.service, ...args) }
104
+
99
105
  globalThis.F3.err = {}
100
106
  globalThis.F3.err.is500 = status => !!status && status >= 500
101
107
  globalThis.F3.err.is400 = status => !!status && status >= 400 && status < 500
102
108
 
109
+ globalThis.F3.err.toObj = err => {
110
+ const base = { name:err.name, message:err.message, stack:err.stack }
111
+ try { return Object.assign(base, Object.fromEntries(Object.entries(err)))}
112
+ catch { return base }
113
+ }
114
+ globalThis.F3.err.toStr = err => {
115
+ if (F3.isErr(err)) return F3.obj.toStr(F3.err.toObj(err))
116
+ if (F3.isObj(err)) return F3.obj.toStr(err)
117
+ if (F3.isStr(err)) return err
118
+ return String(err)
119
+ }
120
+ globalThis.F3.err.logs = err => {
121
+ if (err instanceof F3Error) console.error(F3.obj.toStr(err))
122
+ else console.error('non-F3-error',F3.obj.toStr(err))
123
+ }
124
+
103
125
  globalThis.F3.catch = {}
104
- globalThis.F3.catch.throw = (error, ...rest) => {
105
- if (rest.length > 0) console.log(...rest)
106
- throw error
107
- }
126
+ globalThis.F3.catch.throw = (error, message) => {
127
+ if (error instanceof F3Error) throw error
128
+ F3.throw(message, null, F3.err.toStr(error))
129
+ }
108
130
  globalThis.F3.catch.log = (...args) => console.log(...args)
109
- globalThis.F3.catch.res = (first, ...rest) => {
110
- if (rest.length > 0) console.log(...rest)
131
+ globalThis.F3.catch.res = (first, error) => {
132
+ if (error) F3.err.logs(error)
111
133
  return first
112
- }
113
-
114
- globalThis.F3.throw = (message, params) => { throw new F3Error(F3.service, message, params) }
134
+ }
package/package.json CHANGED
@@ -1,19 +1,20 @@
1
1
  {
2
- "version": "1.0.2",
2
+ "version": "1.0.6",
3
3
  "name": "@fullstackunicorn/initialize",
4
4
  "author": "lucanigido (https://fullstackunicorn.dev/author/lucanigido)",
5
5
  "description": "A collection of global utility functions for JavaScript/Node.js projects (type checks, string helpers, logging, etc.). Side-effect import extends globals.",
6
- "readme": "README.md",
7
- "main": "index.js",
8
- "type": "module",
9
6
  "license": "MIT",
7
+ "type": "module",
8
+ "private": false,
9
+ "readme": "package.readme.md",
10
+ "main": "index.js",
11
+ "files": [
12
+ "index.js"
13
+ ],
10
14
  "repository": {
11
15
  "type": "git",
12
16
  "url": "https://gitlab.com/fullstackunicorn/initialize.git"
13
17
  },
14
- "files": [
15
- "index.js"
16
- ],
17
18
  "sideEffects": [
18
19
  "index.js"
19
20
  ],
@@ -31,6 +32,7 @@
31
32
  "#@/*": "./*"
32
33
  },
33
34
  "scripts": {
34
- "test": "echo \"Error: no test specified\" && exit 1"
35
+ "test": "exit 1",
36
+ "cli": "chmod +x ./config.cli.sh && ./config.cli.sh"
35
37
  }
36
38
  }
package/readme.md DELETED
@@ -1,190 +0,0 @@
1
- # @fullstackunicorn/initialize
2
-
3
- [![NPM version](https://badge.fury.io/js/%40fullstackunicorn%2Finitialize.svg)](https://www.npmjs.com/package/@fullstackunicorn/initialize)
4
- [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
5
- [![Node.js Version](https://img.shields.io/badge/node-v20-green.svg)](https://nodejs.org/)
6
-
7
- A lightweight, zero-dependency utility library for JavaScript/Node.js. It extends global objects with handy helpers: String prototype methods for quick transformations and a `F3` namespace for type checks, safe accessors, logging, templating, and error handling. Designed as a side-effect module—just import once at the top of your project to make everything globally available.
8
-
9
- Ideal for scripts, apps, or teams wanting concise, crash-proof utilities without imports everywhere.
10
-
11
- ## Features
12
- - **Global Extensions**: One import unlocks `String.prototype.cap()`, `F3.isArr(value)`, etc.—no destructuring needed.
13
- - **Safe & Concise**: Guards against nil/empty values (e.g., `F3.arr.safe(arr)` returns `[]` if invalid).
14
- - **Type Guards**: Fast checks for arrays, objects, strings, etc., with `F3.typeOf(value)`.
15
- - **Logging Utils**: Flexible console helpers like `F3.logs(...args)`, `F3.log.obj(obj, ...rest)`, and catch-specific loggers.
16
- - **String & Object Helpers**: URL fabrication, templating, JSON-safe stringifying (handles circular refs).
17
- - **Error Handling**: Quick catch wrappers like `F3.catch.res(first, ...logs)` for graceful returns.
18
- - **No Dependencies**: Pure JS (Node 14+; works in browsers via `globalThis`).
19
-
20
- ## Installation
21
- ```bash
22
- npm install @fullstackunicorn/initialize
23
- ```
24
- ```bash
25
- yarn add @fullstackunicorn/initialize
26
- ```
27
-
28
- ## Quick Start
29
- Add at the top of your entry file (side-effect import—runs once):
30
- ```javascript
31
- import '@fullstackunicorn/initialize'; // Now globals are extended!
32
-
33
- // String prototypes
34
- console.log('hello'.cap()); // "Hello"
35
- console.log('world!'.cut(1)); // "world"
36
-
37
- // F3 type checks
38
- console.log(F3.isArr([])); // true
39
- console.log(F3.isNil(null)); // true
40
-
41
- // Safe accessors
42
- const safeObj = F3.obj.safe({}); // {}
43
- console.log(F3.arr.safe('not an array')); // []
44
-
45
- // Logging
46
- F3.logs('Quick log:', 42);
47
- F3.log.obj({ user: 'Alice', age: 30 }, 'Optional prefix'); // Verbose with separator
48
-
49
- // Catch helper
50
- try {
51
- // ... risky code ...
52
- } catch (err) {
53
- return F3.catch.res(null, 'Handled error:', err.message); // Logs extras, returns null
54
- }
55
- ```
56
-
57
- ## API Reference
58
-
59
- ### String Prototype Extensions
60
- These add methods directly to `String.prototype` for chainable ops.
61
-
62
- | Method | Description | Parameters | Returns |
63
- |--------|-------------|------------|---------|
64
- | `cap()` | Capitalizes first letter. | None | `string` |
65
- | `up()` | Converts to uppercase. | None | `string` |
66
- | `low()` | Converts to lowercase. | None | `string` |
67
- | `cut(n=1)` | Slices from end (removes last `n` chars). | `n: number` (default: 1) | `string` |
68
-
69
- ### F3 Basics (Core Type Guards)
70
- Global `F3` namespace for common checks.
71
-
72
- | Method | Description | Parameters | Returns |
73
- |--------|-------------|------------|---------|
74
- | `isArr(value)` | Checks if array. | `value: any` | `boolean` |
75
- | `isNil(value)` | Checks if null/undefined. | `value: any` | `boolean` |
76
- | `isFnc(value)` | Checks if function. | `value: any` | `boolean` |
77
- | `isObj(value)` | Checks if object (non-null). | `value: any` | `boolean` |
78
- | `isStr(value)` | Checks if string. | `value: any` | `boolean` |
79
- | `isNum(value)` | Checks if finite number. | `value: any` | `boolean` |
80
- | `typeOf(value)` | Returns type string (e.g., 'array', 'nil'). | `value: any` | `string` |
81
-
82
- ### F3.str (String Helpers)
83
- | Method | Description | Parameters | Returns |
84
- |--------|-------------|------------|---------|
85
- | `isGood(str)` | Checks if non-empty trimmed string. | `str: any` | `boolean` |
86
-
87
- ### F3.arr (Array Helpers)
88
- | Method | Description | Parameters | Returns |
89
- |--------|-------------|------------|---------|
90
- | `isGood(arr)` | Checks if non-empty array. | `arr: any` | `boolean` |
91
- | `safe(arr)` | Returns array or empty `[]`. | `arr: any` | `array` |
92
- | `isSameLength(list1, list2)` | Checks if both arrays and same length. | `list1: any`, `list2: any` | `boolean` |
93
-
94
- ### F3.obj (Object Helpers)
95
- | Method | Description | Parameters | Returns |
96
- |--------|-------------|------------|---------|
97
- | `isGood(obj)` | Checks if non-empty object. | `obj: any` | `boolean` |
98
- | `safe(obj)` | Returns object or `{}`. | `obj: any` | `object` |
99
- | `isPlain(obj)` | Checks if plain object (no prototype). | `obj: any` | `boolean` |
100
- | `inKb(obj)` | Estimates size in KB (JSON-encoded). | `obj: any` | `number` |
101
- | `string(obj)` | Safe stringify (falls back to `String(obj)`). | `obj: any` | `string` |
102
-
103
- ### F3.res (Result Validation)
104
- | Method | Description | Parameters | Returns |
105
- |--------|-------------|------------|---------|
106
- | `isGood(res)` | Validates result (handles errors/offline flags). | `res: any` | `boolean` |
107
-
108
- ### F3 Utilities
109
- | Method | Description | Parameters | Returns |
110
- |--------|-------------|------------|---------|
111
- | `fabUrl(path, params)` | Builds URL by replacing `:key` params. | `path: string`, `params: object` | `string` |
112
- | `replacer(string, values)` | Replaces `{{key}}` templates. | `string: string`, `values: object` | `string` |
113
-
114
- ### F3.logs (Simple Logging)
115
- | Method | Description | Parameters | Returns |
116
- |--------|-------------|------------|---------|
117
- | `logs(...args)` | Logs args to console. | `...args: any` | `void` |
118
-
119
- ### F3.log (Structured Logging)
120
- | Method | Description | Parameters | Returns |
121
- |--------|-------------|------------|---------|
122
- | `arr(...args)` | Logs args to console (array-style). | `...args: any` | `void` |
123
- | `obj(object, ...rest)` | Verbose log: Pretty-prints object keys/values with optional prefixes (handles serialization errors). | `object: object`, `...rest: any` | `void` |
124
-
125
- ### F3.err (Error Status Checks)
126
- | Method | Description | Parameters | Returns |
127
- |--------|-------------|------------|---------|
128
- | `is500(status)` | Checks if server error (≥500). | `status: any` | `boolean` |
129
- | `is400(status)` | Checks if client error (400-499). | `status: any` | `boolean` |
130
-
131
- ### F3.catch (Error Handling)
132
- | Method | Description | Parameters | Returns |
133
- |--------|-------------|------------|---------|
134
- | `res(first, ...rest)` | Returns `first`; logs `rest` (for catch blocks). | `first: any`, `...rest: any` | `any` |
135
- | `arr(...args)` | Logs args to console (array-style). | `...args: any` | `void` |
136
- | `obj(object, ...rest)` | Verbose log: Pretty-prints object keys/values with optional prefixes (handles serialization errors). | `object: object`, `...rest: any` | `void` |
137
-
138
- **Notes**:
139
- - All methods are pure functions (no side-effects except logging).
140
- - Globals persist after import—use in any scope.
141
- - Logging handles circular references gracefully (e.g., `[Error serializing value]` fallback).
142
- - For strict mode, wrap in IIFE if needed.
143
-
144
- ## Examples
145
- ### Type-Safe Array Processing
146
- ```javascript
147
- import '@fullstackunicorn/initialize';
148
-
149
- function processUsers(users) {
150
- const safeUsers = F3.arr.safe(users);
151
- if (!F3.arr.isGood(safeUsers)) return [];
152
-
153
- return safeUsers.map(user => ({
154
- name: F3.obj.safe(user).name.low(),
155
- isValid: F3.res.isGood(user)
156
- }));
157
- }
158
- ```
159
-
160
- ### Templated Logging
161
- ```javascript
162
- import '@fullstackunicorn/initialize';
163
-
164
- const template = F3.replacer('Hello {{name}}! Age: {{age}}', { name: 'Alice', age: 30 });
165
- F3.logs(template); // "Hello Alice! Age: 30"
166
-
167
- const apiUrl = F3.fabUrl('/users/:id', { id: 123 });
168
- F3.log.arr('Fetching:', apiUrl); // "/users/123"
169
- ```
170
-
171
- ### Error Handling in Async
172
- ```javascript
173
- import '@fullstackunicorn/initialize';
174
-
175
- async function fetchData() {
176
- try {
177
- // ... API call ...
178
- return data;
179
- } catch (err) {
180
- F3.log.obj({ error: err.message, status: err.status }, 'API Error');
181
- return F3.catch.res(null, 'Handled error details');
182
- }
183
- }
184
- ```
185
-
186
- ## Contributing
187
- Fork the repo, add features/tests, and submit a PR. Focus on safe, concise utils!
188
-
189
- ## License
190
- MIT © [fullstackunicorn.dev/author/lucanigido](https://fullstackunicorn.dev/author/lucanigido)