Tüm .config dosyaları ilk yedekleme

This commit is contained in:
2026-03-28 03:21:14 +03:00
commit 4f7e8904be
7835 changed files with 1631041 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
module.exports = {
cld: require('cld'),
};

View File

@@ -0,0 +1,619 @@
{
"files": [
"node_modules/wrappy/wrappy.js",
"node_modules/wrappy/README.md",
"node_modules/wrappy/package.json",
"node_modules/wrappy/LICENSE",
"node_modules/once/once.js",
"node_modules/once/README.md",
"node_modules/once/package.json",
"node_modules/once/LICENSE",
"node_modules/minimatch/minimatch.js",
"node_modules/minimatch/README.md",
"node_modules/minimatch/package.json",
"node_modules/minimatch/LICENSE",
"node_modules/glob/glob.js",
"node_modules/glob/common.js",
"node_modules/glob/README.md",
"node_modules/glob/package.json",
"node_modules/glob/LICENSE",
"node_modules/glob/sync.js",
"node_modules/inherits/inherits_browser.js",
"node_modules/inherits/README.md",
"node_modules/inherits/package.json",
"node_modules/inherits/inherits.js",
"node_modules/inherits/LICENSE",
"node_modules/inflight/README.md",
"node_modules/inflight/inflight.js",
"node_modules/inflight/package.json",
"node_modules/inflight/LICENSE",
"node_modules/cld/index.js",
"node_modules/cld/README.md",
"node_modules/cld/package.json",
"node_modules/cld/LICENSE",
"node_modules/cld/bin/postinstall.js",
"node_modules/cld/build/Makefile",
"node_modules/cld/build/Release/cld.node",
"node_modules/cld/build/Release/obj.target/cld.node",
"node_modules/cld/deps/cld/LICENSE",
"node_modules/path-is-absolute/index.js",
"node_modules/path-is-absolute/readme.md",
"node_modules/path-is-absolute/license",
"node_modules/path-is-absolute/package.json",
"node_modules/brace-expansion/index.js",
"node_modules/brace-expansion/README.md",
"node_modules/brace-expansion/package.json",
"node_modules/brace-expansion/LICENSE",
"node_modules/node-addon-api/.editorconfig",
"node_modules/node-addon-api/index.js",
"node_modules/node-addon-api/CHANGELOG.md",
"node_modules/node-addon-api/CONTRIBUTING.md",
"node_modules/node-addon-api/LICENSE.md",
"node_modules/node-addon-api/README.md",
"node_modules/node-addon-api/CODE_OF_CONDUCT.md",
"node_modules/node-addon-api/package.json",
"node_modules/node-addon-api/doc/env.md",
"node_modules/node-addon-api/doc/setup.md",
"node_modules/node-addon-api/doc/buffer.md",
"node_modules/node-addon-api/doc/error.md",
"node_modules/node-addon-api/doc/object_lifetime_management.md",
"node_modules/node-addon-api/doc/property_descriptor.md",
"node_modules/node-addon-api/doc/function.md",
"node_modules/node-addon-api/doc/async_context.md",
"node_modules/node-addon-api/doc/object_reference.md",
"node_modules/node-addon-api/doc/creating_a_release.md",
"node_modules/node-addon-api/doc/object.md",
"node_modules/node-addon-api/doc/boolean.md",
"node_modules/node-addon-api/doc/function_reference.md",
"node_modules/node-addon-api/doc/external.md",
"node_modules/node-addon-api/doc/memory_management.md",
"node_modules/node-addon-api/doc/basic_types.md",
"node_modules/node-addon-api/doc/typed_array_of.md",
"node_modules/node-addon-api/doc/number.md",
"node_modules/node-addon-api/doc/promises.md",
"node_modules/node-addon-api/doc/dataview.md",
"node_modules/node-addon-api/doc/cmake-js.md",
"node_modules/node-addon-api/doc/node-gyp.md",
"node_modules/node-addon-api/doc/class_property_descriptor.md",
"node_modules/node-addon-api/doc/callbackinfo.md",
"node_modules/node-addon-api/doc/range_error.md",
"node_modules/node-addon-api/doc/error_handling.md",
"node_modules/node-addon-api/doc/value.md",
"node_modules/node-addon-api/doc/working_with_javascript_values.md",
"node_modules/node-addon-api/doc/Doxyfile",
"node_modules/node-addon-api/doc/symbol.md",
"node_modules/node-addon-api/doc/async_operations.md",
"node_modules/node-addon-api/doc/prebuild_tools.md",
"node_modules/node-addon-api/doc/escapable_handle_scope.md",
"node_modules/node-addon-api/doc/checker-tool.md",
"node_modules/node-addon-api/doc/string.md",
"node_modules/node-addon-api/doc/handle_scope.md",
"node_modules/node-addon-api/doc/typed_array.md",
"node_modules/node-addon-api/doc/async_worker.md",
"node_modules/node-addon-api/doc/callback_scope.md",
"node_modules/node-addon-api/doc/version_management.md",
"node_modules/node-addon-api/doc/generator.md",
"node_modules/node-addon-api/doc/threadsafe_function.md",
"node_modules/node-addon-api/doc/type_error.md",
"node_modules/node-addon-api/doc/object_wrap.md",
"node_modules/node-addon-api/doc/bigint.md",
"node_modules/node-addon-api/doc/conversion-tool.md",
"node_modules/node-addon-api/doc/reference.md",
"node_modules/node-addon-api/doc/array_buffer.md",
"node_modules/node-addon-api/tools/conversion.js",
"node_modules/node-addon-api/tools/check-napi.js",
"node_modules/node-addon-api/tools/README.md",
"node_modules/balanced-match/index.js",
"node_modules/balanced-match/LICENSE.md",
"node_modules/balanced-match/README.md",
"node_modules/balanced-match/package.json",
"node_modules/fs.realpath/index.js",
"node_modules/fs.realpath/old.js",
"node_modules/fs.realpath/README.md",
"node_modules/fs.realpath/package.json",
"node_modules/fs.realpath/LICENSE",
"node_modules/concat-map/index.js",
"node_modules/concat-map/package.json",
"node_modules/concat-map/LICENSE",
"node_modules/concat-map/example/map.js",
"node_modules/underscore/underscore-esm-min.js",
"node_modules/underscore/underscore.js",
"node_modules/underscore/underscore-umd-min.js",
"node_modules/underscore/README.md",
"node_modules/underscore/underscore-umd.js",
"node_modules/underscore/underscore-esm.js",
"node_modules/underscore/underscore-node.cjs",
"node_modules/underscore/underscore-min.js",
"node_modules/underscore/package.json",
"node_modules/underscore/LICENSE",
"node_modules/underscore/underscore-node-f.cjs",
"node_modules/underscore/amd/_isArrayLike.js",
"node_modules/underscore/amd/_tagTester.js",
"node_modules/underscore/amd/result.js",
"node_modules/underscore/amd/toArray.js",
"node_modules/underscore/amd/difference.js",
"node_modules/underscore/amd/_toPath.js",
"node_modules/underscore/amd/indexBy.js",
"node_modules/underscore/amd/uniqueId.js",
"node_modules/underscore/amd/_optimizeCb.js",
"node_modules/underscore/amd/compose.js",
"node_modules/underscore/amd/range.js",
"node_modules/underscore/amd/each.js",
"node_modules/underscore/amd/uniq.js",
"node_modules/underscore/amd/chain.js",
"node_modules/underscore/amd/every.js",
"node_modules/underscore/amd/_createSizePropertyCheck.js",
"node_modules/underscore/amd/_keyInObj.js",
"node_modules/underscore/amd/isTypedArray.js",
"node_modules/underscore/amd/toPath.js",
"node_modules/underscore/amd/sample.js",
"node_modules/underscore/amd/compact.js",
"node_modules/underscore/amd/partial.js",
"node_modules/underscore/amd/min.js",
"node_modules/underscore/amd/_createIndexFinder.js",
"node_modules/underscore/amd/values.js",
"node_modules/underscore/amd/delay.js",
"node_modules/underscore/amd/underscore.js",
"node_modules/underscore/amd/reject.js",
"node_modules/underscore/amd/debounce.js",
"node_modules/underscore/amd/create.js",
"node_modules/underscore/amd/index.js",
"node_modules/underscore/amd/once.js",
"node_modules/underscore/amd/isObject.js",
"node_modules/underscore/amd/rest.js",
"node_modules/underscore/amd/without.js",
"node_modules/underscore/amd/defaults.js",
"node_modules/underscore/amd/_unescapeMap.js",
"node_modules/underscore/amd/isSymbol.js",
"node_modules/underscore/amd/_group.js",
"node_modules/underscore/amd/findLastIndex.js",
"node_modules/underscore/amd/_createEscaper.js",
"node_modules/underscore/amd/isArray.js",
"node_modules/underscore/amd/isMap.js",
"node_modules/underscore/amd/_chainResult.js",
"node_modules/underscore/amd/memoize.js",
"node_modules/underscore/amd/throttle.js",
"node_modules/underscore/amd/invoke.js",
"node_modules/underscore/amd/isString.js",
"node_modules/underscore/amd/isMatch.js",
"node_modules/underscore/amd/_deepGet.js",
"node_modules/underscore/amd/isDate.js",
"node_modules/underscore/amd/functions.js",
"node_modules/underscore/amd/_executeBound.js",
"node_modules/underscore/amd/_hasObjectTag.js",
"node_modules/underscore/amd/_getLength.js",
"node_modules/underscore/amd/intersection.js",
"node_modules/underscore/amd/filter.js",
"node_modules/underscore/amd/pluck.js",
"node_modules/underscore/amd/partition.js",
"node_modules/underscore/amd/wrap.js",
"node_modules/underscore/amd/allKeys.js",
"node_modules/underscore/amd/extendOwn.js",
"node_modules/underscore/amd/_shallowProperty.js",
"node_modules/underscore/amd/mixin.js",
"node_modules/underscore/amd/omit.js",
"node_modules/underscore/amd/union.js",
"node_modules/underscore/amd/sortBy.js",
"node_modules/underscore/amd/where.js",
"node_modules/underscore/amd/findKey.js",
"node_modules/underscore/amd/_createReduce.js",
"node_modules/underscore/amd/negate.js",
"node_modules/underscore/amd/initial.js",
"node_modules/underscore/amd/extend.js",
"node_modules/underscore/amd/_getByteLength.js",
"node_modules/underscore/amd/isNumber.js",
"node_modules/underscore/amd/_baseCreate.js",
"node_modules/underscore/amd/isNaN.js",
"node_modules/underscore/amd/indexOf.js",
"node_modules/underscore/amd/flatten.js",
"node_modules/underscore/amd/lastIndexOf.js",
"node_modules/underscore/amd/size.js",
"node_modules/underscore/amd/isFinite.js",
"node_modules/underscore/amd/zip.js",
"node_modules/underscore/amd/iteratee.js",
"node_modules/underscore/amd/groupBy.js",
"node_modules/underscore/amd/isEmpty.js",
"node_modules/underscore/amd/isWeakSet.js",
"node_modules/underscore/amd/pick.js",
"node_modules/underscore/amd/sortedIndex.js",
"node_modules/underscore/amd/bindAll.js",
"node_modules/underscore/amd/_setup.js",
"node_modules/underscore/amd/restArguments.js",
"node_modules/underscore/amd/_escapeMap.js",
"node_modules/underscore/amd/clone.js",
"node_modules/underscore/amd/random.js",
"node_modules/underscore/amd/reduceRight.js",
"node_modules/underscore/amd/_flatten.js",
"node_modules/underscore/amd/isArguments.js",
"node_modules/underscore/amd/find.js",
"node_modules/underscore/amd/_collectNonEnumProps.js",
"node_modules/underscore/amd/shuffle.js",
"node_modules/underscore/amd/isFunction.js",
"node_modules/underscore/amd/propertyOf.js",
"node_modules/underscore/amd/mapObject.js",
"node_modules/underscore/amd/_baseIteratee.js",
"node_modules/underscore/amd/pairs.js",
"node_modules/underscore/amd/_isBufferLike.js",
"node_modules/underscore/amd/reduce.js",
"node_modules/underscore/amd/contains.js",
"node_modules/underscore/amd/findWhere.js",
"node_modules/underscore/amd/isSet.js",
"node_modules/underscore/amd/after.js",
"node_modules/underscore/amd/chunk.js",
"node_modules/underscore/amd/get.js",
"node_modules/underscore/amd/bind.js",
"node_modules/underscore/amd/map.js",
"node_modules/underscore/amd/_createAssigner.js",
"node_modules/underscore/amd/invert.js",
"node_modules/underscore/amd/isWeakMap.js",
"node_modules/underscore/amd/matcher.js",
"node_modules/underscore/amd/isDataView.js",
"node_modules/underscore/amd/_cb.js",
"node_modules/underscore/amd/isUndefined.js",
"node_modules/underscore/amd/underscore-array-methods.js",
"node_modules/underscore/amd/unzip.js",
"node_modules/underscore/amd/_stringTagBug.js",
"node_modules/underscore/amd/object.js",
"node_modules/underscore/amd/_methodFingerprint.js",
"node_modules/underscore/amd/countBy.js",
"node_modules/underscore/amd/defer.js",
"node_modules/underscore/amd/tap.js",
"node_modules/underscore/amd/constant.js",
"node_modules/underscore/amd/isError.js",
"node_modules/underscore/amd/_createPredicateIndexFinder.js",
"node_modules/underscore/amd/first.js",
"node_modules/underscore/amd/max.js",
"node_modules/underscore/amd/identity.js",
"node_modules/underscore/amd/now.js",
"node_modules/underscore/amd/some.js",
"node_modules/underscore/amd/last.js",
"node_modules/underscore/amd/isEqual.js",
"node_modules/underscore/amd/before.js",
"node_modules/underscore/amd/templateSettings.js",
"node_modules/underscore/amd/noop.js",
"node_modules/underscore/amd/isNull.js",
"node_modules/underscore/amd/escape.js",
"node_modules/underscore/amd/keys.js",
"node_modules/underscore/amd/unescape.js",
"node_modules/underscore/amd/_has.js",
"node_modules/underscore/amd/isBoolean.js",
"node_modules/underscore/amd/property.js",
"node_modules/underscore/amd/isArrayBuffer.js",
"node_modules/underscore/amd/findIndex.js",
"node_modules/underscore/amd/index-default.js",
"node_modules/underscore/amd/_toBufferView.js",
"node_modules/underscore/amd/template.js",
"node_modules/underscore/amd/isRegExp.js",
"node_modules/underscore/amd/isElement.js",
"node_modules/underscore/amd/pipe.js",
"node_modules/underscore/amd/has.js",
"node_modules/underscore/amd/times.js",
"node_modules/underscore/cjs/_isArrayLike.js",
"node_modules/underscore/cjs/_tagTester.js",
"node_modules/underscore/cjs/result.js",
"node_modules/underscore/cjs/toArray.js",
"node_modules/underscore/cjs/difference.js",
"node_modules/underscore/cjs/_toPath.js",
"node_modules/underscore/cjs/indexBy.js",
"node_modules/underscore/cjs/uniqueId.js",
"node_modules/underscore/cjs/_optimizeCb.js",
"node_modules/underscore/cjs/compose.js",
"node_modules/underscore/cjs/range.js",
"node_modules/underscore/cjs/each.js",
"node_modules/underscore/cjs/uniq.js",
"node_modules/underscore/cjs/chain.js",
"node_modules/underscore/cjs/every.js",
"node_modules/underscore/cjs/_createSizePropertyCheck.js",
"node_modules/underscore/cjs/_keyInObj.js",
"node_modules/underscore/cjs/isTypedArray.js",
"node_modules/underscore/cjs/toPath.js",
"node_modules/underscore/cjs/sample.js",
"node_modules/underscore/cjs/compact.js",
"node_modules/underscore/cjs/partial.js",
"node_modules/underscore/cjs/min.js",
"node_modules/underscore/cjs/_createIndexFinder.js",
"node_modules/underscore/cjs/values.js",
"node_modules/underscore/cjs/delay.js",
"node_modules/underscore/cjs/underscore.js",
"node_modules/underscore/cjs/reject.js",
"node_modules/underscore/cjs/debounce.js",
"node_modules/underscore/cjs/create.js",
"node_modules/underscore/cjs/index.js",
"node_modules/underscore/cjs/once.js",
"node_modules/underscore/cjs/isObject.js",
"node_modules/underscore/cjs/rest.js",
"node_modules/underscore/cjs/without.js",
"node_modules/underscore/cjs/defaults.js",
"node_modules/underscore/cjs/_unescapeMap.js",
"node_modules/underscore/cjs/isSymbol.js",
"node_modules/underscore/cjs/_group.js",
"node_modules/underscore/cjs/findLastIndex.js",
"node_modules/underscore/cjs/_createEscaper.js",
"node_modules/underscore/cjs/isArray.js",
"node_modules/underscore/cjs/isMap.js",
"node_modules/underscore/cjs/_chainResult.js",
"node_modules/underscore/cjs/memoize.js",
"node_modules/underscore/cjs/throttle.js",
"node_modules/underscore/cjs/invoke.js",
"node_modules/underscore/cjs/isString.js",
"node_modules/underscore/cjs/isMatch.js",
"node_modules/underscore/cjs/_deepGet.js",
"node_modules/underscore/cjs/isDate.js",
"node_modules/underscore/cjs/functions.js",
"node_modules/underscore/cjs/_executeBound.js",
"node_modules/underscore/cjs/_hasObjectTag.js",
"node_modules/underscore/cjs/_getLength.js",
"node_modules/underscore/cjs/intersection.js",
"node_modules/underscore/cjs/filter.js",
"node_modules/underscore/cjs/pluck.js",
"node_modules/underscore/cjs/partition.js",
"node_modules/underscore/cjs/wrap.js",
"node_modules/underscore/cjs/allKeys.js",
"node_modules/underscore/cjs/extendOwn.js",
"node_modules/underscore/cjs/_shallowProperty.js",
"node_modules/underscore/cjs/mixin.js",
"node_modules/underscore/cjs/omit.js",
"node_modules/underscore/cjs/union.js",
"node_modules/underscore/cjs/sortBy.js",
"node_modules/underscore/cjs/where.js",
"node_modules/underscore/cjs/findKey.js",
"node_modules/underscore/cjs/_createReduce.js",
"node_modules/underscore/cjs/negate.js",
"node_modules/underscore/cjs/initial.js",
"node_modules/underscore/cjs/extend.js",
"node_modules/underscore/cjs/_getByteLength.js",
"node_modules/underscore/cjs/isNumber.js",
"node_modules/underscore/cjs/_baseCreate.js",
"node_modules/underscore/cjs/isNaN.js",
"node_modules/underscore/cjs/indexOf.js",
"node_modules/underscore/cjs/flatten.js",
"node_modules/underscore/cjs/lastIndexOf.js",
"node_modules/underscore/cjs/size.js",
"node_modules/underscore/cjs/isFinite.js",
"node_modules/underscore/cjs/zip.js",
"node_modules/underscore/cjs/iteratee.js",
"node_modules/underscore/cjs/groupBy.js",
"node_modules/underscore/cjs/isEmpty.js",
"node_modules/underscore/cjs/isWeakSet.js",
"node_modules/underscore/cjs/pick.js",
"node_modules/underscore/cjs/sortedIndex.js",
"node_modules/underscore/cjs/bindAll.js",
"node_modules/underscore/cjs/_setup.js",
"node_modules/underscore/cjs/restArguments.js",
"node_modules/underscore/cjs/_escapeMap.js",
"node_modules/underscore/cjs/clone.js",
"node_modules/underscore/cjs/random.js",
"node_modules/underscore/cjs/reduceRight.js",
"node_modules/underscore/cjs/_flatten.js",
"node_modules/underscore/cjs/isArguments.js",
"node_modules/underscore/cjs/find.js",
"node_modules/underscore/cjs/_collectNonEnumProps.js",
"node_modules/underscore/cjs/shuffle.js",
"node_modules/underscore/cjs/isFunction.js",
"node_modules/underscore/cjs/propertyOf.js",
"node_modules/underscore/cjs/mapObject.js",
"node_modules/underscore/cjs/_baseIteratee.js",
"node_modules/underscore/cjs/pairs.js",
"node_modules/underscore/cjs/_isBufferLike.js",
"node_modules/underscore/cjs/reduce.js",
"node_modules/underscore/cjs/contains.js",
"node_modules/underscore/cjs/findWhere.js",
"node_modules/underscore/cjs/isSet.js",
"node_modules/underscore/cjs/after.js",
"node_modules/underscore/cjs/chunk.js",
"node_modules/underscore/cjs/get.js",
"node_modules/underscore/cjs/bind.js",
"node_modules/underscore/cjs/map.js",
"node_modules/underscore/cjs/_createAssigner.js",
"node_modules/underscore/cjs/invert.js",
"node_modules/underscore/cjs/isWeakMap.js",
"node_modules/underscore/cjs/matcher.js",
"node_modules/underscore/cjs/isDataView.js",
"node_modules/underscore/cjs/_cb.js",
"node_modules/underscore/cjs/isUndefined.js",
"node_modules/underscore/cjs/underscore-array-methods.js",
"node_modules/underscore/cjs/unzip.js",
"node_modules/underscore/cjs/_stringTagBug.js",
"node_modules/underscore/cjs/object.js",
"node_modules/underscore/cjs/_methodFingerprint.js",
"node_modules/underscore/cjs/countBy.js",
"node_modules/underscore/cjs/defer.js",
"node_modules/underscore/cjs/tap.js",
"node_modules/underscore/cjs/constant.js",
"node_modules/underscore/cjs/isError.js",
"node_modules/underscore/cjs/_createPredicateIndexFinder.js",
"node_modules/underscore/cjs/first.js",
"node_modules/underscore/cjs/max.js",
"node_modules/underscore/cjs/identity.js",
"node_modules/underscore/cjs/now.js",
"node_modules/underscore/cjs/some.js",
"node_modules/underscore/cjs/last.js",
"node_modules/underscore/cjs/isEqual.js",
"node_modules/underscore/cjs/before.js",
"node_modules/underscore/cjs/templateSettings.js",
"node_modules/underscore/cjs/noop.js",
"node_modules/underscore/cjs/isNull.js",
"node_modules/underscore/cjs/escape.js",
"node_modules/underscore/cjs/keys.js",
"node_modules/underscore/cjs/unescape.js",
"node_modules/underscore/cjs/_has.js",
"node_modules/underscore/cjs/isBoolean.js",
"node_modules/underscore/cjs/property.js",
"node_modules/underscore/cjs/isArrayBuffer.js",
"node_modules/underscore/cjs/findIndex.js",
"node_modules/underscore/cjs/index-default.js",
"node_modules/underscore/cjs/_toBufferView.js",
"node_modules/underscore/cjs/template.js",
"node_modules/underscore/cjs/isRegExp.js",
"node_modules/underscore/cjs/isElement.js",
"node_modules/underscore/cjs/pipe.js",
"node_modules/underscore/cjs/has.js",
"node_modules/underscore/cjs/times.js",
"node_modules/underscore/modules/_isArrayLike.js",
"node_modules/underscore/modules/_tagTester.js",
"node_modules/underscore/modules/result.js",
"node_modules/underscore/modules/toArray.js",
"node_modules/underscore/modules/difference.js",
"node_modules/underscore/modules/_toPath.js",
"node_modules/underscore/modules/indexBy.js",
"node_modules/underscore/modules/uniqueId.js",
"node_modules/underscore/modules/_optimizeCb.js",
"node_modules/underscore/modules/compose.js",
"node_modules/underscore/modules/range.js",
"node_modules/underscore/modules/each.js",
"node_modules/underscore/modules/uniq.js",
"node_modules/underscore/modules/chain.js",
"node_modules/underscore/modules/every.js",
"node_modules/underscore/modules/_createSizePropertyCheck.js",
"node_modules/underscore/modules/_keyInObj.js",
"node_modules/underscore/modules/isTypedArray.js",
"node_modules/underscore/modules/toPath.js",
"node_modules/underscore/modules/sample.js",
"node_modules/underscore/modules/compact.js",
"node_modules/underscore/modules/partial.js",
"node_modules/underscore/modules/min.js",
"node_modules/underscore/modules/_createIndexFinder.js",
"node_modules/underscore/modules/values.js",
"node_modules/underscore/modules/delay.js",
"node_modules/underscore/modules/underscore.js",
"node_modules/underscore/modules/reject.js",
"node_modules/underscore/modules/debounce.js",
"node_modules/underscore/modules/create.js",
"node_modules/underscore/modules/index.js",
"node_modules/underscore/modules/once.js",
"node_modules/underscore/modules/isObject.js",
"node_modules/underscore/modules/rest.js",
"node_modules/underscore/modules/without.js",
"node_modules/underscore/modules/defaults.js",
"node_modules/underscore/modules/_unescapeMap.js",
"node_modules/underscore/modules/isSymbol.js",
"node_modules/underscore/modules/_group.js",
"node_modules/underscore/modules/findLastIndex.js",
"node_modules/underscore/modules/_createEscaper.js",
"node_modules/underscore/modules/isArray.js",
"node_modules/underscore/modules/isMap.js",
"node_modules/underscore/modules/_chainResult.js",
"node_modules/underscore/modules/memoize.js",
"node_modules/underscore/modules/throttle.js",
"node_modules/underscore/modules/invoke.js",
"node_modules/underscore/modules/isString.js",
"node_modules/underscore/modules/isMatch.js",
"node_modules/underscore/modules/_deepGet.js",
"node_modules/underscore/modules/isDate.js",
"node_modules/underscore/modules/functions.js",
"node_modules/underscore/modules/_executeBound.js",
"node_modules/underscore/modules/_hasObjectTag.js",
"node_modules/underscore/modules/_getLength.js",
"node_modules/underscore/modules/intersection.js",
"node_modules/underscore/modules/filter.js",
"node_modules/underscore/modules/pluck.js",
"node_modules/underscore/modules/partition.js",
"node_modules/underscore/modules/wrap.js",
"node_modules/underscore/modules/allKeys.js",
"node_modules/underscore/modules/index-all.js",
"node_modules/underscore/modules/extendOwn.js",
"node_modules/underscore/modules/_shallowProperty.js",
"node_modules/underscore/modules/mixin.js",
"node_modules/underscore/modules/omit.js",
"node_modules/underscore/modules/union.js",
"node_modules/underscore/modules/sortBy.js",
"node_modules/underscore/modules/where.js",
"node_modules/underscore/modules/findKey.js",
"node_modules/underscore/modules/_createReduce.js",
"node_modules/underscore/modules/negate.js",
"node_modules/underscore/modules/initial.js",
"node_modules/underscore/modules/extend.js",
"node_modules/underscore/modules/_getByteLength.js",
"node_modules/underscore/modules/isNumber.js",
"node_modules/underscore/modules/_baseCreate.js",
"node_modules/underscore/modules/isNaN.js",
"node_modules/underscore/modules/indexOf.js",
"node_modules/underscore/modules/flatten.js",
"node_modules/underscore/modules/lastIndexOf.js",
"node_modules/underscore/modules/size.js",
"node_modules/underscore/modules/isFinite.js",
"node_modules/underscore/modules/zip.js",
"node_modules/underscore/modules/iteratee.js",
"node_modules/underscore/modules/groupBy.js",
"node_modules/underscore/modules/isEmpty.js",
"node_modules/underscore/modules/isWeakSet.js",
"node_modules/underscore/modules/pick.js",
"node_modules/underscore/modules/sortedIndex.js",
"node_modules/underscore/modules/bindAll.js",
"node_modules/underscore/modules/_setup.js",
"node_modules/underscore/modules/restArguments.js",
"node_modules/underscore/modules/_escapeMap.js",
"node_modules/underscore/modules/clone.js",
"node_modules/underscore/modules/.eslintrc",
"node_modules/underscore/modules/random.js",
"node_modules/underscore/modules/reduceRight.js",
"node_modules/underscore/modules/_flatten.js",
"node_modules/underscore/modules/isArguments.js",
"node_modules/underscore/modules/find.js",
"node_modules/underscore/modules/_collectNonEnumProps.js",
"node_modules/underscore/modules/shuffle.js",
"node_modules/underscore/modules/isFunction.js",
"node_modules/underscore/modules/propertyOf.js",
"node_modules/underscore/modules/mapObject.js",
"node_modules/underscore/modules/_baseIteratee.js",
"node_modules/underscore/modules/pairs.js",
"node_modules/underscore/modules/_isBufferLike.js",
"node_modules/underscore/modules/reduce.js",
"node_modules/underscore/modules/contains.js",
"node_modules/underscore/modules/findWhere.js",
"node_modules/underscore/modules/isSet.js",
"node_modules/underscore/modules/after.js",
"node_modules/underscore/modules/chunk.js",
"node_modules/underscore/modules/get.js",
"node_modules/underscore/modules/bind.js",
"node_modules/underscore/modules/map.js",
"node_modules/underscore/modules/_createAssigner.js",
"node_modules/underscore/modules/invert.js",
"node_modules/underscore/modules/isWeakMap.js",
"node_modules/underscore/modules/matcher.js",
"node_modules/underscore/modules/isDataView.js",
"node_modules/underscore/modules/_cb.js",
"node_modules/underscore/modules/isUndefined.js",
"node_modules/underscore/modules/underscore-array-methods.js",
"node_modules/underscore/modules/unzip.js",
"node_modules/underscore/modules/_stringTagBug.js",
"node_modules/underscore/modules/object.js",
"node_modules/underscore/modules/_methodFingerprint.js",
"node_modules/underscore/modules/countBy.js",
"node_modules/underscore/modules/defer.js",
"node_modules/underscore/modules/tap.js",
"node_modules/underscore/modules/constant.js",
"node_modules/underscore/modules/isError.js",
"node_modules/underscore/modules/_createPredicateIndexFinder.js",
"node_modules/underscore/modules/first.js",
"node_modules/underscore/modules/max.js",
"node_modules/underscore/modules/identity.js",
"node_modules/underscore/modules/package.json",
"node_modules/underscore/modules/now.js",
"node_modules/underscore/modules/some.js",
"node_modules/underscore/modules/last.js",
"node_modules/underscore/modules/isEqual.js",
"node_modules/underscore/modules/before.js",
"node_modules/underscore/modules/templateSettings.js",
"node_modules/underscore/modules/noop.js",
"node_modules/underscore/modules/isNull.js",
"node_modules/underscore/modules/escape.js",
"node_modules/underscore/modules/keys.js",
"node_modules/underscore/modules/unescape.js",
"node_modules/underscore/modules/_has.js",
"node_modules/underscore/modules/isBoolean.js",
"node_modules/underscore/modules/property.js",
"node_modules/underscore/modules/isArrayBuffer.js",
"node_modules/underscore/modules/findIndex.js",
"node_modules/underscore/modules/index-default.js",
"node_modules/underscore/modules/_toBufferView.js",
"node_modules/underscore/modules/template.js",
"node_modules/underscore/modules/isRegExp.js",
"node_modules/underscore/modules/isElement.js",
"node_modules/underscore/modules/has.js",
"node_modules/underscore/modules/times.js",
"package.json",
"index.js",
"manifest.json"
]
}

View File

