aveazul 1.0.2 → 2.0.0

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.
@@ -1,110 +0,0 @@
1
- "use strict";
2
-
3
- function createNotImplemented(name) {
4
- return function () {
5
- const msg = name + " Not implemented in aveazul";
6
- console.error(msg);
7
- throw new Error(msg);
8
- };
9
- }
10
-
11
- function createInstanceNotImplemented(AveAzul) {
12
- const methods = [
13
- "then",
14
- "spread",
15
- "catch",
16
- "finally",
17
- "bind",
18
- "isFulfilled",
19
- "isRejected",
20
- "isPending",
21
- "isCancelled",
22
- "value",
23
- "reason",
24
- "all",
25
- "props",
26
- "any",
27
- "some",
28
- "map",
29
- "reduce",
30
- "filter",
31
- "each",
32
- "mapSeries",
33
- "disposer",
34
- "asCallback",
35
- "delay",
36
- "timeout",
37
- "cancel",
38
- "tap",
39
- "tapCatch",
40
- "call",
41
- "get",
42
- "return",
43
- "throw",
44
- "catchReturn",
45
- "catchThrow",
46
- "reflect",
47
- "suppressUnhandledRejections",
48
- "done",
49
- ];
50
-
51
- const proto = AveAzul.prototype;
52
- const ret = [];
53
- for (const method of methods) {
54
- if (!proto[method]) {
55
- ret.push(method);
56
- proto[method] = createNotImplemented("instance " + method);
57
- }
58
- }
59
- return ret;
60
- }
61
-
62
- function createStaticNotImplemented(AveAzul) {
63
- const methods = [
64
- "join",
65
- "try",
66
- "method",
67
- "resolve",
68
- "reject",
69
- "props",
70
- "any",
71
- "some",
72
- "map",
73
- "reduce",
74
- "filter",
75
- "each",
76
- "mapSeries",
77
- "race",
78
- "using",
79
- "promisify",
80
- "promisifyAll",
81
- "fromCallback",
82
- "delay",
83
- "coroutine",
84
- "coroutine.addYieldHandler",
85
- "getNewLibraryCopy",
86
- "noConflict",
87
- "setScheduler",
88
- ];
89
- const ret = [];
90
- for (const method of methods) {
91
- if (!AveAzul[method]) {
92
- ret.push(method);
93
- AveAzul[method] = createNotImplemented("static " + method);
94
- }
95
- }
96
- return ret;
97
- }
98
-
99
- function setupNotImplemented(AveAzul) {
100
- const instanceMethods = createInstanceNotImplemented(AveAzul);
101
- const staticMethods = createStaticNotImplemented(AveAzul);
102
- AveAzul.__notImplementedInstance = instanceMethods;
103
- AveAzul.__notImplementedStatic = staticMethods;
104
- }
105
-
106
- module.exports = {
107
- createInstanceNotImplemented,
108
- createStaticNotImplemented,
109
- setupNotImplemented,
110
- };
@@ -1,46 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * OperationalError class for representing errors that are expected during normal operation
5
- * Similar to Bluebird's OperationalError
6
- */
7
- class OperationalError extends Error {
8
- constructor(message) {
9
- super(message);
10
- this.name = "OperationalError";
11
- this.isOperational = true;
12
-
13
- // Capture stack trace
14
- if (Error.captureStackTrace) {
15
- Error.captureStackTrace(this, this.constructor);
16
- }
17
- }
18
- }
19
-
20
- /**
21
- * Check if an error is an operational error
22
- * @param {*} error - Error to check
23
- * @returns {boolean} True if the error is operational
24
- */
25
- function isOperationalError(error) {
26
- if (!error || typeof error !== "object") return false;
27
- return error instanceof OperationalError || error.isOperational === true;
28
- }
29
-
30
- /**
31
- * Check if an error is a programmer error (unexpected, likely a bug)
32
- * @param {*} error - Error to check
33
- * @returns {boolean} True if the error is a programmer error
34
- */
35
- function isProgrammerError(error) {
36
- if (!error || typeof error !== "object") return false;
37
- return !isOperationalError(error);
38
- }
39
-
40
- // Only export the OperationalError class
41
- module.exports = {
42
- OperationalError,
43
- // Internal utilities used by AveAzul.prototype.error
44
- isOperationalError,
45
- isProgrammerError,
46
- };
@@ -1,93 +0,0 @@
1
- "use strict";
2
-
3
- const { promisify } = require("./promisify");
4
- const {
5
- isIdentifier,
6
- isClass,
7
- isPromisified,
8
- getObjectDataKeys,
9
- } = require("./util");
10
-
11
- const defaultSuffix = "Async";
12
-
13
- const defaultFilter = function (name) {
14
- return isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor" && !name.endsWith("Sync");
15
- };
16
-
17
- const defaultPromisifier = (fn, _defaultPromisifier, options) => {
18
- return promisify(fn, {
19
- ...options,
20
- copyProps: false,
21
- });
22
- };
23
-
24
-
25
- function promisifyAll2(obj, options) {
26
- const allKeys = getObjectDataKeys(obj);
27
-
28
- for (const key of allKeys) {
29
- const value = obj[key];
30
- const promisifiedKey = key + options.suffix;
31
- const passesDefaultFilter =
32
- options.filter === defaultFilter ? true : defaultFilter(key, value, obj);
33
- if (
34
- typeof value !== "function" ||
35
- isPromisified(value) ||
36
- obj[promisifiedKey] ||
37
- !options.filter(key, value, obj, passesDefaultFilter)
38
- ) {
39
- continue;
40
- }
41
-
42
- if (key.endsWith(options.suffix)) {
43
- throw new TypeError(
44
- "Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a".replace(
45
- "%s",
46
- options.suffix
47
- )
48
- );
49
- }
50
-
51
- obj[promisifiedKey] = options.promisifier(value, defaultPromisifier, {
52
- // context: obj, // promisified function should get the binded object using this
53
- copyProps: false,
54
- ...options
55
- });
56
- }
57
- }
58
-
59
- function promisifyAll(target, _options) {
60
- if (typeof target !== "function" && typeof target !== "object") {
61
- throw new TypeError("the target of promisifyAll must be an object or a function");
62
- }
63
-
64
- const options = {
65
- suffix: defaultSuffix,
66
- filter: defaultFilter,
67
- promisifier: defaultPromisifier,
68
- Promise: global.Promise,
69
- ..._options,
70
- };
71
-
72
- const suffix = options.suffix;
73
-
74
- if (!isIdentifier(suffix)) {
75
- throw new RangeError(
76
- "suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"
77
- );
78
- }
79
-
80
- const allKeys = getObjectDataKeys(target);
81
-
82
- for (const key of allKeys) {
83
- const value = target[key];
84
- if (value && key !== "constructor" && !key.startsWith("_") && isClass(value)) {
85
- promisifyAll2(value.prototype, options);
86
- promisifyAll2(value, options);
87
- }
88
- }
89
-
90
- promisifyAll2(target, options);
91
- }
92
-
93
- module.exports.promisifyAll = promisifyAll;
package/lib/promisify.js DELETED
@@ -1,70 +0,0 @@
1
- "use strict";
2
-
3
- const { copyOwnProperties, isPromisified } = require("./util");
4
-
5
- module.exports.promisify = function promisify(fn, _options) {
6
- if (typeof fn !== "function") {
7
- throw new TypeError("expecting a function but got " + {}.toString.call(fn));
8
- }
9
-
10
- if (isPromisified(fn)) {
11
- return fn;
12
- }
13
-
14
- const options = {
15
- Promise: global.Promise,
16
- multiArgs: false,
17
- copyProps: true,
18
- suffix: "",
19
- ..._options,
20
- };
21
-
22
- const Promise = options.Promise;
23
- const multiArgs = !!options.multiArgs;
24
-
25
- const promisifiedFn = function (...args) {
26
- return new Promise((resolve, reject) => {
27
- // add a callback to the end of the arguments to transfer the result to the promise
28
- args.push((err, ...values) => {
29
- if (err) {
30
- return reject(err);
31
- }
32
- if (multiArgs) {
33
- resolve(values);
34
- } else {
35
- resolve(values[0]);
36
- }
37
- });
38
-
39
- // call the original function with the updated args
40
- fn.call(options.context || this, ...args);
41
- });
42
- };
43
-
44
- if (options.copyProps) {
45
- copyOwnProperties(fn, promisifiedFn);
46
- }
47
-
48
- Object.defineProperty(promisifiedFn, "__isPromisified__", {
49
- value: true,
50
- writable: false,
51
- enumerable: false,
52
- configurable: true,
53
- });
54
-
55
- Object.defineProperty(promisifiedFn, "length", {
56
- value: fn.length,
57
- writable: false,
58
- enumerable: false,
59
- configurable: false,
60
- });
61
-
62
- Object.defineProperty(promisifiedFn, "name", {
63
- value: fn.name + options.suffix,
64
- writable: false,
65
- enumerable: false,
66
- configurable: false,
67
- });
68
-
69
- return promisifiedFn;
70
- };
package/lib/using.js DELETED
@@ -1,142 +0,0 @@
1
- "use strict";
2
-
3
- const { Disposer } = require("./disposer");
4
- const { isPromise } = require("./util");
5
- const { AggregateError } = require("@jchip/error");
6
-
7
- const SYM_FN_DISPOSE = Symbol("fnDispose");
8
- /**
9
- * @description
10
- * The using function is a utility function that allows you to acquire resources,
11
- * process them, and then dispose of them in an error-safe manner.
12
- *
13
- * @param {Array} resources - An array of resources to acquire.
14
- * @param {Function} handler - A function that will be called with the acquired resources.
15
- * @param {Promise} Promise - The Promise implementation to use. AveAzul or Bluebird.
16
- * @param {boolean} asArray - Whether to return the result as an array.
17
- * @returns {Promise} A promise that resolves to the result of the handler function.
18
- */
19
- function using(resources, handler, Promise, asArray) {
20
- if (typeof handler !== "function") {
21
- throw new TypeError("handler must be a function");
22
- }
23
-
24
- // resources is guaranateed to be an array of disposer, promise like, or any value
25
- // first process all resources by mapping the resources array:
26
- // 1. if it's a disposer, get its promise and resolve its value
27
- // 2. if it's a promise like, get its value
28
- // 3. otherwise, return the value
29
- // Expect Promise to be AveAzul or Bluebird that has map method
30
- const acquisitionErrors = [];
31
-
32
- // Helper function to process a disposer
33
- const processDisposer = async (resource, disposer) => {
34
- try {
35
- const res = await disposer._promise;
36
- resource._result = res;
37
- resource[SYM_FN_DISPOSE] = disposer._data;
38
- } catch (error) {
39
- acquisitionErrors.push(error);
40
- resource._error = error;
41
- }
42
- return resource;
43
- };
44
-
45
- // Helper to check if something is a disposer
46
- const isDisposer = (obj) =>
47
- obj &&
48
- (obj instanceof Disposer ||
49
- (obj._promise && typeof obj._data === "function"));
50
-
51
- const acquireResources = () => {
52
- const promiseRes = resources.map((resource) => {
53
- // if it's a promise-like, wait for its resolved value
54
- if (isPromise(resource)) {
55
- return { ___promise: resource };
56
- }
57
- return resource;
58
- });
59
-
60
- return Promise.map(promiseRes, async (resource) => {
61
- // If it's directly a disposer
62
- if (isDisposer(resource)) {
63
- return processDisposer(resource, resource);
64
- }
65
-
66
- // if it's a promise like, wait for its resolved value
67
- if (resource && resource.___promise) {
68
- try {
69
- const res = await resource.___promise;
70
- // Check if the resolved value is a disposer
71
- if (isDisposer(res)) {
72
- return processDisposer(resource, res);
73
- } else {
74
- resource._result = res;
75
- }
76
- } catch (error) {
77
- acquisitionErrors.push(error);
78
- resource._error = error;
79
- }
80
- return resource;
81
- }
82
-
83
- return { _result: resource };
84
- });
85
- };
86
-
87
- const disposeResources = (processedResources) => {
88
- const errors = [];
89
- return Promise.each(processedResources, async (resource) => {
90
- // dispose all resources that were acquired without errors
91
- if (resource && resource[SYM_FN_DISPOSE]) {
92
- try {
93
- await resource[SYM_FN_DISPOSE](resource._result);
94
- } catch (error) {
95
- errors.push(error);
96
- }
97
- }
98
- }).finally(() => {
99
- if (errors.length > 0) {
100
- Promise.___throwUncaughtError(
101
- new AggregateError(errors, "cleanup resources failed", errors)
102
- );
103
- }
104
- });
105
- };
106
-
107
- return acquireResources().then((processedResources) => {
108
- if (acquisitionErrors.length > 0) {
109
- return disposeResources(processedResources).tap(() => {
110
- throw acquisitionErrors[0];
111
- });
112
- }
113
-
114
- // now collect all the results into an array
115
- const results = [];
116
- for (const resource of processedResources) {
117
- results.push(resource._result);
118
- }
119
-
120
- let handlerPromise;
121
-
122
- try {
123
- // now call the handler with the results
124
- handlerPromise = Promise.resolve(
125
- asArray ? handler(results) : handler(...results)
126
- );
127
- } catch (error) {
128
- // catch sync error from handler
129
- handlerPromise = Promise.reject(error);
130
- }
131
-
132
- return handlerPromise
133
- .tap(() => {
134
- return disposeResources(processedResources);
135
- })
136
- .tapCatch(() => {
137
- return disposeResources(processedResources);
138
- });
139
- });
140
- }
141
-
142
- module.exports.using = using;
package/lib/util.js DELETED
@@ -1,199 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Determines if a function is a class (either ES6 class or ES5 constructor function)
5
- * This function performs several checks to identify different class patterns:
6
- * 1. ES6 classes with the 'class' keyword
7
- * 2. Constructor functions (ES5 classes) with prototype methods
8
- *
9
- * @param {*} fn - The value to check
10
- * @returns {boolean} - True if the function is a class, false otherwise
11
- */
12
- const thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
13
- function isClass(fn) {
14
- try {
15
- if (typeof fn === "function") {
16
- const keys = Object.getOwnPropertyNames(fn.prototype);
17
-
18
- const hasMethods = keys.length > 1;
19
- const hasMethodsOtherThanConstructor = keys.length > 0 &&
20
- !(keys.length === 1 && keys[0] === "constructor");
21
- const hasThisAssignmentAndStaticMethods =
22
- thisAssignmentPattern.test(fn + "") && Object.getOwnPropertyNames (fn).length > 0;
23
-
24
- if (hasMethods || hasMethodsOtherThanConstructor ||
25
- hasThisAssignmentAndStaticMethods) {
26
- return true;
27
- }
28
- }
29
- return false;
30
- } catch (e) {
31
- return false;
32
- }
33
- }
34
-
35
- const rident = /^[a-z$_][a-z$_0-9]*$/i;
36
- function isIdentifier(str) {
37
- return rident.test(str);
38
- }
39
-
40
-
41
- /**
42
- * Prop filtering code copied from bluebird/js/release
43
- */
44
- const noCopyProps = [
45
- "arity",
46
- "length",
47
- "name",
48
- "arguments",
49
- "caller",
50
- "callee",
51
- "prototype",
52
- "__isPromisified__",
53
- ];
54
- const noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
55
-
56
- function propsFilter(key) {
57
- return !noCopyPropsPattern.test(key);
58
- }
59
-
60
- function copyOwnProperties(source, target, filter = propsFilter) {
61
- const names = Object.getOwnPropertyNames(source);
62
-
63
- for (const name of names) {
64
- if (filter(name)) {
65
- Object.defineProperty(target, name, Object.getOwnPropertyDescriptor(source, name));
66
- }
67
- }
68
- }
69
-
70
- /**
71
- * Copied from bluebird/js/release/util.js
72
- * @param {*} fn
73
- * @returns {boolean}
74
- */
75
- function isPromisified(fn) {
76
- try {
77
- return fn.__isPromisified__ === true;
78
- } catch (e) {
79
- return false;
80
- }
81
- }
82
-
83
- /**
84
- * Determines if an object is a Promise instance
85
- * @param {*} obj - The object to check
86
- * @returns {boolean} - True if the object is a Promise instance, false otherwise
87
- */
88
- function isPromise(obj) {
89
- return (
90
- obj instanceof Promise ||
91
- (obj != null &&
92
- typeof obj === "object" &&
93
- typeof obj.then === "function" &&
94
- typeof obj.catch === "function")
95
- );
96
- }
97
-
98
- /**
99
- * Gets all property keys from an object and its prototype chain, excluding standard
100
- * prototypes like Object.prototype, Array.prototype, and Function.prototype
101
- *
102
- * @param {Object} obj - The target object to get keys from
103
- * @param {Array} [excludedPrototypes=[]] - An array of prototype objects to exclude keys from
104
- * @returns {Array<string>} - Array of property keys
105
- */
106
- function getObjectDataKeys(obj, excludedProtos = []) {
107
- const excludedPrototypes = [
108
- Array.prototype,
109
- Object.prototype,
110
- Function.prototype,
111
- ...excludedProtos,
112
- ];
113
-
114
- const isExcludedProto = function (val) {
115
- for (const protoVal of excludedPrototypes) {
116
- if (protoVal === val) {
117
- return true;
118
- }
119
- }
120
- return false;
121
- };
122
-
123
- const ret = [];
124
- const visitedKeys = Object.create(null);
125
-
126
- /* copied from bluebird/js/release/util.js and modified */
127
- while (obj && !isExcludedProto(obj)) {
128
- let keys;
129
- try {
130
- keys = Object.getOwnPropertyNames(obj);
131
- } catch (e) {
132
- /* istanbul ignore next */
133
- return ret;
134
- }
135
-
136
- for (const key of keys) {
137
- /* istanbul ignore if */
138
- if (visitedKeys[key]) {
139
- /* istanbul ignore next */
140
- continue;
141
- }
142
- visitedKeys[key] = true;
143
- const desc = Object.getOwnPropertyDescriptor(obj, key);
144
- /**
145
- * When desc.get && desc.set are falsy, it means the property is a data
146
- * property that holds an actual value, rather than being computed dynamically
147
- * through getter/setter functions.
148
- */
149
- /* istanbul ignore next */
150
- if (desc && !desc.get && !desc.set) {
151
- ret.push(key);
152
- }
153
- }
154
- obj = Object.getPrototypeOf(obj);
155
- }
156
-
157
- return ret;
158
- }
159
-
160
- /**
161
- * Triggers an uncaught exception in a safe way by scheduling it on the next event loop tick
162
- * This is used for fatal errors that should crash the process
163
- * @param {Error} error - The error to throw
164
- */
165
- function triggerUncaughtException(error) {
166
- if (!(error instanceof Error)) {
167
- error = new Error(String(error));
168
- }
169
-
170
- // Use setTimeout with 0ms delay to throw on the next event loop tick
171
- // This ensures the current execution context completes first
172
- setTimeout(() => {
173
- throw error;
174
- }, 0);
175
- }
176
-
177
- function toArray(args) {
178
- if (!Array.isArray(args)) {
179
- // Check if args is iterable
180
- if (args != null && typeof args[Symbol.iterator] === "function") {
181
- // Convert iterable to array, must do this to get the length, in order
182
- // to detect if too many errors occurred and completion is impossible.
183
- args = Array.from(args);
184
- } else {
185
- throw new TypeError("expecting an array or an iterable object but got " + args);
186
- }
187
- }
188
-
189
- return args;
190
- }
191
-
192
- module.exports.copyOwnProperties = copyOwnProperties;
193
- module.exports.isClass = isClass;
194
- module.exports.isIdentifier = isIdentifier;
195
- module.exports.isPromisified = isPromisified;
196
- module.exports.isPromise = isPromise;
197
- module.exports.triggerUncaughtException = triggerUncaughtException;
198
- module.exports.getObjectDataKeys = getObjectDataKeys;
199
- module.exports.toArray = toArray;