@@ -0,0 +1,21 @@
(MIT)
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,97 @@
# balanced-match
Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!
[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)
[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)
[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)
## Example
Get the first matching pair of braces:
```js
var balanced = require('balanced-match');
console.log(balanced('{', '}', 'pre{in{nested}}post'));
console.log(balanced('{', '}', 'pre{first}between{second}post'));
console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'));
```
The matches are:
```bash
$ node example.js
{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
{ start: 3,
end: 9,
pre: 'pre',
body: 'first',
post: 'between{second}post' }
{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
```
## API
### var m = balanced(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
object with those keys:
* **start** the index of the first match of `a`
* **end** the index of the matching `b`
* **pre** the preamble, `a` and `b` not included
* **body** the match, `a` and `b` not included
* **post** the postscript, `a` and `b` not included
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.
### var r = balanced.range(a, b, str)
For the first non-nested matching pair of `a` and `b` in `str`, return an
array with indexes: `[ <a index>, <b index> ]`.
If there's no match, `undefined` will be returned.
If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install balanced-match
```
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,62 @@
'use strict';
module.exports = balanced;
function balanced(a, b, str) {
if (a instanceof RegExp) a = maybeMatch(a, str);
if (b instanceof RegExp) b = maybeMatch(b, str);
var r = range(a, b, str);
return r && {
start: r[0],
end: r[1],
pre: str.slice(0, r[0]),
body: str.slice(r[0] + a.length, r[1]),
post: str.slice(r[1] + b.length)
};
}
function maybeMatch(reg, str) {
var m = str.match(reg);
return m ? m[0] : null;
}
balanced.range = range;
function range(a, b, str) {
var begs, beg, left, right, result;
var ai = str.indexOf(a);
var bi = str.indexOf(b, ai + 1);
var i = ai;
if (ai >= 0 && bi > 0) {
if(a===b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i == ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
} else if (begs.length == 1) {
result = [ begs.pop(), bi ];
} else {
beg = begs.pop();
if (beg < left) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [ left, right ];
}
}
return result;
}

View File

@@ -0,0 +1,48 @@
{
"name": "balanced-match",
"description": "Match balanced character pairs, like \"{\" and \"}\"",
"version": "1.0.2",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/balanced-match.git"
},
"homepage": "https://github.com/juliangruber/balanced-match",
"main": "index.js",
"scripts": {
"test": "tape test/test.js",
"bench": "matcha test/bench.js"
},
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"keywords": [
"match",
"regexp",
"test",
"balanced",
"parse"
],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
}
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,129 @@
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
## Example
```js
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('-v{,,}')
// => ['-v', '-v', '-v']
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
## API
```js
var expand = require('brace-expansion');
```
### var expanded = expand(str)
Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.
Valid expansions are:
```js
/^(.*,)+(.+)?$/
// {a,b,...}
```
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.
For compatibility reasons, the string `${` is not eligible for brace expansion.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install brace-expansion
```
## Contributors
- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)
## Sponsors
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,201 @@
var concatMap = require('concat-map');
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function identity(e) {
return e;
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m || /\$$/.test(m.pre)) return [str];
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,(?!,).*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
var post = m.post.length
? expand(m.post, false)
: [''];
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = concatMap(n, function(el) { return expand(el, false) });
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
return expansions;
}

View File

@@ -0,0 +1,50 @@
{
"name": "brace-expansion",
"description": "Brace expansion as known from sh/bash",
"version": "1.1.12",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/brace-expansion.git"
},
"homepage": "https://github.com/juliangruber/brace-expansion",
"main": "index.js",
"scripts": {
"test": "tape test/*.js",
"gentest": "bash test/generate.sh",
"bench": "matcha test/perf/bench.js"
},
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
},
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"keywords": [],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"publishConfig": {
"tag": "1.x"
}
}

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,106 @@
# node-cld
[![*NIX Build Status](https://secure.travis-ci.org/dachev/node-cld.png)](https://travis-ci.org/dachev/node-cld)
[![Windows Build Status](https://ci.appveyor.com/api/projects/status/github/dachev/node-cld?svg=true&retina=true)](https://ci.appveyor.com/project/dachev/node-cld)
[![Dependencies](https://david-dm.org/dachev/node-cld.png)](https://david-dm.org/dachev/node-cld)
[![NPM version](https://badge.fury.io/js/cld.svg)](http://badge.fury.io/js/cld)
[![Stand With Ukraine](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://stand-with-ukraine.pp.ua)
Language detection for Javascript. Based on the CLD2 (Compact Language Detector) library from Google.
Highly optimized for space and speed. Runs about 10x faster than other libraries. Detects over 160 languages. Full test coverage. Runs on Linux, OS X, and Windows.
## Installation
```bash
$ npm install cld
```
Linux users, make sure you have g++ >= 4.8. If this is not an option, you should be able to install node-cld 2.4.4 even with an older g++ build.
## Examples
### Simple
```js
const cld = require('cld');
// As a promise
cld.detect('This is a language recognition example').then((result) => {
console.log(result);
});
// In an async function
async function testCld() {
const result = await cld.detect('This is a language recognition example');
console.log(result);
}
```
### Advanced
```js
const cld = require('cld');
const text = 'Това е пример за разпознаване на Български език';
const options = {
isHTML : false,
languageHint : 'BULGARIAN',
encodingHint : 'ISO_8859_5',
tldHint : 'bg',
httpHint : 'bg'
};
// As a promise
cld.detect(text, options).then((result) => {
console.log(result);
});
// In an async function
async function testCld() {
const result = await cld.detect(text, options);
console.log(result);
}
```
### Legacy
Detect can be called leveraging the node callback pattern. If options are provided, the third parameter should be the callback.
```javascript
const cld = require('cld');
cld.detect('This is a language recognition example', (err, result) => {
console.log(result);
});
```
## Options
#### isHTML
Set to true if the string contains HTML tags
#### languageHint
Pass a LANGUAGES key or value as a hint
#### encodingHint
Pass an ENCODINGS value as a hint
#### tldHint
Pass top level domain as a hint
#### httpHint
Pass an HTTP "Content-Encoding" value as a hint
#### bestEffort
Set to true to give best-effort answer, instead of UNKNOWN_LANGUAGE. May be useful for
short text if the caller prefers an approximate answer over none.
## Warning
Once the module has been installed, the underlying C sources will remain in the ```deps/cld``` folder and continue to occupy considerable space. This is because they will be required if you ever need to run `npm rebuild`. If you are under severe constraints you can delete this folder and reclam >100M
## Copyright
Copyright 2011-2015, Blagovest Dachev.
## License
Apache 2

View File

@@ -0,0 +1,27 @@
var path = require('path');
var fs = require('fs');
var glob = require('glob');
var _ = require('underscore');
deleteBuildFiles(function(err) {
});
function deleteBuildFiles(cb) {
var pattern = path.resolve(__dirname, '..', 'build', '**', '*');
glob(pattern, {nodir:true}, function(err, files) {
if (err) {
return cb(err);
}
files = _.reject(files, function(val, key) {
return /cld\.(node|pdb)$/.test(val)
});
for (var i = 0; i < files.length; i++) {
var file = files[i];
fs.unlinkSync(file);
}
cb(null);
});
}

View File

@@ -0,0 +1,359 @@
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= gcc
CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS)
CXX.target ?= g++
CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= ar
PLI.target ?= pli
# C++ apps need to be linked with g++.
LINK ?= $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host)
CXX.host ?= g++
CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host)
LINK.host ?= $(CXX.host)
LDFLAGS.host ?= $(LDFLAGS_host)
AR.host ?= ar
PLI.host ?= pli
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) -o $@ $< $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) -o $@ $< $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
quiet_cmd_symlink = SYMLINK $@
cmd_symlink = ln -sf "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) -o $@ $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,--start-group $(LD_INPUTS) $(LIBS) -Wl,--end-group
# Note: this does not handle spaces in paths
define xargs
$(1) $(word 1,$(2))
$(if $(word 2,$(2)),$(call xargs,$(1),$(wordlist 2,$(words $(2)),$(2))))
endef
define write-to-file
@: >$(1)
$(call xargs,@printf "%s\n" >>$(1),$(2))
endef
OBJ_FILE_LIST := ar-file-list
define create_archive
rm -f $(1) $(1).$(OBJ_FILE_LIST); mkdir -p `dirname $(1)`
$(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2)))
$(AR.$(TOOLSET)) crs $(1) @$(1).$(OBJ_FILE_LIST)
endef
define create_thin_archive
rm -f $(1) $(OBJ_FILE_LIST); mkdir -p `dirname $(1)`
$(call write-to-file,$(1).$(OBJ_FILE_LIST),$(filter %.o,$(2)))
$(AR.$(TOOLSET)) crsT $(1) @$(1).$(OBJ_FILE_LIST)
endef
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -o $@ -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,cld.target.mk)))),)
include cld.target.mk
endif
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,deps/cld/cld-c.target.mk)))),)
include deps/cld/cld-c.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /root/.cache/node/corepack/v1/pnpm/9.12.2/dist/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/root/.cache/node-gyp/22.14.0" "-Dnode_gyp_dir=/root/.cache/node/corepack/v1/pnpm/9.12.2/dist/node_modules/node-gyp" "-Dnode_lib_file=/root/.cache/node-gyp/22.14.0/<(target_arch)/node.lib" "-Dmodule_root_dir=/ci/build/discord/discord/discord_desktop/build_x64/modules/discord_spellcheck/node_modules/cld" "-Dnode_engine=v8" "--depth=." "-Goutput_dir=." "--generator-output=build" -I/ci/build/discord/discord/discord_desktop/build_x64/modules/discord_spellcheck/node_modules/cld/build/config.gypi -I/root/.cache/node/corepack/v1/pnpm/9.12.2/dist/node_modules/node-gyp/addon.gypi -I/root/.cache/node-gyp/22.14.0/include/node/common.gypi "--toplevel-dir=." binding.gyp
Makefile: $(srcdir)/../../../../../../../../../../root/.cache/node-gyp/22.14.0/include/node/common.gypi $(srcdir)/deps/cld/binding.gyp $(srcdir)/../../../../../../../../../../root/.cache/node/corepack/v1/pnpm/9.12.2/dist/node_modules/node-gyp/addon.gypi $(srcdir)/binding.gyp $(srcdir)/build/config.gypi
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif

Binary file not shown.

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,92 @@
const _ = require('underscore');
const cld2 = require('./build/Release/cld');
module.exports = {
LANGUAGES : cld2.LANGUAGES,
DETECTED_LANGUAGES : cld2.DETECTED_LANGUAGES,
ENCODINGS : cld2.ENCODINGS,
async detect(text, options) {
let cb = arguments[2];
if (typeof cb !== 'function' && typeof options === 'function') {
cb = options;
options = {};
}
try {
if (arguments.length < 1) {
throw new Error('Not enough arguments provided');
}
if (!_.isString(text) || text.length < 1) {
throw new Error('Empty or invalid text');
}
const defaults = {
isHTML : false,
languageHint : '',
encodingHint : '',
tldHint : '',
httpHint : '',
bestEffort : false
};
options = _.defaults({}, options, defaults);
if (!_.isBoolean(options.isHTML)) {
throw new Error('Invalid isHTML value');
}
if (!_.isBoolean(options.bestEffort)) {
throw new Error('Invalid bestEffort value');
}
if (!_.isString(options.languageHint)) {
throw new Error('Invalid languageHint');
}
if (!_.isString(options.encodingHint)) {
throw new Error('Invalid encodingHint');
}
if (!_.isString(options.tldHint)) {
throw new Error('Invalid tldHint');
}
if (!_.isString(options.httpHint)) {
throw new Error('Invalid httpHint');
}
if (options.encodingHint.length > 0 &&
!~cld2.ENCODINGS.indexOf(options.encodingHint)) {
throw new Error('Invalid encodingHint, see ENCODINGS');
}
if (options.languageHint.length > 0 &&
!~_.keys(cld2.LANGUAGES).indexOf(options.languageHint) &&
!~_.values(cld2.LANGUAGES).indexOf(options.languageHint)) {
throw new Error('Invalid languageHint, see LANGUAGES');
}
const result = await cld2.detectAsync(
text,
!options.isHTML,
options.languageHint,
options.encodingHint,
options.tldHint,
options.httpHint,
options.bestEffort
);
if (result.languages.length < 1) {
throw new Error('Failed to identify language');
}
if (cb) {
return cb(null, result);
} else {
return result;
}
} catch (error) {
if (cb) {
cb(error);
} else {
throw error;
}
}
}
};

View File

@@ -0,0 +1,45 @@
{
"name": "cld",
"description": "Language detection for Javascript. Based on the CLD2 (Compact Language Detector) library from Google. Highly optimized for space and speed. Runs about 10x faster than other libraries. Detects over 160 languages. Full test coverage. Runs on Linux, OS X, and Windows.",
"keywords": [
"language",
"detect",
"language detection",
"cld",
"cld2"
],
"version": "2.10.1",
"main": "./index.js",
"types": "./index.d.ts",
"dependencies": {
"glob": "7",
"node-addon-api": "*",
"underscore": "^1.12.1"
},
"scripts": {
"build": "node-gyp rebuild",
"test": "node test/runner.js",
"postinstall": "node bin/postinstall.js"
},
"author": {
"name": "Blagovest Dachev",
"email": "blago@dachev.com",
"url": "http://www.dachev.com"
},
"contributors": [
"Lovell Fuller <npm@lovell.info>"
],
"repository": {
"type": "git",
"url": "git://github.com/dachev/cld.git"
},
"licenses": [
{
"type": "Apache",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
],
"engines": {
"node": ">=12.0.0"
}
}

View File

@@ -0,0 +1,18 @@
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,6 @@
var concatMap = require('../');
var xs = [ 1, 2, 3, 4, 5, 6 ];
var ys = concatMap(xs, function (x) {
return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
});
console.dir(ys);

View File

@@ -0,0 +1,13 @@
module.exports = function (xs, fn) {
var res = [];
for (var i = 0; i < xs.length; i++) {
var x = fn(xs[i], i);
if (isArray(x)) res.push.apply(res, x);
else res.push(x);
}
return res;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};

View File

@@ -0,0 +1,43 @@
{
"name" : "concat-map",
"description" : "concatenative mapdashery",
"version" : "0.0.1",
"repository" : {
"type" : "git",
"url" : "git://github.com/substack/node-concat-map.git"
},
"main" : "index.js",
"keywords" : [
"concat",
"concatMap",
"map",
"functional",
"higher-order"
],
"directories" : {
"example" : "example",
"test" : "test"
},
"scripts" : {
"test" : "tape test/*.js"
},
"devDependencies" : {
"tape" : "~2.4.0"
},
"license" : "MIT",
"author" : {
"name" : "James Halliday",
"email" : "mail@substack.net",
"url" : "http://substack.net"
},
"testling" : {
"files" : "test/*.js",
"browsers" : {
"ie" : [ 6, 7, 8, 9 ],
"ff" : [ 3.5, 10, 15.0 ],
"chrome" : [ 10, 22 ],
"safari" : [ 5.1 ],
"opera" : [ 12 ]
}
}
}

View File

@@ -0,0 +1,43 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
----
This library bundles a version of the `fs.realpath` and `fs.realpathSync`
methods from Node.js v0.10 under the terms of the Node.js MIT license.
Node's license follows, also included at the header of `old.js` which contains
the licensed code:
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,33 @@
# fs.realpath
A backwards-compatible fs.realpath for Node v6 and above
In Node v6, the JavaScript implementation of fs.realpath was replaced
with a faster (but less resilient) native implementation. That raises
new and platform-specific errors and cannot handle long or excessively
symlink-looping paths.
This module handles those cases by detecting the new errors and
falling back to the JavaScript implementation. On versions of Node
prior to v6, it has no effect.
## USAGE
```js
var rp = require('fs.realpath')
// async version
rp.realpath(someLongAndLoopingPath, function (er, real) {
// the ELOOP was handled, but it was a bit slower
})
// sync version
var real = rp.realpathSync(someLongAndLoopingPath)
// monkeypatch at your own risk!
// This replaces the fs.realpath/fs.realpathSync builtins
rp.monkeypatch()
// un-do the monkeypatching
rp.unmonkeypatch()
```

View File

@@ -0,0 +1,66 @@
module.exports = realpath
realpath.realpath = realpath
realpath.sync = realpathSync
realpath.realpathSync = realpathSync
realpath.monkeypatch = monkeypatch
realpath.unmonkeypatch = unmonkeypatch
var fs = require('fs')
var origRealpath = fs.realpath
var origRealpathSync = fs.realpathSync
var version = process.version
var ok = /^v[0-5]\./.test(version)
var old = require('./old.js')
function newError (er) {
return er && er.syscall === 'realpath' && (
er.code === 'ELOOP' ||
er.code === 'ENOMEM' ||
er.code === 'ENAMETOOLONG'
)
}
function realpath (p, cache, cb) {
if (ok) {
return origRealpath(p, cache, cb)
}
if (typeof cache === 'function') {
cb = cache
cache = null
}
origRealpath(p, cache, function (er, result) {
if (newError(er)) {
old.realpath(p, cache, cb)
} else {
cb(er, result)
}
})
}
function realpathSync (p, cache) {
if (ok) {
return origRealpathSync(p, cache)
}
try {
return origRealpathSync(p, cache)
} catch (er) {
if (newError(er)) {
return old.realpathSync(p, cache)
} else {
throw er
}
}
}
function monkeypatch () {
fs.realpath = realpath
fs.realpathSync = realpathSync
}
function unmonkeypatch () {
fs.realpath = origRealpath
fs.realpathSync = origRealpathSync
}

View File

@@ -0,0 +1,303 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var pathModule = require('path');
var isWindows = process.platform === 'win32';
var fs = require('fs');
// JavaScript implementation of realpath, ported from node pre-v6
var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
function rethrow() {
// Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
// is fairly slow to generate.
var callback;
if (DEBUG) {
var backtrace = new Error;
callback = debugCallback;
} else
callback = missingCallback;
return callback;
function debugCallback(err) {
if (err) {
backtrace.message = err.message;
err = backtrace;
missingCallback(err);
}
}
function missingCallback(err) {
if (err) {
if (process.throwDeprecation)
throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
else if (!process.noDeprecation) {
var msg = 'fs: missing callback ' + (err.stack || err.message);
if (process.traceDeprecation)
console.trace(msg);
else
console.error(msg);
}
}
}
}
function maybeCallback(cb) {
return typeof cb === 'function' ? cb : rethrow();
}
var normalize = pathModule.normalize;
// Regexp that finds the next partion of a (partial) path
// result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
if (isWindows) {
var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
} else {
var nextPartRe = /(.*?)(?:[\/]+|$)/g;
}
// Regex to find the device root, including trailing slash. E.g. 'c:\\'.
if (isWindows) {
var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
} else {
var splitRootRe = /^[\/]*/;
}
exports.realpathSync = function realpathSync(p, cache) {
// make p is absolute
p = pathModule.resolve(p);
if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
return cache[p];
}
var original = p,
seenLinks = {},
knownHard = {};
// current character position in p
var pos;
// the partial path so far, including a trailing slash if any
var current;
// the partial path without a trailing slash (except when pointing at a root)
var base;
// the partial path scanned in the previous round, with slash
var previous;
start();
function start() {
// Skip over roots
var m = splitRootRe.exec(p);
pos = m[0].length;
current = m[0];
base = m[0];
previous = '';
// On windows, check that the root exists. On unix there is no need.
if (isWindows && !knownHard[base]) {
fs.lstatSync(base);
knownHard[base] = true;
}
}
// walk down the path, swapping out linked pathparts for their real
// values
// NB: p.length changes.
while (pos < p.length) {
// find the next part
nextPartRe.lastIndex = pos;
var result = nextPartRe.exec(p);
previous = current;
current += result[0];
base = previous + result[1];
pos = nextPartRe.lastIndex;
// continue if not a symlink
if (knownHard[base] || (cache && cache[base] === base)) {
continue;
}
var resolvedLink;
if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
// some known symbolic link. no need to stat again.
resolvedLink = cache[base];
} else {
var stat = fs.lstatSync(base);
if (!stat.isSymbolicLink()) {
knownHard[base] = true;
if (cache) cache[base] = base;
continue;
}
// read the link if it wasn't read before
// dev/ino always return 0 on windows, so skip the check.
var linkTarget = null;
if (!isWindows) {
var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
if (seenLinks.hasOwnProperty(id)) {
linkTarget = seenLinks[id];
}
}
if (linkTarget === null) {
fs.statSync(base);
linkTarget = fs.readlinkSync(base);
}
resolvedLink = pathModule.resolve(previous, linkTarget);
// track this, if given a cache.
if (cache) cache[base] = resolvedLink;
if (!isWindows) seenLinks[id] = linkTarget;
}
// resolve the link, then start over
p = pathModule.resolve(resolvedLink, p.slice(pos));
start();
}
if (cache) cache[original] = p;
return p;
};
exports.realpath = function realpath(p, cache, cb) {
if (typeof cb !== 'function') {
cb = maybeCallback(cache);
cache = null;
}
// make p is absolute
p = pathModule.resolve(p);
if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
return process.nextTick(cb.bind(null, null, cache[p]));
}
var original = p,
seenLinks = {},
knownHard = {};
// current character position in p
var pos;
// the partial path so far, including a trailing slash if any
var current;
// the partial path without a trailing slash (except when pointing at a root)
var base;
// the partial path scanned in the previous round, with slash
var previous;
start();
function start() {
// Skip over roots
var m = splitRootRe.exec(p);
pos = m[0].length;
current = m[0];
base = m[0];
previous = '';
// On windows, check that the root exists. On unix there is no need.
if (isWindows && !knownHard[base]) {
fs.lstat(base, function(err) {
if (err) return cb(err);
knownHard[base] = true;
LOOP();
});
} else {
process.nextTick(LOOP);
}
}
// walk down the path, swapping out linked pathparts for their real
// values
function LOOP() {
// stop if scanned past end of path
if (pos >= p.length) {
if (cache) cache[original] = p;
return cb(null, p);
}
// find the next part
nextPartRe.lastIndex = pos;
var result = nextPartRe.exec(p);
previous = current;
current += result[0];
base = previous + result[1];
pos = nextPartRe.lastIndex;
// continue if not a symlink
if (knownHard[base] || (cache && cache[base] === base)) {
return process.nextTick(LOOP);
}
if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
// known symbolic link. no need to stat again.
return gotResolvedLink(cache[base]);
}
return fs.lstat(base, gotStat);
}
function gotStat(err, stat) {
if (err) return cb(err);
// if not a symlink, skip to the next path part
if (!stat.isSymbolicLink()) {
knownHard[base] = true;
if (cache) cache[base] = base;
return process.nextTick(LOOP);
}
// stat & read the link if not read before
// call gotTarget as soon as the link target is known
// dev/ino always return 0 on windows, so skip the check.
if (!isWindows) {
var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
if (seenLinks.hasOwnProperty(id)) {
return gotTarget(null, seenLinks[id], base);
}
}
fs.stat(base, function(err) {
if (err) return cb(err);
fs.readlink(base, function(err, target) {
if (!isWindows) seenLinks[id] = target;
gotTarget(err, target);
});
});
}
function gotTarget(err, target, base) {
if (err) return cb(err);
var resolvedLink = pathModule.resolve(previous, target);
if (cache) cache[base] = resolvedLink;
gotResolvedLink(resolvedLink);
}
function gotResolvedLink(resolvedLink) {
// resolve the link, then start over
p = pathModule.resolve(resolvedLink, p.slice(pos));
start();
}
};

View File

@@ -0,0 +1,26 @@
{
"name": "fs.realpath",
"version": "1.0.0",
"description": "Use node's fs.realpath, but fall back to the JS implementation if the native one fails",
"main": "index.js",
"dependencies": {},
"devDependencies": {},
"scripts": {
"test": "tap test/*.js --cov"
},
"repository": {
"type": "git",
"url": "git+https://github.com/isaacs/fs.realpath.git"
},
"keywords": [
"realpath",
"fs",
"polyfill"
],
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)",
"license": "ISC",
"files": [
"old.js",
"index.js"
]
}

View File

@@ -0,0 +1,21 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
## Glob Logo
Glob's logo created by Tanya Brassie <http://tanyabrassie.com/>, licensed
under a Creative Commons Attribution-ShareAlike 4.0 International License
https://creativecommons.org/licenses/by-sa/4.0/

View File

@@ -0,0 +1,378 @@
# Glob
Match files using the patterns the shell uses, like stars and stuff.
[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master)
This is a glob implementation in JavaScript. It uses the `minimatch`
library to do its matching.
![a fun cartoon logo made of glob characters](logo/glob.png)
## Usage
Install with npm
```
npm i glob
```
```javascript
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
```
## Glob Primer
"Globs" are the patterns you type when you do stuff like `ls *.js` on
the command line, or put `build/*` in a `.gitignore` file.
Before parsing the path part patterns, braced sections are expanded
into a set. Braced sections start with `{` and end with `}`, with any
number of comma-delimited sections within. Braced sections may contain
slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
The following characters have special magic meaning when used in a
path portion:
* `*` Matches 0 or more characters in a single path portion
* `?` Matches 1 character
* `[...]` Matches a range of characters, similar to a RegExp range.
If the first character of the range is `!` or `^` then it matches
any character not in the range.
* `!(pattern|pattern|pattern)` Matches anything that does not match
any of the patterns provided.
* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
patterns provided.
* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
patterns provided.
* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
provided
* `**` If a "globstar" is alone in a path portion, then it matches
zero or more directories and subdirectories searching for matches.
It does not crawl symlinked directories.
### Dots
If a file or directory path portion has a `.` as the first character,
then it will not match any glob pattern unless that pattern's
corresponding path part also has a `.` as its first character.
For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
However the pattern `a/*/c` would not, because `*` does not start with
a dot character.
You can make glob treat dots as normal characters by setting
`dot:true` in the options.
### Basename Matching
If you set `matchBase:true` in the options, and the pattern has no
slashes in it, then it will seek for any file anywhere in the tree
with a matching basename. For example, `*.js` would match
`test/simple/basic.js`.
### Empty Sets
If no matching files are found, then an empty array is returned. This
differs from the shell, where the pattern itself is returned. For
example:
$ echo a*s*d*f
a*s*d*f
To get the bash-style behavior, set the `nonull:true` in the options.
### See Also:
* `man sh`
* `man bash` (Search for "Pattern Matching")
* `man 3 fnmatch`
* `man 5 gitignore`
* [minimatch documentation](https://github.com/isaacs/minimatch)
## glob.hasMagic(pattern, [options])
Returns `true` if there are any special characters in the pattern, and
`false` otherwise.
Note that the options affect the results. If `noext:true` is set in
the options object, then `+(a|b)` will not be considered a magic
pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`
then that is considered magical, unless `nobrace:true` is set in the
options.
## glob(pattern, [options], cb)
* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* `cb` `{Function}`
* `err` `{Error | null}`
* `matches` `{Array<String>}` filenames found matching the pattern
Perform an asynchronous glob search.
## glob.sync(pattern, [options])
* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* return: `{Array<String>}` filenames found matching the pattern
Perform a synchronous glob search.
## Class: glob.Glob
Create a Glob object by instantiating the `glob.Glob` class.
```javascript
var Glob = require("glob").Glob
var mg = new Glob(pattern, options, cb)
```
It's an EventEmitter, and starts walking the filesystem to find matches
immediately.
### new glob.Glob(pattern, [options], [cb])
* `pattern` `{String}` pattern to search for
* `options` `{Object}`
* `cb` `{Function}` Called when an error occurs, or matches are found
* `err` `{Error | null}`
* `matches` `{Array<String>}` filenames found matching the pattern
Note that if the `sync` flag is set in the options, then matches will
be immediately available on the `g.found` member.
### Properties
* `minimatch` The minimatch object that the glob uses.
* `options` The options object passed in.
* `aborted` Boolean which is set to true when calling `abort()`. There
is no way at this time to continue a glob search after aborting, but
you can re-use the statCache to avoid having to duplicate syscalls.
* `cache` Convenience object. Each field has the following possible
values:
* `false` - Path does not exist
* `true` - Path exists
* `'FILE'` - Path exists, and is not a directory
* `'DIR'` - Path exists, and is a directory
* `[file, entries, ...]` - Path exists, is a directory, and the
array value is the results of `fs.readdir`
* `statCache` Cache of `fs.stat` results, to prevent statting the same
path multiple times.
* `symlinks` A record of which paths are symbolic links, which is
relevant in resolving `**` patterns.
* `realpathCache` An optional object which is passed to `fs.realpath`
to minimize unnecessary syscalls. It is stored on the instantiated
Glob object, and may be re-used.
### Events
* `end` When the matching is finished, this is emitted with all the
matches found. If the `nonull` option is set, and no match was found,
then the `matches` list contains the original pattern. The matches
are sorted, unless the `nosort` flag is set.
* `match` Every time a match is found, this is emitted with the specific
thing that matched. It is not deduplicated or resolved to a realpath.
* `error` Emitted when an unexpected error is encountered, or whenever
any fs error occurs if `options.strict` is set.
* `abort` When `abort()` is called, this event is raised.
### Methods
* `pause` Temporarily stop the search
* `resume` Resume the search
* `abort` Stop the search forever
### Options
All the options that can be passed to Minimatch can also be passed to
Glob to change pattern matching behavior. Also, some have been added,
or have glob-specific ramifications.
All options are false by default, unless otherwise noted.
All options are added to the Glob object, as well.
If you are running many `glob` operations, you can pass a Glob object
as the `options` argument to a subsequent operation to shortcut some
`stat` and `readdir` calls. At the very least, you may pass in shared
`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
parallel glob operations will be sped up by sharing information about
the filesystem.
* `cwd` The current working directory in which to search. Defaults
to `process.cwd()`.
* `root` The place where patterns starting with `/` will be mounted
onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
systems, and `C:\` or some such on Windows.)
* `dot` Include `.dot` files in normal matches and `globstar` matches.
Note that an explicit dot in a portion of the pattern will always
match dot files.
* `nomount` By default, a pattern starting with a forward-slash will be
"mounted" onto the root setting, so that a valid filesystem path is
returned. Set this flag to disable that behavior.
* `mark` Add a `/` character to directory matches. Note that this
requires additional stat calls.
* `nosort` Don't sort the results.
* `stat` Set to true to stat *all* results. This reduces performance
somewhat, and is completely unnecessary, unless `readdir` is presumed
to be an untrustworthy indicator of file existence.
* `silent` When an unusual error is encountered when attempting to
read a directory, a warning will be printed to stderr. Set the
`silent` option to true to suppress these warnings.
* `strict` When an unusual error is encountered when attempting to
read a directory, the process will just continue on in search of
other matches. Set the `strict` option to raise an error in these
cases.
* `cache` See `cache` property above. Pass in a previously generated
cache object to save some fs calls.
* `statCache` A cache of results of filesystem information, to prevent
unnecessary stat calls. While it should not normally be necessary
to set this, you may pass the statCache from one glob() call to the
options object of another, if you know that the filesystem will not
change between calls. (See "Race Conditions" below.)
* `symlinks` A cache of known symbolic links. You may pass in a
previously generated `symlinks` object to save `lstat` calls when
resolving `**` matches.
* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
* `nounique` In some cases, brace-expanded patterns can result in the
same file showing up multiple times in the result set. By default,
this implementation prevents duplicates in the result set. Set this
flag to disable that behavior.
* `nonull` Set to never return an empty set, instead returning a set
containing the pattern itself. This is the default in glob(3).
* `debug` Set to enable debug logging in minimatch and glob.
* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
* `noglobstar` Do not match `**` against multiple filenames. (Ie,
treat it as a normal `*` instead.)
* `noext` Do not match `+(a|b)` "extglob" patterns.
* `nocase` Perform a case-insensitive match. Note: on
case-insensitive filesystems, non-magic patterns will match by
default, since `stat` and `readdir` will not raise errors.
* `matchBase` Perform a basename-only match if the pattern does not
contain any slash characters. That is, `*.js` would be treated as
equivalent to `**/*.js`, matching all js files in all directories.
* `nodir` Do not match directories, only files. (Note: to match
*only* directories, simply put a `/` at the end of the pattern.)
* `ignore` Add a pattern or an array of glob patterns to exclude matches.
Note: `ignore` patterns are *always* in `dot:true` mode, regardless
of any other settings.
* `follow` Follow symlinked directories when expanding `**` patterns.
Note that this can result in a lot of duplicate references in the
presence of cyclic links.
* `realpath` Set to true to call `fs.realpath` on all of the results.
In the case of a symlink that cannot be resolved, the full absolute
path to the matched entry is returned (though it will usually be a
broken symlink)
* `absolute` Set to true to always receive absolute paths for matched
files. Unlike `realpath`, this also affects the values returned in
the `match` event.
* `fs` File-system object with Node's `fs` API. By default, the built-in
`fs` module will be used. Set to a volume provided by a library like
`memfs` to avoid using the "real" file-system.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between node-glob and other
implementations, and are intentional.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.3, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
Note that symlinked directories are not crawled as part of a `**`,
though their contents may match against subsequent portions of the
pattern. This prevents infinite loops and duplicates and the like.
If an escaped pattern has no matches, and the `nonull` flag is set,
then glob returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
### Comments and Negation
Previously, this module let you mark a pattern as a "comment" if it
started with a `#` character, or a "negated" pattern if it started
with a `!` character.
These options were deprecated in version 5, and removed in version 6.
To specify things that should not match, use the `ignore` option.
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes will always
be interpreted as escape characters, not path separators.
Results from absolute patterns such as `/foo/*` are mounted onto the
root setting using `path.join`. On windows, this will by default result
in `/foo/*` matching `C:\foo\bar.txt`.
## Race Conditions
Glob searching, by its very nature, is susceptible to race conditions,
since it relies on directory walking and such.
As a result, it is possible that a file that exists when glob looks for
it may have been deleted or modified by the time it returns the result.
As part of its internal implementation, this program caches all stat
and readdir calls that it makes, in order to cut down on system
overhead. However, this also makes it even more susceptible to races,
especially if the cache or statCache objects are reused between glob
calls.
Users are thus advised not to use a glob result as a guarantee of
filesystem state in the face of rapid changes. For the vast majority
of operations, this is never a problem.
## Glob Logo
Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo).
The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
## Contributing
Any change to behavior (including bugfixes) must come with a test.
Patches that fail tests or reduce performance will be rejected.
```
# to run tests
npm test
# to re-generate test fixtures
npm run test-regen
# to benchmark against bash/zsh
npm run bench
# to profile javascript
npm run prof
```
![](oh-my-glob.gif)

View File

@@ -0,0 +1,238 @@
exports.setopts = setopts
exports.ownProp = ownProp
exports.makeAbs = makeAbs
exports.finish = finish
exports.mark = mark
exports.isIgnored = isIgnored
exports.childrenIgnored = childrenIgnored
function ownProp (obj, field) {
return Object.prototype.hasOwnProperty.call(obj, field)
}
var fs = require("fs")
var path = require("path")
var minimatch = require("minimatch")
var isAbsolute = require("path-is-absolute")
var Minimatch = minimatch.Minimatch
function alphasort (a, b) {
return a.localeCompare(b, 'en')
}
function setupIgnores (self, options) {
self.ignore = options.ignore || []
if (!Array.isArray(self.ignore))
self.ignore = [self.ignore]
if (self.ignore.length) {
self.ignore = self.ignore.map(ignoreMap)
}
}
// ignore patterns are always in dot:true mode.
function ignoreMap (pattern) {
var gmatcher = null
if (pattern.slice(-3) === '/**') {
var gpattern = pattern.replace(/(\/\*\*)+$/, '')
gmatcher = new Minimatch(gpattern, { dot: true })
}
return {
matcher: new Minimatch(pattern, { dot: true }),
gmatcher: gmatcher
}
}
function setopts (self, pattern, options) {
if (!options)
options = {}
// base-matching: just use globstar for that.
if (options.matchBase && -1 === pattern.indexOf("/")) {
if (options.noglobstar) {
throw new Error("base matching requires globstar")
}
pattern = "**/" + pattern
}
self.silent = !!options.silent
self.pattern = pattern
self.strict = options.strict !== false
self.realpath = !!options.realpath
self.realpathCache = options.realpathCache || Object.create(null)
self.follow = !!options.follow
self.dot = !!options.dot
self.mark = !!options.mark
self.nodir = !!options.nodir
if (self.nodir)
self.mark = true
self.sync = !!options.sync
self.nounique = !!options.nounique
self.nonull = !!options.nonull
self.nosort = !!options.nosort
self.nocase = !!options.nocase
self.stat = !!options.stat
self.noprocess = !!options.noprocess
self.absolute = !!options.absolute
self.fs = options.fs || fs
self.maxLength = options.maxLength || Infinity
self.cache = options.cache || Object.create(null)
self.statCache = options.statCache || Object.create(null)
self.symlinks = options.symlinks || Object.create(null)
setupIgnores(self, options)
self.changedCwd = false
var cwd = process.cwd()
if (!ownProp(options, "cwd"))
self.cwd = cwd
else {
self.cwd = path.resolve(options.cwd)
self.changedCwd = self.cwd !== cwd
}
self.root = options.root || path.resolve(self.cwd, "/")
self.root = path.resolve(self.root)
if (process.platform === "win32")
self.root = self.root.replace(/\\/g, "/")
// TODO: is an absolute `cwd` supposed to be resolved against `root`?
// e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
if (process.platform === "win32")
self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
self.nomount = !!options.nomount
// disable comments and negation in Minimatch.
// Note that they are not supported in Glob itself anyway.
options.nonegate = true
options.nocomment = true
// always treat \ in patterns as escapes, not path separators
options.allowWindowsEscape = false
self.minimatch = new Minimatch(pattern, options)
self.options = self.minimatch.options
}
function finish (self) {
var nou = self.nounique
var all = nou ? [] : Object.create(null)
for (var i = 0, l = self.matches.length; i < l; i ++) {
var matches = self.matches[i]
if (!matches || Object.keys(matches).length === 0) {
if (self.nonull) {
// do like the shell, and spit out the literal glob
var literal = self.minimatch.globSet[i]
if (nou)
all.push(literal)
else
all[literal] = true
}
} else {
// had matches
var m = Object.keys(matches)
if (nou)
all.push.apply(all, m)
else
m.forEach(function (m) {
all[m] = true
})
}
}
if (!nou)
all = Object.keys(all)
if (!self.nosort)
all = all.sort(alphasort)
// at *some* point we statted all of these
if (self.mark) {
for (var i = 0; i < all.length; i++) {
all[i] = self._mark(all[i])
}
if (self.nodir) {
all = all.filter(function (e) {
var notDir = !(/\/$/.test(e))
var c = self.cache[e] || self.cache[makeAbs(self, e)]
if (notDir && c)
notDir = c !== 'DIR' && !Array.isArray(c)
return notDir
})
}
}
if (self.ignore.length)
all = all.filter(function(m) {
return !isIgnored(self, m)
})
self.found = all
}
function mark (self, p) {
var abs = makeAbs(self, p)
var c = self.cache[abs]
var m = p
if (c) {
var isDir = c === 'DIR' || Array.isArray(c)
var slash = p.slice(-1) === '/'
if (isDir && !slash)
m += '/'
else if (!isDir && slash)
m = m.slice(0, -1)
if (m !== p) {
var mabs = makeAbs(self, m)
self.statCache[mabs] = self.statCache[abs]
self.cache[mabs] = self.cache[abs]
}
}
return m
}
// lotta situps...
function makeAbs (self, f) {
var abs = f
if (f.charAt(0) === '/') {
abs = path.join(self.root, f)
} else if (isAbsolute(f) || f === '') {
abs = f
} else if (self.changedCwd) {
abs = path.resolve(self.cwd, f)
} else {
abs = path.resolve(f)
}
if (process.platform === 'win32')
abs = abs.replace(/\\/g, '/')
return abs
}
// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
function isIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
})
}
function childrenIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return !!(item.gmatcher && item.gmatcher.match(path))
})
}

View File

@@ -0,0 +1,790 @@
// Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, then stat(PREFIX) and
// add to matches if it succeeds. END.
//
// If inGlobStar and PREFIX is symlink and points to dir
// set ENTRIES = []
// else readdir(PREFIX) as ENTRIES
// If fail, END
//
// with ENTRIES
// If pattern[n] is GLOBSTAR
// // handle the case where the globstar match is empty
// // by pruning it out, and testing the resulting pattern
// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
// // handle other cases.
// for ENTRY in ENTRIES (not dotfiles)
// // attach globstar + tail onto the entry
// // Mark that this entry is a globstar match
// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
//
// else // not globstar
// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
// Test ENTRY against pattern[n]
// If fails, continue
// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
//
// Caveat:
// Cache all stats and readdirs results to minimize syscall. Since all
// we ever care about is existence and directory-ness, we can just keep
// `true` for files, and [children,...] for directories, or `false` for
// things that don't exist.
module.exports = glob
var rp = require('fs.realpath')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var inherits = require('inherits')
var EE = require('events').EventEmitter
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var globSync = require('./sync.js')
var common = require('./common.js')
var setopts = common.setopts
var ownProp = common.ownProp
var inflight = require('inflight')
var util = require('util')
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
var once = require('once')
function glob (pattern, options, cb) {
if (typeof options === 'function') cb = options, options = {}
if (!options) options = {}
if (options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return globSync(pattern, options)
}
return new Glob(pattern, options, cb)
}
glob.sync = globSync
var GlobSync = glob.GlobSync = globSync.GlobSync
// old api surface
glob.glob = glob
function extend (origin, add) {
if (add === null || typeof add !== 'object') {
return origin
}
var keys = Object.keys(add)
var i = keys.length
while (i--) {
origin[keys[i]] = add[keys[i]]
}
return origin
}
glob.hasMagic = function (pattern, options_) {
var options = extend({}, options_)
options.noprocess = true
var g = new Glob(pattern, options)
var set = g.minimatch.set
if (!pattern)
return false
if (set.length > 1)
return true
for (var j = 0; j < set[0].length; j++) {
if (typeof set[0][j] !== 'string')
return true
}
return false
}
glob.Glob = Glob
inherits(Glob, EE)
function Glob (pattern, options, cb) {
if (typeof options === 'function') {
cb = options
options = null
}
if (options && options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return new GlobSync(pattern, options)
}
if (!(this instanceof Glob))
return new Glob(pattern, options, cb)
setopts(this, pattern, options)
this._didRealPath = false
// process each pattern in the minimatch set
var n = this.minimatch.set.length
// The matches are stored as {<filename>: true,...} so that
// duplicates are automagically pruned.
// Later, we do an Object.keys() on these.
// Keep them as a list so we can fill in when nonull is set.
this.matches = new Array(n)
if (typeof cb === 'function') {
cb = once(cb)
this.on('error', cb)
this.on('end', function (matches) {
cb(null, matches)
})
}
var self = this
this._processing = 0
this._emitQueue = []
this._processQueue = []
this.paused = false
if (this.noprocess)
return this
if (n === 0)
return done()
var sync = true
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false, done)
}
sync = false
function done () {
--self._processing
if (self._processing <= 0) {
if (sync) {
process.nextTick(function () {
self._finish()
})
} else {
self._finish()
}
}
}
}
Glob.prototype._finish = function () {
assert(this instanceof Glob)
if (this.aborted)
return
if (this.realpath && !this._didRealpath)
return this._realpath()
common.finish(this)
this.emit('end', this.found)
}
Glob.prototype._realpath = function () {
if (this._didRealpath)
return
this._didRealpath = true
var n = this.matches.length
if (n === 0)
return this._finish()
var self = this
for (var i = 0; i < this.matches.length; i++)
this._realpathSet(i, next)
function next () {
if (--n === 0)
self._finish()
}
}
Glob.prototype._realpathSet = function (index, cb) {
var matchset = this.matches[index]
if (!matchset)
return cb()
var found = Object.keys(matchset)
var self = this
var n = found.length
if (n === 0)
return cb()
var set = this.matches[index] = Object.create(null)
found.forEach(function (p, i) {
// If there's a problem with the stat, then it means that
// one or more of the links in the realpath couldn't be
// resolved. just return the abs value in that case.
p = self._makeAbs(p)
rp.realpath(p, self.realpathCache, function (er, real) {
if (!er)
set[real] = true
else if (er.syscall === 'stat')
set[p] = true
else
self.emit('error', er) // srsly wtf right here
if (--n === 0) {
self.matches[index] = set
cb()
}
})
})
}
Glob.prototype._mark = function (p) {
return common.mark(this, p)
}
Glob.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}
Glob.prototype.abort = function () {
this.aborted = true
this.emit('abort')
}
Glob.prototype.pause = function () {
if (!this.paused) {
this.paused = true
this.emit('pause')
}
}
Glob.prototype.resume = function () {
if (this.paused) {
this.emit('resume')
this.paused = false
if (this._emitQueue.length) {
var eq = this._emitQueue.slice(0)
this._emitQueue.length = 0
for (var i = 0; i < eq.length; i ++) {
var e = eq[i]
this._emitMatch(e[0], e[1])
}
}
if (this._processQueue.length) {
var pq = this._processQueue.slice(0)
this._processQueue.length = 0
for (var i = 0; i < pq.length; i ++) {
var p = pq[i]
this._processing--
this._process(p[0], p[1], p[2], p[3])
}
}
}
}
Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
assert(this instanceof Glob)
assert(typeof cb === 'function')
if (this.aborted)
return
this._processing++
if (this.paused) {
this._processQueue.push([pattern, index, inGlobStar, cb])
return
}
//console.error('PROCESS %d', this._processing, pattern)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// see if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index, cb)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) ||
isAbsolute(pattern.map(function (p) {
return typeof p === 'string' ? p : '[*]'
}).join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip _processing
if (childrenIgnored(this, read))
return cb()
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
// if the abs isn't a dir, then nothing can match!
if (!entries)
return cb()
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
//console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return cb()
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this._emitMatch(index, e)
}
// This was the last one, and no stats were needed
return cb()
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
this._process([e].concat(remain), index, inGlobStar, cb)
}
cb()
}
Glob.prototype._emitMatch = function (index, e) {
if (this.aborted)
return
if (isIgnored(this, e))
return
if (this.paused) {
this._emitQueue.push([index, e])
return
}
var abs = isAbsolute(e) ? e : this._makeAbs(e)
if (this.mark)
e = this._mark(e)
if (this.absolute)
e = abs
if (this.matches[index][e])
return
if (this.nodir) {
var c = this.cache[abs]
if (c === 'DIR' || Array.isArray(c))
return
}
this.matches[index][e] = true
var st = this.statCache[abs]
if (st)
this.emit('stat', e, st)
this.emit('match', e)
}
Glob.prototype._readdirInGlobStar = function (abs, cb) {
if (this.aborted)
return
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false, cb)
var lstatkey = 'lstat\0' + abs
var self = this
var lstatcb = inflight(lstatkey, lstatcb_)
if (lstatcb)
self.fs.lstat(abs, lstatcb)
function lstatcb_ (er, lstat) {
if (er && er.code === 'ENOENT')
return cb()
var isSym = lstat && lstat.isSymbolicLink()
self.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && lstat && !lstat.isDirectory()) {
self.cache[abs] = 'FILE'
cb()
} else
self._readdir(abs, false, cb)
}
}
Glob.prototype._readdir = function (abs, inGlobStar, cb) {
if (this.aborted)
return
cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
if (!cb)
return
//console.error('RD %j %j', +inGlobStar, abs)
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs, cb)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return cb()
if (Array.isArray(c))
return cb(null, c)
}
var self = this
self.fs.readdir(abs, readdirCb(this, abs, cb))
}
function readdirCb (self, abs, cb) {
return function (er, entries) {
if (er)
self._readdirError(abs, er, cb)
else
self._readdirEntries(abs, entries, cb)
}
}
Glob.prototype._readdirEntries = function (abs, entries, cb) {
if (this.aborted)
return
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
return cb(null, entries)
}
Glob.prototype._readdirError = function (f, er, cb) {
if (this.aborted)
return
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
var abs = this._makeAbs(f)
this.cache[abs] = 'FILE'
if (abs === this.cwdAbs) {
var error = new Error(er.code + ' invalid cwd ' + this.cwd)
error.path = this.cwd
error.code = er.code
this.emit('error', error)
this.abort()
}
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict) {
this.emit('error', er)
// If the error is handled, then we abort
// if not, we threw out of here
this.abort()
}
if (!this.silent)
console.error('glob error', er)
break
}
return cb()
}
Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
//console.error('pgs2', prefix, remain[0], entries)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return cb()
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false, cb)
var isSym = this.symlinks[abs]
var len = entries.length
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return cb()
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true, cb)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true, cb)
}
cb()
}
Glob.prototype._processSimple = function (prefix, index, cb) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var self = this
this._stat(prefix, function (er, exists) {
self._processSimple2(prefix, index, er, exists, cb)
})
}
Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
//console.error('ps2', prefix, exists)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return cb()
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this._emitMatch(index, prefix)
cb()
}
// Returns either 'DIR', 'FILE', or false
Glob.prototype._stat = function (f, cb) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return cb()
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return cb(null, c)
if (needDir && c === 'FILE')
return cb()
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (stat !== undefined) {
if (stat === false)
return cb(null, stat)
else {
var type = stat.isDirectory() ? 'DIR' : 'FILE'
if (needDir && type === 'FILE')
return cb()
else
return cb(null, type, stat)
}
}
var self = this
var statcb = inflight('stat\0' + abs, lstatcb_)
if (statcb)
self.fs.lstat(abs, statcb)
function lstatcb_ (er, lstat) {
if (lstat && lstat.isSymbolicLink()) {
// If it's a symlink, then treat it as the target, unless
// the target does not exist, then treat it as a file.
return self.fs.stat(abs, function (er, stat) {
if (er)
self._stat2(f, abs, null, lstat, cb)
else
self._stat2(f, abs, er, stat, cb)
})
} else {
self._stat2(f, abs, er, lstat, cb)
}
}
}
Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
this.statCache[abs] = false
return cb()
}
var needDir = f.slice(-1) === '/'
this.statCache[abs] = stat
if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
return cb(null, false, stat)
var c = true
if (stat)
c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c === 'FILE')
return cb()
return cb(null, c, stat)
}

View File

@@ -0,0 +1,55 @@
{
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)",
"name": "glob",
"description": "a little globber",
"version": "7.2.3",
"publishConfig": {
"tag": "v7-legacy"
},
"repository": {
"type": "git",
"url": "git://github.com/isaacs/node-glob.git"
},
"main": "glob.js",
"files": [
"glob.js",
"sync.js",
"common.js"
],
"engines": {
"node": "*"
},
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"devDependencies": {
"memfs": "^3.2.0",
"mkdirp": "0",
"rimraf": "^2.2.8",
"tap": "^15.0.6",
"tick": "0.0.6"
},
"tap": {
"before": "test/00-setup.js",
"after": "test/zz-cleanup.js",
"jobs": 1
},
"scripts": {
"prepublish": "npm run benchclean",
"profclean": "rm -f v8.log profile.txt",
"test": "tap",
"test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js",
"bench": "bash benchmark.sh",
"prof": "bash prof.sh && cat profile.txt",
"benchclean": "node benchclean.js"
},
"license": "ISC",
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
}

View File

@@ -0,0 +1,486 @@
module.exports = globSync
globSync.GlobSync = GlobSync
var rp = require('fs.realpath')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var Glob = require('./glob.js').Glob
var util = require('util')
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path-is-absolute')
var common = require('./common.js')
var setopts = common.setopts
var ownProp = common.ownProp
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
function globSync (pattern, options) {
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
return new GlobSync(pattern, options).found
}
function GlobSync (pattern, options) {
if (!pattern)
throw new Error('must provide pattern')
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
if (!(this instanceof GlobSync))
return new GlobSync(pattern, options)
setopts(this, pattern, options)
if (this.noprocess)
return this
var n = this.minimatch.set.length
this.matches = new Array(n)
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false)
}
this._finish()
}
GlobSync.prototype._finish = function () {
assert.ok(this instanceof GlobSync)
if (this.realpath) {
var self = this
this.matches.forEach(function (matchset, index) {
var set = self.matches[index] = Object.create(null)
for (var p in matchset) {
try {
p = self._makeAbs(p)
var real = rp.realpathSync(p, self.realpathCache)
set[real] = true
} catch (er) {
if (er.syscall === 'stat')
set[self._makeAbs(p)] = true
else
throw er
}
}
})
}
common.finish(this)
}
GlobSync.prototype._process = function (pattern, index, inGlobStar) {
assert.ok(this instanceof GlobSync)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// See if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) ||
isAbsolute(pattern.map(function (p) {
return typeof p === 'string' ? p : '[*]'
}).join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip processing
if (childrenIgnored(this, read))
return
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
}
GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// if the abs isn't a dir, then nothing can match!
if (!entries)
return
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix.slice(-1) !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this._emitMatch(index, e)
}
// This was the last one, and no stats were needed
return
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix)
newPattern = [prefix, e]
else
newPattern = [e]
this._process(newPattern.concat(remain), index, inGlobStar)
}
}
GlobSync.prototype._emitMatch = function (index, e) {
if (isIgnored(this, e))
return
var abs = this._makeAbs(e)
if (this.mark)
e = this._mark(e)
if (this.absolute) {
e = abs
}
if (this.matches[index][e])
return
if (this.nodir) {
var c = this.cache[abs]
if (c === 'DIR' || Array.isArray(c))
return
}
this.matches[index][e] = true
if (this.stat)
this._stat(e)
}
GlobSync.prototype._readdirInGlobStar = function (abs) {
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false)
var entries
var lstat
var stat
try {
lstat = this.fs.lstatSync(abs)
} catch (er) {
if (er.code === 'ENOENT') {
// lstat failed, doesn't exist
return null
}
}
var isSym = lstat && lstat.isSymbolicLink()
this.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && lstat && !lstat.isDirectory())
this.cache[abs] = 'FILE'
else
entries = this._readdir(abs, false)
return entries
}
GlobSync.prototype._readdir = function (abs, inGlobStar) {
var entries
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return null
if (Array.isArray(c))
return c
}
try {
return this._readdirEntries(abs, this.fs.readdirSync(abs))
} catch (er) {
this._readdirError(abs, er)
return null
}
}
GlobSync.prototype._readdirEntries = function (abs, entries) {
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
// mark and cache dir-ness
return entries
}
GlobSync.prototype._readdirError = function (f, er) {
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
var abs = this._makeAbs(f)
this.cache[abs] = 'FILE'
if (abs === this.cwdAbs) {
var error = new Error(er.code + ' invalid cwd ' + this.cwd)
error.path = this.cwd
error.code = er.code
throw error
}
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict)
throw er
if (!this.silent)
console.error('glob error', er)
break
}
}
GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false)
var len = entries.length
var isSym = this.symlinks[abs]
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true)
}
}
GlobSync.prototype._processSimple = function (prefix, index) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var exists = this._stat(prefix)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this._emitMatch(index, prefix)
}
// Returns either 'DIR', 'FILE', or false
GlobSync.prototype._stat = function (f) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return false
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return c
if (needDir && c === 'FILE')
return false
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (!stat) {
var lstat
try {
lstat = this.fs.lstatSync(abs)
} catch (er) {
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
this.statCache[abs] = false
return false
}
}
if (lstat && lstat.isSymbolicLink()) {
try {
stat = this.fs.statSync(abs)
} catch (er) {
stat = lstat
}
} else {
stat = lstat
}
}
this.statCache[abs] = stat
var c = true
if (stat)
c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c === 'FILE')
return false
return c
}
GlobSync.prototype._mark = function (p) {
return common.mark(this, p)
}
GlobSync.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}

View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,37 @@
# inflight
Add callbacks to requests in flight to avoid async duplication
## USAGE
```javascript
var inflight = require('inflight')
// some request that does some stuff
function req(key, callback) {
// key is any random string. like a url or filename or whatever.
//
// will return either a falsey value, indicating that the
// request for this key is already in flight, or a new callback
// which when called will call all callbacks passed to inflightk
// with the same key
callback = inflight(key, callback)
// If we got a falsey value back, then there's already a req going
if (!callback) return
// this is where you'd fetch the url or whatever
// callback is also once()-ified, so it can safely be assigned
// to multiple events etc. First call wins.
setTimeout(function() {
callback(null, key)
}, 100)
}
// only assigns a single setTimeout
// when it dings, all cbs get called
req('foo', cb1)
req('foo', cb2)
req('foo', cb3)
req('foo', cb4)
```

View File

@@ -0,0 +1,54 @@
var wrappy = require('wrappy')
var reqs = Object.create(null)
var once = require('once')
module.exports = wrappy(inflight)
function inflight (key, cb) {
if (reqs[key]) {
reqs[key].push(cb)
return null
} else {
reqs[key] = [cb]
return makeres(key)
}
}
function makeres (key) {
return once(function RES () {
var cbs = reqs[key]
var len = cbs.length
var args = slice(arguments)
// XXX It's somewhat ambiguous whether a new callback added in this
// pass should be queued for later execution if something in the
// list of callbacks throws, or if it should just be discarded.
// However, it's such an edge case that it hardly matters, and either
// choice is likely as surprising as the other.
// As it happens, we do go ahead and schedule it for later execution.
try {
for (var i = 0; i < len; i++) {
cbs[i].apply(null, args)
}
} finally {
if (cbs.length > len) {
// added more in the interim.
// de-zalgo, just in case, but don't call again.
cbs.splice(0, len)
process.nextTick(function () {
RES.apply(null, args)
})
} else {
delete reqs[key]
}
}
})
}
function slice (args) {
var length = args.length
var array = []
for (var i = 0; i < length; i++) array[i] = args[i]
return array
}

View File

@@ -0,0 +1,29 @@
{
"name": "inflight",
"version": "1.0.6",
"description": "Add callbacks to requests in flight to avoid async duplication",
"main": "inflight.js",
"files": [
"inflight.js"
],
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
},
"devDependencies": {
"tap": "^7.1.2"
},
"scripts": {
"test": "tap test.js --100"
},
"repository": {
"type": "git",
"url": "https://github.com/npm/inflight.git"
},
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)",
"bugs": {
"url": "https://github.com/isaacs/inflight/issues"
},
"homepage": "https://github.com/isaacs/inflight",
"license": "ISC"
}

View File

@@ -0,0 +1,16 @@
The ISC License
Copyright (c) Isaac Z. Schlueter
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,42 @@
Browser-friendly inheritance fully compatible with standard node.js
[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).
This package exports standard `inherits` from node.js `util` module in
node environment, but also provides alternative browser-friendly
implementation through [browser
field](https://gist.github.com/shtylman/4339901). Alternative
implementation is a literal copy of standard one located in standalone
module to avoid requiring of `util`. It also has a shim for old
browsers with no `Object.create` support.
While keeping you sure you are using standard `inherits`
implementation in node.js environment, it allows bundlers such as
[browserify](https://github.com/substack/node-browserify) to not
include full `util` package to your client code if all you need is
just `inherits` function. It worth, because browser shim for `util`
package is large and `inherits` is often the single function you need
from it.
It's recommended to use this package instead of
`require('util').inherits` for any code that has chances to be used
not only in node.js but in browser too.
## usage
```js
var inherits = require('inherits');
// then use exactly as the standard one
```
## note on version ~1.0
Version ~1.0 had completely different motivation and is not compatible
neither with 2.0 nor with standard node.js `inherits`.
If you are using version ~1.0 and planning to switch to ~2.0, be
careful:
* new version uses `super_` instead of `super` for referencing
superclass
* new version overwrites current prototype while old one preserves any
existing fields on it

View File

@@ -0,0 +1,9 @@
try {
var util = require('util');
/* istanbul ignore next */
if (typeof util.inherits !== 'function') throw '';
module.exports = util.inherits;
} catch (e) {
/* istanbul ignore next */
module.exports = require('./inherits_browser.js');
}

View File

@@ -0,0 +1,27 @@
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}

View File

@@ -0,0 +1,29 @@
{
"name": "inherits",
"description": "Browser-friendly inheritance fully compatible with standard node.js inherits()",
"version": "2.0.4",
"keywords": [
"inheritance",
"class",
"klass",
"oop",
"object-oriented",
"inherits",
"browser",
"browserify"
],
"main": "./inherits.js",
"browser": "./inherits_browser.js",
"repository": "git://github.com/isaacs/inherits",
"license": "ISC",
"scripts": {
"test": "tap"
},
"devDependencies": {
"tap": "^14.2.4"
},
"files": [
"inherits.js",
"inherits_browser.js"
]
}

View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,267 @@
# minimatch
A minimal matching utility.
[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch)
This is the matching library used internally by npm.
It works by converting glob expressions into JavaScript `RegExp`
objects.
## Important Security Consideration!
> [!WARNING]
> This library uses JavaScript regular expressions. Please read
> the following warning carefully, and be thoughtful about what
> you provide to this library in production systems.
_Any_ library in JavaScript that deals with matching string
patterns using regular expressions will be subject to
[ReDoS](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS)
if the pattern is generated using untrusted input.
Efforts have been made to mitigate risk as much as is feasible in
such a library, providing maximum recursion depths and so forth,
but these measures can only ultimately protect against accidents,
not malice. A dedicated attacker can _always_ find patterns that
cannot be defended against by a bash-compatible glob pattern
matching system that uses JavaScript regular expressions.
To be extremely clear:
> [!WARNING]
> **If you create a system where you take user input, and use
> that input as the source of a Regular Expression pattern, in
> this or any extant glob matcher in JavaScript, you will be
> pwned.**
A future version of this library _may_ use a different matching
algorithm which does not exhibit backtracking problems. If and
when that happens, it will likely be a sweeping change, and those
improvements will **not** be backported to legacy versions.
In the near term, it is not reasonable to continue to play
whack-a-mole with security advisories, and so any future ReDoS
reports will be considered "working as intended", and resolved
entirely by this warning.
## Usage
```javascript
var minimatch = require("minimatch")
minimatch("bar.foo", "*.foo") // true!
minimatch("bar.foo", "*.bar") // false!
minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
```
## Features
Supports these glob features:
* Brace Expansion
* Extended glob matching
* "Globstar" `**` matching
See:
* `man sh`
* `man bash`
* `man 3 fnmatch`
* `man 5 gitignore`
## Minimatch Class
Create a minimatch object by instantiating the `minimatch.Minimatch` class.
```javascript
var Minimatch = require("minimatch").Minimatch
var mm = new Minimatch(pattern, options)
```
### Properties
* `pattern` The original pattern the minimatch object represents.
* `options` The options supplied to the constructor.
* `set` A 2-dimensional array of regexp or string expressions.
Each row in the
array corresponds to a brace-expanded pattern. Each item in the row
corresponds to a single path-part. For example, the pattern
`{a,b/c}/d` would expand to a set of patterns like:
[ [ a, d ]
, [ b, c, d ] ]
If a portion of the pattern doesn't have any "magic" in it
(that is, it's something like `"foo"` rather than `fo*o?`), then it
will be left as a string rather than converted to a regular
expression.
* `regexp` Created by the `makeRe` method. A single regular expression
expressing the entire pattern. This is useful in cases where you wish
to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
* `negate` True if the pattern is negated.
* `comment` True if the pattern is a comment.
* `empty` True if the pattern is `""`.
### Methods
* `makeRe` Generate the `regexp` member if necessary, and return it.
Will return `false` if the pattern is invalid.
* `match(fname)` Return true if the filename matches the pattern, or
false otherwise.
* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
filename, and match it against a single row in the `regExpSet`. This
method is mainly for internal use, but is exposed so that it can be
used by a glob-walker that needs to avoid excessive filesystem calls.
All other methods are internal, and will be called as necessary.
### minimatch(path, pattern, options)
Main export. Tests a path against the pattern using the options.
```javascript
var isJS = minimatch(file, "*.js", { matchBase: true })
```
### minimatch.filter(pattern, options)
Returns a function that tests its
supplied argument, suitable for use with `Array.filter`. Example:
```javascript
var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
```
### minimatch.match(list, pattern, options)
Match against the list of
files, in the style of fnmatch or glob. If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.
```javascript
var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
```
### minimatch.makeRe(pattern, options)
Make a regular expression object from the pattern.
## Options
All options are `false` by default.
### debug
Dump a ton of stuff to stderr.
### nobrace
Do not expand `{a,b}` and `{1..3}` brace sets.
### noglobstar
Disable `**` matching against multiple folder names.
### dot
Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.
Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.
### noext
Disable "extglob" style patterns like `+(a|b)`.
### nocase
Perform a case-insensitive match.
### nonull
When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set. When not set, an empty list
is returned if there are no matches.
### matchBase
If set, then patterns without slashes will be matched
against the basename of the path if it contains slashes. For example,
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
### nocomment
Suppress the behavior of treating `#` at the start of a pattern as a
comment.
### nonegate
Suppress the behavior of treating a leading `!` character as negation.
### flipNegate
Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)
### partial
Compare a partial path to a pattern. As long as the parts of the path that
are present are not contradicted by the pattern, it will be treated as a
match. This is useful in applications where you're walking through a
folder structure, and don't yet have the full path, but want to ensure that
you do not walk down paths that can never be a match.
For example,
```js
minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
```
### allowWindowsEscape
Windows path separator `\` is by default converted to `/`, which
prohibits the usage of `\` as a escape character. This flag skips that
behavior and allows using the escape character.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between minimatch and other
implementations, and are intentional.
If the pattern starts with a `!` character, then it is negated. Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally. This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.
If a pattern starts with `#`, then it is treated as a comment, and
will not match anything. Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
{
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)",
"name": "minimatch",
"description": "a glob matcher in javascript",
"version": "3.1.5",
"publishConfig": {
"tag": "legacy-v3"
},
"repository": {
"type": "git",
"url": "git://github.com/isaacs/minimatch.git"
},
"main": "minimatch.js",
"scripts": {
"test": "tap",
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --all; git push origin --tags"
},
"engines": {
"node": "*"
},
"dependencies": {
"brace-expansion": "^1.1.7"
},
"devDependencies": {
"tap": "^15.1.6"
},
"license": "ISC",
"files": [
"minimatch.js"
]
}

View File

@@ -0,0 +1,8 @@
root = true
[*]
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2

View File

@@ -0,0 +1,325 @@
# node-addon-api Changelog
## 2020-06-02 Version 1.7.2, @NickNaso
### Notable changes:
#### API
- Fix memory corruption vulnerability
### Commmits
* [[`801bd068f4`](https://github.com/nodejs/node-addon-api/commit/801bd068f4)] - **napi**: fix memory corruption vulnerability (Tobias Nießen )
## 2019-07-23 Version 1.7.1, @NickNaso
### Notable changes:
#### API
- Fixed compilation problems that happen on Node.js with N-API version less than 4.
### Commmits
* [[`c20bcbd069`](https://github.com/nodejs/node-addon-api/commit/c20bcbd069)] - Merge pull request #518 from NickNaso/master (Nicola Del Gobbo)
* [[`6720d57253`](https://github.com/nodejs/node-addon-api/commit/6720d57253)] - Create the native threadsafe\_function for test only for N-API greater than 3. (NickNaso)
* [[`37b6c185ad`](https://github.com/nodejs/node-addon-api/commit/37b6c185ad)] - Fix compilation breakage on 1.7.0 (NickNaso)
## 2019-07-23 Version 1.7.0, @NickNaso
### Notable changes:
#### API
- Added `Napi::ThreadSafeFunction` api.
- Added `Napi::AsyncWorker::GetResult()` method to `Napi::AsyncWorker`.
- Added `Napi::AsyncWorker::Destroy()()` method to `Napi::AsyncWorker`.
- Use full namespace on macros that create the errors.
#### Documentation
- Added documentation about contribution philosophy.
- Added documentation for `Napi::ThreadSafeFunction`.
- Some minor corrections all over the documentation.
#### TEST
- Added test case for bool operator.
- Fixed test case for `Napi::ObjectWrap`.
### Commmits
* [[`717c9ab163`](https://github.com/nodejs/node-addon-api/commit/717c9ab163)] - **AsyncWorker**: add GetResult() method (Kevin Eady) [#512](https://github.com/nodejs/node-addon-api/pull/512)
* [[`d9d991bbc9`](https://github.com/nodejs/node-addon-api/commit/d9d991bbc9)] - **doc**: add ThreadSafeFunction to main README (#513) (Kevin Eady) [#513](https://github.com/nodejs/node-addon-api/pull/513)
* [[`ac6000d0fd`](https://github.com/nodejs/node-addon-api/commit/ac6000d0fd)] - **doc**: fix minor typo (Yohei Kishimoto) [#510](https://github.com/nodejs/node-addon-api/pull/510)
* [[`e9fa1eaa86`](https://github.com/nodejs/node-addon-api/commit/e9fa1eaa86)] - **doc**: document ThreadSafeFunction (#494) (Kevin Eady) [#494](https://github.com/nodejs/node-addon-api/pull/494)
* [[`cab3b1e2a2`](https://github.com/nodejs/node-addon-api/commit/cab3b1e2a2)] - **doc**: ClassPropertyDescriptor example (Ross Weir) [#507](https://github.com/nodejs/node-addon-api/pull/507)
* [[`c32d7dbdcf`](https://github.com/nodejs/node-addon-api/commit/c32d7dbdcf)] - **macros**: create errors fully namespaced (Gabriel Schulhof) [#506](https://github.com/nodejs/node-addon-api/pull/506)
* [[`0a90df2fcb`](https://github.com/nodejs/node-addon-api/commit/0a90df2fcb)] - Implement ThreadSafeFunction class (Jinho Bang)
* [[`1fb540eeb5`](https://github.com/nodejs/node-addon-api/commit/1fb540eeb5)] - Use curly brackets to include node\_api.h (NickNaso) [#493](https://github.com/nodejs/node-addon-api/pull/493)
* [[`b2b08122ea`](https://github.com/nodejs/node-addon-api/commit/b2b08122ea)] - **AsyncWorker**: make callback optional (Kevin Eady) [#489](https://github.com/nodejs/node-addon-api/pull/489)
* [[`a0cac77c82`](https://github.com/nodejs/node-addon-api/commit/a0cac77c82)] - Added test for bool operator (NickNaso) [#490](https://github.com/nodejs/node-addon-api/pull/490)
* [[`ab7d8fcc48`](https://github.com/nodejs/node-addon-api/commit/ab7d8fcc48)] - **src**: fix objectwrap test case (Michael Dawson) [#495](https://github.com/nodejs/node-addon-api/pull/495)
* [[`3b6b9eb88a`](https://github.com/nodejs/node-addon-api/commit/3b6b9eb88a)] - **AsyncWorker**: introduce Destroy() method (Gabriel Schulhof) [#488](https://github.com/nodejs/node-addon-api/pull/488)
* [[`f633fbd95d`](https://github.com/nodejs/node-addon-api/commit/f633fbd95d)] - string.md: Document existing New(env, value, length) APIs (Tux3) [#486](https://github.com/nodejs/node-addon-api/pull/486)
* [[`aaea55eda9`](https://github.com/nodejs/node-addon-api/commit/aaea55eda9)] - Little fix on code example (Nicola Del Gobbo) [#470](https://github.com/nodejs/node-addon-api/pull/470)
* [[`e1cf9a35a1`](https://github.com/nodejs/node-addon-api/commit/e1cf9a35a1)] - Use `Value::IsEmpty` to check for empty value (NickNaso) [#478](https://github.com/nodejs/node-addon-api/pull/478)
* [[`3ad5dfc7d9`](https://github.com/nodejs/node-addon-api/commit/3ad5dfc7d9)] - Fix link (Alba Mendez) [#481](https://github.com/nodejs/node-addon-api/pull/481)
* [[`a3b4d99c45`](https://github.com/nodejs/node-addon-api/commit/a3b4d99c45)] - **doc**: Add contribution philosophy doc (Hitesh Kanwathirtha)
* [[`36863f087b`](https://github.com/nodejs/node-addon-api/commit/36863f087b)] - **doc**: refer to TypedArray and ArrayBuffer from Array (Gabriel "_|Nix|_" Schulhof) [#465](https://github.com/nodejs/node-addon-api/pull/465)
## 2019-04-03 Version 1.6.3, @NickNaso
### Notable changes:
#### API
- Added `SuppressDestruct` method to `Napi::AsyncWorker`.
- Added new build targets for debug.
- Exposed macros that throw errors.
- Fixed memory leaks caused by callback data when a napi error occurs.
- Fixed missing `void *data` usage in `Napi::PropertyDescriptors`.
#### Documentation
- Some minor corrections all over the documentation.
### Commmits
* [[`83b41c2fe4`](https://github.com/nodejs/node-addon-api/commit/83b41c2fe4)] - Document adding -fvisibility=hidden flag for macOS users (Nicola Del Gobbo) [#460](https://github.com/nodejs/node-addon-api/pull/460)
* [[`1ed7ad8769`](https://github.com/nodejs/node-addon-api/commit/1ed7ad8769)] - **doc**: correct return type of Int32Value to int32\_t (Bill Gallafent) [#459](https://github.com/nodejs/node-addon-api/pull/459)
* [[`b0f6b601aa`](https://github.com/nodejs/node-addon-api/commit/b0f6b601aa)] - **src**: add AsyncWorker destruction suppression (Gabriel Schulhof) [#407](https://github.com/nodejs/node-addon-api/pull/407)
* [[`72b1975cff`](https://github.com/nodejs/node-addon-api/commit/72b1975cff)] - **doc**: fix links to the Property Descriptor docs (Ryuichi Okumura) [#458](https://github.com/nodejs/node-addon-api/pull/458)
* [[`fcfc612728`](https://github.com/nodejs/node-addon-api/commit/fcfc612728)] - **build**: new build targets for debug purposes (Jinho Bang) [#186](https://github.com/nodejs/node-addon-api/pull/186)
* [[`c629553cd7`](https://github.com/nodejs/node-addon-api/commit/c629553cd7)] - **doc**: minor doc corrections and clarifications (Bruce A. MacNaughton) [#426](https://github.com/nodejs/node-addon-api/pull/426)
* [[`7b87e0b999`](https://github.com/nodejs/node-addon-api/commit/7b87e0b999)] - **doc**: update number.md (Bernardo Heynemann) [#436](https://github.com/nodejs/node-addon-api/pull/436)
* [[`fcf173d2a1`](https://github.com/nodejs/node-addon-api/commit/fcf173d2a1)] - **src**: expose macros that throw errors (Gabriel Schulhof) [#448](https://github.com/nodejs/node-addon-api/pull/448)
* [[`b409a2f987`](https://github.com/nodejs/node-addon-api/commit/b409a2f987)] - **package**: add npm search keywords (Sam Roberts) [#452](https://github.com/nodejs/node-addon-api/pull/452)
* [[`0bc7987806`](https://github.com/nodejs/node-addon-api/commit/0bc7987806)] - **doc**: fix references to Weak and Persistent (Jake Barnes) [#428](https://github.com/nodejs/node-addon-api/pull/428)
* [[`ad6f569f85`](https://github.com/nodejs/node-addon-api/commit/ad6f569f85)] - **doc**: dix typo (Abhishek Kumar Singh) [#435](https://github.com/nodejs/node-addon-api/pull/435)
* [[`28df833a49`](https://github.com/nodejs/node-addon-api/commit/28df833a49)] - Merge pull request #441 from jschlight/master (Jim Schlight)
* [[`4921e74d83`](https://github.com/nodejs/node-addon-api/commit/4921e74d83)] - Rearranges names to be alphabetical (Jim Schlight)
* [[`48220335b0`](https://github.com/nodejs/node-addon-api/commit/48220335b0)] - Membership review update (Jim Schlight)
* [[`44f0695533`](https://github.com/nodejs/node-addon-api/commit/44f0695533)] - Merge pull request #394 from NickNaso/create\_release (Nicola DelGobbo)
* [[`fa49d68416`](https://github.com/nodejs/node-addon-api/commit/fa49d68416)] - **doc**: fix some `Finalizer` signatures (Philipp Renoth) [#414](https://github.com/nodejs/node-addon-api/pull/414)
* [[`020ac4a628`](https://github.com/nodejs/node-addon-api/commit/020ac4a628)] - **src**: make `Object::GetPropertyNames()` const (Philipp Renoth)[#415](https://github.com/nodejs/node-addon-api/pull/415)
* [[`91eaa6f4cb`](https://github.com/nodejs/node-addon-api/commit/91eaa6f4cb)] - **src**: fix callbackData leaks on error napi status (Philipp Renoth) [#417](https://github.com/nodejs/node-addon-api/pull/417)
* [[`0b40275752`](https://github.com/nodejs/node-addon-api/commit/0b40275752)] - **src**: fix noexcept control flow issues (Philipp Renoth) [#420](https://github.com/nodejs/node-addon-api/pull/420)
* [[`c1ff2936f9`](https://github.com/nodejs/node-addon-api/commit/c1ff2936f9)] - **src**: fix missing void\*data usage in PropertyDescriptors (Luciano Martorella) [#374](https://github.com/nodejs/node-addon-api/pull/374)
## 2018-11-29 Version 1.6.2, @NickNaso
### Notable changes:
#### API
- Fixed selection logic for version 6.x.
### Commmits
* [[`07a0fc4e95`](https://github.com/nodejs/node-addon-api/commit/07a0fc4e95)] - **src**: fix selection logic for 6.x (Michael Dawson) [#402](https://github.com/nodejs/node-addon-api/pull/402)
## 2018-11-14 Version 1.6.1, @NickNaso
### Notable changes:
#### Documentation
- Updated links for examples to point to node-addon-examples repo.
- Fixed typos on some parts of documentation.
#### API
- Removed unused member on `Napi::CallbackScope`.
- Enabled `Napi::CallbackScope` only with N-API v3.
### Commmits
* [[`e7cd292a74`](https://github.com/nodejs/node-addon-api/commit/e7cd292a74)] - **src**: remove unused CallbackScope member (Gabriel Schulhof) [#391](https://github.com/nodejs/node-addon-api/pull/391)
* [[`d47399fe25`](https://github.com/nodejs/node-addon-api/commit/d47399fe25)] - **src**: guard CallbackScope with N-API v3 (Michael Dawson) [#395](https://github.com/nodejs/node-addon-api/pull/395)
* [[`29a0262ab9`](https://github.com/nodejs/node-addon-api/commit/29a0262ab9)] - **doc**: fix typo (Dongjin Na) [#385](https://github.com/nodejs/node-addon-api/pull/385)
* [[`b6dc15b88d`](https://github.com/nodejs/node-addon-api/commit/b6dc15b88d)] - **doc**: make links point to node-addon-examples repo (Nicola Del Gobbo) [#389](https://github.com/nodejs/node-addon-api/pull/389)
## 2018-11-02 Version 1.6.0, @NickNaso
### Notable changes:
#### Documentation
- Improved documentation about ABI stability.
#### API
- Add `Napi::CallbackScope` class that help to have the equivalent of the scope
associated with a callback in place when making certain N-API calls
#### TEST
- Added tests for `Napi::Array` class.
- Added tests for `Napi::ArrayBuffer` class.
### Commmits
* [[`8ce605c657`](https://github.com/nodejs/node-addon-api/commit/8ce605c657)] - **build**: avoid using package-lock.json (Jaeseok Yoon) [#359](https://github.com/nodejs/node-addon-api/pull/359)
* [[`fa3a6150b3`](https://github.com/nodejs/node-addon-api/commit/fa3a6150b3)] - **src**: use MakeCallback() -\> Call() in AsyncWorker (Jinho Bang) [#361](https://github.com/nodejs/node-addon-api/pull/361)
* [[`2342415463`](https://github.com/nodejs/node-addon-api/commit/2342415463)] - **test**: create test objects in the stack instead of the heap (Dongjin Na) [#371](https://github.com/nodejs/node-addon-api/pull/371)
* [[`67b7db0a6f`](https://github.com/nodejs/node-addon-api/commit/67b7db0a6f)] - **test**: write tests for Array class (Jaeseok Yoon) [#363](https://github.com/nodejs/node-addon-api/pull/363)
* [[`729f6dc4ee`](https://github.com/nodejs/node-addon-api/commit/729f6dc4ee)] - **test**: add arraybuffer tests (Dongjin Na) [#369](https://github.com/nodejs/node-addon-api/pull/369)
* [[`405f3e5b5b`](https://github.com/nodejs/node-addon-api/commit/405f3e5b5b)] - **src**: implement CallbackScope class (Jinho Bang) [#362](https://github.com/nodejs/node-addon-api/pull/362)
* [[`015d95312f`](https://github.com/nodejs/node-addon-api/commit/015d95312f)] - **doc**: fix Napi::Reference link (Gentilhomme) [#365](https://github.com/nodejs/node-addon-api/pull/365)
* [[`fd65078e3c`](https://github.com/nodejs/node-addon-api/commit/fd65078e3c)] - README.md: link to new ABI stability guide (Gabriel Schulhof) [#367](https://github.com/nodejs/node-addon-api/pull/367)
* [[`ffebf9ba9a`](https://github.com/nodejs/node-addon-api/commit/ffebf9ba9a)] - Updates for release 1.5.0 (NickNaso)
## 2018-10-03 Version 1.5.0, @NickNaso
### Notable changes:
#### Documentation
- Completed the documentation to cover all the API surface.
- Numerous fixes to make documentation more consistent in all of its parts.
#### API
- Add `Napi::AsyncContext` class to handle asynchronous operation.
- Add `Napi::BigInt` class to work with BigInt type.
- Add `Napi::VersionManagement` class to retrieve the versions of Node.js and N-API.
- Fix potential memory leaks.
- DataView feature is enabled by default
- Add descriptor for Symbols
- Add new methods on `Napi::FunctionReference`.
- Add the possibility to retrieve the environment on `Napi::Promise::Deferred`
#### TOOL
- Add tool to check if a native add-on is built using N-API
#### TEST
- Start to increase the test coverage
- Fix in the test suite to better handle the experimental features that are not
yet backported in the previous Node.js version.
### Commits
* [[`2009c019af`](https://github.com/nodejs/node-addon-api/commit/2009c019af)] - Merge pull request #292 from devsnek/feature/bigint (Gus Caplan)
* [[`e44aca985e`](https://github.com/nodejs/node-addon-api/commit/e44aca985e)] - add bigint class (Gus Caplan)
* [[`a3951ab973`](https://github.com/nodejs/node-addon-api/commit/a3951ab973)] - Add documentation for Env(). (Rolf Timmermans) [#318](https://github.com/nodejs/node-addon-api/pull/318)
* [[`a6f7a6ad51`](https://github.com/nodejs/node-addon-api/commit/a6f7a6ad51)] - Add Env() to Promise::Deferred. (Rolf Timmermans)
* [[`0097e96b92`](https://github.com/nodejs/node-addon-api/commit/0097e96b92)] - Fixed broken links for Symbol and String (NickNaso)
* [[`b0ecd38d76`](https://github.com/nodejs/node-addon-api/commit/b0ecd38d76)] - Fix Code of conduct link properly (#323) (Jake Yoon) [#323](https://github.com/nodejs/node-addon-api/pull/323)
* [[`223474900f`](https://github.com/nodejs/node-addon-api/commit/223474900f)] - **doc**: update Version management (Dongjin Na) [#360](https://github.com/nodejs/node-addon-api/pull/360)
* [[`4f76262a10`](https://github.com/nodejs/node-addon-api/commit/4f76262a10)] - **doc**: some fix on `Napi::Boolean` documentation (NickNaso) [#354](https://github.com/nodejs/node-addon-api/pull/354)
* [[`78374f72d2`](https://github.com/nodejs/node-addon-api/commit/78374f72d2)] - **doc**: number documentation (NickNaso) [#356](https://github.com/nodejs/node-addon-api/pull/356)
* [[`51ffe453f8`](https://github.com/nodejs/node-addon-api/commit/51ffe453f8)] - **doc**: doc cleanup (NickNaso) [#353](https://github.com/nodejs/node-addon-api/pull/353)
* [[`fc11c944b2`](https://github.com/nodejs/node-addon-api/commit/fc11c944b2)] - **doc**: major doc cleanup (NickNaso) [#335](https://github.com/nodejs/node-addon-api/pull/335)
* [[`100d0a7cb2`](https://github.com/nodejs/node-addon-api/commit/100d0a7cb2)] - **doc**: first pass on objectwrap documentation (NickNaso) [#321](https://github.com/nodejs/node-addon-api/pull/321)
* [[`c7d54180ff`](https://github.com/nodejs/node-addon-api/commit/c7d54180ff)] - **doc**: the Napi::ObjectWrap example does not compile (Arnaud Botella) [#339](https://github.com/nodejs/node-addon-api/pull/339)
* [[`7cdd78726a`](https://github.com/nodejs/node-addon-api/commit/7cdd78726a)] - **doc**: added cpp highlight for string.md (Jaeseok Yoon) [#329](https://github.com/nodejs/node-addon-api/pull/329)
* [[`8ed29f547c`](https://github.com/nodejs/node-addon-api/commit/8ed29f547c)] - **doc**: add blurb about ABI stability (Gabriel Schulhof) [#326](https://github.com/nodejs/node-addon-api/pull/326)
* [[`757eb1f5a3`](https://github.com/nodejs/node-addon-api/commit/757eb1f5a3)] - **doc**: add function and function reference doc (NickNaso) [#299](https://github.com/nodejs/node-addon-api/pull/299)
* [[`2885c18591`](https://github.com/nodejs/node-addon-api/commit/2885c18591)] - **doc**: Create changelog for release 1.4.0 (Nicola Del Gobbo)
* [[`917bd60baa`](https://github.com/nodejs/node-addon-api/commit/917bd60baa)] - **src**: remove TODOs by fixing memory leaks (Gabriel Schulhof) [#343](https://github.com/nodejs/node-addon-api/pull/343)
* [[`dfcb93945f`](https://github.com/nodejs/node-addon-api/commit/dfcb93945f)] - **src**: implement AsyncContext class (Jinho Bang) [#252](https://github.com/nodejs/node-addon-api/pull/252)
* [[`211ed38d0d`](https://github.com/nodejs/node-addon-api/commit/211ed38d0d)] - **src**: make 'nothing' target a static library (Gabriel Schulhof) [#348](https://github.com/nodejs/node-addon-api/pull/348)
* [[`97c4ab5cf2`](https://github.com/nodejs/node-addon-api/commit/97c4ab5cf2)] - **src**: add Call and MakeCallback that accept cargs (NickNaso) [#344](https://github.com/nodejs/node-addon-api/pull/344)
* [[`b6e2d92c09`](https://github.com/nodejs/node-addon-api/commit/b6e2d92c09)] - **src**: enable DataView feature by default (Jinho) [#331](https://github.com/nodejs/node-addon-api/pull/331)
* [[`0a00e7c97b`](https://github.com/nodejs/node-addon-api/commit/0a00e7c97b)] - **src**: implement missing descriptor defs for symbols (Philipp Renoth) [#280](https://github.com/nodejs/node-addon-api/pull/280)
* [[`38e01b7e3b`](https://github.com/nodejs/node-addon-api/commit/38e01b7e3b)] - **src**: first pass on adding version management apis (NickNaso) [#325](https://github.com/nodejs/node-addon-api/pull/325)
* [[`79ee8381d2`](https://github.com/nodejs/node-addon-api/commit/79ee8381d2)] - **src**: fix compile failure in test (Michael Dawson) [#345](https://github.com/nodejs/node-addon-api/pull/345)
* [[`4d92a6066f`](https://github.com/nodejs/node-addon-api/commit/4d92a6066f)] - **src**: Add ObjectReference test case (Anisha Rohra) [#212](https://github.com/nodejs/node-addon-api/pull/212)
* [[`779560f397`](https://github.com/nodejs/node-addon-api/commit/779560f397)] - **test**: add operator overloading tests in Number (Your Name) [#355](https://github.com/nodejs/node-addon-api/pull/355)
* [[`73fed84ceb`](https://github.com/nodejs/node-addon-api/commit/73fed84ceb)] - **test**: add ability to control experimental tests (Michael Dawson) [#350](https://github.com/nodejs/node-addon-api/pull/350)
* [[`14c69abd46`](https://github.com/nodejs/node-addon-api/commit/14c69abd46)] - **test**: write tests for Boolean class (Jaeseok Yoon) [#328](https://github.com/nodejs/node-addon-api/pull/328)
* [[`2ad47a83b1`](https://github.com/nodejs/node-addon-api/commit/2ad47a83b1)] - **test**: explicitly cast to uint32\_t in test (Gabriel Schulhof) [#341](https://github.com/nodejs/node-addon-api/pull/341)
* [[`622ffaea76`](https://github.com/nodejs/node-addon-api/commit/622ffaea76)] - **test**: Tighten up compiler warnings (Mikhail Cheshkov) [#315](https://github.com/nodejs/node-addon-api/pull/315)
* [[`fd3c37b0f2`](https://github.com/nodejs/node-addon-api/commit/fd3c37b0f2)] - **tools**: add tool to check for N-API modules (Gabriel Schulhof) [#346](https://github.com/nodejs/node-addon-api/pull/346)
## 2018-07-19 Version 1.4.0, @NickNaso
### Notable changes:
#### Documentation
- Numerous additions to the documentation, filling out coverage
of API surface
#### API
- Add resource parameters to AsyncWorker constructor
- Add memory management feature
### Commits
* [[`7dc5ac8bc3`](https://github.com/nodejs/node-addon-api/commit/7dc5ac8bc3)] - **doc**: update metadata for release (Nicola Del Gobbo)
* [[`d68e86adb4`](https://github.com/nodejs/node-addon-api/commit/d68e86adb4)] - **doc**: Added documentation for PropertyDescriptor (Anisha Rohra) [#309](https://github.com/nodejs/node-addon-api/pull/309)
* [[`968a5f2000`](https://github.com/nodejs/node-addon-api/commit/968a5f2000)] - **doc**: Add documentation for ObjectReference.md (Anisha Rohra) [#307](https://github.com/nodejs/node-addon-api/pull/307)
* [[`908cdc314c`](https://github.com/nodejs/node-addon-api/commit/908cdc314c)] - **doc**: add `TypedArray` and `TypedArrayOf` (Kyle Farnung) [#305](https://github.com/nodejs/node-addon-api/pull/305)
* [[`2ff776ffe3`](https://github.com/nodejs/node-addon-api/commit/2ff776ffe3)] - backport node::Persistent (Gabriel Schulhof) [#300](https://github.com/nodejs/node-addon-api/pull/300)
* [[`98161970c9`](https://github.com/nodejs/node-addon-api/commit/98161970c9)] - Backport perf, crash and exception handling fixes (Gabriel Schulhof) [#295](https://github.com/nodejs/node-addon-api/pull/295)
* [[`dd1191e086`](https://github.com/nodejs/node-addon-api/commit/dd1191e086)] - **test**: fix asyncworker test so it runs on 6.x (Michael Dawson) [#298](https://github.com/nodejs/node-addon-api/pull/298)
* [[`11697fcecd`](https://github.com/nodejs/node-addon-api/commit/11697fcecd)] - **doc**: ArrayBuffer and Buffer documentation (Kyle Farnung) [#256](https://github.com/nodejs/node-addon-api/pull/256)
* [[`605aa2babf`](https://github.com/nodejs/node-addon-api/commit/605aa2babf)] - Add memory management feature (NickNaso) [#286](https://github.com/nodejs/node-addon-api/pull/286)
* [[`86be13a611`](https://github.com/nodejs/node-addon-api/commit/86be13a611)] - **doc**: Fix HandleScope docs (Ben Berman) [#287](https://github.com/nodejs/node-addon-api/pull/287)
* [[`90f92c4dc0`](https://github.com/nodejs/node-addon-api/commit/90f92c4dc0)] - **doc**: Update broken links in README.md (Hitesh Kanwathirtha) [#290](https://github.com/nodejs/node-addon-api/pull/290)
* [[`c2a620dc11`](https://github.com/nodejs/node-addon-api/commit/c2a620dc11)] - **doc**: Clarify positioning versus N-API (Michael Dawson) [#288](https://github.com/nodejs/node-addon-api/pull/288)
* [[`6cff890ee5`](https://github.com/nodejs/node-addon-api/commit/6cff890ee5)] - **doc**: Fix typo in docs (Ben Berman) [#284](https://github.com/nodejs/node-addon-api/pull/284)
* [[`7394bfd154`](https://github.com/nodejs/node-addon-api/commit/7394bfd154)] - **doc**: Fix typo in docs (Ben Berman) [#285](https://github.com/nodejs/node-addon-api/pull/285)
* [[`12b2cdeed3`](https://github.com/nodejs/node-addon-api/commit/12b2cdeed3)] - fix test files (Kyle Farnung) [#257](https://github.com/nodejs/node-addon-api/pull/257)
* [[`9ab6607242`](https://github.com/nodejs/node-addon-api/commit/9ab6607242)] - **doc**: Update Doc Version Number (joshgarde) [#277](https://github.com/nodejs/node-addon-api/pull/277)
* [[`e029a076c6`](https://github.com/nodejs/node-addon-api/commit/e029a076c6)] - **doc**: First pass at basic Node Addon API docs (Hitesh Kanwathirtha) [#268](https://github.com/nodejs/node-addon-api/pull/268)
* [[`74ff79717e`](https://github.com/nodejs/node-addon-api/commit/74ff79717e)] - **doc**: fix link to async\_worker.md (Michael Dawson)
* [[`5a63f45eda`](https://github.com/nodejs/node-addon-api/commit/5a63f45eda)] - **doc**: First step of error and async doc (NickNaso) [#272](https://github.com/nodejs/node-addon-api/pull/272)
* [[`9d38f61afb`](https://github.com/nodejs/node-addon-api/commit/9d38f61afb)] - **doc**: New Promise and Reference docs (Jim Schlight) [#243](https://github.com/nodejs/node-addon-api/pull/243)
* [[`43ff9fa836`](https://github.com/nodejs/node-addon-api/commit/43ff9fa836)] - **doc**: Updated Object documentation (Anisha Rohra) [#254](https://github.com/nodejs/node-addon-api/pull/254)
* [[`b197f7cc8b`](https://github.com/nodejs/node-addon-api/commit/b197f7cc8b)] - **doc**: minor typos (Nick Soggin) [#248](https://github.com/nodejs/node-addon-api/pull/248)
* [[`4b8918b352`](https://github.com/nodejs/node-addon-api/commit/4b8918b352)] - Add resource parameters to AsyncWorker constructor (Jinho Bang) [#253](https://github.com/nodejs/node-addon-api/pull/253)
* [[`1ecf7c19b6`](https://github.com/nodejs/node-addon-api/commit/1ecf7c19b6)] - **doc**: fix wrong link in readme (miloas) [#255](https://github.com/nodejs/node-addon-api/pull/255)
* [[`a750ed1932`](https://github.com/nodejs/node-addon-api/commit/a750ed1932)] - **release**: updates to metadata for next release (Michael Dawson)
## 2018-05-08 Version 1.3.0, @mhdawson
### Notable changes:
#### Documentation
- Added documentation for Scopes
- Added documentation for migration from NAN
- Update documentation to better explain the use of NODE_ADDON_API
#### API
- Implement data manipulation methods for dataview
- Use built-in N-API on Node.js >= 6.14.2
- Value
- Added IsExternal()
- IsObject() allow functions
- String
- Fixed initialization of std::string to nullptr
#### Tests
- Fix test failures on linuxOne and AIX
- Added basic tests for Scopes
- Fix MSVC warning C4244 in tests
### Commits
* [386c2aeb74] - test: remove dep on later C++ feature (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/267
* [10697734da] - Use built-in N-API on Node.js >= 6.14.2 (Gabriel Schulhof)
* [75086da273] - test: add basic tests and doc for scopes (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/250
* [341dbd25d5] - doc: update blurb explaining NODE_ADDON_API (Gabriel Schulhof) https://github.com/nodejs/node-addon-api/pull/251
* [cf6c93e4ee] - don't try to escape null (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/245
* [15e4b35fc2] - test: fix MSVC warning C4244 in tests (Kyle Farnung) https://github.com/nodejs/node-addon-api/pull/236
* [7f3ca03b8e] - Create a doc for migration (Sampson Gao) https://github.com/nodejs/node-addon-api/pull/118
* [0a2177debe] - Fix test failures on linuxOne and AIX (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/232
* [d567f4b6b5] - Added Napi::Value::IsExternal() (Eric Bickle) https://github.com/nodejs/node-addon-api/pull/227
* [1b0f0e004a] - Update node-gyp.md (Michele Campus) https://github.com/nodejs/node-addon-api/pull/226
* [faf19c4f7a] - Fixed initialization of std::string to nullptr (Eric Bickle) https://github.com/nodejs/node-addon-api/pull/228
* [9c4d321b57] - Implement data manipulation methods for dataview (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/218
* [5a39fdca6f] - n-api: throw RangeError napi_create_typedarray() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/216
* [1376377202] - Make IsObject() allow functions (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/217
* [673b59d319] - src: Initial implementation of DataView class (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/205
* [0a899bf1c5] - doc: update indication of latest version (Michael Dawson) https://github.com/nodejs/node-addon-api/pull/211
* [17c74e5a5e] - n-api: RangeError in napi_create_dataview() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/214
* [4058a29989] - n-api: fix memory leak in napi_async_destroy() (Jinho Bang) https://github.com/nodejs/node-addon-api/pull/213

View File

@@ -0,0 +1,4 @@
# Code of Conduct
The Node.js Code of Conduct, which applies to this project, can be found at
https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md.

View File

@@ -0,0 +1,66 @@
# **node-addon-api** Contribution Philosophy
The **node-addon-api** team loves contributions. There are many ways in which you can
contribute to **node-addon-api**:
- Source code fixes
- Additional tests
- Documentation improvements
- Joining the N-API working group and participating in meetings
## Source changes
**node-addon-api** is meant to be a thin convenience wrapper around N-API. With this
in mind, contributions of any new APIs that wrap around a core N-API API will
be considered for merge. However, changes that wrap existing **node-addon-api**
APIs are encouraged to instead be provided as an ecosystem module. The
**node-addon-api** team is happy to link to a curated set of modules that build on
top of **node-addon-api** if they have broad usefulness to the community and promote
a recommended idiom or pattern.
### Rationale
The N-API team considered a couple different approaches with regards to changes
extending **node-addon-api**
- Larger core module - Incorporate these helpers and patterns into **node-addon-api**
- Extras package - Create a new package (strawman name '**node-addon-api**-extras')
that contain utility classes and methods that help promote good patterns and
idioms while writing native addons with **node-addon-api**.
- Ecosystem - Encourage creation of a module ecosystem around **node-addon-api**
where folks can build on top of it.
#### Larger Core
This is probably our simplest option in terms of immediate action needed. It
would involve landing any open PRs against **node-addon-api**, and continuing to
encourage folks to make PRs for utility helpers against the same repository.
The downside of the approach is the following:
- Less coherency for our API set
- More maintenance burden on the N-API WG core team.
#### Extras Package
This involves us spinning up a new package which contains the utility classes
and methods. This has the benefit of having a separate module where helpers
which make it easier to implement certain patterns and idioms for native addons
easier.
The downside of this approach is the following:
- Potential for confusion - we'll need to provide clear documentation to help the
community understand where a particular contribution should be directed to (what
belongs in **node-addon-api** vs **node-addon-api-extras**)
- Need to define the level of support/API guarantees
- Unclear if the maintenance burden on the N-API WG is reduced or not
#### Ecosystem
This doesn't require a ton of up-front work from the N-API WG. Instead of
accepting utility PRs into **node-addon-api** or creating and maintaining a new
module, the WG will encourage the creation of an ecosystem of modules that
build on top of **node-addon-api**, and provide some level of advertising for these
modules (listing them out on the repository/wiki, using them in workshops/tutorials
etc).
The downside of this approach is the following:
- Potential for lack of visibility - evangelism and education is hard, and module
authors might not find right patterns and instead implement things themselves
- There might be greater friction for the N-API WG in evolving APIs since the
ecosystem would have taken dependencies on the API shape of **node-addon-api**

View File

@@ -0,0 +1,13 @@
The MIT License (MIT)
=====================
Copyright (c) 2017 Node.js API collaborators
-----------------------------------
*Node.js API collaborators listed at <https://github.com/nodejs/node-addon-api#collaborators>*
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,200 @@
# **node-addon-api module**
This module contains **header-only C++ wrapper classes** which simplify
the use of the C based [N-API](https://nodejs.org/dist/latest/docs/api/n-api.html)
provided by Node.js when using C++. It provides a C++ object model
and exception handling semantics with low overhead.
N-API is an ABI stable C interface provided by Node.js for building native
addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore)
and is maintained as part of Node.js itself. It is intended to insulate
native addons from changes in the underlying JavaScript engine and allow
modules compiled for one version to run on later versions of Node.js without
recompilation.
The `node-addon-api` module, which is not part of Node.js, preserves the benefits
of the N-API as it consists only of inline code that depends only on the stable API
provided by N-API. As such, modules built against one version of Node.js
using node-addon-api should run without having to be rebuilt with newer versions
of Node.js.
It is important to remember that *other* Node.js interfaces such as
`libuv` (included in a project via `#include <uv.h>`) are not ABI-stable across
Node.js major versions. Thus, an addon must use N-API and/or `node-addon-api`
exclusively and build against a version of Node.js that includes an
implementation of N-API (meaning a version of Node.js newer than 6.14.2) in
order to benefit from ABI stability across Node.js major versions. Node.js
provides an [ABI stability guide][] containing a detailed explanation of ABI
stability in general, and the N-API ABI stability guarantee in particular.
As new APIs are added to N-API, node-addon-api must be updated to provide
wrappers for those new APIs. For this reason node-addon-api provides
methods that allow callers to obtain the underlying N-API handles so
direct calls to N-API and the use of the objects/methods provided by
node-addon-api can be used together. For example, in order to be able
to use an API for which the node-addon-api does not yet provide a wrapper.
APIs exposed by node-addon-api are generally used to create and
manipulate JavaScript values. Concepts and operations generally map
to ideas specified in the **ECMA262 Language Specification**.
- **[Setup](#setup)**
- **[API Documentation](#api)**
- **[Examples](#examples)**
- **[Tests](#tests)**
- **[More resource and info about native Addons](#resources)**
- **[Code of Conduct](CODE_OF_CONDUCT.md)**
- **[Contributors](#contributors)**
- **[License](#license)**
## **Current version: 1.7.2**
(See [CHANGELOG.md](CHANGELOG.md) for complete Changelog)
[![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/)
<a name="setup"></a>
## Setup
- [Installation and usage](doc/setup.md)
- [node-gyp](doc/node-gyp.md)
- [cmake-js](doc/cmake-js.md)
- [Conversion tool](doc/conversion-tool.md)
- [Checker tool](doc/checker-tool.md)
- [Generator](doc/generator.md)
- [Prebuild tools](doc/prebuild_tools.md)
<a name="api"></a>
### **API Documentation**
The following is the documentation for node-addon-api.
- [Basic Types](doc/basic_types.md)
- [Array](doc/basic_types.md#array)
- [Symbol](doc/symbol.md)
- [String](doc/string.md)
- [Name](doc/basic_types.md#name)
- [Number](doc/number.md)
- [BigInt](doc/bigint.md)
- [Boolean](doc/boolean.md)
- [Env](doc/env.md)
- [Value](doc/value.md)
- [CallbackInfo](doc/callbackinfo.md)
- [Reference](doc/reference.md)
- [External](doc/external.md)
- [Object](doc/object.md)
- [ObjectReference](doc/object_reference.md)
- [PropertyDescriptor](doc/property_descriptor.md)
- [Error Handling](doc/error_handling.md)
- [Error](doc/error.md)
- [TypeError](doc/type_error.md)
- [RangeError](doc/range_error.md)
- [Object Lifetime Management](doc/object_lifetime_management.md)
- [HandleScope](doc/handle_scope.md)
- [EscapableHandleScope](doc/escapable_handle_scope.md)
- [Working with JavaScript Values](doc/working_with_javascript_values.md)
- [Function](doc/function.md)
- [FunctionReference](doc/function_reference.md)
- [ObjectWrap](doc/object_wrap.md)
- [ClassPropertyDescriptor](doc/class_property_descriptor.md)
- [Buffer](doc/buffer.md)
- [ArrayBuffer](doc/array_buffer.md)
- [TypedArray](doc/typed_array.md)
- [TypedArrayOf](doc/typed_array_of.md)
- [DataView](doc/dataview.md)
- [Memory Management](doc/memory_management.md)
- [Async Operations](doc/async_operations.md)
- [AsyncWorker](doc/async_worker.md)
- [AsyncContext](doc/async_context.md)
- [Thread-safe Functions](doc/threadsafe_function.md)
- [Promises](doc/promises.md)
- [Version management](doc/version_management.md)
<a name="examples"></a>
### **Examples**
Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)**
- **[Hello World](https://github.com/nodejs/node-addon-examples/tree/master/1_hello_world/node-addon-api)**
- **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/master/2_function_arguments/node-addon-api)**
- **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/master/3_callbacks/node-addon-api)**
- **[Object factory](https://github.com/nodejs/node-addon-examples/tree/master/4_object_factory/node-addon-api)**
- **[Function factory](https://github.com/nodejs/node-addon-examples/tree/master/5_function_factory/node-addon-api)**
- **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/master/6_object_wrap/node-addon-api)**
- **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/master/7_factory_wrap/node-addon-api)**
- **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/master/8_passing_wrapped/node-addon-api)**
<a name="tests"></a>
### **Tests**
To run the **node-addon-api** tests do:
```
npm install
npm test
```
To avoid testing the deprecated portions of the API run
```
npm install
npm test --disable-deprecated
```
### **Debug**
To run the **node-addon-api** tests with `--debug` option:
```
npm run-script dev
```
If you want faster build, you might use the following option:
```
npm run-script dev:incremental
```
Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/master/test)**
<a name="resources"></a>
## **Contributing**
We love contributions from the community to **node-addon-api**.
See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module.
### **More resource and info about native Addons**
- **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)**
- **[N-API](https://nodejs.org/dist/latest/docs/api/n-api.html)**
- **[N-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)**
<a name="contributors"></a>
## WG Members / Collaborators
### Active
| Name | GitHub Link |
| ------------------- | ----------------------------------------------------- |
| Anna Henningsen | [addaleax](https://github.com/addaleax) |
| Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) |
| Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) |
| Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) |
| Jim Schlight | [jschlight](https://github.com/jschlight) |
| Michael Dawson | [mhdawson](https://github.com/mhdawson) |
| Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) |
| Taylor Woll | [boingoing](https://github.com/boingoing) |
### Emeritus
| Name | GitHub Link |
| ------------------- | ----------------------------------------------------- |
| Benjamin Byholm | [kkoopa](https://github.com/kkoopa) |
| Jason Ginchereau | [jasongin](https://github.com/jasongin) |
| Sampson Gao | [sampsongao](https://github.com/sampsongao) |
<a name="license"></a>
Licensed under [MIT](./LICENSE.md)
[ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,129 @@
# ArrayBuffer
The `Napi::ArrayBuffer` class corresponds to the
[JavaScript `ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
class.
## Methods
### New
Allocates a new `Napi::ArrayBuffer` instance with a given length.
```cpp
static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, size_t byteLength);
```
- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance.
- `[in] byteLength`: The length to be allocated, in bytes.
Returns a new `Napi::ArrayBuffer` instance.
### New
Wraps the provided external data into a new `Napi::ArrayBuffer` instance.
The `Napi::ArrayBuffer` instance does not assume ownership for the data and
expects it to be valid for the lifetime of the instance. Since the
`Napi::ArrayBuffer` is subject to garbage collection this overload is only
suitable for data which is static and never needs to be freed.
```cpp
static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env, void* externalData, size_t byteLength);
```
- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance.
- `[in] externalData`: The pointer to the external data to wrap.
- `[in] byteLength`: The length of the `externalData`, in bytes.
Returns a new `Napi::ArrayBuffer` instance.
### New
Wraps the provided external data into a new `Napi::ArrayBuffer` instance.
The `Napi::ArrayBuffer` instance does not assume ownership for the data and
expects it to be valid for the lifetime of the instance. The data can only be
freed once the `finalizeCallback` is invoked to indicate that the
`Napi::ArrayBuffer` has been released.
```cpp
template <typename Finalizer>
static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env,
void* externalData,
size_t byteLength,
Finalizer finalizeCallback);
```
- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance.
- `[in] externalData`: The pointer to the external data to wrap.
- `[in] byteLength`: The length of the `externalData`, in bytes.
- `[in] finalizeCallback`: A function to be called when the `Napi::ArrayBuffer` is
destroyed. It must implement `operator()`, accept a `void*` (which is the
`externalData` pointer), and return `void`.
Returns a new `Napi::ArrayBuffer` instance.
### New
Wraps the provided external data into a new `Napi::ArrayBuffer` instance.
The `Napi::ArrayBuffer` instance does not assume ownership for the data and expects it
to be valid for the lifetime of the instance. The data can only be freed once
the `finalizeCallback` is invoked to indicate that the `Napi::ArrayBuffer` has been
released.
```cpp
template <typename Finalizer, typename Hint>
static Napi::ArrayBuffer Napi::ArrayBuffer::New(napi_env env,
void* externalData,
size_t byteLength,
Finalizer finalizeCallback,
Hint* finalizeHint);
```
- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance.
- `[in] externalData`: The pointer to the external data to wrap.
- `[in] byteLength`: The length of the `externalData`, in bytes.
- `[in] finalizeCallback`: The function to be called when the `Napi::ArrayBuffer` is
destroyed. It must implement `operator()`, accept a `void*` (which is the
`externalData` pointer) and `Hint*`, and return `void`.
- `[in] finalizeHint`: The hint to be passed as the second parameter of the
finalize callback.
Returns a new `Napi::ArrayBuffer` instance.
### Constructor
Initializes an empty instance of the `Napi::ArrayBuffer` class.
```cpp
Napi::ArrayBuffer::ArrayBuffer();
```
### Constructor
Initializes a wrapper instance of an existing `Napi::ArrayBuffer` object.
```cpp
Napi::ArrayBuffer::ArrayBuffer(napi_env env, napi_value value);
```
- `[in] env`: The environment in which to create the `Napi::ArrayBuffer` instance.
- `[in] value`: The `Napi::ArrayBuffer` reference to wrap.
### ByteLength
```cpp
size_t Napi::ArrayBuffer::ByteLength() const;
```
Returns the length of the wrapped data, in bytes.
### Data
```cpp
T* Napi::ArrayBuffer::Data() const;
```
Returns a pointer the wrapped data.

View File

@@ -0,0 +1,76 @@
# AsyncContext
The [Napi::AsyncWorker](async_worker.md) class may not be appropriate for every
scenario. When using any other async mechanism, introducing a new class
`Napi::AsyncContext` is necessary to ensure an async operation is properly
tracked by the runtime. The `Napi::AsyncContext` class can be passed to
[Napi::Function::MakeCallback()](function.md) method to properly restore the
correct async execution context.
## Methods
### Constructor
Creates a new `Napi::AsyncContext`.
```cpp
explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name);
```
- `[in] env`: The environment in which to create the `Napi::AsyncContext`.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the `async_hooks` API.
### Constructor
Creates a new `Napi::AsyncContext`.
```cpp
explicit Napi::AsyncContext::AsyncContext(napi_env env, const char* resource_name, const Napi::Object& resource);
```
- `[in] env`: The environment in which to create the `Napi::AsyncContext`.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the `async_hooks` API.
- `[in] resource`: Object associated with the asynchronous operation that
will be passed to possible `async_hooks`.
### Destructor
The `Napi::AsyncContext` to be destroyed.
```cpp
virtual Napi::AsyncContext::~AsyncContext();
```
## Operator
```cpp
Napi::AsyncContext::operator napi_async_context() const;
```
Returns the N-API `napi_async_context` wrapped by the `Napi::AsyncContext`
object. This can be used to mix usage of the C N-API and node-addon-api.
## Example
```cpp
#include "napi.h"
void MakeCallbackWithAsyncContext(const Napi::CallbackInfo& info) {
Napi::Function callback = info[0].As<Napi::Function>();
Napi::Object resource = info[1].As<Napi::Object>();
// Creat a new async context instance.
Napi::AsyncContext context(info.Env(), "async_context_test", resource);
// Invoke the callback with the async context instance.
callback.MakeCallback(Napi::Object::New(info.Env()),
std::initializer_list<napi_value>{}, context);
// The async context instance is automatically destroyed here because it's
// block-scope like `Napi::HandleScope`.
}
```

View File

@@ -0,0 +1,31 @@
# Asynchronous operations
Node.js native add-ons often need to execute long running tasks and to avoid
blocking the **event loop** they have to run them asynchronously from the
**event loop**.
In the Node.js model of execution the event loop thread represents the thread
where JavaScript code is executing. The node.js guidance is to avoid blocking
other work queued on the event loop thread. Therefore, we need to do this work on
another thread.
All this means that native add-ons need to leverage async helpers from libuv as
part of their implementation. This allows them to schedule work to be executed
asynchronously so that their methods can return in advance of the work being
completed.
Node Addon API provides an interface to support functions that cover
the most common asynchronous use cases. There is an abstract classes to implement
asynchronous operations:
- **[`Napi::AsyncWorker`](async_worker.md)**
These class helps manage asynchronous operations through an abstraction
of the concept of moving data between the **event loop** and **worker threads**.
Also, the above class may not be appropriate for every scenario. When using any
other asynchronous mechanism, the following API is necessary to ensure an
asynchronous operation is properly tracked by the runtime:
- **[AsyncContext](async_context.md)**
- **[CallbackScope](callback_scope.md)**

View File

@@ -0,0 +1,397 @@
# AsyncWorker
`Napi::AsyncWorker` is an abstract class that you can subclass to remove many of
the tedious tasks of moving data between the event loop and worker threads. This
class internally handles all the details of creating and executing an asynchronous
operation.
Once created, execution is requested by calling `Napi::AsyncWorker::Queue`. When
a thread is available for execution the `Napi::AsyncWorker::Execute` method will
be invoked. Once `Napi::AsyncWorker::Execute` completes either
`Napi::AsyncWorker::OnOK` or `Napi::AsyncWorker::OnError` will be invoked. Once
the `Napi::AsyncWorker::OnOK` or `Napi::AsyncWorker::OnError` methods are
complete the `Napi::AsyncWorker` instance is destructed.
For the most basic use, only the `Napi::AsyncWorker::Execute` method must be
implemented in a subclass.
## Methods
### Env
Requests the environment in which the async worker has been initially created.
```cpp
Napi::Env Napi::AsyncWorker::Env() const;
```
Returns the environment in which the async worker has been created.
### Queue
Requests that the work be queued for execution.
```cpp
void Napi::AsyncWorker::Queue();
```
### Cancel
Cancels queued work if it has not yet been started. If it has already started
executing, it cannot be cancelled. If cancelled successfully neither
`OnOK` nor `OnError` will be called.
```cpp
void Napi::AsyncWorker::Cancel();
```
### Receiver
```cpp
Napi::ObjectReference& Napi::AsyncWorker::Receiver();
```
Returns the persistent object reference of the receiver object set when the async
worker was created.
### Callback
```cpp
Napi::FunctionReference& Napi::AsyncWorker::Callback();
```
Returns the persistent function reference of the callback set when the async
worker was created. The returned function reference will receive the results of
the computation that happened in the `Napi::AsyncWorker::Execute` method, unless
the default implementation of `Napi::AsyncWorker::OnOK` or
`Napi::AsyncWorker::OnError` is overridden.
### SuppressDestruct
```cpp
void Napi::AsyncWorker::SuppressDestruct();
```
Prevents the destruction of the `Napi::AsyncWorker` instance upon completion of
the `Napi::AsyncWorker::OnOK` callback.
### SetError
Sets the error message for the error that happened during the execution. Setting
an error message will cause the `Napi::AsyncWorker::OnError` method to be
invoked instead of `Napi::AsyncWorker::OnOK` once the
`Napi::AsyncWorker::Execute` method completes.
```cpp
void Napi::AsyncWorker::SetError(const std::string& error);
```
- `[in] error`: The reference to the string that represent the message of the error.
### Execute
This method is used to execute some tasks out of the **event loop** on a libuv
worker thread. Subclasses must implement this method and the method is run on
a thread other than that running the main event loop. As the method is not
running on the main event loop, it must avoid calling any methods from node-addon-api
or running any code that might invoke JavaScript. Instead, once this method is
complete any interaction through node-addon-api with JavaScript should be implemented
in the `Napi::AsyncWorker::OnOK` method which runs on the main thread and is
invoked when the `Napi::AsyncWorker::Execute` method completes.
```cpp
virtual void Napi::AsyncWorker::Execute() = 0;
```
### OnOK
This method is invoked when the computation in the `Execute` method ends.
The default implementation runs the Callback optionally provided when the AsyncWorker class
was created. The callback will by default receive no arguments. To provide arguments,
override the `GetResult()` method.
```cpp
virtual void Napi::AsyncWorker::OnOK();
```
### GetResult
This method returns the arguments passed to the Callback invoked by the default
`OnOK()` implementation. The default implementation returns an empty vector,
providing no arguments to the Callback.
```cpp
virtual std::vector<napi_value> Napi::AsyncWorker::GetResult(Napi::Env env);
```
### OnError
This method is invoked after `Napi::AsyncWorker::Execute` completes if an error
occurs while `Napi::AsyncWorker::Execute` is running and C++ exceptions are
enabled or if an error was set through a call to `Napi::AsyncWorker::SetError`.
The default implementation calls the callback provided when the `Napi::AsyncWorker`
class was created, passing in the error as the first parameter.
```cpp
virtual void Napi::AsyncWorker::OnError(const Napi::Error& e);
```
### Destroy
This method is invoked when the instance must be deallocated. If
`SuppressDestruct()` was not called then this method will be called after either
`OnError()` or `OnOK()` complete. The default implementation of this method
causes the instance to delete itself using the `delete` operator. The method is
provided so as to ensure that instances allocated by means other than the `new`
operator can be deallocated upon work completion.
```cpp
virtual void Napi::AsyncWorker::Destroy();
```
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(const Napi::Function& callback);
```
- `[in] callback`: The function which will be called when an asynchronous
operations ends. The given function is called from the main event loop thread.
Returns a `Napi::AsyncWorker` instance which can later be queued for execution by calling
`Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(const Napi::Function& callback, const char* resource_name);
```
- `[in] callback`: The function which will be called when an asynchronous
operations ends. The given function is called from the main event loop thread.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the async_hooks API.
Returns a `Napi::AsyncWorker` instance which can later be queued for execution by
calling `Napi::AsyncWork::Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(const Napi::Function& callback, const char* resource_name, const Napi::Object& resource);
```
- `[in] callback`: The function which will be called when an asynchronous
operations ends. The given function is called from the main event loop thread.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the async_hooks API.
- `[in] resource`: Object associated with the asynchronous operation that
will be passed to possible async_hooks.
Returns a `Napi::AsyncWorker` instance which can later be queued for execution by
calling `Napi::AsyncWork::Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(const Napi::Object& receiver, const Napi::Function& callback);
```
- `[in] receiver`: The `this` object passed to the called function.
- `[in] callback`: The function which will be called when an asynchronous
operations ends. The given function is called from the main event loop thread.
Returns a `Napi::AsyncWorker` instance which can later be queued for execution by
calling `Napi::AsyncWork::Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name);
```
- `[in] receiver`: The `this` object passed to the called function.
- `[in] callback`: The function which will be called when an asynchronous
operations ends. The given function is called from the main event loop thread.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the async_hooks API.
Returns a `Napi::AsyncWork` instance which can later be queued for execution by
calling `Napi::AsyncWork::Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(const Napi::Object& receiver, const Napi::Function& callback, const char* resource_name, const Napi::Object& resource);
```
- `[in] receiver`: The `this` object passed to the called function.
- `[in] callback`: The function which will be called when an asynchronous
operations ends. The given function is called from the main event loop thread.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the async_hooks API.
- `[in] resource`: Object associated with the asynchronous operation that
will be passed to possible async_hooks.
Returns a `Napi::AsyncWork` instance which can later be queued for execution by
calling `Napi::AsyncWork::Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(Napi::Env env);
```
- `[in] env`: The environment in which to create the `Napi::AsyncWorker`.
Returns an `Napi::AsyncWorker` instance which can later be queued for execution by calling
`Napi::AsyncWorker::Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(Napi::Env env, const char* resource_name);
```
- `[in] env`: The environment in which to create the `Napi::AsyncWorker`.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the async_hooks API.
Returns a `Napi::AsyncWorker` instance which can later be queued for execution by
calling `Napi::AsyncWorker::Queue`.
### Constructor
Creates a new `Napi::AsyncWorker`.
```cpp
explicit Napi::AsyncWorker(Napi::Env env, const char* resource_name, const Napi::Object& resource);
```
- `[in] env`: The environment in which to create the `Napi::AsyncWorker`.
- `[in] resource_name`: Null-terminated strings that represents the
identifier for the kind of resource that is being provided for diagnostic
information exposed by the async_hooks API.
- `[in] resource`: Object associated with the asynchronous operation that
will be passed to possible async_hooks.
Returns a `Napi::AsyncWorker` instance which can later be queued for execution by
calling `Napi::AsyncWorker::Queue`.
### Destructor
Deletes the created work object that is used to execute logic asynchronously.
```cpp
virtual Napi::AsyncWorker::~AsyncWorker();
```
## Operator
```cpp
Napi::AsyncWorker::operator napi_async_work() const;
```
Returns the N-API napi_async_work wrapped by the `Napi::AsyncWorker` object. This
can be used to mix usage of the C N-API and node-addon-api.
## Example
The first step to use the `Napi::AsyncWorker` class is to create a new class that
inherits from it and implement the `Napi::AsyncWorker::Execute` abstract method.
Typically input to your worker will be saved within class' fields generally
passed in through its constructor.
When the `Napi::AsyncWorker::Execute` method completes without errors the
`Napi::AsyncWorker::OnOK` function callback will be invoked. In this function the
results of the computation will be reassembled and returned back to the initial
JavaScript context.
`Napi::AsyncWorker` ensures that all the code in the `Napi::AsyncWorker::Execute`
function runs in the background out of the **event loop** thread and at the end
the `Napi::AsyncWorker::OnOK` or `Napi::AsyncWorker::OnError` function will be
called and are executed as part of the event loop.
The code below show a basic example of `Napi::AsyncWorker` the implementation:
```cpp
#include<napi.h>
#include <chrono>
#include <thread>
use namespace Napi;
class EchoWorker : public AsyncWorker {
public:
EchoWorker(Function& callback, std::string& echo)
: AsyncWorker(callback), echo(echo) {}
~EchoWorker() {}
// This code will be executed on the worker thread
void Execute() {
// Need to simulate cpu heavy task
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void OnOK() {
HandleScope scope(Env());
Callback().Call({Env().Null(), String::New(Env(), echo)});
}
private:
std::string echo;
};
```
The `EchoWorker`'s contructor calls the base class' constructor to pass in the
callback that the `Napi::AsyncWorker` base class will store persistently. When
the work on the `Napi::AsyncWorker::Execute` method is done the
`Napi::AsyncWorker::OnOk` method is called and the results return back to
JavaScript invoking the stored callback with its associated environment.
The following code shows an example on how to create and use an `Napi::AsyncWorker`
```cpp
#include<napi.h>
// Include EchoWorker class
// ..
use namespace Napi;
Value Echo(const CallbackInfo& info) {
// You need to check the input data here
Function cb = info[1].As<Function>();
std::string in = info[0].As<String>();
EchoWorker* wk = new EchoWorker(cb, in);
wk->Queue();
return info.Env().Undefined();
```
Using the implementation of a `Napi::AsyncWorker` is straight forward. You only
need to create a new instance and pass to its constructor the callback you want to
execute when your asynchronous task ends and other data you need for your
computation. Once created the only other action you have to do is to call the
`Napi::AsyncWorker::Queue` method that will queue the created worker for execution.

View File

@@ -0,0 +1,415 @@
# Basic Types
Node Addon API consists of a few fundamental data types. These allow a user of
the API to create, convert and introspect fundamental JavaScript types, and
interoperate with their C++ counterparts.
## Value
`Napi::Value` is the base class of Node Addon API's fundamental object type hierarchy.
It represents a JavaScript value of an unknown type. It is a thin wrapper around
the N-API datatype `napi_value`. Methods on this class can be used to check
the JavaScript type of the underlying N-API `napi_value` and also to convert to
C++ types.
### Constructor
```cpp
Napi::Value::Value();
```
Used to create a Node Addon API `Napi::Value` that represents an **empty** value.
```cpp
Napi::Value::Value(napi_env env, napi_value value);
```
- `[in] env` - The `napi_env` environment in which to construct the `Napi::Value`
object.
- `[in] value` - The underlying JavaScript value that the `Napi::Value` instance
represents.
Returns a Node.js Addon API `Napi::Value` that represents the `napi_value` passed
in.
### Operators
#### operator napi_value
```cpp
Napi::Value::operator napi_value() const;
```
Returns the underlying N-API `napi_value`. If the instance is _empty_, this
returns `nullptr`.
#### operator ==
```cpp
bool Napi::Value::operator ==(const Value& other) const;
```
Returns `true` if this value strictly equals another value, or `false` otherwise.
#### operator !=
```cpp
bool Napi::Value::operator !=(const Value& other) const;
```
Returns `false` if this value strictly equals another value, or `true` otherwise.
### Methods
#### From
```cpp
template <typename T>
static Napi::Value Napi::Value::From(napi_env env, const T& value);
```
- `[in] env` - The `napi_env` environment in which to construct the `Napi::Value` object.
- `[in] value` - The C++ type to represent in JavaScript.
Returns a `Napi::Value` representing the input C++ type in JavaScript.
This method is used to convert from a C++ type to a JavaScript value.
Here, `value` may be any of:
- `bool` - returns a `Napi::Boolean`.
- Any integer type - returns a `Napi::Number`.
- Any floating point type - returns a `Napi::Number`.
- `const char*` (encoded using UTF-8, null-terminated) - returns a `Napi::String`.
- `const char16_t*` (encoded using UTF-16-LE, null-terminated) - returns a `Napi::String`.
- `std::string` (encoded using UTF-8) - returns a `Napi::String`.
- `std::u16string` - returns a `Napi::String`.
- `napi::Value` - returns a `Napi::Value`.
- `napi_value` - returns a `Napi::Value`.
#### As
```cpp
template <typename T> T Napi::Value::As() const;
```
Returns the `Napi::Value` cast to a desired C++ type.
Use this when the actual type is known or assumed.
Note:
This conversion does NOT coerce the type. Calling any methods inappropriate for
the actual value type will throw `Napi::Error`.
#### StrictEquals
```cpp
bool Napi::Value::StrictEquals(const Value& other) const;
```
- `[in] other` - The value to compare against.
Returns true if the other `Napi::Value` is strictly equal to this one.
#### Env
```cpp
Napi::Env Napi::Value::Env() const;
```
Returns the environment that the value is associated with. See
[`Napi::Env`](env.md) for more details about environments.
#### IsEmpty
```cpp
bool Napi::Value::IsEmpty() const;
```
Returns `true` if the value is uninitialized.
An empty value is invalid, and most attempts to perform an operation on an
empty value will result in an exception. An empty value is distinct from
JavaScript `null` or `undefined`, which are valid values.
When C++ exceptions are disabled at compile time, a method with a `Napi::Value`
return type may return an empty value to indicate a pending exception. If C++
exceptions are not being used, callers should check the result of
`Env::IsExceptionPending` before attempting to use the value.
#### Type
```cpp
napi_valuetype Napi::Value::Type() const;
```
Returns the underlying N-API `napi_valuetype` of the value.
#### IsUndefined
```cpp
bool Napi::Value::IsUndefined() const;
```
Returns `true` if the underlying value is a JavaScript `undefined` or `false`
otherwise.
#### IsNull
```cpp
bool Napi::Value::IsNull() const;
```
Returns `true` if the underlying value is a JavaScript `null` or `false`
otherwise.
#### IsBoolean
```cpp
bool Napi::Value::IsBoolean() const;
```
Returns `true` if the underlying value is a JavaScript `true` or JavaScript
`false`, or `false` if the value is not a `Napi::Boolean` value in JavaScript.
#### IsNumber
```cpp
bool Napi::Value::IsNumber() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Number` or `false`
otherwise.
#### IsString
```cpp
bool Napi::Value::IsString() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::String` or `false`
otherwise.
#### IsSymbol
```cpp
bool Napi::Value::IsSymbol() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Symbol` or `false`
otherwise.
#### IsArray
```cpp
bool Napi::Value::IsArray() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Array` or `false`
otherwise.
#### IsArrayBuffer
```cpp
bool Napi::Value::IsArrayBuffer() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::ArrayBuffer` or `false`
otherwise.
#### IsTypedArray
```cpp
bool Napi::Value::IsTypedArray() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::TypedArray` or `false`
otherwise.
#### IsObject
```cpp
bool Napi::Value::IsObject() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Object` or `false`
otherwise.
#### IsFunction
```cpp
bool Napi::Value::IsFunction() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Function` or `false`
otherwise.
#### IsPromise
```cpp
bool Napi::Value::IsPromise() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::Promise` or `false`
otherwise.
#### IsDataView
```cpp
bool Napi::Value::IsDataView() const;
```
Returns `true` if the underlying value is a JavaScript `Napi::DataView` or `false`
otherwise.
#### IsBuffer
```cpp
bool Napi::Value::IsBuffer() const;
```
Returns `true` if the underlying value is a Node.js `Napi::Buffer` or `false`
otherwise.
#### IsExternal
```cpp
bool Napi::Value::IsExternal() const;
```
Returns `true` if the underlying value is a N-API external object or `false`
otherwise.
#### ToBoolean
```cpp
Napi::Boolean Napi::Value::ToBoolean() const;
```
Returns a `Napi::Boolean` representing the `Napi::Value`.
This is a wrapper around `napi_coerce_to_boolean`. This will throw a JavaScript
exception if the coercion fails. If C++ exceptions are not being used, callers
should check the result of `Env::IsExceptionPending` before attempting to use
the returned value.
#### ToNumber
```cpp
Napi::Number Napi::Value::ToNumber() const;
```
Returns a `Napi::Number` representing the `Napi::Value`.
Note:
This can cause script code to be executed according to JavaScript semantics.
This is a wrapper around `napi_coerce_to_number`. This will throw a JavaScript
exception if the coercion fails. If C++ exceptions are not being used, callers
should check the result of `Env::IsExceptionPending` before attempting to use
the returned value.
#### ToString
```cpp
Napi::String Napi::Value::ToString() const;
```
Returns a `Napi::String` representing the `Napi::Value`.
Note that this can cause script code to be executed according to JavaScript
semantics. This is a wrapper around `napi_coerce_to_string`. This will throw a
JavaScript exception if the coercion fails. If C++ exceptions are not being
used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
#### ToObject
```cpp
Napi::Object Napi::Value::ToObject() const;
```
Returns a `Napi::Object` representing the `Napi::Value`.
This is a wrapper around `napi_coerce_to_object`. This will throw a JavaScript
exception if the coercion fails. If C++ exceptions are not being used, callers
should check the result of `Env::IsExceptionPending` before attempting to use
the returned value.
## Name
Names are JavaScript values that can be used as a property name. There are two
specialized types of names supported in Node.js Addon API [`Napi::String`](string.md)
and [`Napi::Symbol`](symbol.md).
### Methods
#### Constructor
```cpp
Napi::Name::Name();
```
Returns an empty `Napi::Name`.
```cpp
Napi::Name::Name(napi_env env, napi_value value);
```
- `[in] env` - The environment in which to create the array.
- `[in] value` - The primitive to wrap.
Returns a `Napi::Name` created from the JavaScript primitive.
Note:
The value is not coerced to a string.
## Array
Arrays are native representations of JavaScript Arrays. `Napi::Array` is a wrapper
around `napi_value` representing a JavaScript Array.
[`Napi::TypedArray`][] and [`Napi::ArrayBuffer`][] correspond to JavaScript data
types such as [`Int32Array`][] and [`ArrayBuffer`][], respectively, that can be
used for transferring large amounts of data from JavaScript to the native side.
An example illustrating the use of a JavaScript-provided `ArrayBuffer` in native
code is available [here](https://github.com/nodejs/node-addon-examples/tree/master/array_buffer_to_native/node-addon-api).
### Constructor
```cpp
Napi::Array::Array();
```
Returns an empty array.
If an error occurs, a `Napi::Error` will be thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
```cpp
Napi::Array::Array(napi_env env, napi_value value);
```
- `[in] env` - The environment in which to create the array.
- `[in] value` - The primitive to wrap.
Returns a `Napi::Array` wrapping a `napi_value`.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
### Methods
#### New
```cpp
static Napi::Array Napi::Array::New(napi_env env);
```
- `[in] env` - The environment in which to create the array.
Returns a new `Napi::Array`.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
#### New
```cpp
static Napi::Array Napi::Array::New(napi_env env, size_t length);
```
- `[in] env` - The environment in which to create the array.
- `[in] length` - The length of the array.
Returns a new `Napi::Array` with the given length.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
#### Length
```cpp
uint32_t Napi::Array::Length() const;
```
Returns the length of the array.
Note:
This can execute JavaScript code implicitly according to JavaScript semantics.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
[`Napi::TypedArray`]: ./typed_array.md
[`Napi::ArrayBuffer`]: ./array_buffer.md
[`Int32Array`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Int32Array
[`ArrayBuffer`]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer

View File

@@ -0,0 +1,92 @@
# BigInt
A JavaScript BigInt value.
## Methods
### New
```cpp
static Napi::BigInt Napi::BigInt::New(Napi::Env env, int64_t value);
```
- `[in] env`: The environment in which to construct the `Napi::BigInt` object.
- `[in] value`: The value the JavaScript `BigInt` will contain
These APIs convert the C `int64_t` and `uint64_t` types to the JavaScript
`BigInt` type.
```cpp
static Napi::BigInt Napi::BigInt::New(Napi::Env env,
int sign_bit,
size_t word_count,
const uint64_t* words);
```
- `[in] env`: The environment in which to construct the `Napi::BigInt` object.
- `[in] sign_bit`: Determines if the resulting `BigInt` will be positive or negative.
- `[in] word_count`: The length of the words array.
- `[in] words`: An array of `uint64_t` little-endian 64-bit words.
This API converts an array of unsigned 64-bit words into a single `BigInt`
value.
The resulting `BigInt` is calculated as: (1)<sup>`sign_bit`</sup> (`words[0]`
× (2<sup>64</sup>)<sup>0</sup> + `words[1]` × (2<sup>64</sup>)<sup>1</sup> + …)
Returns a new JavaScript `BigInt`.
### Constructor
```cpp
Napi::BigInt();
```
Returns a new empty JavaScript `Napi::BigInt`.
### Int64Value
```cpp
int64_t Napi::BitInt::Int64Value(bool* lossless) const;
```
- `[out] lossless`: Indicates whether the `BigInt` value was converted losslessly.
Returns the C `int64_t` primitive equivalent of the given JavaScript
`BigInt`. If needed it will truncate the value, setting lossless to false.
### Uint64Value
```cpp
uint64_t Napi::BigInt::Uint64Value(bool* lossless) const;
```
- `[out] lossless`: Indicates whether the `BigInt` value was converted
losslessly.
Returns the C `uint64_t` primitive equivalent of the given JavaScript
`BigInt`. If needed it will truncate the value, setting lossless to false.
### WordCount
```cpp
size_t Napi::BigInt::WordCount() const;
```
Returns the number of words needed to store this `BigInt` value.
### ToWords
```cpp
void Napi::BigInt::ToWords(size_t* word_count, int* sign_bit, uint64_t* words);
```
- `[out] sign_bit`: Integer representing if the JavaScript `BigInt` is positive
or negative.
- `[in/out] word_count`: Must be initialized to the length of the words array.
Upon return, it will be set to the actual number of words that would be
needed to store this `BigInt`.
- `[out] words`: Pointer to a pre-allocated 64-bit word array.
Returns a single `BigInt` value into a sign bit, 64-bit little-endian array,
and the number of elements in the array.

View File

@@ -0,0 +1,64 @@
# Boolean
`Napi::Boolean` class is a representation of the JavaScript `Boolean` object. The
`Napi::Boolean` class inherits its behavior from the `Napi::Value` class
(for more info see: [`Napi::Value`](value.md)).
## Methods
### Constructor
Creates a new empty instance of an `Napi::Boolean` object.
```cpp
Napi::Boolean::Boolean();
```
Returns a new _empty_ `Napi::Boolean` object.
### Contructor
Creates a new instance of the `Napi::Boolean` object.
```cpp
Napi::Boolean(napi_env env, napi_value value);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Boolean` object.
- `[in] value`: The `napi_value` which is a handle for a JavaScript `Boolean`.
Returns a non-empty `Napi::Boolean` object.
### New
Initializes a new instance of the `Napi::Boolean` object.
```cpp
Napi::Boolean Napi::Boolean::New(napi_env env, bool value);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Boolean` object.
- `[in] value`: The primitive boolean value (`true` or `false`).
Returns a new instance of the `Napi::Boolean` object.
### Value
Converts a `Napi::Boolean` value to a boolean primitive.
```cpp
bool Napi::Boolean::Value() const;
```
Returns the boolean primitive type of the corresponding `Napi::Boolean` object.
## Operators
### operator bool
Converts a `Napi::Boolean` value to a boolean primitive.
```cpp
Napi::Boolean::operator bool() const;
```
Returns the boolean primitive type of the corresponding `Napi::Boolean` object.

View File

@@ -0,0 +1,140 @@
# Buffer
The `Napi::Buffer` class creates a projection of raw data that can be consumed by
script.
## Methods
### New
Allocates a new `Napi::Buffer` object with a given length.
```cpp
static Napi::Buffer<T> Napi::Buffer::New(napi_env env, size_t length);
```
- `[in] env`: The environment in which to create the `Napi::Buffer` object.
- `[in] length`: The number of `T` elements to allocate.
Returns a new `Napi::Buffer` object.
### New
Wraps the provided external data into a new `Napi::Buffer` object.
The `Napi::Buffer` object does not assume ownership for the data and expects it to be
valid for the lifetime of the object. Since the `Napi::Buffer` is subject to garbage
collection this overload is only suitable for data which is static and never
needs to be freed.
```cpp
static Napi::Buffer<T> Napi::Buffer::New(napi_env env, T* data, size_t length);
```
- `[in] env`: The environment in which to create the `Napi::Buffer` object.
- `[in] data`: The pointer to the external data to expose.
- `[in] length`: The number of `T` elements in the external data.
Returns a new `Napi::Buffer` object.
### New
Wraps the provided external data into a new `Napi::Buffer` object.
The `Napi::Buffer` object does not assume ownership for the data and expects it
to be valid for the lifetime of the object. The data can only be freed once the
`finalizeCallback` is invoked to indicate that the `Napi::Buffer` has been released.
```cpp
template <typename Finalizer>
static Napi::Buffer<T> Napi::Buffer::New(napi_env env,
T* data,
size_t length,
Finalizer finalizeCallback);
```
- `[in] env`: The environment in which to create the `Napi::Buffer` object.
- `[in] data`: The pointer to the external data to expose.
- `[in] length`: The number of `T` elements in the external data.
- `[in] finalizeCallback`: The function to be called when the `Napi::Buffer` is
destroyed. It must implement `operator()`, accept a `T*` (which is the
external data pointer), and return `void`.
Returns a new `Napi::Buffer` object.
### New
Wraps the provided external data into a new `Napi::Buffer` object.
The `Napi::Buffer` object does not assume ownership for the data and expects it to be
valid for the lifetime of the object. The data can only be freed once the
`finalizeCallback` is invoked to indicate that the `Napi::Buffer` has been released.
```cpp
template <typename Finalizer, typename Hint>
static Napi::Buffer<T> Napi::Buffer::New(napi_env env,
T* data,
size_t length,
Finalizer finalizeCallback,
Hint* finalizeHint);
```
- `[in] env`: The environment in which to create the `Napi::Buffer` object.
- `[in] data`: The pointer to the external data to expose.
- `[in] length`: The number of `T` elements in the external data.
- `[in] finalizeCallback`: The function to be called when the `Napi::Buffer` is
destroyed. It must implement `operator()`, accept a `T*` (which is the
external data pointer) and `Hint*`, and return `void`.
- `[in] finalizeHint`: The hint to be passed as the second parameter of the
finalize callback.
Returns a new `Napi::Buffer` object.
### Copy
Allocates a new `Napi::Buffer` object and copies the provided external data into it.
```cpp
static Napi::Buffer<T> Napi::Buffer::Copy(napi_env env, const T* data, size_t length);
```
- `[in] env`: The environment in which to create the `Napi::Buffer` object.
- `[in] data`: The pointer to the external data to copy.
- `[in] length`: The number of `T` elements in the external data.
Returns a new `Napi::Buffer` object containing a copy of the data.
### Constructor
Initializes an empty instance of the `Napi::Buffer` class.
```cpp
Napi::Buffer::Buffer();
```
### Constructor
Initializes the `Napi::Buffer` object using an existing Uint8Array.
```cpp
Napi::Buffer::Buffer(napi_env env, napi_value value);
```
- `[in] env`: The environment in which to create the `Napi::Buffer` object.
- `[in] value`: The Uint8Array reference to wrap.
### Data
```cpp
T* Napi::Buffer::Data() const;
```
Returns a pointer the external data.
### Length
```cpp
size_t Napi::Buffer::Length() const;
```
Returns the number of `T` elements in the external data.

View File

@@ -0,0 +1,54 @@
# CallbackScope
There are cases (for example, resolving promises) where it is necessary to have
the equivalent of the scope associated with a callback in place when making
certain N-API calls.
## Methods
### Constructor
Creates a new callback scope on the stack.
```cpp
Napi::CallbackScope::CallbackScope(napi_env env, napi_callback_scope scope);
```
- `[in] env`: The environment in which to create the `Napi::CallbackScope`.
- `[in] scope`: The pre-existing `napi_callback_scope` or `Napi::CallbackScope`.
### Constructor
Creates a new callback scope on the stack.
```cpp
Napi::CallbackScope::CallbackScope(napi_env env, napi_async_context context);
```
- `[in] env`: The environment in which to create the `Napi::CallbackScope`.
- `[in] async_context`: The pre-existing `napi_async_context` or `Napi::AsyncContext`.
### Destructor
Deletes the instance of `Napi::CallbackScope` object.
```cpp
virtual Napi::CallbackScope::~CallbackScope();
```
### Env
```cpp
Napi::Env Napi::CallbackScope::Env() const;
```
Returns the `Napi::Env` associated with the `Napi::CallbackScope`.
## Operator
```cpp
Napi::CallbackScope::operator napi_callback_scope() const;
```
Returns the N-API `napi_callback_scope` wrapped by the `Napi::CallbackScope`
object. This can be used to mix usage of the C N-API and node-addon-api.

View File

@@ -0,0 +1,97 @@
# CallbackInfo
The object representing the components of the JavaScript request being made.
The `Napi::CallbackInfo` object is usually created and passed by the Node.js runtime or node-addon-api infrastructure.
The `Napi::CallbackInfo` object contains the arguments passed by the caller. The number of arguments is returned by the `Length` method. Each individual argument can be accessed using the `operator[]` method.
The `SetData` and `Data` methods are used to set and retrieve the data pointer contained in the `Napi::CallbackInfo` object.
## Methods
### Constructor
```cpp
Napi::CallbackInfo::CallbackInfo(napi_env env, napi_callback_info info);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::CallbackInfo` object.
- `[in] info`: The `napi_callback_info` data structure from which to construct the `Napi::CallbackInfo` object.
### Env
```cpp
Napi::Env Napi::CallbackInfo::Env() const;
```
Returns the `Env` object in which the request is being made.
### NewTarget
```cpp
Napi::Value Napi::CallbackInfo::NewTarget() const;
```
Returns the `new.target` value of the constructor call. If the function that was invoked (and for which the `Napi::NCallbackInfo` was passed) is not a constructor call, a call to `IsEmpty()` on the returned value returns true.
### IsConstructCall
```cpp
bool Napi::CallbackInfo::IsConstructCall() const;
```
Returns a `bool` indicating if the function that was invoked (and for which the `Napi::CallbackInfo` was passed) is a constructor call.
### Length
```cpp
size_t Napi::CallbackInfo::Length() const;
```
Returns the number of arguments passed in the `Napi::CallbackInfo` object.
### operator []
```cpp
const Napi::Value operator [](size_t index) const;
```
- `[in] index`: The zero-based index of the requested argument.
Returns a `Napi::Value` object containing the requested argument.
### This
```cpp
Napi::Value Napi::CallbackInfo::This() const;
```
Returns the JavaScript `this` value for the call
### Data
```cpp
void* Napi::CallbackInfo::Data() const;
```
Returns the data pointer for the callback.
### SetData
```cpp
void Napi::CallbackInfo::SetData(void* data);
```
- `[in] data`: The new data pointer to associate with this `Napi::CallbackInfo` object.
Returns `void`.
### Not documented here
```cpp
Napi::CallbackInfo::~CallbackInfo();
// Disallow copying to prevent multiple free of _dynamicArgs
Napi::CallbackInfo::CallbackInfo(CallbackInfo const &) = delete;
void Napi::CallbackInfo::operator=(CallbackInfo const &) = delete;
```

View File

@@ -0,0 +1,32 @@
# Checker Tool
**node-addon-api** provides a [checker tool][] that will inspect a given
directory tree, identifying all Node.js native addons therein, and further
indicating for each addon whether it is an N-API addon.
## To use the checker tool:
1. Install the application with `npm install`.
2. If the application does not depend on **node-addon-api**, copy the
checker tool into the application's directory.
3. If the application does not depend on **node-addon-api**, run the checker
tool from the application's directory:
```sh
node ./check-napi.js
```
Otherwise, the checker tool can be run from the application's
`node_modules/` subdirectory:
```sh
node ./node_modules/node-addon-api/tools/check-napi.js
```
The tool accepts the root directory from which to start checking for Node.js
native addons as a single optional command line parameter. If ommitted it will
start checking from the current directory (`.`).
[checker tool]: ../tools/check-napi.js

View File

@@ -0,0 +1,118 @@
# Class property and descriptor
Property descriptor for use with `Napi::ObjectWrap::DefineClass()`.
This is different from the standalone `Napi::PropertyDescriptor` because it is
specific to each `Napi::ObjectWrap<T>` subclass.
This prevents using descriptors from a different class when defining a new class
(preventing the callbacks from having incorrect `this` pointers).
## Example
```cpp
#include <napi.h>
class Example : public Napi::ObjectWrap<Example> {
public:
static Napi::Object Init(Napi::Env env, Napi::Object exports);
Example(const Napi::CallbackInfo &info);
private:
static Napi::FunctionReference constructor;
double _value;
Napi::Value GetValue(const Napi::CallbackInfo &info);
Napi::Value SetValue(const Napi::CallbackInfo &info);
};
Napi::Object Example::Init(Napi::Env env, Napi::Object exports) {
Napi::Function func = DefineClass(env, "Example", {
// Register a class instance accessor with getter and setter functions.
InstanceAccessor("value", &Example::GetValue, &Example::SetValue),
// We can also register a readonly accessor by passing nullptr as the setter.
InstanceAccessor("readOnlyProp", &Example::GetValue, nullptr)
});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("Example", func);
return exports;
}
Example::Example(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Example>(info) {
Napi::Env env = info.Env();
// ...
Napi::Number value = info[0].As<Napi::Number>();
this->_value = value.DoubleValue();
}
Napi::FunctionReference Example::constructor;
Napi::Value Example::GetValue(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
return Napi::Number::New(env, this->_value);
}
Napi::Value Example::SetValue(const Napi::CallbackInfo &info, const Napi::Value &value) {
Napi::Env env = info.Env();
// ...
Napi::Number arg = value.As<Napi::Number>();
this->_value = arg.DoubleValue();
return this->GetValue(info);
}
// Initialize native add-on
Napi::Object Init (Napi::Env env, Napi::Object exports) {
Example::Init(env, exports);
return exports;
}
// Register and initialize native add-on
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
```
The above code can be used from JavaScript as follows:
```js
'use strict';
const { Example } = require('bindings')('addon');
const example = new Example(11);
console.log(example.value);
// It prints 11
example.value = 19;
console.log(example.value);
// It prints 19
example.readOnlyProp = 500;
console.log(example.readOnlyProp);
// Unchanged. It prints 19
```
## Methods
### Constructor
Creates new instance of `Napi::ClassPropertyDescriptor` descriptor object.
```cpp
Napi::ClassPropertyDescriptor(napi_property_descriptor desc) : _desc(desc) {}
```
- `[in] desc`: The `napi_property_descriptor`
Returns new instance of `Napi::ClassPropertyDescriptor` that is used as property descriptor
inside the `Napi::ObjectWrap<T>` class.
### Operator
```cpp
operator napi_property_descriptor&() { return _desc; }
```
Returns the original N-API `napi_property_descriptor` wrapped inside the `Napi::ClassPropertyDescriptor`
```cpp
operator const napi_property_descriptor&() const { return _desc; }
```
Returns the original N-API `napi_property_descriptor` wrapped inside the `Napi::ClassPropertyDescriptor`

View File

@@ -0,0 +1,19 @@
# CMake.js
**CMake.js** is a build tool that allow native addon developer to compile their
C++ code into executable form. It works like **[node-gyp](node-gyp.md)** but
instead of Google's **gyp** format it is base on **CMake** build system.
## **CMake** reference
- [Installation](https://www.npmjs.com/package/cmake-js#installation)
- [How to use](https://www.npmjs.com/package/cmake-js#usage)
- [Using N-API and node-addon-api](https://github.com/cmake-js/cmake-js#n-api-and-node-addon-api)
- [Tutorials](https://www.npmjs.com/package/cmake-js#tutorials)
- [Use case in the works - ArrayFire.js](https://www.npmjs.com/package/cmake-js#use-case-in-the-works---arrayfirejs)
Sometimes finding the right settings is not easy so to accomplish at most
complicated task please refer to:
- [CMake documentation](https://cmake.org/)
- [CMake.js wiki](https://github.com/cmake-js/cmake-js/wiki)

View File

@@ -0,0 +1,28 @@
# Conversion Tool
To make the migration to **node-addon-api** easier, we have provided a script to
help complete some tasks.
## To use the conversion script:
1. Go to your module directory
```
cd [module_path]
```
2. Install node-addon-api module
```
npm install node-addon-api
```
3. Run node-addon-api conversion script
```
node ./node_modules/node-addon-api/tools/conversion.js ./
```
4. While this script makes conversion easier, it still cannot fully convert
the module. The next step is to try to build the module and complete the
remaining conversions necessary to allow it to compile and pass all of the
module's tests.

View File

@@ -0,0 +1,62 @@
# Creating a release
Only collaborators in npm for **node-addon-api** can create releases.
If you want to be able to do releases ask one of the existing
collaborators to add you. If necessary you can ask the build
Working Group who manages the Node.js npm user to add you if
there are no other active collaborators.
## Prerequisites
Before to start creating a new release check if you have installed the following
tools:
* [Changelog maker](https://www.npmjs.com/package/changelog-maker)
If not please follow the instruction reported in the tool's documentation to
install it.
## Publish new release
These are the steps to follow to create a new release:
* Open an issue in the **node-addon-api** repo documenting the intent to create a
new release. Give people some time to comment or suggest PRs that should land first.
* Validate all tests pass by running npm test on master.
* Update the version in **package.json** appropriately.
* Update the [README.md](https://github.com/nodejs/node-addon-api/blob/master/README.md)
to show the new version as the latest.
* Generate the changelog for the new version using **changelog maker** tool. From
the route folder of the repo launch the following command:
```bash
> changelog-maker
```
* Use the output generated by **changelog maker** to pdate the [CHANGELOG.md](https://github.com/nodejs/node-addon-api/blob/master/CHANGELOG.md)
following the style used in publishing the previous release.
* Add any new contributors to the "contributors" section in the package.json
* Validate all tests pass by running npm test on master.
* Use **[CI](https://ci.nodejs.org/view/x%20-%20Abi%20stable%20module%20API/job/node-test-node-addon-api/)**
to validate tests pass for latest 11, 10, 8, 6 releases (note there are still some issues on SmartOS and
Windows in the testing).
* Do a clean checkout of node-addon-api.
* Login and then run `npm publish`.
* Create a release in Github (look at existing releases for an example).
* Validate that you can run `npm install node-addon-api` successfully
and that the correct version is installed.
* Comment on the issue opened in the first step that the release has been created
and close the issue.
* Tweet that the release has been created.

View File

@@ -0,0 +1,244 @@
# DataView
The `Napi::DataView` class corresponds to the
[JavaScript `DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)
class.
## Methods
### New
Allocates a new `Napi::DataView` instance with a given `Napi::ArrayBuffer`.
```cpp
static Napi::DataView Napi::DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer);
```
- `[in] env`: The environment in which to create the `Napi::DataView` instance.
- `[in] arrayBuffer` : `Napi::ArrayBuffer` underlying the `Napi::DataView`.
Returns a new `Napi::DataView` instance.
### New
Allocates a new `Napi::DataView` instance with a given `Napi::ArrayBuffer`.
```cpp
static Napi::DataView Napi::DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset);
```
- `[in] env`: The environment in which to create the `Napi::DataView` instance.
- `[in] arrayBuffer` : `Napi::ArrayBuffer` underlying the `Napi::DataView`.
- `[in] byteOffset` : The byte offset within the `Napi::ArrayBuffer` from which to start projecting the `Napi::DataView`.
Returns a new `Napi::DataView` instance.
### New
Allocates a new `Napi::DataView` instance with a given `Napi::ArrayBuffer`.
```cpp
static Napi::DataView Napi::DataView::New(napi_env env, Napi::ArrayBuffer arrayBuffer, size_t byteOffset, size_t byteLength);
```
- `[in] env`: The environment in which to create the `Napi::DataView` instance.
- `[in] arrayBuffer` : `Napi::ArrayBuffer` underlying the `Napi::DataView`.
- `[in] byteOffset` : The byte offset within the `Napi::ArrayBuffer` from which to start projecting the `Napi::DataView`.
- `[in] byteLength` : Number of elements in the `Napi::DataView`.
Returns a new `Napi::DataView` instance.
### Constructor
Initializes an empty instance of the `Napi::DataView` class.
```cpp
Napi::DataView();
```
### Constructor
Initializes a wrapper instance of an existing `Napi::DataView` instance.
```cpp
Napi::DataView(napi_env env, napi_value value);
```
- `[in] env`: The environment in which to create the `Napi::DataView` instance.
- `[in] value`: The `Napi::DataView` reference to wrap.
### ArrayBuffer
```cpp
Napi::ArrayBuffer Napi::DataView::ArrayBuffer() const;
```
Returns the backing array buffer.
### ByteOffset
```cpp
size_t Napi::DataView::ByteOffset() const;
```
Returns the offset into the `Napi::DataView` where the array starts, in bytes.
### ByteLength
```cpp
size_t Napi::DataView::ByteLength() const;
```
Returns the length of the array, in bytes.
### GetFloat32
```cpp
float Napi::DataView::GetFloat32(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a signed 32-bit float (float) at the specified byte offset from the start of the `Napi::DataView`.
### GetFloat64
```cpp
double Napi::DataView::GetFloat64(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a signed 64-bit float (double) at the specified byte offset from the start of the `Napi::DataView`.
### GetInt8
```cpp
int8_t Napi::DataView::GetInt8(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a signed 8-bit integer (byte) at the specified byte offset from the start of the `Napi::DataView`.
### GetInt16
```cpp
int16_t Napi::DataView::GetInt16(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a signed 16-bit integer (short) at the specified byte offset from the start of the `Napi::DataView`.
### GetInt32
```cpp
int32_t Napi::DataView::GetInt32(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a signed 32-bit integer (long) at the specified byte offset from the start of the `Napi::DataView`.
### GetUint8
```cpp
uint8_t Napi::DataView::GetUint8(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a unsigned 8-bit integer (unsigned byte) at the specified byte offset from the start of the `Napi::DataView`.
### GetUint16
```cpp
uint16_t Napi::DataView::GetUint16(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a unsigned 16-bit integer (unsigned short) at the specified byte offset from the start of the `Napi::DataView`.
### GetUint32
```cpp
uint32_t Napi::DataView::GetUint32(size_t byteOffset) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
Returns a unsigned 32-bit integer (unsigned long) at the specified byte offset from the start of the `Napi::DataView`.
### SetFloat32
```cpp
void Napi::DataView::SetFloat32(size_t byteOffset, float value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.
### SetFloat64
```cpp
void Napi::DataView::SetFloat64(size_t byteOffset, double value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.
### SetInt8
```cpp
void Napi::DataView::SetInt8(size_t byteOffset, int8_t value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.
### SetInt16
```cpp
void Napi::DataView::SetInt16(size_t byteOffset, int16_t value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.
### SetInt32
```cpp
void Napi::DataView::SetInt32(size_t byteOffset, int32_t value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.
### SetUint8
```cpp
void Napi::DataView::SetUint8(size_t byteOffset, uint8_t value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.
### SetUint16
```cpp
void Napi::DataView::SetUint16(size_t byteOffset, uint16_t value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.
### SetUint32
```cpp
void Napi::DataView::SetUint32(size_t byteOffset, uint32_t value) const;
```
- `[in] byteOffset`: The offset, in byte, from the start of the view where to read the data.
- `[in] value`: The value to set.

View File

@@ -0,0 +1,63 @@
# Env
The opaque data structure containing the environment in which the request is being run.
The Env object is usually created and passed by the Node.js runtime or node-addon-api infrastructure.
## Methods
### Constructor
```cpp
Napi::Env::Env(napi_env env);
```
- `[in] env`: The `napi_env` environment from which to construct the `Napi::Env` object.
### napi_env
```cpp
operator napi_env() const;
```
Returns the `napi_env` opaque data structure representing the environment.
### Global
```cpp
Napi::Object Napi::Env::Global() const;
```
Returns the `Napi::Object` representing the environment's JavaScript Global Object.
### Undefined
```cpp
Napi::Value Napi::Env::Undefined() const;
```
Returns the `Napi::Value` representing the environment's JavaScript Undefined Object.
### Null
```cpp
Napi::Value Napi::Env::Null() const;
```
Returns the `Napi::Value` representing the environment's JavaScript Null Object.
### IsExceptionPending
```cpp
bool Napi::Env::IsExceptionPending() const;
```
Returns a `bool` indicating if an exception is pending in the environment.
### GetAndClearPendingException
```cpp
Napi::Error Napi::Env::GetAndClearPendingException();
```
Returns an `Napi::Error` object representing the environment's pending exception, if any.

View File

@@ -0,0 +1,115 @@
# Error
The `Napi::Error` class is a representation of the JavaScript `Error` object that is thrown
when runtime errors occur. The Error object can also be used as a base object for
user-defined exceptions.
The `Napi::Error` class is a persistent reference to a JavaScript error object thus
inherits its behavior from the `Napi::ObjectReference` class (for more info see: [`Napi::ObjectReference`](object_reference.md)).
If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the
`Napi::Error` class extends `std::exception` and enables integrated
error-handling for C++ exceptions and JavaScript exceptions.
For more details about error handling refer to the section titled [Error handling](error_handling.md).
## Methods
### New
Creates empty instance of an `Napi::Error` object for the specified environment.
```cpp
Napi::Error::New(Napi::Env env);
```
- `[in] env`: The environment in which to construct the `Napi::Error` object.
Returns an instance of `Napi::Error` object.
### New
Creates instance of an `Napi::Error` object.
```cpp
Napi::Error::New(Napi::Env env, const char* message);
```
- `[in] env`: The environment in which to construct the `Napi::Error` object.
- `[in] message`: Null-terminated string to be used as the message for the `Napi::Error`.
Returns instance of an `Napi::Error` object.
### New
Creates instance of an `Napi::Error` object
```cpp
Napi::Error::New(Napi::Env env, const std::string& message);
```
- `[in] env`: The environment in which to construct the `Napi::Error` object.
- `[in] message`: Reference string to be used as the message for the `Napi::Error`.
Returns instance of an `Napi::Error` object.
### Fatal
In case of an unrecoverable error in a native module, a fatal error can be thrown
to immediately terminate the process.
```cpp
static NAPI_NO_RETURN void Napi::Error::Fatal(const char* location, const char* message);
```
The function call does not return, the process will be terminated.
### Constructor
Creates empty instance of an `Napi::Error`.
```cpp
Napi::Error::Error();
```
Returns an instance of `Napi::Error` object.
### Constructor
Initializes an `Napi::Error` instance from an existing JavaScript error object.
```cpp
Napi::Error::Error(napi_env env, napi_value value);
```
- `[in] env`: The environment in which to construct the error object.
- `[in] value`: The `Napi::Error` reference to wrap.
Returns instance of an `Napi::Error` object.
### Message
```cpp
std::string& Napi::Error::Message() const NAPI_NOEXCEPT;
```
Returns the reference to the string that represent the message of the error.
### ThrowAsJavaScriptException
Throw the error as JavaScript exception.
```cpp
void Napi::Error::ThrowAsJavaScriptException() const;
```
Throws the error as a JavaScript exception.
### what
```cpp
const char* Napi::Error::what() const NAPI_NOEXCEPT override;
```
Returns a pointer to a null-terminated string that is used to identify the
exception. This method can be used only if the exception mechanism is enabled.

View File

@@ -0,0 +1,186 @@
# Error handling
Error handling represents one of the most important considerations when
implementing a Node.js native add-on. When an error occurs in your C++ code you
have to handle and dispatch it correctly. **node-addon-api** uses return values and
JavaScript exceptions for error handling. You can choose return values or
exception handling based on the mechanism that works best for your add-on.
The `Napi::Error` is a persistent reference (for more info see: [`Napi::ObjectReference`](object_reference.md))
to a JavaScript error object. Use of this class depends on whether C++
exceptions are enabled at compile time.
If C++ exceptions are enabled (for more info see: [Setup](setup.md)), then the
`Napi::Error` class extends `std::exception` and enables integrated
error-handling for C++ exceptions and JavaScript exceptions.
The following sections explain the approach for each case:
- [Handling Errors With C++ Exceptions](#exceptions)
- [Handling Errors Without C++ Exceptions](#noexceptions)
<a name="exceptions"></a>
In most cases when an error occurs, the addon should do whatever clean is possible
and then return to JavaScript so that they error can be propagated. In less frequent
cases the addon may be able to recover from the error, clear the error and then
continue.
## Handling Errors With C++ Exceptions
When C++ exceptions are enabled try/catch can be used to catch exceptions thrown
from calls to JavaScript and then they can either be handled or rethrown before
returning from a native method.
If a node-addon-api call fails without executing any JavaScript code (for example due to
an invalid argument), then node-addon-api automatically converts and throws
the error as a C++ exception of type `Napi::Error`.
If a JavaScript function called by C++ code via node-addon-api throws a JavaScript
exception, then node-addon-api automatically converts and throws it as a C++
exception of type `Napi:Error` on return from the JavaScript code to the native
method.
If a C++ exception of type `Napi::Error` escapes from a N-API C++ callback, then
the N-API wrapper automatically converts and throws it as a JavaScript exception.
On return from a native method, node-addon-api will automatically convert a pending C++
exception to a JavaScript exception.
When C++ exceptions are enabled try/catch can be used to catch exceptions thrown
from calls to JavaScript and then they can either be handled or rethrown before
returning from a native method.
## Examples with C++ exceptions enabled
### Throwing a C++ exception
```cpp
Env env = ...
throw Napi::Error::New(env, "Example exception");
// other C++ statements
// ...
```
The statements following the throw statement will not be executed. The exception
will bubble up as a C++ exception of type `Napi::Error`, until it is either caught
while still in C++, or else automatically propagated as a JavaScript exception
when returning to JavaScript.
### Propagating a N-API C++ exception
```cpp
Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
// other C++ statements
// ...
```
The C++ statements following the call to the JavaScript function will not be
executed. The exception will bubble up as a C++ exception of type `Napi::Error`,
until it is either caught while still in C++, or else automatically propagated as
a JavaScript exception when returning to JavaScript.
### Handling a N-API C++ exception
```cpp
Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
Napi::Value result;
try {
result = jsFunctionThatThrows({ arg1, arg2 });
} catch (const Error& e) {
cerr << "Caught JavaScript exception: " + e.what();
}
```
Since the exception was caught here, it will not be propagated as a JavaScript
exception.
<a name="noexceptions"></a>
## Handling Errors Without C++ Exceptions
If C++ exceptions are disabled (for more info see: [Setup](setup.md)), then the
`Napi::Error` class does not extend `std::exception`. This means that any calls to
node-addon-api function do not throw a C++ exceptions. Instead, it raises
_pending_ JavaScript exceptions and returns an _empty_ `Napi::Value`.
The calling code should check `env.IsExceptionPending()` before attempting to use a
returned value, and may use methods on the `Napi::Env` class
to check for, get, and clear a pending JavaScript exception (for more info see: [Env](env.md)).
If the pending exception is not cleared, it will be thrown when the native code
returns to JavaScript.
## Examples with C++ exceptions disabled
### Throwing a JS exception
```cpp
Napi::Env env = ...
Napi::Error::New(env, "Example exception").ThrowAsJavaScriptException();
return;
```
After throwing a JavaScript exception, the code should generally return
immediately from the native callback, after performing any necessary cleanup.
### Propagating a N-API JS exception
```cpp
Napi::Env env = ...
Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
if (env.IsExceptionPending()) {
Error e = env.GetAndClearPendingException();
return e.Value();
}
```
If env.IsExceptionPending() returns true a JavaScript exception is pending. To
let the exception propagate, the code should generally return immediately from
the native callback, after performing any necessary cleanup.
### Handling a N-API JS exception
```cpp
Napi::Env env = ...
Napi::Function jsFunctionThatThrows = someObj.As<Napi::Function>();
Napi::Value result = jsFunctionThatThrows({ arg1, arg2 });
if (env.IsExceptionPending()) {
Napi::Error e = env.GetAndClearPendingException();
cerr << "Caught JavaScript exception: " + e.Message();
}
```
Since the exception was cleared here, it will not be propagated as a JavaScript
exception after the native callback returns.
## Calling N-API directly from a **node-addon-api** addon
**node-addon-api** provides macros for throwing errors in response to non-OK
`napi_status` results when calling [N-API](https://nodejs.org/docs/latest/api/n-api.html)
functions from within a native addon. These macros are defined differently
depending on whether C++ exceptions are enabled or not, but are available for
use in either case.
### `NAPI_THROW(e, ...)`
This macro accepts a `Napi::Error`, throws it, and returns the value given as
the last parameter. If C++ exceptions are enabled (by defining
`NAPI_CPP_EXCEPTIONS` during the build), the return value will be ignored.
### `NAPI_THROW_IF_FAILED(env, status, ...)`
This macro accepts a `Napi::Env` and a `napi_status`. It constructs an error
from the `napi_status`, throws it, and returns the value given as the last
parameter. If C++ exceptions are enabled (by defining `NAPI_CPP_EXCEPTIONS`
during the build), the return value will be ignored.
### `NAPI_THROW_IF_FAILED_VOID(env, status)`
This macro accepts a `Napi::Env` and a `napi_status`. It constructs an error
from the `napi_status`, throws it, and returns.
### `NAPI_FATAL_IF_FAILED(status, location, message)`
This macro accepts a `napi_status`, a C string indicating the location where the
error occurred, and a second C string for the message to display.

View File

@@ -0,0 +1,82 @@
# EscapableHandleScope
The `Napi::EscapableHandleScope` class is used to manage the lifetime of object handles
which are created through the use of node-addon-api. These handles
keep an object alive in the heap in order to ensure that the objects
are not collected by the garbage collector while native code is using them.
A handle may be created when any new node-addon-api Value or one
of its subclasses is created or returned.
The `Napi::EscapableHandleScope` is a special type of `Napi::HandleScope`
which allows a single handle to be "promoted" to an outer scope.
For more details refer to the section titled
[Object lifetime management](object_lifetime_management.md).
## Methods
### Constructor
Creates a new escapable handle scope.
```cpp
Napi::EscapableHandleScope Napi::EscapableHandleScope::New(Napi:Env env);
```
- `[in] Env`: The environment in which to construct the `Napi::EscapableHandleScope` object.
Returns a new `Napi::EscapableHandleScope`
### Constructor
Creates a new escapable handle scope.
```cpp
Napi::EscapableHandleScope Napi::EscapableHandleScope::New(napi_env env, napi_handle_scope scope);
```
- `[in] env`: napi_env in which the scope passed in was created.
- `[in] scope`: pre-existing napi_handle_scope.
Returns a new `Napi::EscapableHandleScope` instance which wraps the
napi_escapable_handle_scope handle passed in. This can be used
to mix usage of the C N-API and node-addon-api.
operator EscapableHandleScope::napi_escapable_handle_scope
```cpp
operator Napi::EscapableHandleScope::napi_escapable_handle_scope() const
```
Returns the N-API napi_escapable_handle_scope wrapped by the `Napi::EscapableHandleScope` object.
This can be used to mix usage of the C N-API and node-addon-api by allowing
the class to be used be converted to a napi_escapable_handle_scope.
### Destructor
```cpp
Napi::EscapableHandleScope::~EscapableHandleScope();
```
Deletes the `Napi::EscapableHandleScope` instance and allows any objects/handles created
in the scope to be collected by the garbage collector. There is no
guarantee as to when the gargbage collector will do this.
### Escape
```cpp
napi::Value Napi::EscapableHandleScope::Escape(napi_value escapee);
```
- `[in] escapee`: Napi::Value or napi_env to promote to the outer scope
Returns `Napi::Value` which can be used in the outer scope. This method can
be called at most once on a given `Napi::EscapableHandleScope`. If it is called
more than once an exception will be thrown.
### Env
```cpp
Napi::Env Napi::EscapableHandleScope::Env() const;
```
Returns the `Napi::Env` associated with the `Napi::EscapableHandleScope`.

View File

@@ -0,0 +1,59 @@
# External (template)
The `Napi::External` template class implements the ability to create a `Napi::Value` object with arbitrary C++ data. It is the user's responsibility to manage the memory for the arbitrary C++ data.
`Napi::External` objects can be created with an optional Finalizer function and optional Hint value. The Finalizer function, if specified, is called when your `Napi::External` object is released by Node's garbage collector. It gives your code the opportunity to free any dynamically created data. If you specify a Hint value, it is passed to your Finalizer function.
## Methods
### New
```cpp
template <typename T>
static Napi::External Napi::External::New(napi_env env, T* data);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object.
- `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object.
Returns the created `Napi::External<T>` object.
### New
```cpp
template <typename T>
static Napi::External Napi::External::New(napi_env env,
T* data,
Finalizer finalizeCallback);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object.
- `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object.
- `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting a T* and returning void.
Returns the created `Napi::External<T>` object.
### New
```cpp
template <typename T>
static Napi::External Napi::External::New(napi_env env,
T* data,
Finalizer finalizeCallback,
Hint* finalizeHint);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::External` object.
- `[in] data`: The arbitrary C++ data to be held by the `Napi::External` object.
- `[in] finalizeCallback`: A function called when the `Napi::External` object is released by the garbage collector accepting T* and Hint* parameters and returning void.
- `[in] finalizeHint`: A hint value passed to the `finalizeCallback` function.
Returns the created `Napi::External<T>` object.
### Data
```cpp
T* Napi::External::Data() const;
```
Returns a pointer to the arbitrary C++ data held by the `Napi::External` object.

View File

@@ -0,0 +1,294 @@
# Function
The `Napi::Function` class provides a set of methods for creating a function object in
native code that can later be called from JavaScript. The created function is not
automatically visible from JavaScript. Instead it needs to be part of the add-on's
module exports or be returned by one of the module's exported functions.
In addition the `Napi::Function` class also provides methods that can be used to call
functions that were created in JavaScript and passed to the native add-on.
The `Napi::Function` class inherits its behavior from the `Napi::Object` class (for more info
see: [`Napi::Object`](object.md)).
## Example
```cpp
#include <napi.h>
using namespace Napi;
Value Fn(const CallbackInfo& info) {
Env env = info.Env();
// ...
return String::New(env, "Hello World");
}
Object Init(Env env, Object exports) {
exports.Set(String::New(env, "fn"), Function::New(env, Fn));
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
```
The above code can be used from JavaScript as follows:
```js
const addon = require('./addon');
addon.fn();
```
With the `Napi::Function` class it is possible to call a JavaScript function object
from a native add-on with two different methods: `Call` and `MakeCallback`.
The API of these two methods is very similar, but they are used in different
contexts. The `MakeCallback` method is used to call from native code back into
JavaScript after returning from an [asynchronous operation](async_operations.md)
and in general in situations which don't have an existing JavaScript function on
the stack. The `Call` method is used when there is already a JavaScript function
on the stack (for example when running a native method called from JavaScript).
## Methods
### Constructor
Creates a new empty instance of `Napi::Function`.
```cpp
Napi::Function::Function();
```
### Constructor
Creates a new instance of the `Napi::Function` object.
```cpp
Napi::Function::Function(napi_env env, napi_value value);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object.
- `[in] value`: The `napi_value` which is a handle for a JavaScript function.
Returns a non-empty `Napi::Function` instance.
### New
Creates an instance of a `Napi::Function` object.
```cpp
template <typename Callable>
static Napi::Function Napi::Function::New(napi_env env, Callable cb, const char* utf8name = nullptr, void* data = nullptr);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object.
- `[in] cb`: Object that implements `Callable`.
- `[in] utf8name`: Null-terminated string to be used as the name of the function.
- `[in] data`: User-provided data context. This will be passed back into the
function when invoked later.
Returns an instance of a `Napi::Function` object.
### New
```cpp
template <typename Callable>
static Napi::Function Napi::Function::New(napi_env env, Callable cb, const std::string& utf8name, void* data = nullptr);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Function` object.
- `[in] cb`: Object that implements `Callable`.
- `[in] utf8name`: String to be used as the name of the function.
- `[in] data`: User-provided data context. This will be passed back into the
function when invoked later.
Returns an instance of a `Napi::Function` object.
### New
Creates a new JavaScript value from one that represents the constructor for the
object.
```cpp
Napi::Object Napi::Function::New(const std::initializer_list<napi_value>& args) const;
```
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the contructor function.
Returns a new JavaScript object.
### New
Creates a new JavaScript value from one that represents the constructor for the
object.
```cpp
Napi::Object Napi::Function::New(const std::vector<napi_value>& args) const;
```
- `[in] args`: Vector of JavaScript values as `napi_value` representing the
arguments of the constructor function.
Returns a new JavaScript object.
### New
Creates a new JavaScript value from one that represents the constructor for the
object.
```cpp
Napi::Object Napi::Function::New(size_t argc, const napi_value* args) const;
```
- `[in] argc`: The number of the arguments passed to the contructor function.
- `[in] args`: Array of JavaScript values as `napi_value` representing the
arguments of the constructor function.
Returns a new JavaScript object.
### Call
Calls a Javascript function from a native add-on.
```cpp
Napi::Value Napi::Function::Call(const std::initializer_list<napi_value>& args) const;
```
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the function.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### Call
Calls a JavaScript function from a native add-on.
```cpp
Napi::Value Napi::Function::Call(const std::vector<napi_value>& args) const;
```
- `[in] args`: Vector of JavaScript values as `napi_value` representing the
arguments of the function.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### Call
Calls a Javascript function from a native add-on.
```cpp
Napi::Value Napi::Function::Call(size_t argc, const napi_value* args) const;
```
- `[in] argc`: The number of the arguments passed to the function.
- `[in] args`: Array of JavaScript values as `napi_value` representing the
arguments of the function.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### Call
Calls a Javascript function from a native add-on.
```cpp
Napi::Value Napi::Function::Call(napi_value recv, const std::initializer_list<napi_value>& args) const;
```
- `[in] recv`: The `this` object passed to the called function.
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the function.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### Call
Calls a Javascript function from a native add-on.
```cpp
Napi::Value Napi::Function::Call(napi_value recv, const std::vector<napi_value>& args) const;
```
- `[in] recv`: The `this` object passed to the called function.
- `[in] args`: Vector of JavaScript values as `napi_value` representing the
arguments of the function.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### Call
Calls a Javascript function from a native add-on.
```cpp
Napi::Value Napi::Function::Call(napi_value recv, size_t argc, const napi_value* args) const;
```
- `[in] recv`: The `this` object passed to the called function.
- `[in] argc`: The number of the arguments passed to the function.
- `[in] args`: Array of JavaScript values as `napi_value` representing the
arguments of the function.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### MakeCallback
Calls a Javascript function from a native add-on after an asynchronous operation.
```cpp
Napi::Value Napi::Function::MakeCallback(napi_value recv, const std::initializer_list<napi_value>& args, napi_async_context context = nullptr) const;
```
- `[in] recv`: The `this` object passed to the called function.
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the function.
- `[in] context`: Context for the async operation that is invoking the callback.
This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md).
However `nullptr` is also allowed, which indicates the current async context
(if any) is to be used for the callback.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### MakeCallback
Calls a Javascript function from a native add-on after an asynchronous operation.
```cpp
Napi::Value Napi::Function::MakeCallback(napi_value recv, const std::vector<napi_value>& args, napi_async_context context = nullptr) const;
```
- `[in] recv`: The `this` object passed to the called function.
- `[in] args`: List of JavaScript values as `napi_value` representing the
arguments of the function.
- `[in] context`: Context for the async operation that is invoking the callback.
This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md).
However `nullptr` is also allowed, which indicates the current async context
(if any) is to be used for the callback.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
### MakeCallback
Calls a Javascript function from a native add-on after an asynchronous operation.
```cpp
Napi::Value Napi::Function::MakeCallback(napi_value recv, size_t argc, const napi_value* args, napi_async_context context = nullptr) const;
```
- `[in] recv`: The `this` object passed to the called function.
- `[in] argc`: The number of the arguments passed to the function.
- `[in] args`: Array of JavaScript values as `napi_value` representing the
arguments of the function.
- `[in] context`: Context for the async operation that is invoking the callback.
This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md).
However `nullptr` is also allowed, which indicates the current async context
(if any) is to be used for the callback.
Returns a `Napi::Value` representing the JavaScript value returned by the function.
## Operator
```cpp
Napi::Value Napi::Function::operator ()(const std::initializer_list<napi_value>& args) const;
```
- `[in] args`: Initializer list of JavaScript values as `napi_value`.
Returns a `Napi::Value` representing the JavaScript value returned by the function.

View File

@@ -0,0 +1,238 @@
# FunctionReference
`Napi::FunctionReference` is a subclass of [`Napi::Reference`](reference.md), and
is equivalent to an instance of `Napi::Reference<Napi::Function>`. This means
that a `Napi::FunctionReference` holds a [`Napi::Function`](function.md), and a
count of the number of references to that `Napi::Function`. When the count is
greater than 0, a `Napi::FunctionReference` is not eligible for garbage collection.
This ensures that the `Function` will remain accessible, even if the original
reference to it is no longer available.
`Napi::FunctionReference` allows the referenced JavaScript function object to be
called from a native add-on with two different methods: `Call` and `MakeCallback`.
See the documentation for [`Napi::Function`](function.md) for when `Call` should
be used instead of `MakeCallback` and vice-versa.
The `Napi::FunctionReference` class inherits its behavior from the `Napi::Reference`
class (for more info see: [`Napi::Reference`](reference.md)).
## Methods
### Weak
Creates a "weak" reference to the value, in that the initial reference count is
set to 0.
```cpp
static Napi::FunctionReference Napi::Weak(const Napi::Function& value);
```
- `[in] value`: The value which is to be referenced.
Returns the newly created reference.
### Persistent
Creates a "persistent" reference to the value, in that the initial reference
count is set to 1.
```cpp
static Napi::FunctionReference Napi::Persistent(const Napi::Function& value);
```
- `[in] value`: The value which is to be referenced.
Returns the newly created reference.
### Constructor
Creates a new empty instance of `Napi::FunctionReference`.
```cpp
Napi::FunctionReference::FunctionReference();
```
### Constructor
Creates a new instance of the `Napi::FunctionReference`.
```cpp
Napi::FunctionReference::FunctionReference(napi_env env, napi_ref ref);
```
- `[in] env`: The environment in which to construct the `Napi::FunctionReference` object.
- `[in] ref`: The N-API reference to be held by the `Napi::FunctionReference`.
Returns a newly created `Napi::FunctionReference` object.
### New
Constructs a new instance by calling the constructor held by this reference.
```cpp
Napi::Object Napi::FunctionReference::New(const std::initializer_list<napi_value>& args) const;
```
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the contructor function.
Returns a new JavaScript object.
### New
Constructs a new instance by calling the constructor held by this reference.
```cpp
Napi::Object Napi::FunctionReference::New(const std::vector<napi_value>& args) const;
```
- `[in] args`: Vector of JavaScript values as `napi_value` representing the
arguments of the constructor function.
Returns a new JavaScript object.
### Call
Calls a referenced Javascript function from a native add-on.
```cpp
Napi::Value Napi::FunctionReference::Call(const std::initializer_list<napi_value>& args) const;
```
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the referenced function.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
### Call
Calls a referenced JavaScript function from a native add-on.
```cpp
Napi::Value Napi::FunctionReference::Call(const std::vector<napi_value>& args) const;
```
- `[in] args`: Vector of JavaScript values as `napi_value` representing the
arguments of the referenced function.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
### Call
Calls a referenced JavaScript function from a native add-on.
```cpp
Napi::Value Napi::FunctionReference::Call(napi_value recv, const std::initializer_list<napi_value>& args) const;
```
- `[in] recv`: The `this` object passed to the referenced function when it's called.
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the referenced function.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
### Call
Calls a referenced JavaScript function from a native add-on.
```cpp
Napi::Value Napi::FunctionReference::Call(napi_value recv, const std::vector<napi_value>& args) const;
```
- `[in] recv`: The `this` object passed to the referenced function when it's called.
- `[in] args`: Vector of JavaScript values as `napi_value` representing the
arguments of the referenced function.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
### Call
Calls a referenced JavaScript function from a native add-on.
```cpp
Napi::Value Napi::FunctionReference::Call(napi_value recv, size_t argc, const napi_value* args) const;
```
- `[in] recv`: The `this` object passed to the referenced function when it's called.
- `[in] argc`: The number of arguments passed to the referenced function.
- `[in] args`: Array of JavaScript values as `napi_value` representing the
arguments of the referenced function.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
### MakeCallback
Calls a referenced JavaScript function from a native add-on after an asynchronous
operation.
```cpp
Napi::Value Napi::FunctionReference::MakeCallback(napi_value recv, const std::initializer_list<napi_value>& args, napi_async_context = nullptr) const;
```
- `[in] recv`: The `this` object passed to the referenced function when it's called.
- `[in] args`: Initializer list of JavaScript values as `napi_value` representing
the arguments of the referenced function.
- `[in] context`: Context for the async operation that is invoking the callback.
This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md).
However `nullptr` is also allowed, which indicates the current async context
(if any) is to be used for the callback.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
### MakeCallback
Calls a referenced JavaScript function from a native add-on after an asynchronous
operation.
```cpp
Napi::Value Napi::FunctionReference::MakeCallback(napi_value recv, const std::vector<napi_value>& args, napi_async_context context = nullptr) const;
```
- `[in] recv`: The `this` object passed to the referenced function when it's called.
- `[in] args`: Vector of JavaScript values as `napi_value` representing the
arguments of the referenced function.
- `[in] context`: Context for the async operation that is invoking the callback.
This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md).
However `nullptr` is also allowed, which indicates the current async context
(if any) is to be used for the callback.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
### MakeCallback
Calls a referenced JavaScript function from a native add-on after an asynchronous
operation.
```cpp
Napi::Value Napi::FunctionReference::MakeCallback(napi_value recv, size_t argc, const napi_value* args, napi_async_context context = nullptr) const;
```
- `[in] recv`: The `this` object passed to the referenced function when it's called.
- `[in] argc`: The number of arguments passed to the referenced function.
- `[in] args`: Array of JavaScript values as `napi_value` representing the
arguments of the referenced function.
- `[in] context`: Context for the async operation that is invoking the callback.
This should normally be a value previously obtained from [Napi::AsyncContext](async_context.md).
However `nullptr` is also allowed, which indicates the current async context
(if any) is to be used for the callback.
Returns a `Napi::Value` representing the JavaScript object returned by the referenced
function.
## Operator
```cpp
Napi::Value operator ()(const std::initializer_list<napi_value>& args) const;
```
- `[in] args`: Initializer list of reference to JavaScript values as `napi_value`
Returns a `Napi::Value` representing the JavaScript value returned by the referenced
function.

View File

@@ -0,0 +1,13 @@
# Generator
## What is generator
**[generator-napi-module](https://www.npmjs.com/package/generator-napi-module)** is a module to quickly generate a skeleton module using
**N-API**, the new API for Native addons. This module automatically sets up your
**gyp file** to use **node-addon-api**, the C++ wrappers for N-API and generates
a wrapper JS module. Optionally, it can even configure the generated project to
use **TypeScript** instead.
## **generator-napi-module** reference
- [Installation and usage](https://www.npmjs.com/package/generator-napi-module#installation)

View File

@@ -0,0 +1,65 @@
# HandleScope
The HandleScope class is used to manage the lifetime of object handles
which are created through the use of node-addon-api. These handles
keep an object alive in the heap in order to ensure that the objects
are not collected while native code is using them.
A handle may be created when any new node-addon-api Value or one
of its subclasses is created or returned. For more details refer to
the section titled [Object lifetime management](object_lifetime_management.md).
## Methods
### Constructor
Creates a new handle scope on the stack.
```cpp
Napi::HandleScope::HandleScope(Napi::Env env);
```
- `[in] env`: The environment in which to construct the `Napi::HandleScope` object.
Returns a new `Napi::HandleScope`
### Constructor
Creates a new handle scope on the stack.
```cpp
Napi::HandleScope::HandleScope(Napi::Env env, Napi::HandleScope scope);
```
- `[in] env`: `Napi::Env` in which the scope passed in was created.
- `[in] scope`: pre-existing `Napi::HandleScope`.
Returns a new `Napi::HandleScope` instance which wraps the napi_handle_scope
handle passed in. This can be used to mix usage of the C N-API
and node-addon-api.
operator HandleScope::napi_handle_scope
```cpp
operator Napi::HandleScope::napi_handle_scope() const
```
Returns the N-API napi_handle_scope wrapped by the `Napi::EscapableHandleScope` object.
This can be used to mix usage of the C N-API and node-addon-api by allowing
the class to be used be converted to a napi_handle_scope.
### Destructor
```cpp
Napi::HandleScope::~HandleScope();
```
Deletes the `Napi::HandleScope` instance and allows any objects/handles created
in the scope to be collected by the garbage collector. There is no
guarantee as to when the gargbage collector will do this.
### Env
```cpp
Napi::Env Napi::HandleScope::Env() const;
```
Returns the `Napi::Env` associated with the `Napi::HandleScope`.

View File

@@ -0,0 +1,27 @@
# MemoryManagement
The `Napi::MemoryManagement` class contains functions that give the JavaScript engine
an indication of the amount of externally allocated memory that is kept alive by
JavaScript objects.
## Methods
### AdjustExternalMemory
The function `AdjustExternalMemory` adjusts the amount of registered external
memory used to give the JavaScript engine an indication of the amount of externally
allocated memory that is kept alive by JavaScript objects.
The JavaScript engine uses this to decide when to perform global garbage collections.
Registering externally allocated memory will trigger global garbage collections
more often than it would otherwise in an attempt to garbage collect the JavaScript
objects that keep the externally allocated memory alive.
```cpp
static int64_t Napi::MemoryManagement::AdjustExternalMemory(Napi::Env env, int64_t change_in_bytes);
```
- `[in] env`: The environment in which the API is invoked under.
- `[in] change_in_bytes`: The change in externally allocated memory that is kept
alive by JavaScript objects expressed in bytes.
Returns the adjusted memory value.

View File

@@ -0,0 +1,82 @@
# node-gyp
C++ code needs to be compiled into executable form whether it be as an object
file to linked with others, a shared library, or a standalone executable.
The main reason for this is that we need to link to the Node.js dependencies and
headers correctly, another reason is that we need a cross platform way to build
C++ source into binary for the target platform.
Until now **node-gyp** is the **de-facto** standard build tool for writing
Node.js addons. It's based on Google's **gyp** build tool, which abstract away
many of the tedious issues related to cross platform building.
**node-gyp** uses a file called ```binding.gyp``` that is located on the root of
your addon project.
```binding.gyp``` file, contains all building configurations organized with a
JSON like syntax. The most important parameter is the **target** that must be
set to the same value used on the initialization code of the addon as in the
examples reported below:
### **binding.gyp**
```gyp
{
"targets": [
{
# myModule is the name of your native addon
"target_name": "myModule",
"sources": ["src/my_module.cc", ...],
...
]
}
```
### **my_module.cc**
```cpp
#include <napi.h>
// ...
/**
* This code is our entry-point. We receive two arguments here, the first is the
* environment that represent an independent instance of the JavaScript runtime,
* the second is exports, the same as module.exports in a .js file.
* You can either add properties to the exports object passed in or create your
* own exports object. In either case you must return the object to be used as
* the exports for the module when you return from the Init function.
*/
Napi::Object Init(Napi::Env env, Napi::Object exports) {
// ...
return exports;
}
/**
* This code defines the entry-point for the Node addon, it tells Node where to go
* once the library has been loaded into active memory. The first argument must
* match the "target" in our *binding.gyp*. Using NODE_GYP_MODULE_NAME ensures
* that the argument will be correct, as long as the module is built with
* node-gyp (which is the usual way of building modules). The second argument
* points to the function to invoke. The function must not be namespaced.
*/
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
```
## **node-gyp** reference
- [Installation](https://www.npmjs.com/package/node-gyp#installation)
- [How to use](https://www.npmjs.com/package/node-gyp#how-to-use)
- [The binding.gyp file](https://www.npmjs.com/package/node-gyp#the-bindinggyp-file)
- [Commands](https://www.npmjs.com/package/node-gyp#commands)
- [Command options](https://www.npmjs.com/package/node-gyp#command-options)
- [Configuration](https://www.npmjs.com/package/node-gyp#configuration)
Sometimes finding the right settings for ```binding.gyp``` is not easy so to
accomplish at most complicated task please refer to:
- [GYP documentation](https://gyp.gsrc.io/index.md)
- [node-gyp wiki](https://github.com/nodejs/node-gyp/wiki)

View File

@@ -0,0 +1,163 @@
# Number
`Napi::Number` class is a representation of the JavaScript `Number` object. The
`Napi::Number` class inherits its behavior from `Napi::Value` class
(for more info see [`Napi::Value`](value.md))
## Methods
### Constructor
Creates a new _empty_ instance of a `Napi::Number` object.
```cpp
Napi::Number();
```
Returns a new _empty_ `Napi::Number` object.
### Contructor
Creates a new instance of a `Napi::Number` object.
```cpp
Napi::Number(napi_env env, napi_value value);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Number` object.
- `[in] value`: The JavaScript value holding a number.
Returns a non-empty `Napi::Number` object.
### New
Creates a new instance of a `Napi::Number` object.
```cpp
Napi::Number Napi::Number::New(napi_env env, double value);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Number` object.
- `[in] value`: The C++ primitive from which to instantiate the `Napi::Number`.
Creates a new instance of a `Napi::Number` object.
### Int32Value
Converts a `Napi::Number` value to a `int32_t` primitive type.
```cpp
Napi::Number::Int32Value() const;
```
Returns the `int32_t` primitive type of the corresponding `Napi::Number` object.
### Uint32Value
Converts a `Napi::Number` value to a `uint32_t` primitive type.
```cpp
Napi::Number::Uint32Value() const;
```
Returns the `uint32_t` primitive type of the corresponding `Napi::Number` object.
### Int64Value
Converts a `Napi::Number` value to a `int64_t` primitive type.
```cpp
Napi::Number::Int64Value() const;
```
Returns the `int64_t` primitive type of the corresponding `Napi::Number` object.
### FloatValue
Converts a `Napi::Number` value to a `float` primitive type.
```cpp
Napi::Number::FloatValue() const;
```
Returns the `float` primitive type of the corresponding `Napi::Number` object.
### DoubleValue
Converts a `Napi::Number` value to a `double` primitive type.
```cpp
Napi::Number::DoubleValue() const;
```
Returns the `double` primitive type of the corresponding `Napi::Number` object.
## Operators
The `Napi::Number` class contains a set of operators to easily cast JavaScript
`Number` object to one of the following primitive types:
- `int32_t`
- `uint32_t`
- `int64_t`
- `float`
- `double`
### operator int32_t
Converts a `Napi::Number` value to a `int32_t` primitive.
```cpp
Napi::Number::operator int32_t() const;
```
Returns the `int32_t` primitive type of the corresponding `Napi::Number` object.
### operator uint32_t
Converts a `Napi::Number` value to a `uint32_t` primitive type.
```cpp
Napi::Number::operator uint32_t() const;
```
Returns the `uint32_t` primitive type of the corresponding `Napi::Number` object.
### operator int64_t
Converts a `Napi::Number` value to a `int64_t` primitive type.
```cpp
Napi::Number::operator int64_t() const;
```
Returns the `int64_t` primitive type of the corresponding `Napi::Number` object.
### operator float
Converts a `Napi::Number` value to a `float` primitive type.
```cpp
Napi::Number::operator float() const;
```
Returns the `float` primitive type of the corresponding `Napi::Number` object.
### operator double
Converts a `Napi::Number` value to a `double` primitive type.
```cpp
Napi::Number::operator double() const;
```
Returns the `double` primitive type of the corresponding `Napi::Number` object.
### Example
The following shows an example of casting a number to an `uint32_t` value.
```cpp
uint32_t operatorVal = Napi::Number::New(Env(), 10.0); // Number to unsigned 32 bit integer
// or
auto instanceVal = info[0].As<Napi::Number>().Uint32Value();
```

View File

@@ -0,0 +1,202 @@
# Object
The `Napi::Object` class corresponds to a JavaScript object. It is extended by the following node-addon-api classes that you may use when working with more specific types:
- [`Napi::Value`](value.md) and extends [`Napi::Array`](array.md)
- [`Napi::ArrayBuffer`](array_buffer.md)
- [`Napi::Buffer<T>`](buffer.md)
- [`Napi::Function`](function.md)
- [`Napi::TypedArray`](typed_array.md).
This class provides a number of convenience methods, most of which are used to set or get properties on a JavaScript object. For example, Set() and Get().
## Example
```cpp
#include <napi.h>
using namespace Napi;
Void Init(Env env) {
// Create a new instance
Object obj = Object::New(env);
// Assign values to properties
obj.Set("hello", "world");
obj.Set(uint32_t(42), "The Answer to Life, the Universe, and Everything");
obj.Set("Douglas Adams", true);
// Get properties
Value val1 = obj.Get("hello");
Value val2 = obj.Get(uint32_t(42));
Value val3 = obj.Get("Douglas Adams");
// Test if objects have properties.
bool obj1 = obj.Has("hello"); // true
bool obj2 = obj.Has("world"); // false
}
```
## Methods
### Empty Constructor
```cpp
Napi::Object::Object();
```
Creates a new empty Object instance.
### Constructor
```cpp
Napi::Object::Object(napi_env env, napi_value value);
```
- `[in] env`: The `napi_env` environment in which to construct the Value object.
- `[in] value`: The C++ primitive from which to instantiate the Value. `value` may be any of:
- bool
- Any integer type
- Any floating point type
- const char* (encoded using UTF-8, null-terminated)
- const char16_t* (encoded using UTF-16-LE, null-terminated)
- std::string (encoded using UTF-8)
- std::u16string
- Napi::Value
- napi_value
Creates a non-empty `Napi::Object` instance.
### New()
```cpp
Napi::Object Napi::Object::New(napi_env env);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Value` object.
Creates a new `Napi::Object` value.
### Set()
```cpp
void Napi::Object::Set (____ key, ____ value);
```
- `[in] key`: The name for the property being assigned.
- `[in] value`: The value being assigned to the property.
Add a property with the specified key with the specified value to the object.
The key can be any of the following types:
- `napi_value`
- [`Napi::Value`](value.md)
- `const char*`
- `const std::string&`
- `uint32_t`
While the value must be any of the following types:
- `napi_value`
- [`Napi::Value`](value.md)
- `const char*`
- `std::string&`
- `bool`
- `double`
### Get()
```cpp
Napi::Value Napi::Object::Get(____ key);
```
- `[in] key`: The name of the property to return the value for.
Returns the [`Napi::Value`](value.md) associated with the key property. Returns the value *undefined* if the key does not exist.
The `key` can be any of the following types:
- `napi_value`
- [`Napi::Value`](value.md)
- `const char *`
- `const std::string &`
- `uint32_t`
### Has()
```cpp
bool Napi::Object::Has (____ key) const;
```
- `[in] key`: The name of the property to check.
Returns a `bool` that is *true* if the object has a property named `key` and *false* otherwise.
### InstanceOf()
```cpp
bool Napi::Object::InstanceOf (const Function& constructor) const
```
- `[in] constructor`: The constructor [`Napi::Function`](function.md) of the value that is being compared with the object.
Returns a `bool` that is true if the `Napi::Object` is an instance created by the `constructor` and false otherwise.
Note: This is equivalent to the JavaScript instanceof operator.
### DefineProperty()
```cpp
void Napi::Object::DefineProperty (const Napi::PropertyDescriptor& property);
```
- `[in] property`: A [`Napi::PropertyDescriptor`](property_descriptor.md).
Define a property on the object.
### DefineProperties()
```cpp
void Napi::Object::DefineProperties (____ properties)
```
- `[in] properties`: A list of [`Napi::PropertyDescriptor`](property_descriptor.md). Can be one of the following types:
- const std::initializer_list<Napi::PropertyDescriptor>&
- const std::vector<Napi::PropertyDescriptor>&
Defines properties on the object.
### Operator[]()
```cpp
Napi::PropertyLValue<std::string> Napi::Object::operator[] (const char* utf8name);
```
- `[in] utf8name`: UTF-8 encoded null-terminated property name.
Returns a [`Napi::PropertyLValue`](propertylvalue.md) as the named property or sets the named property.
```cpp
Napi::PropertyLValue<std::string> Napi::Object::operator[] (const std::string& utf8name);
```
- `[in] utf8name`: UTF-8 encoded property name.
Returns a [`Napi::PropertyLValue`](propertylvalue.md) as the named property or sets the named property.
```cpp
Napi::PropertyLValue<uint32_t> Napi::Object::operator[] (uint32_t index);
```
- `[in] index`: Element index.
Returns a [`Napi::PropertyLValue`](propertylvalue.md) or sets an indexed property or array element.
```cpp
Napi::Value Napi::Object::operator[] (const char* utf8name) const;
```
- `[in] utf8name`: UTF-8 encoded null-terminated property name.
Returns the named property as a [`Napi::Value`](value.md).
```cpp
Napi::Value Napi::Object::operator[] (const std::string& utf8name) const;
```
- `[in] utf8name`: UTF-8 encoded property name.
Returns the named property as a [`Napi::Value`](value.md).
```cpp
Napi::Value Napi::Object::operator[] (uint32_t index) const;
```
- `[in] index`: Element index.
Returns an indexed property or array element as a [`Napi::Value`](value.md).

View File

@@ -0,0 +1,83 @@
# Object lifetime management
A handle may be created when any new node-addon-api Value and
its subclasses is created or returned.
As the methods and classes within the node-addon-api are used,
handles to objects in the heap for the underlying
VM may be created. A handle may be created when any new
node-addon-api Value or one of its subclasses is created or returned.
These handles must hold the objects 'live' until they are no
longer required by the native code, otherwise the objects could be
collected by the garbage collector before the native code was
finished using them.
As handles are created they are associated with a
'scope'. The lifespan for the default scope is tied to the lifespan
of the native method call. The result is that, by default, handles
remain valid and the objects associated with these handles will be
held live for the lifespan of the native method call.
In many cases, however, it is necessary that the handles remain valid for
either a shorter or longer lifespan than that of the native method.
The sections which follow describe the node-addon-api classes and
methods that than can be used to change the handle lifespan from
the default.
## Making handle lifespan shorter than that of the native method
It is often necessary to make the lifespan of handles shorter than
the lifespan of a native method. For example, consider a native method
that has a loop which creates a number of values and does something
with each of the values, one at a time:
```C++
for (int i = 0; i < LOOP_MAX; i++) {
std::string name = std::string("inner-scope") + std::to_string(i);
Napi::Value newValue = Napi::String::New(info.Env(), name.c_str());
// do something with newValue
};
```
This would result in a large number of handles being created, consuming
substantial resources. In addition, even though the native code could only
use the most recently created value, all of the previously created
values would also be kept alive since they all share the same scope.
To handle this case, node-addon-api provides the ability to establish
a new 'scope' to which newly created handles will be associated. Once those
handles are no longer required, the scope can be deleted and any handles
associated with the scope are invalidated. The `Napi::HandleScope`
and `Napi::EscapableHandleScope` classes are provided by node-addon-api for
creating additional scopes.
node-addon-api only supports a single nested hierarchy of scopes. There is
only one active scope at any time, and all new handles will be associated
with that scope while it is active. Scopes must be deleted in the reverse
order from which they are opened. In addition, all scopes created within
a native method must be deleted before returning from that method. Since
`Napi::HandleScopes` are typically stack allocated the compiler will take care of
deletion, however, care must be taken to create the scope in the right
place such that you achieve the desired lifetime.
Taking the earlier example, creating a `Napi::HandleScope` in the innner loop
would ensure that at most a single new value is held alive throughout the
execution of the loop:
```C
for (int i = 0; i < LOOP_MAX; i++) {
Napi::HandleScope scope(info.Env());
std::string name = std::string("inner-scope") + std::to_string(i);
Napi::Value newValue = Napi::String::New(info.Env(), name.c_str());
// do something with neValue
};
```
When nesting scopes, there are cases where a handle from an
inner scope needs to live beyond the lifespan of that scope. node-addon-api
provides the `Napi::EscapableHandleScope` with the `Escape` method
in order to support this case. An escapable scope
allows one object to be 'promoted' so that it 'escapes' the
current scope and the lifespan of the handle changes from the current
scope to that of the outer scope. The `Escape` method can only be called
once for a given `Napi::EscapableHandleScope`.

View File

@@ -0,0 +1,117 @@
# Object Reference
`Napi::ObjectReference` is a subclass of [`Napi::Reference`](reference.md), and is equivalent to an instance of `Napi::Reference<Object>`. This means that a `Napi::ObjectReference` holds a [`Napi::Object`](object.md), and a count of the number of references to that Object. When the count is greater than 0, an ObjectReference is not eligible for garbage collection. This ensures that the Object being held as a value of the ObjectReference will remain accessible, even if the original Object no longer is. However, ObjectReference is unique from a Reference since properties can be set and get to the Object itself that can be accessed through the ObjectReference.
For more general information on references, please consult [`Napi::Reference`](reference.md).
## Example
```cpp
#include <napi.h>
using namescape Napi;
void Init(Env env) {
// Create an empty ObjectReference that has an initial reference count of 2.
ObjectReference obj_ref = Reference<Object>::New(Object::New(env), 2);
// Set a couple of different properties on the reference.
obj_ref.Set("hello", String::New(env, "world"));
obj_ref.Set(42, "The Answer to Life, the Universe, and Everything");
// Get the properties using the keys.
Value val1 = obj_ref.Get("hello");
Value val2 = obj_ref.Get(42);
}
```
## Methods
### Initialization
```cpp
static Napi::ObjectReference Napi::ObjectReference::New(const Napi::Object& value, uint32_t initialRefcount = 0);
```
* `[in] value`: The `Napi::Object` which is to be referenced.
* `[in] initialRefcount`: The initial reference count.
Returns the newly created reference.
```cpp
static Napi::ObjectReference Napi::Weak(const Napi::Object& value);
```
Creates a "weak" reference to the value, in that the initial count of number of references is set to 0.
* `[in] value`: The value which is to be referenced.
Returns the newly created reference.
```cpp
static Napi::ObjectReference Napi::Persistent(const Napi::Object& value);
```
Creates a "persistent" reference to the value, in that the initial count of number of references is set to 1.
* `[in] value`: The value which is to be referenced.
Returns the newly created reference.
### Empty Constructor
```cpp
Napi::ObjectReference::ObjectReference();
```
Returns a new _empty_ `Napi::ObjectReference` instance.
### Constructor
```cpp
Napi::ObjectReference::ObjectReference(napi_env env, napi_value value);
```
* `[in] env`: The `napi_env` environment in which to construct the `Napi::ObjectReference` object.
* `[in] value`: The N-API primitive value to be held by the `Napi::ObjectReference`.
Returns the newly created reference.
### Set
```cpp
void Napi::ObjectReference::Set(___ key, ___ value);
```
* `[in] key`: The name for the property being assigned.
* `[in] value`: The value being assigned to the property.
The `key` can be any of the following types:
- `const char*`
- `const std::string`
- `uint32_t`
The `value` can be any of the following types:
- `napi_value`
- `Napi::Value`
- `const char*`
- `bool`
- `double`
### Get
```cpp
Napi::Value Napi::ObjectReference::Get(___ key);
```
* `[in] key`: The name of the property to return the value for.
Returns the [`Napi::Value`](value.md) associated with the key property. Returns NULL if no such key exists.
The `key` can be any of the following types:
- `const char*`
- `const std::string`
- `uint32_t`

View File

@@ -0,0 +1,546 @@
# Object Wrap
The `Napi::ObjectWrap` class is used to bind the lifetime of C++ code to a
JavaScript object. Once bound, each time an instance of the JavaScript object
is created, an instance of the C++ class will also be created. When a method
is called on the JavaScript object which is defined as an InstanceMethod, the
corresponding C++ method on the wrapped C++ class will be invoked.
In order to create a wrapper it's necessary to extend the
`Napi::ObjectWrap`class which contains all the plumbing to connect JavaScript code
with a C++ object. Classes extending `Napi::ObjectWrap` can be instantiated from
JavaScript using the **new** operator, and their methods can be directly invoked
from JavaScript. The **wrap** word refers to a way of grouping methods and state
of the class because it will be necessary write custom code to bridge each of
your C++ class methods.
## Example
```cpp
#include <napi.h>
class Example : public Napi::ObjectWrap<Example> {
public:
static Napi::Object Init(Napi::Env env, Napi::Object exports);
Example(const Napi::CallbackInfo &info);
private:
static Napi::FunctionReference constructor;
double _value;
Napi::Value GetValue(const Napi::CallbackInfo &info);
Napi::Value SetValue(const Napi::CallbackInfo &info);
};
Napi::Object Example::Init(Napi::Env env, Napi::Object exports) {
// This method is used to hook the accessor and method callbacks
Napi::Function func = DefineClass(env, "Example", {
InstanceMethod("GetValue", &Example::GetValue),
InstanceMethod("SetValue", &Example::SetValue)
});
// Create a peristent reference to the class constructor. This will allow
// a function called on a class prototype and a function
// called on instance of a class to be distinguished from each other.
constructor = Napi::Persistent(func);
// Call the SuppressDestruct() method on the static data prevent the calling
// to this destructor to reset the reference when the environment is no longer
// available.
constructor.SuppressDestruct();
exports.Set("Example", func);
return exports;
}
Example::Example(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Example>(info) {
Napi::Env env = info.Env();
// ...
Napi::Number value = info[0].As<Napi::Number>();
this->_value = value.DoubleValue();
}
Napi::FunctionReference Example::constructor;
Napi::Value Example::GetValue(const Napi::CallbackInfo &info){
Napi::Env env = info.Env();
return Napi::Number::New(env, this->_value);
}
Napi::Value Example::SetValue(const Napi::CallbackInfo &info){
Napi::Env env = info.Env();
// ...
Napi::Number value = info[0].As<Napi::Number>();
this->_value = value.DoubleValue();
return this->GetValue(info);
}
// Initialize native add-on
Napi::Object Init (Napi::Env env, Napi::Object exports) {
Example::Init(env, exports);
return exports;
}
// Register and initialize native add-on
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
```
The above code can be used from JavaScript as follows:
```js
'use strict'
const { Example } = require('bindings')('addon')
const example = new Example(11)
console.log(example.GetValue())
// It prints 11
example.SetValue(19)
console.log(example.GetValue());
// It prints 19
```
At initialization time, the `Napi::ObjectWrap::DefineClass()` method must be used
to hook up the accessor and method callbacks. It takes a list of property
descriptors, which can be constructed via the various static methods on the base
class.
When JavaScript code invokes the constructor, the constructor callback will create
a new C++ instance and "wrap" it into the newly created JavaScript object.
When JavaScript code invokes a method or a property accessor on the class the
corresponding C++ callback function will be executed.
For a wrapped object it could be difficult to distinguish between a function called
on a class prototype and a function called on instance of a class. Therefore it is
good practice to save a persistent reference to the class constructor. This allows
the two cases to be distinguished from each other by checking the this object
against the class constructor.
## Methods
### Constructor
Creates a new instance of a JavaScript object that wraps native instance.
```cpp
Napi::ObjectWrap(const Napi::CallbackInfo& callbackInfo);
```
- `[in] callbackInfo`: The object representing the components of the JavaScript
request being made.
### Unwrap
Retrieves a native instance wrapped in a JavaScript object.
```cpp
static T* Napi::ObjectWrap::Unwrap(Napi::Object wrapper);
```
* `[in] wrapper`: The JavaScript object that wraps the native instance.
Returns a native instace wrapped in a JavaScript object. Given the
Napi:Object, this allows a method to get a pointer to the wrapped
C++ object and then reference fields, call methods, etc. within that class.
In many cases calling Unwrap is not required, as methods can
use the `this` field for ObjectWrap when running in a method on a
class that extends ObjectWrap.
### DefineClass
Defnines a JavaScript class with constructor, static and instance properties and
methods.
```cpp
static Napi::Function Napi::ObjectWrap::DefineClass(Napi::Env env,
const char* utf8name,
const std::initializer_list<PropertyDescriptor>& properties,
void* data = nullptr);
```
* `[in] env`: The environment in which to construct a JavaScript class.
* `[in] utf8name`: Null-terminated string that represents the name of the
JavaScript constructor function.
* `[in] properties`: Initializer list of class property descriptor describing
static and instance properties and methods of the class.
See: [`Class propertry and descriptor`](class_property_descriptor.md).
* `[in] data`: User-provided data passed to the constructor callback as `data`
property of the `Napi::CallbackInfo`.
Returns a `Napi::Function` representing the constructor function for the class.
### DefineClass
Defnines a JavaScript class with constructor, static and instance properties and
methods.
```cpp
static Napi::Function Napi::ObjectWrap::DefineClass(Napi::Env env,
const char* utf8name,
const std::vector<PropertyDescriptor>& properties,
void* data = nullptr);
```
* `[in] env`: The environment in which to construct a JavaScript class.
* `[in] utf8name`: Null-terminated string that represents the name of the
JavaScript constructor function.
* `[in] properties`: Vector of class property descriptor describing static and
instance properties and methods of the class.
See: [`Class propertry and descriptor`](class_property_descriptor.md).
* `[in] data`: User-provided data passed to the constructor callback as `data`
property of the `Napi::CallbackInfo`.
Returns a `Napi::Function` representing the constructor function for the class.
### StaticMethod
Creates property descriptor that represents a static method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(const char* utf8name,
StaticVoidMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] utf8name`: Null-terminated string that represents the name of a static
method for the class.
- `[in] method`: The native function that represents a static method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents the static method of a
JavaScript class.
### StaticMethod
Creates property descriptor that represents a static method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(const char* utf8name,
StaticMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] utf8name`: Null-terminated string that represents the name of a static
method for the class.
- `[in] method`: The native function that represents a static method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents a static method of a
JavaScript class.
### StaticMethod
Creates property descriptor that represents a static method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(Symbol name,
StaticVoidMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] name`: Napi:Symbol that represents the name of a static
method for the class.
- `[in] method`: The native function that represents a static method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents the static method of a
JavaScript class.
### StaticMethod
Creates property descriptor that represents a static method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticMethod(Symbol name,
StaticMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
method for the class.
- `[in] name`: Napi:Symbol that represents the name of a static.
- `[in] method`: The native function that represents a static method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents a static method of a
JavaScript class.
### StaticAccessor
Creates property descriptor that represents a static accessor property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticAccessor(const char* utf8name,
StaticGetterCallback getter,
StaticSetterCallback setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] utf8name`: Null-terminated string that represents the name of a static
accessor property for the class.
- `[in] getter`: The native function to call when a get access to the property of
a JavaScript class is performed.
- `[in] setter`: The native function to call when a set access to the property of
a JavaScript class is performed.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into getter or setter when
is invoked.
Returns `Napi::PropertyDescriptor` object that represents a static accessor
property of a JavaScript class.
### StaticAccessor
Creates property descriptor that represents a static accessor property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticAccessor(Symbol name,
StaticGetterCallback getter,
StaticSetterCallback setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] name`: Napi:Symbol that represents the name of a static accessor.
- `[in] getter`: The native function to call when a get access to the property of
a JavaScript class is performed.
- `[in] setter`: The native function to call when a set access to the property of
a JavaScript class is performed.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into getter or setter when
is invoked.
Returns `Napi::PropertyDescriptor` object that represents a static accessor
property of a JavaScript class.
### InstanceMethod
Creates property descriptor that represents an instance method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(const char* utf8name,
InstanceVoidMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] utf8name`: Null-terminated string that represents the name of an instance
method for the class.
- `[in] method`: The native function that represents an instance method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents an instance method of a
JavaScript class.
### InstanceMethod
Creates property descriptor that represents an instance method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(const char* utf8name,
InstanceMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] utf8name`: Null-terminated string that represents the name of an instance
method for the class.
- `[in] method`: The native function that represents an instance method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents an instance method of a
JavaScript class.
### InstanceMethod
Creates property descriptor that represents an instance method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(Napi::Symbol name,
InstanceVoidMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] name`: The `Napi::Symbol` object whose value is used to identify the
instance method for the class.
- `[in] method`: The native function that represents an instance method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents an instance method of a
JavaScript class.
### InstanceMethod
Creates property descriptor that represents an instance method of a JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceMethod(Napi::Symbol name,
InstanceMethodCallback method,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] name`: The `Napi::Symbol` object whose value is used to identify the
instance method for the class.
- `[in] method`: The native function that represents an instance method of a
JavaScript class.
- `[in] attributes`: The attributes associated with a particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into method when it is invoked.
Returns `Napi::PropertyDescriptor` object that represents an instance method of a
JavaScript class.
### InstanceAccessor
Creates property descriptor that represents an instance accessor property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceAccessor(const char* utf8name,
InstanceGetterCallback getter,
InstanceSetterCallback setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] utf8name`: Null-terminated string that represents the name of an instance
accessor property for the class.
- `[in] getter`: The native function to call when a get access to the property of
a JavaScript class is performed.
- `[in] setter`: The native function to call when a set access to the property of
a JavaScript class is performed.
- `[in] attributes`: The attributes associated with the particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into getter or setter when this is invoked.
Returns `Napi::PropertyDescriptor` object that represents an instance accessor
property of a JavaScript class.
### InstanceAccessor
Creates property descriptor that represents an instance accessor property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceAccessor(Symbol name,
InstanceGetterCallback getter,
InstanceSetterCallback setter,
napi_property_attributes attributes = napi_default,
void* data = nullptr);
```
- `[in] name`: The `Napi::Symbol` object whose value is used to identify the
instance accessor.
- `[in] getter`: The native function to call when a get access to the property of
a JavaScript class is performed.
- `[in] setter`: The native function to call when a set access to the property of
a JavaScript class is performed.
- `[in] attributes`: The attributes associated with the particular property.
One or more of `napi_property_attributes`.
- `[in] data`: User-provided data passed into getter or setter when this is invoked.
Returns `Napi::PropertyDescriptor` object that represents an instance accessor
property of a JavaScript class.
### StaticValue
Creates property descriptor that represents an static value property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticValue(const char* utf8name,
Napi::Value value,
napi_property_attributes attributes = napi_default);
```
- `[in] utf8name`: Null-terminated string that represents the name of the static
property.
- `[in] value`: The value that's retrieved by a get access of the property.
- `[in] attributes`: The attributes to be associated with the property in addition
to the napi_static attribute. One or more of `napi_property_attributes`.
Returns `Napi::PropertyDescriptor` object that represents an static value
property of a JavaScript class
### StaticValue
Creates property descriptor that represents an static value property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::StaticValue(Symbol name,
Napi::Value value,
napi_property_attributes attributes = napi_default);
```
- `[in] name`: The `Napi::Symbol` object whose value is used to identify the
name of the static property.
- `[in] value`: The value that's retrieved by a get access of the property.
- `[in] attributes`: The attributes to be associated with the property in addition
to the napi_static attribute. One or more of `napi_property_attributes`.
Returns `Napi::PropertyDescriptor` object that represents an static value
property of a JavaScript class
### InstanceValue
Creates property descriptor that represents an instance value property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceValue(const char* utf8name,
Napi::Value value,
napi_property_attributes attributes = napi_default);
```
- `[in] utf8name`: Null-terminated string that represents the name of the property.
- `[in] value`: The value that's retrieved by a get access of the property.
- `[in] attributes`: The attributes to be associated with the property.
One or more of `napi_property_attributes`.
Returns `Napi::PropertyDescriptor` object that represents an instance value
property of a JavaScript class.
### InstanceValue
Creates property descriptor that represents an instance value property of a
JavaScript class.
```cpp
static Napi::PropertyDescriptor Napi::ObjectWrap::InstanceValue(Symbol name,
Napi::Value value,
napi_property_attributes attributes = napi_default);
```
- `[in] name`: The `Napi::Symbol` object whose value is used to identify the
name of the property.
- `[in] value`: The value that's retrieved by a get access of the property.
- `[in] attributes`: The attributes to be associated with the property.
One or more of `napi_property_attributes`.
Returns `Napi::PropertyDescriptor` object that represents an instance value

View File

@@ -0,0 +1,16 @@
# Prebuild tools
The distribution of a native add-on is just as important as its implementation.
In order to install a native add-on it's important to have all the necessary
dependencies installed and well configured (see the [setup](setup.md) section).
The end-user will need to compile the add-on when they will do an `npm install`
and in some cases this could create problems. To avoid the compilation process it's
possible to ditribute the native add-on in pre-built form for different platform
and architectures. The prebuild tools help to create and distrubute the pre-built
form of a native add-on.
The following list report two of the tools that are compatible with **N-API**:
- **[node-pre-gyp](https://www.npmjs.com/package/node-pre-gyp)**
- **[prebuild](https://www.npmjs.com/package/prebuild)**
- **[prebuildify](https://www.npmjs.com/package/prebuildify)**

View File

@@ -0,0 +1,74 @@
# Promise
The `Napi::Promise` class, along with its `Napi::Promise::Deferred` class, implement the ability to create, resolve, and reject Promise objects.
The basic approach is to create a `Napi::Promise::Deferred` object and return to your caller the value returned by the `Napi::Promise::Deferred::Promise` method. For example:
```cpp
Napi::Value YourFunction(const Napi::CallbackInfo& info) {
// your code goes here...
Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(info.Env());
// deferred needs to survive this call...
return deferred.Promise();
}
```
Later, when the asynchronous process completes, call either the `Resolve` or `Reject` method on the `Napi::Promise::Deferred` object created earlier:
```cpp
deferred.Resolve(String::New(info.Env(), "OK"));
```
## Promise::Deferred Methods
### Factory Method
```cpp
static Napi::Promise::Deferred Napi::Promise::Deferred::New(napi_env env);
```
* `[in] env`: The `napi_env` environment in which to create the `Napi::Promise::Deferred` object.
### Constructor
```cpp
Napi::Promise::Deferred(napi_env env);
```
* `[in] env`: The `napi_env` environment in which to construct the `Napi::Promise::Deferred` object.
### Env
```cpp
Napi::Env Napi::Promise::Deferred::Env() const;
```
Returns the Env environment this `Napi::Promise::Deferred` object is associated with.
### Promise
```cpp
Napi::Promise Napi::Promise::Deferred::Promise() const;
```
Returns the `Napi::Promise` object held by the `Napi::Promise::Deferred` object.
### Resolve
```cpp
void Napi::Promise::Deferred::Resolve(napi_value value) const;
```
Resolves the `Napi::Promise` object held by the `Napi::Promise::Deferred` object.
* `[in] value`: The N-API primitive value with which to resolve the `Napi::Promise`.
### Reject
```cpp
void Napi::Promise::Deferred::Reject(napi_value value) const;
```
Rejects the Promise object held by the `Napi::Promise::Deferred` object.
* `[in] value`: The N-API primitive value with which to reject the `Napi::Promise`.

View File

@@ -0,0 +1,231 @@
# Property Descriptor
A [`Napi::Object`](object.md) can be assigned properites via its [`DefineProperty`](object.md#defineproperty) and [`DefineProperties`](object.md#defineproperties) functions, which take PropertyDescrptor(s) as their parameters. The `Napi::PropertyDescriptor` can contain either values or functions, which are then assigned to the `Napi::Object`. Note that a single instance of a `Napi::PropertyDescriptor` class can only contain either one value, or at most two functions. PropertyDescriptors can only be created through the class methods [`Accessor`](#accessor), [`Function`](#function), or [`Value`](#value), each of which return a new static instance of a `Napi::PropertyDescriptor`.
## Example
```cpp
#include <napi.h>
using namespace Napi;
Value TestGetter(const CallbackInfo& info) {
return Boolean::New(info.Env(), testValue);
}
void TestSetter(const CallbackInfo& info) {
testValue = info[0].As<Boolean>();
}
Value TestFunction(const CallbackInfo& info) {
return Boolean::New(info.Env(), true);
}
Void Init(Env env) {
// Create an object.
Object obj = Object::New(env);
// Accessor
PropertyDescriptor pd1 = PropertyDescriptor::Accessor(env,
obj,
"pd1",
TestGetter);
PropertyDescriptor pd2 = PropertyDescriptor::Accessor(env,
obj,
"pd2",
TestGetter,
TestSetter);
// Function
PropertyDescriptor pd3 = PropertyDescriptor::Function(env,
"function",
TestFunction);
// Value
Boolean true_bool = Boolean::New(env, true);
PropertyDescriptor pd4 =
PropertyDescriptor::Value("boolean value",
Napi::Boolean::New(env, true),
napi_writable);
// Assign properties to the object.
obj.DefineProperties({pd1, pd2, pd3, pd4});
}
```
## Methods
### Constructor
```cpp
Napi::PropertyDescriptor::PropertyDescriptor (napi_property_descriptor desc);
```
* `[in] desc`: A PropertyDescriptor that is needed in order to create another PropertyDescriptor.
### Accessor
```cpp
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name,
Getter getter,
napi_property_attributes attributes = napi_default,
void *data = nullptr);
```
* `[in] name`: The name used for the getter function.
* `[in] getter`: A getter function.
* `[in] attributes`: Potential attributes for the getter function.
* `[in] data`: A pointer to data of any type, default is a null pointer.
Returns a PropertyDescriptor that contains a function.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `napi_value value`
- `Napi::Name`
**This signature is deprecated. It will result in a memory leak if used.**
```cpp
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (
Napi::Env env,
Napi::Object object,
___ name,
Getter getter,
napi_property_attributes attributes = napi_default,
void *data = nullptr);
```
* `[in] env`: The environemnt in which to create this accessor.
* `[in] object`: The object on which the accessor will be defined.
* `[in] name`: The name used for the getter function.
* `[in] getter`: A getter function.
* `[in] attributes`: Potential attributes for the getter function.
* `[in] data`: A pointer to data of any type, default is a null pointer.
Returns a `Napi::PropertyDescriptor` that contains a `Getter` accessor.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `Napi::Name`
```cpp
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (___ name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void *data = nullptr);
```
* `[in] name`: The name of the getter and setter function.
* `[in] getter`: The getter function.
* `[in] setter`: The setter function.
* `[in] attributes`: Potential attributes for the getter function.
* `[in] data`: A pointer to data of any type, default is a null pointer.
Returns a `Napi::PropertyDescriptor` that contains a `Getter` and `Setter` function.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `napi_value value`
- `Napi::Name`
**This signature is deprecated. It will result in a memory leak if used.**
```cpp
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Accessor (
Napi::Env env,
Napi::Object object,
___ name,
Getter getter,
Setter setter,
napi_property_attributes attributes = napi_default,
void *data = nullptr);
```
* `[in] env`: The environemnt in which to create this accessor.
* `[in] object`: The object on which the accessor will be defined.
* `[in] name`: The name of the getter and setter function.
* `[in] getter`: The getter function.
* `[in] setter`: The setter function.
* `[in] attributes`: Potential attributes for the getter function.
* `[in] data`: A pointer to data of any type, default is a null pointer.
Returns a `Napi::PropertyDescriptor` that contains a `Getter` and `Setter` function.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `Napi::Name`
### Function
```cpp
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Function (___ name,
Callable cb,
napi_property_attributes attributes = napi_default,
void *data = nullptr);
```
* `[in] name`: The name of the Callable function.
* `[in] cb`: The function
* `[in] attributes`: Potential attributes for the getter function.
* `[in] data`: A pointer to data of any type, default is a null pointer.
Returns a `Napi::PropertyDescriptor` that contains a callable `Napi::Function`.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `napi_value value`
- `Napi::Name`
**This signature is deprecated. It will result in a memory leak if used.**
```cpp
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Function (
Napi::Env env,
___ name,
Callable cb,
napi_property_attributes attributes = napi_default,
void *data = nullptr);
```
* `[in] env`: The environment in which to create this accessor.
* `[in] name`: The name of the Callable function.
* `[in] cb`: The function
* `[in] attributes`: Potential attributes for the getter function.
* `[in] data`: A pointer to data of any type, default is a null pointer.
Returns a `Napi::PropertyDescriptor` that contains a callable `Napi::Function`.
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `Napi::Name`
### Value
```cpp
static Napi::PropertyDescriptor Napi::PropertyDescriptor::Value (___ name,
napi_value value,
napi_property_attributes attributes = napi_default);
```
The name of the property can be any of the following types:
- `const char*`
- `const std::string &`
- `napi_value value`
- `Napi::Name`
## Related Information
### napi\_property\_attributes
`napi_property_attributes` are flags used to indicate to JavaScript certain permissions that the property is meant to have. The following are the flag options:
- napi\_default,
- napi\_writable,
- napi\_enumerable,
- napi\_configurable
For more information on the flags and on napi\_property\_attributes, please read the documentation [here](https://github.com/nodejs/node/blob/master/doc/api/n-api.md#napi_property_attributes).

View File

@@ -0,0 +1,59 @@
# RangeError
The `Napi::RangeError` class is a representation of the JavaScript `RangeError` that is
thrown when trying to pass a value as an argument to a function that does not allow
a range that includes the value.
The `Napi::RangeError` class inherits its behaviors from the `Napi::Error` class (for
more info see: [`Napi::Error`](error.md)).
For more details about error handling refer to the section titled [Error handling](error_handling.md).
## Methods
### New
Creates a new instance of a `Napi::RangeError` object.
```cpp
Napi::RangeError::New(Napi::Env env, const char* message);
```
- `[in] Env`: The environment in which to construct the `Napi::RangeError` object.
- `[in] message`: Null-terminated string to be used as the message for the `Napi::RangeError`.
Returns an instance of a `Napi::RangeError` object.
### New
Creates a new instance of a `Napi::RangeError` object.
```cpp
Napi::RangeError::New(Napi::Env env, const std::string& message);
```
- `[in] Env`: The environment in which to construct the `Napi::RangeError` object.
- `[in] message`: Reference string to be used as the message for the `Napi::RangeError`.
Returns an instance of a `Napi::RangeError` object.
### Constructor
Creates a new empty instance of a `Napi::RangeError`.
```cpp
Napi::RangeError::RangeError();
```
### Constructor
Initializes a `Napi::RangeError` instance from an existing Javascript error object.
```cpp
Napi::RangeError::RangeError(napi_env env, napi_value value);
```
- `[in] Env`: The environment in which to construct the `Napi::RangeError` object.
- `[in] value`: The `Napi::Error` reference to wrap.
Returns an instance of a `Napi::RangeError` object.

View File

@@ -0,0 +1,111 @@
# Reference (template)
Holds a counted reference to a [`Napi::Value`](value.md) object; initially a weak reference unless otherwise specified, may be changed to/from a strong reference by adjusting the refcount.
The referenced `Napi::Value` is not immediately destroyed when the reference count is zero; it is merely then eligible for garbage-collection if there are no other references to the `Napi::Value`.
`Napi::Reference` objects allocated in static space, such as a global static instance, must call the `SuppressDestruct` method to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid.
The following classes inherit, either directly or indirectly, from `Napi::Reference`:
* [`Napi::ObjectWrap`](object_wrap.md)
* [`Napi::ObjectReference`](object_reference.md)
* [`Napi::FunctionReference`](function_reference.md)
## Methods
### Factory Method
```cpp
static Napi::Reference<T> Napi::Reference::New(const T& value, uint32_t initialRefcount = 0);
```
* `[in] value`: The value which is to be referenced.
* `[in] initialRefcount`: The initial reference count.
### Empty Constructor
```cpp
Napi::Reference::Reference();
```
Creates a new _empty_ `Napi::Reference` instance.
### Constructor
```cpp
Napi::Reference::Reference(napi_env env, napi_value value);
```
* `[in] env`: The `napi_env` environment in which to construct the `Napi::Reference` object.
* `[in] value`: The N-API primitive value to be held by the `Napi::Reference`.
### Env
```cpp
Napi::Env Napi::Reference::Env() const;
```
Returns the `Napi::Env` value in which the `Napi::Reference` was instantiated.
### IsEmpty
```cpp
bool Napi::Reference::IsEmpty() const;
```
Determines whether the value held by the `Napi::Reference` is empty.
### Value
```cpp
T Napi::Reference::Value() const;
```
Returns the value held by the `Napi::Reference`.
### Ref
```cpp
uint32_t Napi::Reference::Ref();
```
Increments the reference count for the `Napi::Reference` and returns the resulting reference count. Throws an error if the increment fails.
### Unref
```cpp
uint32_t Napi::Reference::Unref();
```
Decrements the reference count for the `Napi::Reference` and returns the resulting reference count. Throws an error if the decrement fails.
### Reset (Empty)
```cpp
void Napi::Reference::Reset();
```
Sets the value held by the `Napi::Reference` to be empty.
### Reset
```cpp
void Napi::Reference::Reset(const T& value, uint32_t refcount = 0);
```
* `[in] value`: The value which is to be referenced.
* `[in] initialRefcount`: The initial reference count.
Sets the value held by the `Napi::Reference`.
### SuppressDestruct
```cpp
void Napi::Reference::SuppressDestruct();
```
Call this method on a `Napi::Reference` that is declared as static data to prevent its destructor, running at program shutdown time, from attempting to reset the reference when the environment is no longer valid.

View File

@@ -0,0 +1,82 @@
# Setup
## Prerequisites
Before starting to use **N-API** you need to assure you have the following
prerequisites:
* **Node.JS** see: [Installing Node.js](https://nodejs.org/)
* **Node.js native addon build tool**
- **[node-gyp](node-gyp.md)**
## Installation and usage
To use **N-API** in a native module:
1. Add a dependency on this package to `package.json`:
```json
"dependencies": {
"node-addon-api": "*",
}
```
2. Reference this package's include directory and gyp file in `binding.gyp`:
```gyp
'include_dirs': ["<!@(node -p \"require('node-addon-api').include\")"],
'dependencies': ["<!(node -p \"require('node-addon-api').gyp\")"],
```
3. Decide whether the package will enable C++ exceptions in the N-API wrapper.
The base ABI-stable C APIs do not throw or handle C++ exceptions, but the
N-API C++ wrapper classes may _optionally_
[integrate C++ and JavaScript exception-handling
](https://nodejs.github.io/node-addon-api/class_napi_1_1_error.html).
To enable that capability, C++ exceptions must be enabled in `binding.gyp`:
```gyp
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'CLANG_CXX_LIBRARY': 'libc++',
'MACOSX_DEPLOYMENT_TARGET': '10.7',
},
'msvs_settings': {
'VCCLCompilerTool': { 'ExceptionHandling': 1 },
},
```
Alternatively, disable use of C++ exceptions in N-API:
```gyp
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
```
4. If you would like your native addon to support OSX, please also add the
following settings in the `binding.gyp` file:
```gyp
['OS=="mac"', {
'cflags+': ['-fvisibility=hidden'],
'xcode_settings': {
'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden
}
}]
```
5. Include `napi.h` in the native module code.
To ensure only ABI-stable APIs are used, DO NOT include
`node.h`, `nan.h`, or `v8.h`.
```C++
#include "napi.h"
```
At build time, the N-API back-compat library code will be used only when the
targeted node version *does not* have N-API built-in.
The preprocessor directive `NODE_ADDON_API_DISABLE_DEPRECATED` can be defined at
compile time before including `napi.h` to skip the definition of deprecated APIs.

View File

@@ -0,0 +1,89 @@
# String
## Constructor
```cpp
Napi::String::String();
```
Returns a new **empty** `Napi::String` instance.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
```cpp
Napi::String::String(napi_env env, napi_value value); ///< Wraps a N-API value primitive.
```
- `[in] env` - The environment in which to create the string.
- `[in] value` - The primitive to wrap.
Returns a `Napi::String` wrapping a `napi_value`.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
## Operators
### operator std::string
```cpp
Napi::String::operator std::string() const;
```
Returns a UTF-8 encoded C++ string.
### operator std::u16string
```cpp
Napi::String::operator std::u16string() const;
```
Returns a UTF-16 encoded C++ string.
## Methods
### New
```cpp
Napi::String::New();
```
Returns a new empty `Napi::String`.
### New
```cpp
Napi::String::New(napi_env env, const std::string& value);
Napi::String::New(napi_env env, const std::u16::string& value);
Napi::String::New(napi_env env, const char* value);
Napi::String::New(napi_env env, const char16_t* value);
Napi::String::New(napi_env env, const char* value, size_t length);
Napi::String::New(napi_env env, const char16_t* value, size_t length);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Value` object.
- `[in] value`: The C++ primitive from which to instantiate the `Napi::Value`. `value` may be any of:
- `std::string&` - represents an ANSI string.
- `std::u16string&` - represents a UTF16-LE string.
- `const char*` - represents a UTF8 string.
- `const char16_t*` - represents a UTF16-LE string.
- `[in] length`: The length of the string (not necessarily null-terminated) in code units.
Returns a new `Napi::String` that represents the passed in C++ string.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Env::IsExceptionPending` before
attempting to use the returned value.
### Utf8Value
```cpp
std::string Napi::String::Utf8Value() const;
```
Returns a UTF-8 encoded C++ string.
### Utf16Value
```cpp
std::u16string Napi::String::Utf16Value() const;
```
Returns a UTF-16 encoded C++ string.

View File

@@ -0,0 +1,44 @@
# Symbol
## Methods
### Constructor
Instantiates a new `Napi::Symbol` value.
```cpp
Napi::Symbol::Symbol();
```
Returns a new empty `Napi::Symbol`.
### New
```cpp
Napi::Symbol::New(napi_env env, const std::string& description);
Napi::Symbol::New(napi_env env, const char* description);
Napi::Symbol::New(napi_env env, Napi::String description);
Napi::Symbol::New(napi_env env, napi_value description);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Symbol` object.
- `[in] value`: The C++ primitive which represents the description hint for the `Napi::Symbol`.
`description` may be any of:
- `std::string&` - ANSI string description.
- `const char*` - represents a UTF8 string description.
- `String` - Node addon API String description.
- `napi_value` - N-API `napi_value` description.
If an error occurs, a `Napi::Error` will get thrown. If C++ exceptions are not
being used, callers should check the result of `Napi::Env::IsExceptionPending` before
attempting to use the returned value.
### Utf8Value
```cpp
static Napi::Symbol Napi::Symbol::WellKnown(napi_env env, const std::string& name);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Symbol` object.
- `[in] name`: The C++ string representing the `Napi::Symbol` to retrieve.
Returns a `Napi::Symbol` representing a well-known `Symbol` from the
`Symbol` registry.

View File

@@ -0,0 +1,303 @@
# ThreadSafeFunction
JavaScript functions can normally only be called from a native addon's main
thread. If an addon creates additional threads, then node-addon-api functions
that require a `Napi::Env`, `Napi::Value`, or `Napi::Reference` must not be
called from those threads.
When an addon has additional threads and JavaScript functions need to be invoked
based on the processing completed by those threads, those threads must
communicate with the addon's main thread so that the main thread can invoke the
JavaScript function on their behalf. The thread-safe function APIs provide an
easy way to do this.
These APIs provide the type `Napi::ThreadSafeFunction` as well as APIs to
create, destroy, and call objects of this type.
`Napi::ThreadSafeFunction::New()` creates a persistent reference that holds a
JavaScript function which can be called from multiple threads. The calls happen
asynchronously. This means that values with which the JavaScript callback is to
be called will be placed in a queue, and, for each value in the queue, a call
will eventually be made to the JavaScript function.
`Napi::ThreadSafeFunction` objects are destroyed when every thread which uses
the object has called `Release()` or has received a return status of
`napi_closing` in response to a call to `BlockingCall()` or `NonBlockingCall()`.
The queue is emptied before the `Napi::ThreadSafeFunction` is destroyed. It is
important that `Release()` be the last API call made in conjunction with a given
`Napi::ThreadSafeFunction`, because after the call completes, there is no
guarantee that the `Napi::ThreadSafeFunction` is still allocated. For the same
reason it is also important that no more use be made of a thread-safe function
after receiving a return value of `napi_closing` in response to a call to
`BlockingCall()` or `NonBlockingCall()`. Data associated with the
`Napi::ThreadSafeFunction` can be freed in its `Finalizer` callback which was
passed to `ThreadSafeFunction::New()`.
Once the number of threads making use of a `Napi::ThreadSafeFunction` reaches
zero, no further threads can start making use of it by calling `Acquire()`. In
fact, all subsequent API calls associated with it, except `Release()`, will
return an error value of `napi_closing`.
## Methods
### Constructor
Creates a new empty instance of `Napi::ThreadSafeFunction`.
```cpp
Napi::Function::ThreadSafeFunction();
```
### Constructor
Creates a new instance of the `Napi::ThreadSafeFunction` object.
```cpp
Napi::ThreadSafeFunction::ThreadSafeFunction(napi_threadsafe_function tsfn);
```
- `tsfn`: The `napi_threadsafe_function` which is a handle for an existing
thread-safe function.
Returns a non-empty `Napi::ThreadSafeFunction` instance.
### New
Creates a new instance of the `Napi::ThreadSafeFunction` object. The `New`
function has several overloads for the various optional parameters: skip the
optional parameter for that specific overload.
```cpp
New(napi_env env,
const Function& callback,
const Object& resource,
ResourceString resourceName,
size_t maxQueueSize,
size_t initialThreadCount,
ContextType* context,
Finalizer finalizeCallback,
FinalizerDataType* data);
```
- `env`: The `napi_env` environment in which to construct the
`Napi::ThreadSafeFunction` object.
- `callback`: The `Function` to call from another thread.
- `[optional] resource`: An object associated with the async work that will be
passed to possible async_hooks init hooks.
- `resourceName`: A JavaScript string to provide an identifier for the kind of
resource that is being provided for diagnostic information exposed by the
async_hooks API.
- `maxQueueSize`: Maximum size of the queue. `0` for no limit.
- `initialThreadCount`: The initial number of threads, including the main
thread, which will be making use of this function.
- `[optional] context`: Data to attach to the resulting `ThreadSafeFunction`.
- `[optional] finalizeCallback`: Function to call when the `ThreadSafeFunction`
is being destroyed. This callback will be invoked on the main thread when the
thread-safe function is about to be destroyed. It receives the context and the
finalize data given during construction (if given), and provides an
opportunity for cleaning up after the threads e.g. by calling
`uv_thread_join()`. It is important that, aside from the main loop thread,
there be no threads left using the thread-safe function after the finalize
callback completes. Must implement `void operator()(Env env, DataType* data,
Context* hint)`, skipping `data` or `hint` if they are not provided.
Can be retreived via `GetContext()`.
- `[optional] data`: Data to be passed to `finalizeCallback`.
Returns a non-empty `Napi::ThreadSafeFunction` instance.
### Acquire
Add a thread to this thread-safe function object, indicating that a new thread
will start making use of the thread-safe function.
```cpp
napi_status Napi::ThreadSafeFunction::Acquire()
```
Returns one of:
- `napi_ok`: The thread has successfully acquired the thread-safe function
for its use.
- `napi_closing`: The thread-safe function has been marked as closing via a
previous call to `Abort()`.
### Release
Indicate that an existing thread will stop making use of the thread-safe
function. A thread should call this API when it stops making use of this
thread-safe function. Using any thread-safe APIs after having called this API
has undefined results in the current thread, as it may have been destroyed.
```cpp
napi_status Napi::ThreadSafeFunction::Release()
```
Returns one of:
- `napi_ok`: The thread-safe function has been successfully released.
- `napi_invalid_arg`: The thread-safe function's thread-count is zero.
- `napi_generic_failure`: A generic error occurred when attemping to release
the thread-safe function.
### Abort
"Abort" the thread-safe function. This will cause all subsequent APIs associated
with the thread-safe function except `Release()` to return `napi_closing` even
before its reference count reaches zero. In particular, `BlockingCall` and
`NonBlockingCall()` will return `napi_closing`, thus informing the threads that
it is no longer possible to make asynchronous calls to the thread-safe function.
This can be used as a criterion for terminating the thread. Upon receiving a
return value of `napi_closing` from a thread-safe function call a thread must
make no further use of the thread-safe function because it is no longer
guaranteed to be allocated.
```cpp
napi_status Napi::ThreadSafeFunction::Abort()
```
Returns one of:
- `napi_ok`: The thread-safe function has been successfully aborted.
- `napi_invalid_arg`: The thread-safe function's thread-count is zero.
- `napi_generic_failure`: A generic error occurred when attemping to abort
the thread-safe function.
### BlockingCall / NonBlockingCall
Calls the Javascript function in either a blocking or non-blocking fashion.
- `BlockingCall()`: the API blocks until space becomes available in the queue.
Will never block if the thread-safe function was created with a maximum queue
size of `0`.
- `NonBlockingCall()`: will return `napi_queue_full` if the queue was full,
preventing data from being successfully added to the queue.
There are several overloaded implementations of `BlockingCall()` and
`NonBlockingCall()` for use with optional parameters: skip the optional
parameter for that specific overload.
```cpp
napi_status Napi::ThreadSafeFunction::BlockingCall(DataType* data, Callback callback) const
napi_status Napi::ThreadSafeFunction::NonBlockingCall(DataType* data, Callback callback) const
```
- `[optional] data`: Data to pass to `callback`.
- `[optional] callback`: C++ function that is invoked on the main thread. The
callback receives the `ThreadSafeFunction`'s JavaScript callback function to
call as an `Napi::Function` in its parameters and the `DataType*` data pointer
(if provided). Must implement `void operator()(Napi::Env env, Function
jsCallback, DataType* data)`, skipping `data` if not provided. It is not
necessary to call into JavaScript via `MakeCallback()` because N-API runs
`callback` in a context appropriate for callbacks.
Returns one of:
- `napi_ok`: The call was successfully added to the queue.
- `napi_queue_full`: The queue was full when trying to call in a non-blocking
method.
- `napi_closing`: The thread-safe function is aborted and cannot accept more
calls.
- `napi_invalid_arg`: The thread-safe function is closed.
- `napi_generic_failure`: A generic error occurred when attemping to add to the
queue.
## Example
```cpp
#include <chrono>
#include <thread>
#include <napi.h>
using namespace Napi;
std::thread nativeThread;
ThreadSafeFunction tsfn;
Value Start( const CallbackInfo& info )
{
Napi::Env env = info.Env();
if ( info.Length() < 2 )
{
throw TypeError::New( env, "Expected two arguments" );
}
else if ( !info[0].IsFunction() )
{
throw TypeError::New( env, "Expected first arg to be function" );
}
else if ( !info[1].IsNumber() )
{
throw TypeError::New( env, "Expected second arg to be number" );
}
int count = info[1].As<Number>().Int32Value();
// Create a ThreadSafeFunction
tsfn = ThreadSafeFunction::New(
env,
info[0].As<Function>(), // JavaScript function called asynchronously
"Resource Name", // Name
0, // Unlimited queue
1, // Only one thread will use this initially
[]( Napi::Env ) { // Finalizer used to clean threads up
nativeThread.join();
} );
// Create a native thread
nativeThread = std::thread( [count] {
auto callback = []( Napi::Env env, Function jsCallback, int* value ) {
// Transform native data into JS data, passing it to the provided
// `jsCallback` -- the TSFN's JavaScript function.
jsCallback.Call( {Number::New( env, *value )} );
// We're finished with the data.
delete value;
};
for ( int i = 0; i < count; i++ )
{
// Create new data
int* value = new int( clock() );
// Perform a blocking call
napi_status status = tsfn.BlockingCall( value, callback );
if ( status != napi_ok )
{
// Handle error
break;
}
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
}
// Release the thread-safe function
tsfn.Release();
} );
return Boolean::New(env, true);
}
Napi::Object Init( Napi::Env env, Object exports )
{
exports.Set( "start", Function::New( env, Start ) );
return exports;
}
NODE_API_MODULE( clock, Init )
```
The above code can be used from JavaScript as follows:
```js
const { start } = require('bindings')('clock');
start(function () {
console.log("JavaScript callback called with arguments", Array.from(arguments));
}, 5);
```
When executed, the output will show the value of `clock()` five times at one
second intervals:
```
JavaScript callback called with arguments [ 84745 ]
JavaScript callback called with arguments [ 103211 ]
JavaScript callback called with arguments [ 104516 ]
JavaScript callback called with arguments [ 105104 ]
JavaScript callback called with arguments [ 105691 ]
```

View File

@@ -0,0 +1,59 @@
# TypeError
The `Napi::TypeError` class is a representation of the JavaScript `TypeError` that is
thrown when an operand or argument passed to a function is incompatible with the
type expected by the operator or function.
The `Napi::TypeError` class inherits its behaviors from the `Napi::Error` class (for more info
see: [`Napi::Error`](error.md)).
For more details about error handling refer to the section titled [Error handling](error_handling.md).
## Methods
### New
Creates a new instance of the `Napi::TypeError` object.
```cpp
Napi::TypeError::New(Napi:Env env, const char* message);
```
- `[in] Env`: The environment in which to construct the `Napi::TypeError` object.
- `[in] message`: Null-terminated string to be used as the message for the `Napi::TypeError`.
Returns an instance of a `Napi::TypeError` object.
### New
Creates a new instance of a `Napi::TypeError` object.
```cpp
Napi::TypeError::New(Napi:Env env, const std::string& message);
```
- `[in] Env`: The environment in which to construct the `Napi::TypeError` object.
- `[in] message`: Reference string to be used as the message for the `Napi::TypeError`.
Returns an instance of a `Napi::TypeError` object.
### Constructor
Creates a new empty instance of a `Napi::TypeError`.
```cpp
Napi::TypeError::TypeError();
```
### Constructor
Initializes a `Napi::TypeError` instance from an existing JavaScript error object.
```cpp
Napi::TypeError::TypeError(napi_env env, napi_value value);
```
- `[in] Env`: The environment in which to construct the `Napi::TypeError` object.
- `[in] value`: The `Napi::Error` reference to wrap.
Returns an instance of a `Napi::TypeError` object.

View File

@@ -0,0 +1,74 @@
# TypedArray
The `Napi::TypedArray` class corresponds to the
[JavaScript `TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
class.
## Methods
### Constructor
Initializes an empty instance of the `Napi::TypedArray` class.
```cpp
Napi::TypedArray::TypedArray();
```
### Constructor
Initializes a wrapper instance of an existing `Napi::TypedArray` instance.
```cpp
Napi::TypedArray::TypedArray(napi_env env, napi_value value);
```
- `[in] env`: The environment in which to create the `Napi::TypedArray` instance.
- `[in] value`: The `Napi::TypedArray` reference to wrap.
### TypedArrayType
```cpp
napi_typedarray_type Napi::TypedArray::TypedArrayType() const;
```
Returns the type of this instance.
### ArrayBuffer
```cpp
Napi::ArrayBuffer Napi::TypedArray::ArrayBuffer() const;
```
Returns the backing array buffer.
### ElementSize
```cpp
uint8_t Napi::TypedArray::ElementSize() const;
```
Returns the size of one element, in bytes.
### ElementLength
```cpp
size_t Napi::TypedArray::ElementLength() const;
```
Returns the number of elements.
### ByteOffset
```cpp
size_t Napi::TypedArray::ByteOffset() const;
```
Returns the offset into the `Napi::ArrayBuffer` where the array starts, in bytes.
### ByteLength
```cpp
size_t Napi::TypedArray::ByteLength() const;
```
Returns the length of the array, in bytes.

View File

@@ -0,0 +1,133 @@
# TypedArrayOf
The `Napi::TypedArrayOf` class corresponds to the various
[JavaScript `TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
classes.
## Typedefs
The common JavaScript `TypedArray` types are pre-defined for each of use:
```cpp
typedef Napi::TypedArrayOf<int8_t> Int8Array;
typedef Napi::TypedArrayOf<uint8_t> Uint8Array;
typedef Napi::TypedArrayOf<int16_t> Int16Array;
typedef Napi::TypedArrayOf<uint16_t> Uint16Array;
typedef Napi::TypedArrayOf<int32_t> Int32Array;
typedef Napi::TypedArrayOf<uint32_t> Uint32Array;
typedef Napi::TypedArrayOf<float> Float32Array;
typedef Napi::TypedArrayOf<double> Float64Array;
```
The one exception is the `Uint8ClampedArray` which requires explicit
initialization:
```cpp
Uint8Array::New(env, length, napi_uint8_clamped_array)
```
Note that while it's possible to create a "clamped" array the _clamping_
behavior is only applied in JavaScript.
## Methods
### New
Allocates a new `Napi::TypedArray` instance with a given length. The underlying
`Napi::ArrayBuffer` is allocated automatically to the desired number of elements.
The array type parameter can normally be omitted (because it is inferred from
the template parameter T), except when creating a "clamped" array.
```cpp
static Napi::TypedArrayOf Napi::TypedArrayOf::New(napi_env env,
size_t elementLength,
napi_typedarray_type type);
```
- `[in] env`: The environment in which to create the `Napi::TypedArrayOf` instance.
- `[in] elementLength`: The length to be allocated, in elements.
- `[in] type`: The type of array to allocate (optional).
Returns a new `Napi::TypedArrayOf` instance.
### New
Wraps the provided `Napi::ArrayBuffer` into a new `Napi::TypedArray` instance.
The array `type` parameter can normally be omitted (because it is inferred from
the template parameter `T`), except when creating a "clamped" array.
```cpp
static Napi::TypedArrayOf Napi::TypedArrayOf::New(napi_env env,
size_t elementLength,
Napi::ArrayBuffer arrayBuffer,
size_t bufferOffset,
napi_typedarray_type type);
```
- `[in] env`: The environment in which to create the `Napi::TypedArrayOf` instance.
- `[in] elementLength`: The length to array, in elements.
- `[in] arrayBuffer`: The backing `Napi::ArrayBuffer` instance.
- `[in] bufferOffset`: The offset into the `Napi::ArrayBuffer` where the array starts,
in bytes.
- `[in] type`: The type of array to allocate (optional).
Returns a new `Napi::TypedArrayOf` instance.
### Constructor
Initializes an empty instance of the `Napi::TypedArrayOf` class.
```cpp
Napi::TypedArrayOf::TypedArrayOf();
```
### Constructor
Initializes a wrapper instance of an existing `Napi::TypedArrayOf` object.
```cpp
Napi::TypedArrayOf::TypedArrayOf(napi_env env, napi_value value);
```
- `[in] env`: The environment in which to create the `Napi::TypedArrayOf` object.
- `[in] value`: The `Napi::TypedArrayOf` reference to wrap.
### operator []
```cpp
T& Napi::TypedArrayOf::operator [](size_t index);
```
- `[in] index: The element index into the array.
Returns the element found at the given index.
### operator []
```cpp
const T& Napi::TypedArrayOf::operator [](size_t index) const;
```
- `[in] index: The element index into the array.
Returns the element found at the given index.
### Data
```cpp
T* Napi::TypedArrayOf::Data() const;
```
Returns a pointer into the backing `Napi::ArrayBuffer` which is offset to point to the
start of the array.
### Data
```cpp
const T* Napi::TypedArrayOf::Data() const
```
Returns a pointer into the backing `Napi::ArrayBuffer` which is offset to point to the
start of the array.

View File

@@ -0,0 +1,269 @@
# Value
`Napi::Value` is the C++ manifestation of a JavaScript value.
Value is a the base class upon which other JavaScript values such as Number, Boolean, String, and Object are based.
The following classes inherit, either directly or indirectly, from `Napi::Value`:
- [`Napi::Array`](array.md)
- [`Napi::ArrayBuffer`](array_buffer.md)
- [`Napi::Boolean`](boolean.md)
- [`Napi::Buffer`](buffer.md)
- [`Napi::External`](external.md)
- [`Napi::Function`](function.md)
- [`Napi::Name`](name.md)
- [`Napi::Number`](number.md)
- [`Napi::Object`](object.md)
- [`Napi::String`](string.md)
- [`Napi::Symbol`](symbol.md)
- [`Napi::TypedArray`](typed_array.md)
- [`Napi::TypedArrayOf`](typed_array_of.md)
## Methods
### Empty Constructor
```cpp
Napi::Value::Value();
```
Creates a new *empty* `Napi::Value` instance.
### Constructor
```cpp
Napi::Value::Value(napi_env env, napi_value value);
```
- `[in] env`: The `napi_env` environment in which to construct the `Napi::Value` object.
- `[in] value`: The C++ primitive from which to instantiate the `Napi::Value`. `value` may be any of:
- `bool`
- Any integer type
- Any floating point type
- `const char*` (encoded using UTF-8, null-terminated)
- `const char16_t*` (encoded using UTF-16-LE, null-terminated)
- `std::string` (encoded using UTF-8)
- `std::u16string`
- `Napi::Value`
- `napi_value`
### From
```cpp
template <typename T> static Napi::Value Napi::Value::From(napi_env env, const T& value);
```
- `[in] env`: The `napi_env` environment in which to create the `Napi::Value` object.
- `[in] value`: The N-API primitive value from which to create the `Napi::Value` object.
Returns a `Napi::Value` object from an N-API primitive value.
### operator napi_value
```cpp
operator napi_value() const;
```
Returns this Value's N-API value primitive.
Returns `nullptr` if this `Napi::Value` is *empty*.
### operator ==
```cpp
bool Napi::Value::operator ==(const Napi::Value& other) const;
```
- `[in] other`: The `Napi::Value` object to be compared.
Returns a `bool` indicating if this `Napi::Value` strictly equals another `Napi::Value`.
### operator !=
```cpp
bool Napi::Value::operator !=(const Napi::Value& other) const;
```
- `[in] other`: The `Napi::Value` object to be compared.
Returns a `bool` indicating if this `Napi::Value` does not strictly equal another `Napi::Value`.
### StrictEquals
```cpp
bool Napi::Value::StrictEquals(const Napi::Value& other) const;
```
- `[in] other`: The `Napi::Value` object to be compared.
Returns a `bool` indicating if this `Napi::Value` strictly equals another `Napi::Value`.
### Env
```cpp
Napi::Env Napi::Value::Env() const;
```
Returns the `Napi::Env` environment this value is associated with.
### IsEmpty
```cpp
bool Napi::Value::IsEmpty() const;
```
Returns a `bool` indicating if this `Napi::Value` is *empty* (uninitialized).
An empty `Napi::Value` is invalid, and most attempts to perform an operation on an empty Value will result in an exception.
Note an empty `Napi::Value` is distinct from JavaScript `null` or `undefined`, which are valid values.
When C++ exceptions are disabled at compile time, a method with a `Napi::Value` return type may return an empty Value to indicate a pending exception. So when not using C++ exceptions, callers should check whether this `Napi::Value` is empty before attempting to use it.
### Type
```cpp
napi_valuetype Napi::Value::Type() const;
```
Returns the `napi_valuetype` type of the `Napi::Value`.
### IsUndefined
```cpp
bool Napi::Value::IsUndefined() const;
```
Returns a `bool` indicating if this `Napi::Value` is an undefined JavaScript value.
### IsNull
```cpp
bool Napi::Value::IsNull() const;
```
Returns a `bool` indicating if this `Napi::Value` is a null JavaScript value.
### IsBoolean
```cpp
bool Napi::Value::IsBoolean() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript boolean.
### IsNumber
```cpp
bool Napi::Value::IsNumber() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript number.
### IsString
```cpp
bool Napi::Value::IsString() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript string.
### IsSymbol
```cpp
bool Napi::Value::IsSymbol() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript symbol.
### IsArray
```cpp
bool Napi::Value::IsArray() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript array.
### IsArrayBuffer
```cpp
bool Napi::Value::IsArrayBuffer() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript array buffer.
### IsTypedArray
```cpp
bool Napi::Value::IsTypedArray() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript typed array.
### IsObject
```cpp
bool Napi::Value::IsObject() const;
```
Returns a `bool` indicating if this `Napi::Value` is JavaScript object.
### IsFunction
```cpp
bool Napi::Value::IsFunction() const;
```
Returns a `bool` indicating if this `Napi::Value` is a JavaScript function.
### IsBuffer
```cpp
bool Napi::Value::IsBuffer() const;
```
Returns a `bool` indicating if this `Napi::Value` is a Node buffer.
### As
```cpp
template <typename T> T Napi::Value::As() const;
```
Casts to another type of `Napi::Value`, when the actual type is known or assumed.
This conversion does not coerce the type. Calling any methods inappropriate for the actual value type will throw `Napi::Error`.
### ToBoolean
```cpp
Napi::Boolean Napi::Value::ToBoolean() const;
```
Returns the `Napi::Value` coerced to a JavaScript boolean.
### ToNumber
```cpp
Napi::Number Napi::Value::ToNumber() const;
```
Returns the `Napi::Value` coerced to a JavaScript number.
### ToString
```cpp
Napi::String Napi::Value::ToString() const;
```
Returns the `Napi::Value` coerced to a JavaScript string.
### ToObject
```cpp
Napi::Object Napi::Value::ToObject() const;
```
Returns the `Napi::Value` coerced to a JavaScript object.

View File

@@ -0,0 +1,43 @@
# VersionManagement
The `Napi::VersionManagement` class contains methods that allow information
to be retrieved about the version of N-API and Node.js. In some cases it is
important to make decisions based on different versions of the system.
## Methods
### GetNapiVersion
Retrieves the highest N-API version supported by Node.js runtime.
```cpp
static uint32_t Napi::VersionManagement::GetNapiVersion(Env env);
```
- `[in] env`: The environment in which the API is invoked under.
Returns the highest N-API version supported by Node.js runtime.
### GetNodeVersion
Retrives information about Node.js version present on the system. All the
information is stored in the `napi_node_version` structrue that is defined as
shown below:
```cpp
typedef struct {
uint32_t major;
uint32_t minor;
uint32_t patch;
const char* release;
} napi_node_version;
````
```cpp
static const napi_node_version* Napi::VersionManagement::GetNodeVersion(Env env);
```
- `[in] env`: The environment in which the API is invoked under.
Returns the structure a pointer to the structure `napi_node_version` populated by
the version information of Node.js runtime.

Some files were not shown because too many files have changed in this diff Show More