diff --git a/node_modules/nan/.dntrc b/node_modules/nan/.dntrc new file mode 100644 index 00000000..47971da6 --- /dev/null +++ b/node_modules/nan/.dntrc @@ -0,0 +1,30 @@ +## DNT config file +## see https://github.com/rvagg/dnt + +NODE_VERSIONS="\ + master \ + v0.11.13 \ + v0.10.30 \ + v0.10.29 \ + v0.10.28 \ + v0.10.26 \ + v0.10.25 \ + v0.10.24 \ + v0.10.23 \ + v0.10.22 \ + v0.10.21 \ + v0.10.20 \ + v0.10.19 \ + v0.8.28 \ + v0.8.27 \ + v0.8.26 \ + v0.8.24 \ +" +OUTPUT_PREFIX="nan-" +TEST_CMD=" \ + cd /dnt/ && \ + npm install && \ + node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ + node_modules/.bin/tap --gc test/js/*-test.js \ +" + diff --git a/node_modules/nan/CHANGELOG.md b/node_modules/nan/CHANGELOG.md new file mode 100644 index 00000000..146cbb5c --- /dev/null +++ b/node_modules/nan/CHANGELOG.md @@ -0,0 +1,200 @@ +# NAN ChangeLog + +### Version 1.3.0: current Node unstable: 0.11.13, Node stable: 0.10.30 + + +**1.3.0 Aug 2 2014** + + - Added NanNew(std::string) + - Added NanNew(std::string&) + - Added NanAsciiString helper class + - Added NanUtf8String helper class + - Added NanUcs2String helper class + - Deprecated NanRawString() + - Deprecated NanCString() + - Added NanGetIsolateData(v8::Isolate *isolate) + - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) + - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) + - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + +**1.2.0 Jun 5 2014** + + - Add NanSetPrototypeTemplate + - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, + introduced _NanWeakCallbackDispatcher + - Removed -Wno-unused-local-typedefs from test builds + - Made test builds Windows compatible ('Sleep()') + +**1.1.2 May 28 2014** + + - Release to fix more stuff-ups in 1.1.1 + +**1.1.1 May 28 2014** + + - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 + +**1.1.0 May 25 2014** + + - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead + - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), + (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, + v8::String::ExternalAsciiStringResource* + - Deprecate NanSymbol() + - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker + +**1.0.0 May 4 2014** + + - Heavy API changes for V8 3.25 / Node 0.11.13 + - Use cpplint.py + - Removed NanInitPersistent + - Removed NanPersistentToLocal + - Removed NanFromV8String + - Removed NanMakeWeak + - Removed NanNewLocal + - Removed NAN_WEAK_CALLBACK_OBJECT + - Removed NAN_WEAK_CALLBACK_DATA + - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions + - Introduce NanUndefined, NanNull, NanTrue and NanFalse + - Introduce NanEscapableScope and NanEscapeScope + - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) + - Introduce NanMakeCallback for node::MakeCallback + - Introduce NanSetTemplate + - Introduce NanGetCurrentContext + - Introduce NanCompileScript and NanRunScript + - Introduce NanAdjustExternalMemory + - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback + - Introduce NanGetHeapStatistics + - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() + +**0.8.0 Jan 9 2014** + + - NanDispose -> NanDisposePersistent, deprecate NanDispose + - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() + +**0.7.1 Jan 9 2014** + + - Fixes to work against debug builds of Node + - Safer NanPersistentToLocal (avoid reinterpret_cast) + - Speed up common NanRawString case by only extracting flattened string when necessary + +**0.7.0 Dec 17 2013** + + - New no-arg form of NanCallback() constructor. + - NanCallback#Call takes Handle rather than Local + - Removed deprecated NanCallback#Run method, use NanCallback#Call instead + - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS + - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() + - Introduce NanRawString() for char* (or appropriate void*) from v8::String + (replacement for NanFromV8String) + - Introduce NanCString() for null-terminated char* from v8::String + +**0.6.0 Nov 21 2013** + + - Introduce NanNewLocal(v8::Handle value) for use in place of + v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 + +**0.5.2 Nov 16 2013** + + - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public + +**0.5.1 Nov 12 2013** + + - Use node::MakeCallback() instead of direct v8::Function::Call() + +**0.5.0 Nov 11 2013** + + - Added @TooTallNate as collaborator + - New, much simpler, "include_dirs" for binding.gyp + - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros + +**0.4.4 Nov 2 2013** + + - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ + +**0.4.3 Nov 2 2013** + + - Include node_object_wrap.h, removed from node.h for Node 0.11.8. + +**0.4.2 Nov 2 2013** + + - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for + Node 0.11.8 release. + +**0.4.1 Sep 16 2013** + + - Added explicit `#include ` as it was removed from node.h for v0.11.8 + +**0.4.0 Sep 2 2013** + + - Added NAN_INLINE and NAN_DEPRECATED and made use of them + - Added NanError, NanTypeError and NanRangeError + - Cleaned up code + +**0.3.2 Aug 30 2013** + + - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent + in NanAsyncWorker + +**0.3.1 Aug 20 2013** + + - fix "not all control paths return a value" compile warning on some platforms + +**0.3.0 Aug 19 2013** + + - Made NAN work with NPM + - Lots of fixes to NanFromV8String, pulling in features from new Node core + - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API + - Added optional error number argument for NanThrowError() + - Added NanInitPersistent() + - Added NanReturnNull() and NanReturnEmptyString() + - Added NanLocker and NanUnlocker + - Added missing scopes + - Made sure to clear disposed Persistent handles + - Changed NanAsyncWorker to allocate error messages on the heap + - Changed NanThrowError(Local) to NanThrowError(Handle) + - Fixed leak in NanAsyncWorker when errmsg is used + +**0.2.2 Aug 5 2013** + + - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() + +**0.2.1 Aug 5 2013** + + - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for + NanFromV8String() + +**0.2.0 Aug 5 2013** + + - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, + NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY + - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, + _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, + _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, + _NAN_PROPERTY_QUERY_ARGS + - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer + - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, + NAN_WEAK_CALLBACK_DATA, NanMakeWeak + - Renamed THROW_ERROR to _NAN_THROW_ERROR + - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) + - Added NanBufferUse(char*, uint32_t) + - Added NanNewContextHandle(v8::ExtensionConfiguration*, + v8::Handle, v8::Handle) + - Fixed broken NanCallback#GetFunction() + - Added optional encoding and size arguments to NanFromV8String() + - Added NanGetPointerSafe() and NanSetPointerSafe() + - Added initial test suite (to be expanded) + - Allow NanUInt32OptionValue to convert any Number object + +**0.1.0 Jul 21 2013** + + - Added `NAN_GETTER`, `NAN_SETTER` + - Added `NanThrowError` with single Local argument + - Added `NanNewBufferHandle` with single uint32_t argument + - Added `NanHasInstance(Persistent&, Handle)` + - Added `Local NanCallback#GetFunction()` + - Added `NanCallback#Call(int, Local[])` + - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/node_modules/nan/LICENSE b/node_modules/nan/LICENSE new file mode 100644 index 00000000..d502e18a --- /dev/null +++ b/node_modules/nan/LICENSE @@ -0,0 +1,46 @@ +Copyright 2013, NAN contributors: + - Rod Vagg + - Benjamin Byholm + - Trevor Norris + - Nathan Rajlich + - Brett Lawson + - Ben Noordhuis +(the "Original Author") +All rights reserved. + +MIT +no-false-attribs 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. + +Distributions of all or part of the Software intended to be used +by the recipients as they would use the unmodified Software, +containing modifications that substantially alter, remove, or +disable functionality of the Software, outside of the documented +configuration mechanisms provided by the Software, shall be +modified such that the Original Author's bug reporting email +addresses and urls are either replaced with the contact information +of the parties responsible for the changes, or removed entirely. + +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. + + +Except where noted, this license applies to any and all software +programs and associated documentation files created by the +Original Author, when distributed with the Software. diff --git a/node_modules/nan/README.md b/node_modules/nan/README.md new file mode 100644 index 00000000..2904a380 --- /dev/null +++ b/node_modules/nan/README.md @@ -0,0 +1,1054 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.11, and eventually 0.12.** + +***Current version: 1.3.0*** + +*(See [nan.h](https://github.com/rvagg/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[![NPM](https://nodei.co/npm/nan.png?downloads=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6)](https://nodei.co/npm/nan/) + +[![Build Status](https://secure.travis-ci.org/rvagg/nan.png)](http://travis-ci.org/rvagg/nan) +[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.11/0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + + +## News & Updates + +### Aug-2014: 1.3.0 release + +* `NanCString()` and `NanRawString()` have been deprecated in favour of new NanAsciiString, NanUtf8String and NanUcs2String. These classes manage the underlying memory for you in a safer way than just handing off an allocated array. You should now `*NanAsciiString(handle)` to access the raw `char` data, you can also allocate on the heap if you need to keep a reference. +* Two more NanMakeCallback overloads have been added to for parity with Node core. +* You can now `NanNew(std::string)` (use `NanNew(std::string&)` to pass by reference) +* NanSetTemplate, NanSetPrototypeTemplate and NanSetInstanceTemplate have been added. + +### May-2014: 1.1.0 release + +* We've deprecated `NanSymbol()`, you should just use `NanNew()` now. +* `NanNull()`, `NanUndefined()`, `NanTrue()`, `NanFalse()` all return `Local`s now. +* `nan_isolate` is gone, it was intended to be internal-only but if you were using it then you should switch to `v8::Isolate::GetCurrent()`. +* `NanNew()` has received some additional overload-love so you should be able to give it many kinds of values without specifying the ``. +* Lots of small fixes and additions to expand the V8 API coverage, *use the source, Luke*. + + +### May-2014: Major changes for V8 3.25 / Node 0.11.13 + +Node 0.11.11 and 0.11.12 were both broken releases for native add-ons, you simply can't properly compile against either of them for different reasons. But we now have a 0.11.13 release that jumps a couple of versions of V8 ahead and includes some more, major (traumatic) API changes. + +Because we are now nearing Node 0.12 and estimate that the version of V8 we are using in Node 0.11.13 will be close to the API we get for 0.12, we have taken the opportunity to not only *fix* NAN for 0.11.13 but make some major changes to improve the NAN API. + +We have **removed support for Node 0.11 versions prior to 0.11.13**. As usual, our tests are run against (and pass) the last 5 versions of Node 0.8 and Node 0.10. We also include Node 0.11.13 obviously. + +The major change is something that [Benjamin Byholm](kkoopa) has put many hours in to. We now have a fantastic new `NanNew(args)` interface for creating new `Local`s, this replaces `NanNewLocal()` and much more. If you look in [./nan.h](nan.h) you'll see a large number of overloaded versions of this method. In general you should be able to `NanNew(arguments)` for any type you want to make a `Local` from. This includes `Persistent` types, so we now have a `Local NanNew(const Persistent arg)` to replace `NanPersistentToLocal()`. + +We also now have `NanUndefined()`, `NanNull()`, `NanTrue()` and `NanFalse()`. Mainly because of the new requirement for an `Isolate` argument for each of the native V8 versions of this. + +V8 has now introduced an `EscapableHandleScope` from which you `scope.Escape(Local value)` to *return* a value from a one scope to another. This replaces the standard `HandleScope` and `scope.Close(Local value)`, although `HandleScope` still exists for when you don't need to return a handle to the caller. For NAN we are exposing it as `NanEscapableScope()` and `NanEscapeScope()`, while `NanScope()` is still how you create a new scope that doesn't need to return handles. For older versions of Node/V8, it'll still map to the older `HandleScope` functionality. + +`NanFromV8String()` was deprecated and has now been removed. You should use `NanCString()` or `NanRawString()` instead. + +Because `node::MakeCallback()` now takes an `Isolate`, and because it doesn't exist in older versions of Node, we've introduced `NanMakeCallback()`. You should *always* use this when calling a JavaScript function from C++. + +There's lots more, check out the Changelog in nan.h or look through [#86](https://github.com/rvagg/nan/pull/86) for all the gory details. + +### Dec-2013: NanCString and NanRawString + +Two new functions have been introduced to replace the functionality that's been provided by `NanFromV8String` until now. NanCString has sensible defaults so it's super easy to fetch a null-terminated c-style string out of a `v8::String`. `NanFromV8String` is still around and has defaults that allow you to pass a single handle to fetch a `char*` while `NanRawString` requires a little more attention to arguments. + +### Nov-2013: Node 0.11.9+ breaking V8 change + +The version of V8 that's shipping with Node 0.11.9+ has changed the signature for new `Local`s to: `v8::Local::New(isolate, value)`, i.e. introducing the `isolate` argument and therefore breaking all new `Local` declarations for previous versions. NAN 0.6+ now includes a `NanNewLocal(value)` that can be used in place to work around this incompatibility and maintain compatibility with 0.8->0.11.9+ (minus a few early 0.11 releases). + +For example, if you wanted to return a `null` on a callback you will have to change the argument from `v8::Local::New(v8::Null())` to `NanNewLocal(v8::Null())`. + +### Nov-2013: Change to binding.gyp `"include_dirs"` for NAN + +Inclusion of NAN in a project's binding.gyp is now greatly simplified. You can now just use `" +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: + +``` python +"include_dirs" : [ + "` when compiling your addon. + + +## Example + +See **[LevelDOWN](https://github.com/rvagg/node-leveldown/pull/48)** for a full example of **NAN** in use. + +For a simpler example, see the **[async pi estimation example](https://github.com/rvagg/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +Compare to the current 0.10 version of this example, found in the [node-addon-examples](https://github.com/rvagg/node-addon-examples/tree/master/9_async_work) repository and also a 0.11 version of the same found [here](https://github.com/kkoopa/node-addon-examples/tree/5c01f58fc993377a567812597e54a83af69686d7/9_async_work). + +Note that there is no embedded version sniffing going on here and also the async work is made much simpler, see below for details on the `NanAsyncWorker` class. + +```c++ +// addon.cc +#include +#include +// ... + +using v8::FunctionTemplate; +using v8::Handle; +using v8::Object; +using v8::String; + +void InitAll(Handle exports) { + exports->Set(NanNew("calculateSync"), + NanNew(CalculateSync)->GetFunction()); + + exports->Set(NanNew("calculateAsync"), + NanNew(CalculateAsync)->GetFunction()); +} + +NODE_MODULE(addon, InitAll) +``` + +```c++ +// sync.h +#include +#include + +NAN_METHOD(CalculateSync); +``` + +```c++ +// sync.cc +#include +#include +#include "./sync.h" +// ... + +using v8::Number; + +// Simple synchronous access to the `Estimate()` function +NAN_METHOD(CalculateSync) { + NanScope(); + + // expect a number as the first argument + int points = args[0]->Uint32Value(); + double est = Estimate(points); + + NanReturnValue(NanNew(est)); +} +``` + +```c++ +// async.h +#include +#include + +NAN_METHOD(CalculateAsync); +``` + +```c++ +// async.cc +#include +#include +#include "./async.h" + +// ... + +using v8::Function; +using v8::Local; +using v8::Null; +using v8::Number; +using v8::Value; + +class PiWorker : public NanAsyncWorker { + public: + PiWorker(NanCallback *callback, int points) + : NanAsyncWorker(callback), points(points) {} + ~PiWorker() {} + + // Executed inside the worker-thread. + // It is not safe to access V8, or V8 data structures + // here, so everything we need for input and output + // should go on `this`. + void Execute () { + estimate = Estimate(points); + } + + // Executed when the async work is complete + // this function will be run inside the main event loop + // so it is safe to use V8 again + void HandleOKCallback () { + NanScope(); + + Local argv[] = { + NanNull() + , NanNew(estimate) + }; + + callback->Call(2, argv); + }; + + private: + int points; + double estimate; +}; + +// Asynchronous access to the `Estimate()` function +NAN_METHOD(CalculateAsync) { + NanScope(); + + int points = args[0]->Uint32Value(); + NanCallback *callback = new NanCallback(args[1].As()); + + NanAsyncQueueWorker(new PiWorker(callback, points)); + NanReturnUndefined(); +} +``` + + +## API + + * NAN_METHOD + * NAN_GETTER + * NAN_SETTER + * NAN_PROPERTY_GETTER + * NAN_PROPERTY_SETTER + * NAN_PROPERTY_ENUMERATOR + * NAN_PROPERTY_DELETER + * NAN_PROPERTY_QUERY + * NAN_INDEX_GETTER + * NAN_INDEX_SETTER + * NAN_INDEX_ENUMERATOR + * NAN_INDEX_DELETER + * NAN_INDEX_QUERY + * NAN_WEAK_CALLBACK + * NAN_DEPRECATED + * NAN_INLINE + * NanNew + * NanUndefined + * NanNull + * NanTrue + * NanFalse + * NanReturnValue + * NanReturnUndefined + * NanReturnNull + * NanReturnEmptyString + * NanScope + * NanEscapableScope + * NanEscapeScope + * NanLocker + * NanUnlocker + * NanGetInternalFieldPointer + * NanSetInternalFieldPointer + * NanObjectWrapHandle + * NanSymbol + * NanGetPointerSafe + * NanSetPointerSafe + * NanRawString + * NanCString + * NanAsciiString + * NanUtf8String + * NanUcs2String + * NanBooleanOptionValue + * NanUInt32OptionValue + * NanError, NanTypeError, NanRangeError + * NanThrowError, NanThrowTypeError, NanThrowRangeError, NanThrowError(Handle), NanThrowError(Handle, int) + * NanNewBufferHandle(char *, size_t, FreeCallback, void *), NanNewBufferHandle(char *, uint32_t), NanNewBufferHandle(uint32_t) + * NanBufferUse(char *, uint32_t) + * NanNewContextHandle + * NanGetCurrentContext + * NanHasInstance + * NanDisposePersistent + * NanAssignPersistent + * NanMakeWeakPersistent + * NanSetTemplate + * NanSetPrototypeTemplate + * NanSetInstanceTemplate + * NanMakeCallback + * NanCompileScript + * NanRunScript + * NanAdjustExternalMemory + * NanAddGCEpilogueCallback + * NanAddGCPrologueCallback + * NanRemoveGCEpilogueCallback + * NanRemoveGCPrologueCallback + * NanGetHeapStatistics + * NanCallback + * NanAsyncWorker + * NanAsyncQueueWorker + + +### NAN_METHOD(methodname) + +Use `NAN_METHOD` to define your V8 accessible methods: + +```c++ +// .h: +class Foo : public node::ObjectWrap { + ... + + static NAN_METHOD(Bar); + static NAN_METHOD(Baz); +} + + +// .cc: +NAN_METHOD(Foo::Bar) { + ... +} + +NAN_METHOD(Foo::Baz) { + ... +} +``` + +The reason for this macro is because of the method signature change in 0.11: + +```c++ +// 0.10 and below: +Handle name(const Arguments& args) + +// 0.11 and above +void name(const FunctionCallbackInfo& args) +``` + +The introduction of `FunctionCallbackInfo` brings additional complications: + + +### NAN_GETTER(methodname) + +Use `NAN_GETTER` to declare your V8 accessible getters. You get a `Local` `property` and an appropriately typed `args` object that can act like the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_GETTER`. + + +### NAN_SETTER(methodname) + +Use `NAN_SETTER` to declare your V8 accessible setters. Same as `NAN_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_GETTER(cbname) +Use `NAN_PROPERTY_GETTER` to declare your V8 accessible property getters. You get a `Local` `property` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_GETTER`. + + +### NAN_PROPERTY_SETTER(cbname) +Use `NAN_PROPERTY_SETTER` to declare your V8 accessible property setters. Same as `NAN_PROPERTY_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_PROPERTY_ENUMERATOR(cbname) +Use `NAN_PROPERTY_ENUMERATOR` to declare your V8 accessible property enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_PROPERTY_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_ENUMERATOR`. + + +### NAN_PROPERTY_DELETER(cbname) +Use `NAN_PROPERTY_DELETER` to declare your V8 accessible property deleters. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_DELETER`. + + +### NAN_PROPERTY_QUERY(cbname) +Use `NAN_PROPERTY_QUERY` to declare your V8 accessible property queries. Same as `NAN_PROPERTY_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_QUERY`. + + +### NAN_INDEX_GETTER(cbname) +Use `NAN_INDEX_GETTER` to declare your V8 accessible index getters. You get a `uint32_t` `index` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_GETTER`. + + +### NAN_INDEX_SETTER(cbname) +Use `NAN_INDEX_SETTER` to declare your V8 accessible index setters. Same as `NAN_INDEX_GETTER` but you also get a `Local` `value` object to work with. + + +### NAN_INDEX_ENUMERATOR(cbname) +Use `NAN_INDEX_ENUMERATOR` to declare your V8 accessible index enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_INDEX_GETTER` call. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_ENUMERATOR`. + + +### NAN_INDEX_DELETER(cbname) +Use `NAN_INDEX_DELETER` to declare your V8 accessible index deleters. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_DELETER`. + + +### NAN_INDEX_QUERY(cbname) +Use `NAN_INDEX_QUERY` to declare your V8 accessible index queries. Same as `NAN_INDEX_GETTER`. + +You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_INDEX_QUERY`. + + +### NAN_WEAK_CALLBACK(cbname) + +Use `NAN_WEAK_CALLBACK` to define your V8 WeakReference callbacks. There is an argument object `const _NanWeakCallbackData &data` allowing access to the weak object and the supplied parameter through its `GetValue` and `GetParameter` methods. You can even access the weak callback info object through the `GetCallbackInfo()`method, but you probably should not. `Revive()` keeps the weak object alive until the next GC round. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + int *parameter = data.GetParameter(); + NanMakeCallback(NanGetCurrentContext()->Global(), data.GetValue(), 0, NULL); + if ((*parameter)++ == 0) { + data.Revive(); + } else { + delete parameter; + } +} +``` + + +### NAN_DEPRECATED +Declares a function as deprecated. + +```c++ +static NAN_DEPRECATED NAN_METHOD(foo) { + ... +} +``` + + +### NAN_INLINE +Inlines a function. + +```c++ +NAN_INLINE int foo(int bar) { + ... +} +``` + + +### Local<T> NanNew<T>( ... ) + +Use `NanNew` to construct almost all v8 objects and make new local handles. + +Note: Using NanNew with an std::string is possible, however, you should ensure +to use the overload version (`NanNew(stdString)`) rather than the template +version (`NanNew(stdString)`) as there is an unnecessary +performance penalty to using the template version because of the inability for +compilers to appropriately deduce to reference types on template specialization. + +```c++ +Local s = NanNew("value"); + +... + +Persistent o; + +... + +Local lo = NanNew(o); + +``` + + +### Local<Primitive> NanUndefined() + +Use instead of `Undefined()` + + +### Local<Primitive> NanNull() + +Use instead of `Null()` + + +### Local<Boolean> NanTrue() + +Use instead of `True()` + + +### Local<Boolean> NanFalse() + +Use instead of `False()` + + +### NanReturnValue(Handle<Value>) + +Use `NanReturnValue` when you want to return a value from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Bar) { + ... + + NanReturnValue(NanNew("FooBar!")); +} +``` + +No `return` statement required. + + +### NanReturnUndefined() + +Use `NanReturnUndefined` when you don't want to return anything from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnUndefined(); +} +``` + + +### NanReturnNull() + +Use `NanReturnNull` when you want to return `Null` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnNull(); +} +``` + + +### NanReturnEmptyString() + +Use `NanReturnEmptyString` when you want to return an empty `String` from your V8 accessible method: + +```c++ +NAN_METHOD(Foo::Baz) { + ... + + NanReturnEmptyString(); +} +``` + + +### NanScope() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanScope()` necessary, use it in place of `HandleScope scope` when you do not wish to return handles (`Handle` or `Local`) to the surrounding scope (or in functions directly exposed to V8, as they do not return values in the normal sense): + +```c++ +NAN_METHOD(Foo::Bar) { + NanScope(); + + NanReturnValue(NanNew("FooBar!")); +} +``` + +This method is not directly exposed to V8, nor does it return a handle, so it uses an unescapable scope: + +```c++ +bool Foo::Bar() { + NanScope(); + + Local val = NanFalse(); + ... + return val->Value(); +} +``` + + +### NanEscapableScope() + +The separation of handle scopes into escapable and inescapable scopes makes `NanEscapableScope()` necessary, use it in place of `HandleScope scope` when you later wish to return a handle (`Handle` or `Local`) from the scope, this is for internal functions not directly exposed to V8: + +```c++ +Handle Foo::Bar() { + NanEscapableScope(); + + return NanEscapeScope(NanNew("FooBar!")); +} +``` + + +### Local<T> NanEscapeScope(Handle<T> value); +Use together with `NanEscapableScope` to escape the scope. Corresponds to `HandleScope::Close` or `EscapableHandleScope::Escape`. + + +### NanLocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanLocker()` necessary, use it in place of `Locker locker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### NanUnlocker() + +The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanUnlocker()` necessary, use it in place of `Unlocker unlocker`: + +```c++ +NAN_METHOD(Foo::Bar) { + NanLocker(); + ... + NanUnlocker(); +} +``` + + +### void * NanGetInternalFieldPointer(Handle<Object>, int) + +Gets a pointer to the internal field with at `index` from a V8 `Object` handle. + +```c++ +Local obj; +... +NanGetInternalFieldPointer(obj, 0); +``` + +### void NanSetInternalFieldPointer(Handle<Object>, int, void *) + +Sets the value of the internal field at `index` on a V8 `Object` handle. + +```c++ +static Persistent dataWrapperCtor; +... +Local wrapper = NanNew(dataWrapperCtor)->NewInstance(); +NanSetInternalFieldPointer(wrapper, 0, this); +``` + + +### Local<Object> NanObjectWrapHandle(Object) + +When you want to fetch the V8 object handle from a native object you've wrapped with Node's `ObjectWrap`, you should use `NanObjectWrapHandle`: + +```c++ +NanObjectWrapHandle(iterator)->Get(NanNew("end")) +``` + + +### Local<String> NanSymbol(const char *) + +Deprecated. Use `NanNew` instead. +Use to create string symbol objects (i.e. `v8::String::NewSymbol(x)`), for getting and setting object properties, or names of objects. + +```c++ +bool foo = false; +if (obj->Has(NanNew("foo"))) + foo = optionsObj->Get(NanNew("foo"))->BooleanValue() +``` + + +### Type NanGetPointerSafe(Type *[, Type]) + +A helper for getting values from optional pointers. If the pointer is `NULL`, the function returns the optional default value, which defaults to `0`. Otherwise, the function returns the value the pointer points to. + +```c++ +char *plugh(uint32_t *optional) { + char res[] = "xyzzy"; + uint32_t param = NanGetPointerSafe(optional, 0x1337); + switch (param) { + ... + } + NanSetPointerSafe(optional, 0xDEADBEEF); +} +``` + + +### bool NanSetPointerSafe(Type *, Type) + +A helper for setting optional argument pointers. If the pointer is `NULL`, the function simply returns `false`. Otherwise, the value is assigned to the variable the pointer points to. + +```c++ +const char *plugh(size_t *outputsize) { + char res[] = "xyzzy"; + if !(NanSetPointerSafe(outputsize, strlen(res) + 1)) { + ... + } + + ... +} +``` + + +### void* NanRawString(Handle<Value>, enum Nan::Encoding, size_t *, void *, size_t, int) + +Deprecated. Use something else. + +When you want to convert a V8 `String` to a `char*` buffer, use `NanRawString`. You have to supply an encoding as well as a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows setting `String::WriteOptions`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer: + +```c++ +size_t count; +void* decoded = NanRawString(args[1], Nan::BASE64, &count, NULL, 0, String::HINT_MANY_WRITES_EXPECTED); +... +delete[] reinterpret_cast(decoded); +``` + + +### char* NanCString(Handle<Value>, size_t *[, char *, size_t, int]) + +Deprecated. Use `NanUtf8String` instead. + +When you want to convert a V8 `String` to a null-terminated C `char*` use `NanCString`. The resulting `char*` will be UTF-8-encoded, and you need to supply a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows optionally setting `String::WriteOptions`, which default to `v8::String::NO_OPTIONS`. +Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer: + +```c++ +size_t count; +char* name = NanCString(args[0], &count); +... +delete[] name; +``` + + +### NanAsciiString + +Convert a `String` to zero-terminated, Ascii-encoded `char *`. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanAsciiString(arg[0]))); +} +``` + + +### NanUtf8String + +Convert a `String` to zero-terminated, Utf8-encoded `char *`. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUtf8String(arg[0]))); +} +``` + + +### NanUcs2String + +Convert a `String` to zero-terminated, Ucs2-encoded `uint16_t *`. + +```c++ +NAN_METHOD(foo) { + NanScope(); + NanReturnValue(NanNew(*NanUcs2String(arg[0]))); +} +``` + + +### bool NanBooleanOptionValue(Handle<Value>, Handle<String>[, bool]) + +When you have an "options" object that you need to fetch properties from, boolean options can be fetched with this pair. They check first if the object exists (`IsEmpty`), then if the object has the given property (`Has`) then they get and convert/coerce the property to a `bool`. + +The optional last parameter is the *default* value, which is `false` if left off: + +```c++ +// `foo` is false unless the user supplies a truthy value for it +bool foo = NanBooleanOptionValue(optionsObj, NanNew("foo")); +// `bar` is true unless the user supplies a falsy value for it +bool bar = NanBooleanOptionValueDefTrue(optionsObj, NanNew("bar"), true); +``` + + +### uint32_t NanUInt32OptionValue(Handle<Value>, Handle<String>, uint32_t) + +Similar to `NanBooleanOptionValue`, use `NanUInt32OptionValue` to fetch an integer option from your options object. Can be any kind of JavaScript `Number` and it will be coerced to an unsigned 32-bit integer. + +Requires all 3 arguments as a default is not optional: + +```c++ +uint32_t count = NanUInt32OptionValue(optionsObj, NanNew("count"), 1024); +``` + + +### NanError(message), NanTypeError(message), NanRangeError(message) + +For making `Error`, `TypeError` and `RangeError` objects. + +```c++ +Local res = NanError("you must supply a callback argument"); +``` + + +### NanThrowError(message), NanThrowTypeError(message), NanThrowRangeError(message), NanThrowError(Local<Value>), NanThrowError(Local<Value>, int) + +For throwing `Error`, `TypeError` and `RangeError` objects. + +```c++ +NanThrowError("you must supply a callback argument"); +``` + +Can also handle any custom object you may want to throw. If used with the error code argument, it will add the supplied error code to the error object as a property called `code`. + + +### Local<Object> NanNewBufferHandle(char *, uint32_t), Local<Object> NanNewBufferHandle(uint32_t) + +The `Buffer` API has changed a little in Node 0.11, this helper provides consistent access to `Buffer` creation: + +```c++ +NanNewBufferHandle((char*)value.data(), value.size()); +``` + +Can also be used to initialize a `Buffer` with just a `size` argument. + +Can also be supplied with a `NanFreeCallback` and a hint for the garbage collector. + + +### Local<Object> NanBufferUse(char*, uint32_t) + +`Buffer::New(char*, uint32_t)` prior to 0.11 would make a copy of the data. +While it was possible to get around this, it required a shim by passing a +callback. So the new API `Buffer::Use(char*, uint32_t)` was introduced to remove +needing to use this shim. + +`NanBufferUse` uses the `char*` passed as the backing data, and will free the +memory automatically when the weak callback is called. Keep this in mind, as +careless use can lead to "double free or corruption" and other cryptic failures. + + +### bool NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>) + +Can be used to check the type of an object to determine it is of a particular class you have already defined and have a `Persistent` handle for. + + +### Local<Context> NanNewContextHandle([ExtensionConfiguration*, Handle<ObjectTemplate>, Handle<Value>]) +Creates a new `Local` handle. + +```c++ +Local ftmpl = NanNew(); +Local otmpl = ftmpl->InstanceTemplate(); +Local ctx = NanNewContextHandle(NULL, otmpl); +``` + + +### Local<Context> NanGetCurrentContext() + +Gets the current context. + +```c++ +Local ctx = NanGetCurrentContext(); +``` + + +### void NanDisposePersistent(Persistent<T> &) + +Use `NanDisposePersistent` to dispose a `Persistent` handle. + +```c++ +NanDisposePersistent(persistentHandle); +``` + + +### NanAssignPersistent(handle, object) + +Use `NanAssignPersistent` to assign a non-`Persistent` handle to a `Persistent` one. You can no longer just declare a `Persistent` handle and assign directly to it later, you have to `Reset` it in Node 0.11, so this makes it easier. + +In general it is now better to place anything you want to protect from V8's garbage collector as properties of a generic `Object` and then assign that to a `Persistent`. This works in older versions of Node also if you use `NanAssignPersistent`: + +```c++ +Persistent persistentHandle; + +... + +Local obj = NanNew(); +obj->Set(NanNew("key"), keyHandle); // where keyHandle might be a Local +NanAssignPersistent(persistentHandle, obj) +``` + + +### _NanWeakCallbackInfo<T, P>* NanMakeWeakPersistent(Handle<T>, P*, _NanWeakCallbackInfo<T, P>::Callback) + +Creates a weak persistent handle with the supplied parameter and `NAN_WEAK_CALLBACK`. + +```c++ +NAN_WEAK_CALLBACK(weakCallback) { + +... + +} + +Local func; + +... + +int *parameter = new int(0); +NanMakeWeakPersistent(func, parameter, &weakCallback); +``` + + +### NanSetTemplate(templ, name, value [, attributes]) + +Use to add properties on object and function templates. + + +### NanSetPrototypeTemplate(templ, name, value [, attributes]) + +Use to add prototype properties on function templates. + + +### NanSetInstanceTemplate(templ, name, value [, attributes]) + +Use to add instance properties on function templates. + + +### NanMakeCallback(target, func, argc, argv) + +Use instead of `node::MakeCallback` to call javascript functions. This is the only proper way of calling functions. + + +### NanCompileScript(Handle s [, const ScriptOrigin& origin]) + +Use to create new scripts bound to the current context. + + +### NanRunScript(script) + +Use to run both bound and unbound scripts. + + +### NanAdjustExternalMemory(int change_in_bytes) + +Simply does `AdjustAmountOfExternalAllocatedMemory`, note that the argument and returned value have type `int`. + + +### NanAddGCEpilogueCallback(GCEpilogueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCEpilogueCallback` + + +### NanAddGCPrologueCallback(GCPrologueCallback callback, GCType gc_type_filter=kGCTypeAll) + +Simply does `AddGCPrologueCallback` + + +### NanRemoveGCEpilogueCallback(GCEpilogueCallback callback) + +Simply does `RemoveGCEpilogueCallback` + + +### NanRemoveGCPrologueCallback(GCPrologueCallback callback) + +Simply does `RemoveGCPrologueCallback` + + +### NanGetHeapStatistics(HeapStatistics *heap_statistics) + +Simply does `GetHeapStatistics` + + +### NanCallback + +Because of the difficulties imposed by the changes to `Persistent` handles in V8 in Node 0.11, creating `Persistent` versions of your `Handle` is annoyingly tricky. `NanCallback` makes it easier by taking your handle, making it persistent until the `NanCallback` is deleted and even providing a handy `Call()` method to fetch and execute the callback `Function`. + +```c++ +Local callbackHandle = args[0].As(); +NanCallback *callback = new NanCallback(callbackHandle); +// pass `callback` around and it's safe from GC until you: +delete callback; +``` + +You can execute the callback like so: + +```c++ +// no arguments: +callback->Call(0, NULL); + +// an error argument: +Handle argv[] = { + NanError(NanNew("fail!")) +}; +callback->Call(1, argv); + +// a success argument: +Handle argv[] = { + NanNull(), + NanNew("w00t!") +}; +callback->Call(2, argv); +``` + +`NanCallback` also has a `Local GetCallback()` method that you can use +to fetch a local handle to the underlying callback function, as well as a +`void SetFunction(Handle)` for setting the callback on the +`NanCallback`. You can check if a `NanCallback` is empty with the `bool IsEmpty()` method. Additionally a generic constructor is available for using +`NanCallback` without performing heap allocations. + + +### NanAsyncWorker + +`NanAsyncWorker` is an abstract class that you can subclass to have much of the annoying async queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the async work is in progress. + +See a rough outline of the implementation: + +```c++ +class NanAsyncWorker { +public: + NanAsyncWorker (NanCallback *callback); + + // Clean up persistent handles and delete the *callback + virtual ~NanAsyncWorker (); + + // Check the `ErrorMessage()` and call HandleOKCallback() + // or HandleErrorCallback depending on whether it has been set or not + virtual void WorkComplete (); + + // You must implement this to do some async work. If there is an + // error then use `SetErrorMessage()` to set an error message and the callback will + // be passed that string in an Error object + virtual void Execute (); + + // Save a V8 object in a Persistent handle to protect it from GC + void SaveToPersistent(const char *key, Local &obj); + + // Fetch a stored V8 object (don't call from within `Execute()`) + Local GetFromPersistent(const char *key); + + // Get the error message (or NULL) + const char *ErrorMessage(); + + // Set an error message + void SetErrorMessage(const char *msg); + +protected: + // Default implementation calls the callback function with no arguments. + // Override this to return meaningful data + virtual void HandleOKCallback (); + + // Default implementation calls the callback function with an Error object + // wrapping the `errmsg` string + virtual void HandleErrorCallback (); +}; +``` + + +### NanAsyncQueueWorker(NanAsyncWorker *) + +`NanAsyncQueueWorker` will run a `NanAsyncWorker` asynchronously via libuv. Both the *execute* and *after_work* steps are taken care of for you—most of the logic for this is embedded in `NanAsyncWorker`. + +### Contributors + +NAN is only possible due to the excellent work of the following contributors: + + + + + + + + +
Rod VaggGitHub/rvaggTwitter/@rvagg
Benjamin ByholmGitHub/kkoopa-
Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
Brett LawsonGitHub/brett19Twitter/@brett19x
Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
+ +Licence & copyright +----------------------- + +Copyright (c) 2014 NAN contributors (listed above). + +Native Abstractions for Node.js is licensed under an MIT +no-false-attribs license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/node_modules/nan/appveyor.yml b/node_modules/nan/appveyor.yml new file mode 100644 index 00000000..657eed6d --- /dev/null +++ b/node_modules/nan/appveyor.yml @@ -0,0 +1,32 @@ +# http://www.appveyor.com/docs/appveyor-yml + +# Test against these versions of Node.js. +environment: + matrix: + - nodejs_version: "0.8" + - nodejs_version: "0.10" + - nodejs_version: "0.11" + +# Install scripts. (runs after repo cloning) +install: + # Get the latest stable version of Node 0.STABLE.latest + - npm install npm + - move node_modules npm + - ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) + # Typical npm stuff. + - npm/.bin/npm install + - npm/.bin/npm run rebuild-tests + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + - cmd: npm test + +# Don't actually build. +build: off + +# Set build version format here instead of in the admin panel. +version: "{build}" + diff --git a/node_modules/nan/include_dirs.js b/node_modules/nan/include_dirs.js new file mode 100644 index 00000000..4f1dfb41 --- /dev/null +++ b/node_modules/nan/include_dirs.js @@ -0,0 +1 @@ +console.log(require('path').relative('.', __dirname)); diff --git a/node_modules/nan/nan.h b/node_modules/nan/nan.h new file mode 100644 index 00000000..063de4e5 --- /dev/null +++ b/node_modules/nan/nan.h @@ -0,0 +1,2331 @@ +/********************************************************************************** + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2014 NAN contributors: + * - Rod Vagg + * - Benjamin Byholm + * - Trevor Norris + * - Nathan Rajlich + * - Brett Lawson + * - Ben Noordhuis + * + * MIT +no-false-attribs License + * + * Version 1.3.0: current Node unstable: 0.11.13, Node stable: 0.10.30 + * + * See https://github.com/rvagg/nan for the latest update to this file + **********************************************************************************/ + +#ifndef NAN_H_ +#define NAN_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__GNUC__) && !defined(DEBUG) +# define NAN_INLINE inline __attribute__((always_inline)) +#elif defined(_MSC_VER) && !defined(DEBUG) +# define NAN_INLINE __forceinline +#else +# define NAN_INLINE inline +#endif + +#if defined(__GNUC__) && !V8_DISABLE_DEPRECATIONS +# define NAN_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) && !V8_DISABLE_DEPRECATIONS +# define NAN_DEPRECATED __declspec(deprecated) +#else +# define NAN_DEPRECATED +#endif + +// some generic helpers + +template NAN_INLINE bool NanSetPointerSafe( + T *var + , T val +) { + if (var) { + *var = val; + return true; + } else { + return false; + } +} + +template NAN_INLINE T NanGetPointerSafe( + T *var + , T fallback = reinterpret_cast(0) +) { + if (var) { + return *var; + } else { + return fallback; + } +} + +NAN_INLINE bool NanBooleanOptionValue( + v8::Local optionsObj + , v8::Handle opt, bool def +) { + if (def) { + return optionsObj.IsEmpty() + || !optionsObj->Has(opt) + || optionsObj->Get(opt)->BooleanValue(); + } else { + return !optionsObj.IsEmpty() + && optionsObj->Has(opt) + && optionsObj->Get(opt)->BooleanValue(); + } +} + +NAN_INLINE bool NanBooleanOptionValue( + v8::Local optionsObj + , v8::Handle opt +) { + return NanBooleanOptionValue(optionsObj, opt, false); +} + +NAN_INLINE uint32_t NanUInt32OptionValue( + v8::Local optionsObj + , v8::Handle opt + , uint32_t def +) { + return !optionsObj.IsEmpty() + && optionsObj->Has(opt) + && optionsObj->Get(opt)->IsNumber() + ? optionsObj->Get(opt)->Uint32Value() + : def; +} + +#if (NODE_MODULE_VERSION > 0x000B) +// Node 0.11+ (0.11.3 and below won't compile with these) + +# define _NAN_METHOD_ARGS_TYPE const v8::FunctionCallbackInfo& +# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args +# define _NAN_METHOD_RETURN_TYPE void + +# define _NAN_GETTER_ARGS_TYPE const v8::PropertyCallbackInfo& +# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args +# define _NAN_GETTER_RETURN_TYPE void + +# define _NAN_SETTER_ARGS_TYPE const v8::PropertyCallbackInfo& +# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args +# define _NAN_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_GETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args +# define _NAN_PROPERTY_GETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_SETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args +# define _NAN_PROPERTY_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args +# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE void + +# define _NAN_PROPERTY_DELETER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_DELETER_ARGS \ + _NAN_PROPERTY_DELETER_ARGS_TYPE args +# define _NAN_PROPERTY_DELETER_RETURN_TYPE void + +# define _NAN_PROPERTY_QUERY_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args +# define _NAN_PROPERTY_QUERY_RETURN_TYPE void + +# define _NAN_INDEX_GETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args +# define _NAN_INDEX_GETTER_RETURN_TYPE void + +# define _NAN_INDEX_SETTER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args +# define _NAN_INDEX_SETTER_RETURN_TYPE void + +# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args +# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE void + +# define _NAN_INDEX_DELETER_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args +# define _NAN_INDEX_DELETER_RETURN_TYPE void + +# define _NAN_INDEX_QUERY_ARGS_TYPE \ + const v8::PropertyCallbackInfo& +# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args +# define _NAN_INDEX_QUERY_RETURN_TYPE void + + typedef v8::FunctionCallback NanFunctionCallback; + + template + NAN_INLINE v8::Local NanNew() { + return T::New(v8::Isolate::GetCurrent()); + } + + template + NAN_INLINE v8::Local NanNew(P arg1) { + return T::New(v8::Isolate::GetCurrent(), arg1); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Handle receiver + , int argc + , v8::Handle argv[] = 0) { + return v8::Signature::New(v8::Isolate::GetCurrent(), receiver, argc, argv); + } + + template + NAN_INLINE v8::Local NanNew( + NanFunctionCallback callback + , v8::Handle data = v8::Handle() + , v8::Handle signature = v8::Handle()) { + return T::New(v8::Isolate::GetCurrent(), callback, data, signature); + } + + template + NAN_INLINE v8::Local NanNew(v8::Handle arg1) { + return v8::Local::New(v8::Isolate::GetCurrent(), arg1); + } + + template + NAN_INLINE v8::Local NanNew(const v8::Persistent &arg1) { + return v8::Local::New(v8::Isolate::GetCurrent(), arg1); + } + + template + NAN_INLINE v8::Local NanNew(P arg1, int arg2) { + return T::New(v8::Isolate::GetCurrent(), arg1, arg2); + } + + template<> + NAN_INLINE v8::Local NanNew() { + return v8::Array::New(v8::Isolate::GetCurrent()); + } + + template<> + NAN_INLINE v8::Local NanNew(int length) { + return v8::Array::New(v8::Isolate::GetCurrent(), length); + } + + template<> + NAN_INLINE v8::Local NanNew(double time) { + return v8::Date::New(v8::Isolate::GetCurrent(), time).As(); + } + + template<> + NAN_INLINE v8::Local NanNew(int time) { + return v8::Date::New(v8::Isolate::GetCurrent(), time).As(); + } + + typedef v8::UnboundScript NanUnboundScript; + typedef v8::Script NanBoundScript; + + template + NAN_INLINE v8::Local NanNew( + P s + , const v8::ScriptOrigin& origin + ) { + v8::ScriptCompiler::Source source(s, origin); + return v8::ScriptCompiler::CompileUnbound( + v8::Isolate::GetCurrent(), &source); + } + + template<> + NAN_INLINE v8::Local NanNew( + v8::Local s + ) { + v8::ScriptCompiler::Source source(s); + return v8::ScriptCompiler::CompileUnbound( + v8::Isolate::GetCurrent(), &source); + } + + template<> + NAN_INLINE v8::Local NanNew(bool value) { + return v8::BooleanObject::New(value).As(); + } + + template<> + NAN_INLINE v8::Local + NanNew >( + v8::Local value) { + return v8::StringObject::New(value).As(); + } + + template<> + NAN_INLINE v8::Local + NanNew >( + v8::Handle value) { + return v8::StringObject::New(value).As(); + } + + template<> + NAN_INLINE v8::Local NanNew(double val) { + return v8::NumberObject::New( + v8::Isolate::GetCurrent(), val).As(); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Handle pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Local pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Handle pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Local pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template<> + NAN_INLINE v8::Local NanNew(int32_t val) { + return v8::Uint32::NewFromUnsigned( + v8::Isolate::GetCurrent(), val)->ToUint32(); + } + + template<> + NAN_INLINE v8::Local NanNew(uint32_t val) { + return v8::Uint32::NewFromUnsigned( + v8::Isolate::GetCurrent(), val)->ToUint32(); + } + + template<> + NAN_INLINE v8::Local NanNew(int32_t val) { + return v8::Int32::New(v8::Isolate::GetCurrent(), val)->ToInt32(); + } + + template<> + NAN_INLINE v8::Local NanNew(uint32_t val) { + return v8::Int32::New(v8::Isolate::GetCurrent(), val)->ToInt32(); + } + + template<> + NAN_INLINE v8::Local NanNew( + char *arg + , int length) { + return v8::String::NewFromUtf8( + v8::Isolate::GetCurrent() + , arg + , v8::String::kNormalString + , length); + } + + template<> + NAN_INLINE v8::Local NanNew( + const char *arg + , int length) { + return v8::String::NewFromUtf8( + v8::Isolate::GetCurrent() + , arg + , v8::String::kNormalString + , length); + } + + template<> + NAN_INLINE v8::Local NanNew(char *arg) { + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), arg); + } + + template<> + NAN_INLINE v8::Local NanNew( + const char *arg) { + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), arg); + } + + template<> + NAN_INLINE v8::Local NanNew( + uint8_t *arg + , int length) { + return v8::String::NewFromOneByte( + v8::Isolate::GetCurrent() + , arg + , v8::String::kNormalString + , length); + } + + template<> + NAN_INLINE v8::Local NanNew( + const uint8_t *arg + , int length) { + return v8::String::NewFromOneByte( + v8::Isolate::GetCurrent() + , arg + , v8::String::kNormalString + , length); + } + + template<> + NAN_INLINE v8::Local NanNew(uint8_t *arg) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), arg); + } + + template<> + NAN_INLINE v8::Local NanNew( + const uint8_t *arg) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), arg); + } + + template<> + NAN_INLINE v8::Local NanNew( + uint16_t *arg + , int length) { + return v8::String::NewFromTwoByte( + v8::Isolate::GetCurrent() + , arg + , v8::String::kNormalString + , length); + } + + template<> + NAN_INLINE v8::Local NanNew( + const uint16_t *arg + , int length) { + return v8::String::NewFromTwoByte( + v8::Isolate::GetCurrent() + , arg + , v8::String::kNormalString + , length); + } + template<> + NAN_INLINE v8::Local NanNew( + uint16_t *arg) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), arg); + } + + template<> + NAN_INLINE v8::Local NanNew( + const uint16_t *arg) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), arg); + } + + template<> + NAN_INLINE v8::Local NanNew( + std::string arg) { + return NanNew(arg.c_str(), arg.size()); + } + + template<> + NAN_INLINE v8::Local NanNew() { + return v8::String::Empty(v8::Isolate::GetCurrent()); + } + + NAN_INLINE v8::Local NanNew(const char* arg, int length = -1) { + return NanNew(arg, length); + } + + NAN_INLINE v8::Local NanNew( + const uint8_t* arg + , int length = -1) { + return NanNew(arg, length); + } + + NAN_INLINE v8::Local NanNew( + const uint16_t* arg + , int length = -1) { + return NanNew(arg, length); + } + + NAN_INLINE v8::Local NanNew( + const std::string& arg) { + return NanNew(arg.c_str(), arg.size()); + } + + NAN_INLINE v8::Local NanNew(double val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew(int val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew(unsigned int val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew(bool val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew( + v8::String::ExternalStringResource *resource) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), resource); + } + + NAN_INLINE v8::Local NanNew( + v8::String::ExternalAsciiStringResource *resource) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), resource); + } + +# define NanScope() v8::HandleScope scope(v8::Isolate::GetCurrent()) +# define NanEscapableScope() \ + v8::EscapableHandleScope scope(v8::Isolate::GetCurrent()) + + template + NAN_INLINE v8::Local _NanEscapeScopeHelper(v8::Handle val) { + return NanNew(val); + } + + template + NAN_INLINE v8::Local _NanEscapeScopeHelper(v8::Local val) { + return val; + } + +# define NanEscapeScope(val) scope.Escape(_NanEscapeScopeHelper(val)) +# define NanLocker() v8::Locker locker(v8::Isolate::GetCurrent()) +# define NanUnlocker() v8::Unlocker unlocker(v8::Isolate::GetCurrent()) +# define NanReturnValue(value) return args.GetReturnValue().Set(value) +# define NanReturnUndefined() return +# define NanReturnNull() return args.GetReturnValue().SetNull() +# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() + +# define NanObjectWrapHandle(obj) obj->handle() + + NAN_INLINE v8::Local NanUndefined() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Undefined(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanNull() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Null(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanTrue() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::True(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE v8::Local NanFalse() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::False(v8::Isolate::GetCurrent()))); + } + + NAN_INLINE int NanAdjustExternalMemory(int bc) { + return static_cast( + v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , const char *name + , v8::Handle value) { + templ->Set(v8::Isolate::GetCurrent(), name, value); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + NAN_INLINE v8::Local NanGetCurrentContext() { + return v8::Isolate::GetCurrent()->GetCurrentContext(); + } + + NAN_INLINE void* NanGetInternalFieldPointer( + v8::Handle object + , int index) { + return object->GetAlignedPointerFromInternalField(index); + } + + NAN_INLINE void NanSetInternalFieldPointer( + v8::Handle object + , int index + , void* value) { + object->SetAlignedPointerInInternalField(index, value); + } + + NAN_INLINE void NanAddGCEpilogueCallback( + v8::Isolate::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); + } + + NAN_INLINE void NanRemoveGCEpilogueCallback( + v8::Isolate::GCEpilogueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); + } + + NAN_INLINE void NanAddGCPrologueCallback( + v8::Isolate::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); + } + + NAN_INLINE void NanRemoveGCPrologueCallback( + v8::Isolate::GCPrologueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); + } + + NAN_INLINE void NanGetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); + } + + NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( + const char* data, int length = -1) { + return NanNew(data, length); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , v8::Handle obj) { + handle.Reset(v8::Isolate::GetCurrent(), obj); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , const v8::Persistent& obj) { + handle.Reset(v8::Isolate::GetCurrent(), obj); + } + + template + class _NanWeakCallbackData; + + template + struct _NanWeakCallbackInfo { + typedef void (*Callback)(const _NanWeakCallbackData& data); + NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) + : parameter(param), callback(cb) { + NanAssignPersistent(persistent, handle); + } + + NAN_INLINE ~_NanWeakCallbackInfo() { + persistent.Reset(); + } + + P* const parameter; + Callback const callback; + v8::Persistent persistent; + }; + + template + class _NanWeakCallbackData { + public: + NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) + : info_(info) { } + + NAN_INLINE v8::Local GetValue() const { + return NanNew(info_->persistent); + } + + NAN_INLINE P* GetParameter() const { return info_->parameter; } + + NAN_INLINE bool IsNearDeath() const { + return info_->persistent.IsNearDeath(); + } + + NAN_INLINE void Revive() const; + + NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { + return info_; + } + + NAN_DEPRECATED NAN_INLINE void Dispose() const { + } + + private: + _NanWeakCallbackInfo* info_; + }; + + template + static void _NanWeakCallbackDispatcher( + const v8::WeakCallbackData > &data) { + _NanWeakCallbackInfo *info = data.GetParameter(); + _NanWeakCallbackData wcbd(info); + info->callback(wcbd); + if (wcbd.IsNearDeath()) { + delete wcbd.GetCallbackInfo(); + } + } + + template + NAN_INLINE void _NanWeakCallbackData::Revive() const { + info_->persistent.SetWeak(info_, &_NanWeakCallbackDispatcher); + } + +template +NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( + v8::Handle handle + , P* parameter + , typename _NanWeakCallbackInfo::Callback callback) { + _NanWeakCallbackInfo *cbinfo = + new _NanWeakCallbackInfo(handle, parameter, callback); + cbinfo->persistent.SetWeak(cbinfo, &_NanWeakCallbackDispatcher); + return cbinfo; +} + +# define NAN_WEAK_CALLBACK(name) \ + template \ + static void name(const _NanWeakCallbackData &data) + +# define _NAN_ERROR(fun, errmsg) fun(NanNew(errmsg)) + +# define _NAN_THROW_ERROR(fun, errmsg) \ + do { \ + NanScope(); \ + v8::Isolate::GetCurrent()->ThrowException(_NAN_ERROR(fun, errmsg)); \ + } while (0); + + NAN_INLINE v8::Local NanError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE void NanThrowError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE void NanThrowError(v8::Handle error) { + NanScope(); + v8::Isolate::GetCurrent()->ThrowException(error); + } + + NAN_INLINE v8::Local NanError( + const char *msg + , const int errorNumber + ) { + v8::Local err = v8::Exception::Error(NanNew(msg)); + v8::Local obj = err.As(); + obj->Set(NanNew("code"), NanNew(errorNumber)); + return err; + } + + NAN_INLINE void NanThrowError( + const char *msg + , const int errorNumber + ) { + NanThrowError(NanError(msg, errorNumber)); + } + + NAN_INLINE v8::Local NanTypeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE void NanThrowTypeError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanRangeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::RangeError, errmsg); + } + + NAN_INLINE void NanThrowRangeError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); + } + + template NAN_INLINE void NanDisposePersistent( + v8::Persistent &handle + ) { + handle.Reset(); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + char *data + , size_t length + , node::smalloc::FreeCallback callback + , void *hint + ) { + return node::Buffer::New( + v8::Isolate::GetCurrent(), data, length, callback, hint); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + const char *data + , uint32_t size + ) { + return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); + } + + NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { + return node::Buffer::New(v8::Isolate::GetCurrent(), size); + } + + NAN_INLINE v8::Local NanBufferUse( + char* data + , uint32_t size + ) { + return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); + } + + NAN_INLINE bool NanHasInstance( + v8::Persistent& function_template + , v8::Handle value + ) { + return NanNew(function_template)->HasInstance(value); + } + + NAN_INLINE v8::Local NanNewContextHandle( + v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle() + ) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + return v8::Local::New( + isolate + , v8::Context::New(isolate, extensions, tmpl, obj) + ); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + , const v8::ScriptOrigin& origin + ) { + v8::ScriptCompiler::Source source(s, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + ) { + v8::ScriptCompiler::Source source(s); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + NAN_INLINE v8::Local NanRunScript( + v8::Handle script + ) { + return script->BindToCurrentContext()->Run(); + } + + NAN_INLINE v8::Local NanRunScript( + v8::Handle script + ) { + return script->Run(); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle func + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv)); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle symbol + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv)); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , const char* method + , int argc + , v8::Handle* argv) { + return NanNew(node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv)); + } + + template + NAN_INLINE void NanSetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(0, data); + } + + template + NAN_INLINE T *NanGetIsolateData( + v8::Isolate *isolate + ) { + return static_cast(isolate->GetData(0)); + } + + class NanAsciiString { + public: + NAN_INLINE explicit NanAsciiString(v8::Handle from) { + v8::Local toStr = from->ToString(); + int buf_size = toStr->Length() + 1; + buf = new char[buf_size]; + size = toStr->WriteOneByte( + reinterpret_cast(buf), 0, buf_size); + } + + NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + + NAN_INLINE ~NanAsciiString() { + delete[] buf; + } + + private: + char *buf; + int size; + }; + + class NanUtf8String { + public: + NAN_INLINE explicit NanUtf8String(v8::Handle from) { + v8::Local toStr = from->ToString(); + int buf_size = toStr->Utf8Length() + 1; + buf = new char[buf_size]; + size = toStr->WriteUtf8(buf, buf_size); + } + + NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + + NAN_INLINE ~NanUtf8String() { + delete[] buf; + } + + private: + char *buf; + int size; + }; + + class NanUcs2String { + public: + NAN_INLINE explicit NanUcs2String(v8::Handle from) { + v8::Local toStr = from->ToString(); + int buf_size = toStr->Length() + 1; + buf = new uint16_t[buf_size]; + size = toStr->Write(buf, 0, buf_size); + } + + NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE uint16_t* operator*() { return buf; } + + NAN_INLINE ~NanUcs2String() { + delete[] buf; + } + + private: + uint16_t *buf; + int size; + }; + +#else +// Node 0.8 and 0.10 + +# define _NAN_METHOD_ARGS_TYPE const v8::Arguments& +# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args +# define _NAN_METHOD_RETURN_TYPE v8::Handle + +# define _NAN_GETTER_ARGS_TYPE const v8::AccessorInfo & +# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args +# define _NAN_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_SETTER_ARGS_TYPE const v8::AccessorInfo & +# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args +# define _NAN_SETTER_RETURN_TYPE void + +# define _NAN_PROPERTY_GETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args +# define _NAN_PROPERTY_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_SETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args +# define _NAN_PROPERTY_SETTER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args +# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_DELETER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_DELETER_ARGS _NAN_PROPERTY_DELETER_ARGS_TYPE args +# define _NAN_PROPERTY_DELETER_RETURN_TYPE v8::Handle + +# define _NAN_PROPERTY_QUERY_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args +# define _NAN_PROPERTY_QUERY_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_GETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args +# define _NAN_INDEX_GETTER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_SETTER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args +# define _NAN_INDEX_SETTER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args +# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_DELETER_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args +# define _NAN_INDEX_DELETER_RETURN_TYPE v8::Handle + +# define _NAN_INDEX_QUERY_ARGS_TYPE const v8::AccessorInfo& +# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args +# define _NAN_INDEX_QUERY_RETURN_TYPE v8::Handle + + typedef v8::InvocationCallback NanFunctionCallback; + + NAN_DEPRECATED NAN_INLINE v8::Local NanSymbol( + const char* data, int length = -1) { + return v8::String::NewSymbol(data, length); + } + + template + NAN_INLINE v8::Local NanNew() { + return v8::Local::New(T::New()); + } + + template + NAN_INLINE v8::Local NanNew(v8::Handle arg) { + return v8::Local::New(arg); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Handle receiver + , int argc + , v8::Handle argv[] = 0) { + return v8::Signature::New(receiver, argc, argv); + } + + template + NAN_INLINE v8::Local NanNew( + NanFunctionCallback callback + , v8::Handle data = v8::Handle() + , v8::Handle signature = v8::Handle()) { + return T::New(callback, data, signature); + } + + template + NAN_INLINE v8::Local NanNew(const v8::Persistent &arg) { + return v8::Local::New(arg); + } + + template + NAN_INLINE v8::Local NanNew(P arg) { + return v8::Local::New(T::New(arg)); + } + + template + NAN_INLINE v8::Local NanNew(P arg, int length) { + return v8::Local::New(T::New(arg, length)); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Handle pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Local pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Handle pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template + NAN_INLINE v8::Local NanNew( + v8::Local pattern, v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); + } + + template<> + NAN_INLINE v8::Local NanNew() { + return v8::Array::New(); + } + + template<> + NAN_INLINE v8::Local NanNew(int length) { + return v8::Array::New(length); + } + + template<> + NAN_INLINE v8::Local NanNew(double time) { + return v8::Date::New(time).As(); + } + + template<> + NAN_INLINE v8::Local NanNew(int time) { + return v8::Date::New(time).As(); + } + + typedef v8::Script NanUnboundScript; + typedef v8::Script NanBoundScript; + + template + NAN_INLINE v8::Local NanNew( + P s + , const v8::ScriptOrigin& origin + ) { + return v8::Script::New(s, const_cast(&origin)); + } + + template<> + NAN_INLINE v8::Local NanNew( + v8::Local s + ) { + return v8::Script::New(s); + } + + template<> + NAN_INLINE v8::Local NanNew(bool value) { + return v8::BooleanObject::New(value).As(); + } + + template<> + NAN_INLINE v8::Local + NanNew >( + v8::Local value) { + return v8::StringObject::New(value).As(); + } + + template<> + NAN_INLINE v8::Local + NanNew >( + v8::Handle value) { + return v8::StringObject::New(value).As(); + } + + template<> + NAN_INLINE v8::Local NanNew(double val) { + return v8::NumberObject::New(val).As(); + } + + template<> + NAN_INLINE v8::Local NanNew(int32_t val) { + return v8::Uint32::NewFromUnsigned(val)->ToUint32(); + } + + template<> + NAN_INLINE v8::Local NanNew(uint32_t val) { + return v8::Uint32::NewFromUnsigned(val)->ToUint32(); + } + + template<> + NAN_INLINE v8::Local NanNew(int32_t val) { + return v8::Int32::New(val)->ToInt32(); + } + + template<> + NAN_INLINE v8::Local NanNew(uint32_t val) { + return v8::Int32::New(val)->ToInt32(); + } + + template<> + NAN_INLINE v8::Local NanNew( + uint8_t *arg + , int length) { + int len = length; + if (len < 0) { + size_t temp = strlen(reinterpret_cast(arg)); + assert(temp <= INT_MAX && "too long string"); + len = static_cast(temp); + } + uint16_t *warg = new uint16_t[len]; + for (int i = 0; i < len; i++) { + warg[i] = arg[i]; + } + v8::Local retval = v8::String::New(warg, len); + delete[] warg; + return retval; + } + + template<> + NAN_INLINE v8::Local NanNew( + const uint8_t *arg + , int length) { + int len = length; + if (len < 0) { + size_t temp = strlen(reinterpret_cast(arg)); + assert(temp <= INT_MAX && "too long string"); + len = static_cast(temp); + } + uint16_t *warg = new uint16_t[len]; + for (int i = 0; i < len; i++) { + warg[i] = arg[i]; + } + v8::Local retval = v8::String::New(warg, len); + delete[] warg; + return retval; + } + + template<> + NAN_INLINE v8::Local NanNew(uint8_t *arg) { + size_t temp = strlen(reinterpret_cast(arg)); + assert(temp <= INT_MAX && "too long string"); + int length = static_cast(temp); + uint16_t *warg = new uint16_t[length]; + for (int i = 0; i < length; i++) { + warg[i] = arg[i]; + } + + v8::Local retval = v8::String::New(warg, length); + delete[] warg; + return retval; + } + + template<> + NAN_INLINE v8::Local NanNew( + const uint8_t *arg) { + size_t temp = strlen(reinterpret_cast(arg)); + assert(temp <= INT_MAX && "too long string"); + int length = static_cast(temp); + uint16_t *warg = new uint16_t[length]; + for (int i = 0; i < length; i++) { + warg[i] = arg[i]; + } + v8::Local retval = v8::String::New(warg, length); + delete[] warg; + return retval; + } + + template<> + NAN_INLINE v8::Local NanNew( + std::string arg) { + return NanNew(arg.c_str(), arg.size()); + } + + template<> + NAN_INLINE v8::Local NanNew() { + return v8::String::Empty(); + } + + NAN_INLINE v8::Local NanNew(const char* arg, int length = -1) { + return NanNew(arg, length); + } + + NAN_INLINE v8::Local NanNew( + const uint8_t* arg + , int length = -1) { + return NanNew(arg, length); + } + + NAN_INLINE v8::Local NanNew( + const uint16_t* arg + , int length = -1) { + return NanNew(arg, length); + } + + NAN_INLINE v8::Local NanNew( + std::string& arg) { + return NanNew(arg.c_str(), arg.size()); + } + + NAN_INLINE v8::Local NanNew(double val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew(int val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew(unsigned int val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew(bool val) { + return NanNew(val); + } + + NAN_INLINE v8::Local NanNew( + v8::String::ExternalStringResource *resource) { + return v8::String::NewExternal(resource); + } + + NAN_INLINE v8::Local NanNew( + v8::String::ExternalAsciiStringResource *resource) { + return v8::String::NewExternal(resource); + } + +# define NanScope() v8::HandleScope scope +# define NanEscapableScope() v8::HandleScope scope +# define NanEscapeScope(val) scope.Close(val) +# define NanLocker() v8::Locker locker +# define NanUnlocker() v8::Unlocker unlocker +# define NanReturnValue(value) return scope.Close(value) +# define NanReturnUndefined() return v8::Undefined() +# define NanReturnNull() return v8::Null() +# define NanReturnEmptyString() return v8::String::Empty() +# define NanObjectWrapHandle(obj) v8::Local::New(obj->handle_) + + NAN_INLINE v8::Local NanUndefined() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Undefined())); + } + + NAN_INLINE v8::Local NanNull() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::Null())); + } + + NAN_INLINE v8::Local NanTrue() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::True())); + } + + NAN_INLINE v8::Local NanFalse() { + NanEscapableScope(); + return NanEscapeScope(NanNew(v8::False())); + } + + NAN_INLINE int NanAdjustExternalMemory(int bc) { + return static_cast(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , const char *name + , v8::Handle value) { + templ->Set(name, value); + } + + NAN_INLINE void NanSetTemplate( + v8::Handle templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + NAN_INLINE v8::Local NanGetCurrentContext() { + return v8::Context::GetCurrent(); + } + + NAN_INLINE void* NanGetInternalFieldPointer( + v8::Handle object + , int index) { + return object->GetPointerFromInternalField(index); + } + + NAN_INLINE void NanSetInternalFieldPointer( + v8::Handle object + , int index + , void* value) { + object->SetPointerInInternalField(index, value); + } + + NAN_INLINE void NanAddGCEpilogueCallback( + v8::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); + } + NAN_INLINE void NanRemoveGCEpilogueCallback( + v8::GCEpilogueCallback callback) { + v8::V8::RemoveGCEpilogueCallback(callback); + } + NAN_INLINE void NanAddGCPrologueCallback( + v8::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCPrologueCallback(callback, gc_type_filter); + } + NAN_INLINE void NanRemoveGCPrologueCallback( + v8::GCPrologueCallback callback) { + v8::V8::RemoveGCPrologueCallback(callback); + } + NAN_INLINE void NanGetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::V8::GetHeapStatistics(heap_statistics); + } + + template + NAN_INLINE void NanAssignPersistent( + v8::Persistent& handle + , v8::Handle obj) { + handle.Dispose(); + handle = v8::Persistent::New(obj); + } + + template + class _NanWeakCallbackData; + + template + struct _NanWeakCallbackInfo { + typedef void (*Callback)(const _NanWeakCallbackData &data); + NAN_INLINE _NanWeakCallbackInfo(v8::Handle handle, P* param, Callback cb) + : parameter(param) + , callback(cb) + , persistent(v8::Persistent::New(handle)) { } + + NAN_INLINE ~_NanWeakCallbackInfo() { + persistent.Dispose(); + persistent.Clear(); + } + + P* const parameter; + Callback const callback; + v8::Persistent persistent; + }; + + template + class _NanWeakCallbackData { + public: + NAN_INLINE _NanWeakCallbackData(_NanWeakCallbackInfo *info) + : info_(info) { } + + NAN_INLINE v8::Local GetValue() const { + return NanNew(info_->persistent); + } + + NAN_INLINE P* GetParameter() const { return info_->parameter; } + + NAN_INLINE bool IsNearDeath() const { + return info_->persistent.IsNearDeath(); + } + + NAN_INLINE void Revive() const; + + NAN_INLINE _NanWeakCallbackInfo* GetCallbackInfo() const { + return info_; + } + + NAN_DEPRECATED NAN_INLINE void Dispose() const { + } + + private: + _NanWeakCallbackInfo* info_; + }; + + template + static void _NanWeakPersistentDispatcher( + v8::Persistent object, void *data) { + _NanWeakCallbackInfo* info = + static_cast<_NanWeakCallbackInfo*>(data); + _NanWeakCallbackData wcbd(info); + info->callback(wcbd); + if (wcbd.IsNearDeath()) { + delete wcbd.GetCallbackInfo(); + } + } + + template + NAN_INLINE void _NanWeakCallbackData::Revive() const { + info_->persistent.MakeWeak( + info_ + , &_NanWeakPersistentDispatcher); + } + + template + NAN_INLINE _NanWeakCallbackInfo* NanMakeWeakPersistent( + v8::Handle handle + , P* parameter + , typename _NanWeakCallbackInfo::Callback callback) { + _NanWeakCallbackInfo *cbinfo = + new _NanWeakCallbackInfo(handle, parameter, callback); + cbinfo->persistent.MakeWeak( + cbinfo + , &_NanWeakPersistentDispatcher); + return cbinfo; + } + +# define NAN_WEAK_CALLBACK(name) \ + template \ + static void name(const _NanWeakCallbackData &data) + +# define _NAN_ERROR(fun, errmsg) \ + fun(v8::String::New(errmsg)) + +# define _NAN_THROW_ERROR(fun, errmsg) \ + do { \ + NanScope(); \ + return v8::Local::New( \ + v8::ThrowException(_NAN_ERROR(fun, errmsg))); \ + } while (0); + + NAN_INLINE v8::Local NanError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE v8::Local NanThrowError(const char* errmsg) { + _NAN_THROW_ERROR(v8::Exception::Error, errmsg); + } + + NAN_INLINE v8::Local NanThrowError( + v8::Handle error + ) { + NanScope(); + return v8::Local::New(v8::ThrowException(error)); + } + + NAN_INLINE v8::Local NanError( + const char *msg + , const int errorNumber + ) { + v8::Local err = v8::Exception::Error(v8::String::New(msg)); + v8::Local obj = err.As(); + obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); + return err; + } + + NAN_INLINE v8::Local NanThrowError( + const char *msg + , const int errorNumber + ) { + return NanThrowError(NanError(msg, errorNumber)); + } + + NAN_INLINE v8::Local NanTypeError(const char* errmsg) { + return _NAN_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanThrowTypeError( + const char* errmsg + ) { + _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); + } + + NAN_INLINE v8::Local NanRangeError( + const char* errmsg + ) { + return _NAN_ERROR(v8::Exception::RangeError, errmsg); + } + + NAN_INLINE v8::Local NanThrowRangeError( + const char* errmsg + ) { + _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); + } + + template + NAN_INLINE void NanDisposePersistent( + v8::Persistent &handle) { // NOLINT(runtime/references) + handle.Dispose(); + handle.Clear(); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + char *data + , size_t length + , node::Buffer::free_callback callback + , void *hint + ) { + return NanNew( + node::Buffer::New(data, length, callback, hint)->handle_); + } + + NAN_INLINE v8::Local NanNewBufferHandle ( + const char *data + , uint32_t size + ) { +#if NODE_MODULE_VERSION >= 0x000B + return NanNew(node::Buffer::New(data, size)->handle_); +#else + return NanNew( + node::Buffer::New(const_cast(data), size)->handle_); +#endif + } + + NAN_INLINE v8::Local NanNewBufferHandle (uint32_t size) { + return NanNew(node::Buffer::New(size)->handle_); + } + + NAN_INLINE void FreeData(char *data, void *hint) { + delete[] data; + } + + NAN_INLINE v8::Local NanBufferUse( + char* data + , uint32_t size + ) { + return NanNew( + node::Buffer::New(data, size, FreeData, NULL)->handle_); + } + + NAN_INLINE bool NanHasInstance( + v8::Persistent& function_template + , v8::Handle value + ) { + return function_template->HasInstance(value); + } + + NAN_INLINE v8::Local NanNewContextHandle( + v8::ExtensionConfiguration* extensions = NULL + , v8::Handle tmpl = v8::Handle() + , v8::Handle obj = v8::Handle() + ) { + v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); + v8::Local lctx = NanNew(ctx); + ctx.Dispose(); + return lctx; + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + , const v8::ScriptOrigin& origin + ) { + return v8::Script::Compile(s, const_cast(&origin)); + } + + NAN_INLINE v8::Local NanCompileScript( + v8::Local s + ) { + return v8::Script::Compile(s); + } + + NAN_INLINE v8::Local NanRunScript(v8::Handle script) { + return script->Run(); + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle func + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, func, argc, argv)); +# else + v8::TryCatch try_catch; + v8::Local result = NanNew(func->Call(target, argc, argv)); + if (try_catch.HasCaught()) { + node::FatalException(try_catch); + } + return result; +# endif + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , v8::Handle symbol + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, symbol, argc, argv)); +# else + v8::Local callback = target->Get(symbol).As(); + return NanMakeCallback(target, callback, argc, argv); +# endif + } + + NAN_INLINE v8::Local NanMakeCallback( + v8::Handle target + , const char* method + , int argc + , v8::Handle* argv) { +# if NODE_VERSION_AT_LEAST(0, 8, 0) + return NanNew(node::MakeCallback(target, method, argc, argv)); +# else + return NanMakeCallback(target, NanNew(method), argc, argv); +# endif + } + + template + NAN_INLINE void NanSetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(data); + } + + template + NAN_INLINE T *NanGetIsolateData( + v8::Isolate *isolate + ) { + return static_cast(isolate->GetData()); + } + + class NanAsciiString { + public: + NAN_INLINE explicit NanAsciiString(v8::Handle from) { + v8::Local toStr = from->ToString(); + int buf_size = toStr->Length() + 1; + buf = new char[buf_size]; + size = toStr->WriteAscii(buf, 0, buf_size); + } + + NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + + NAN_INLINE ~NanAsciiString() { + delete[] buf; + } + + private: + char *buf; + int size; + }; + + class NanUtf8String { + public: + NAN_INLINE explicit NanUtf8String(v8::Handle from) { + v8::Local toStr = from->ToString(); + int buf_size = toStr->Utf8Length() + 1; + buf = new char[buf_size]; + size = toStr->WriteUtf8(buf, buf_size); + } + + NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE char* operator*() { return buf; } + + NAN_INLINE ~NanUtf8String() { + delete[] buf; + } + + private: + char *buf; + int size; + }; + + class NanUcs2String { + public: + NAN_INLINE explicit NanUcs2String(v8::Handle from) { + v8::Local toStr = from->ToString(); + int buf_size = toStr->Length() + 1; + buf = new uint16_t[buf_size]; + size = toStr->Write(buf, 0, buf_size); + } + + NAN_INLINE int Size() const { + return size; + } + + NAN_INLINE uint16_t* operator*() { return buf; } + + NAN_INLINE ~NanUcs2String() { + delete[] buf; + } + + private: + uint16_t *buf; + int size; + }; + +#endif // NODE_MODULE_VERSION + +typedef void (*NanFreeCallback)(char *data, void *hint); + +#define NAN_METHOD(name) _NAN_METHOD_RETURN_TYPE name(_NAN_METHOD_ARGS) +#define NAN_GETTER(name) \ + _NAN_GETTER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_GETTER_ARGS) +#define NAN_SETTER(name) \ + _NAN_SETTER_RETURN_TYPE name( \ + v8::Local property \ + , v8::Local value \ + , _NAN_SETTER_ARGS) +#define NAN_PROPERTY_GETTER(name) \ + _NAN_PROPERTY_GETTER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_GETTER_ARGS) +#define NAN_PROPERTY_SETTER(name) \ + _NAN_PROPERTY_SETTER_RETURN_TYPE name( \ + v8::Local property \ + , v8::Local value \ + , _NAN_PROPERTY_SETTER_ARGS) +#define NAN_PROPERTY_ENUMERATOR(name) \ + _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(_NAN_PROPERTY_ENUMERATOR_ARGS) +#define NAN_PROPERTY_DELETER(name) \ + _NAN_PROPERTY_DELETER_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_DELETER_ARGS) +#define NAN_PROPERTY_QUERY(name) \ + _NAN_PROPERTY_QUERY_RETURN_TYPE name( \ + v8::Local property \ + , _NAN_PROPERTY_QUERY_ARGS) +# define NAN_INDEX_GETTER(name) \ + _NAN_INDEX_GETTER_RETURN_TYPE name(uint32_t index, _NAN_INDEX_GETTER_ARGS) +#define NAN_INDEX_SETTER(name) \ + _NAN_INDEX_SETTER_RETURN_TYPE name( \ + uint32_t index \ + , v8::Local value \ + , _NAN_INDEX_SETTER_ARGS) +#define NAN_INDEX_ENUMERATOR(name) \ + _NAN_INDEX_ENUMERATOR_RETURN_TYPE name(_NAN_INDEX_ENUMERATOR_ARGS) +#define NAN_INDEX_DELETER(name) \ + _NAN_INDEX_DELETER_RETURN_TYPE name( \ + uint32_t index \ + , _NAN_INDEX_DELETER_ARGS) +#define NAN_INDEX_QUERY(name) \ + _NAN_INDEX_QUERY_RETURN_TYPE name(uint32_t index, _NAN_INDEX_QUERY_ARGS) + +class NanCallback { + public: + NanCallback() { + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(handle, obj); + } + + explicit NanCallback(const v8::Handle &fn) { + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(handle, obj); + SetFunction(fn); + } + + ~NanCallback() { + if (handle.IsEmpty()) return; + NanDisposePersistent(handle); + } + + NAN_INLINE void SetFunction(const v8::Handle &fn) { + NanScope(); + NanNew(handle)->Set(kCallbackIndex, fn); + } + + NAN_INLINE v8::Local GetFunction() const { + NanEscapableScope(); + return NanEscapeScope(NanNew(handle)->Get(kCallbackIndex) + .As()); + } + + NAN_INLINE bool IsEmpty() const { + NanScope(); + return NanNew(handle)->Get(kCallbackIndex)->IsUndefined(); + } + + v8::Handle Call(int argc, v8::Handle argv[]) const { + NanEscapableScope(); +#if (NODE_MODULE_VERSION > 0x000B) // 0.11.12+ + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::Local callback = NanNew(handle)-> + Get(kCallbackIndex).As(); + return NanEscapeScope(node::MakeCallback( + isolate + , isolate->GetCurrentContext()->Global() + , callback + , argc + , argv + )); +#else +#if NODE_VERSION_AT_LEAST(0, 8, 0) + v8::Local callback = handle-> + Get(kCallbackIndex).As(); + return NanEscapeScope(node::MakeCallback( + v8::Context::GetCurrent()->Global() + , callback + , argc + , argv + )); +#else + v8::Local callback = handle-> + Get(kCallbackIndex).As(); + return NanEscapeScope(NanMakeCallback( + v8::Context::GetCurrent()->Global(), callback, argc, argv)); +#endif +#endif + } + + private: + v8::Persistent handle; + static const uint32_t kCallbackIndex = 0; +}; + +/* abstract */ class NanAsyncWorker { + public: + explicit NanAsyncWorker(NanCallback *callback) + : callback(callback), errmsg_(NULL) { + request.data = this; + + NanScope(); + v8::Local obj = NanNew(); + NanAssignPersistent(persistentHandle, obj); + } + + virtual ~NanAsyncWorker() { + NanScope(); + + if (!persistentHandle.IsEmpty()) + NanDisposePersistent(persistentHandle); + if (callback) + delete callback; + if (errmsg_) + delete[] errmsg_; + } + + virtual void WorkComplete() { + NanScope(); + + if (errmsg_ == NULL) + HandleOKCallback(); + else + HandleErrorCallback(); + delete callback; + callback = NULL; + } + + NAN_INLINE void SaveToPersistent( + const char *key, const v8::Local &obj) { + v8::Local handle = NanNew(persistentHandle); + handle->Set(NanNew(key), obj); + } + + v8::Local GetFromPersistent(const char *key) const { + NanEscapableScope(); + v8::Local handle = NanNew(persistentHandle); + return NanEscapeScope(handle->Get(NanNew(key)).As()); + } + + virtual void Execute() = 0; + + uv_work_t request; + + protected: + v8::Persistent persistentHandle; + NanCallback *callback; + + virtual void HandleOKCallback() { + NanScope(); + + callback->Call(0, NULL); + } + + virtual void HandleErrorCallback() { + NanScope(); + + v8::Local argv[] = { + v8::Exception::Error(NanNew(ErrorMessage())) + }; + callback->Call(1, argv); + } + + void SetErrorMessage(const char *msg) { + if (errmsg_) { + delete[] errmsg_; + } + + size_t size = strlen(msg) + 1; + errmsg_ = new char[size]; + memcpy(errmsg_, msg, size); + } + + const char* ErrorMessage() const { + return errmsg_; + } + + private: + char *errmsg_; +}; + +NAN_INLINE void NanAsyncExecute (uv_work_t* req) { + NanAsyncWorker *worker = static_cast(req->data); + worker->Execute(); +} + +NAN_INLINE void NanAsyncExecuteComplete (uv_work_t* req) { + NanAsyncWorker* worker = static_cast(req->data); + worker->WorkComplete(); + delete worker; +} + +NAN_INLINE void NanAsyncQueueWorker (NanAsyncWorker* worker) { + uv_queue_work( + uv_default_loop() + , &worker->request + , NanAsyncExecute + , (uv_after_work_cb)NanAsyncExecuteComplete + ); +} + +//// Base 64 //// + +#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) + +// Doesn't check for padding at the end. Can be 1-2 bytes over. +NAN_INLINE size_t _nan_base64_decoded_size_fast(size_t size) { + size_t remainder = size % 4; + + size = (size / 4) * 3; + if (remainder) { + if (size == 0 && remainder == 1) { + // special case: 1-byte input cannot be decoded + size = 0; + } else { + // non-padded input, add 1 or 2 extra bytes + size += 1 + (remainder == 3); + } + } + + return size; +} + +template +NAN_INLINE size_t _nan_base64_decoded_size( + const T* src + , size_t size +) { + if (size == 0) + return 0; + + if (src[size - 1] == '=') + size--; + if (size > 0 && src[size - 1] == '=') + size--; + + return _nan_base64_decoded_size_fast(size); +} + +// supports regular and URL-safe base64 +static const int _nan_unbase64_table[] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 + , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 + , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 + , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 + , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 + , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 +}; + +#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] + +template static size_t _nan_base64_decode( + char* buf + , size_t len + , const T* src + , const size_t srcLen +) { + char* dst = buf; + char* dstEnd = buf + len; + const T* srcEnd = src + srcLen; + + while (src < srcEnd && dst < dstEnd) { + ptrdiff_t remaining = srcEnd - src; + char a, b, c, d; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining == 0 || *src == '=') break; + a = _nan_unbase64(*src++); + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 1 || *src == '=') break; + b = _nan_unbase64(*src++); + + *dst++ = (a << 2) | ((b & 0x30) >> 4); + if (dst == dstEnd) break; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 2 || *src == '=') break; + c = _nan_unbase64(*src++); + + *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); + if (dst == dstEnd) break; + + while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; + if (remaining <= 3 || *src == '=') break; + d = _nan_unbase64(*src++); + + *dst++ = ((c & 0x03) << 6) | (d & 0x3F); + } + + return dst - buf; +} + +//// HEX //// + +template unsigned _nan_hex2bin(T c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); + if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); + return static_cast(-1); +} + +template static size_t _nan_hex_decode( + char* buf + , size_t len + , const T* src + , const size_t srcLen +) { + size_t i; + for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { + unsigned a = _nan_hex2bin(src[i * 2 + 0]); + unsigned b = _nan_hex2bin(src[i * 2 + 1]); + if (!~a || !~b) return i; + buf[i] = a * 16 + b; + } + + return i; +} + +static bool _NanGetExternalParts( + v8::Handle val + , const char** data + , size_t* len +) { + if (node::Buffer::HasInstance(val)) { + *data = node::Buffer::Data(val.As()); + *len = node::Buffer::Length(val.As()); + return true; + } + + assert(val->IsString()); + v8::Local str = NanNew(val.As()); + + if (str->IsExternalAscii()) { + const v8::String::ExternalAsciiStringResource* ext; + ext = str->GetExternalAsciiStringResource(); + *data = ext->data(); + *len = ext->length(); + return true; + + } else if (str->IsExternal()) { + const v8::String::ExternalStringResource* ext; + ext = str->GetExternalStringResource(); + *data = reinterpret_cast(ext->data()); + *len = ext->length(); + return true; + } + + return false; +} + +namespace Nan { + enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; +} + +/* NAN_DEPRECATED */ NAN_INLINE void* _NanRawString( + v8::Handle from + , enum Nan::Encoding encoding + , size_t *datalen + , void *buf + , size_t buflen + , int flags +) { + NanScope(); + + size_t sz_; + size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); + char *data = NULL; + size_t len; + bool is_extern = _NanGetExternalParts( + from + , const_cast(&data) + , &len); + + if (is_extern && !term_len) { + NanSetPointerSafe(datalen, len); + return data; + } + + v8::Local toStr = from->ToString(); + + char *to = static_cast(buf); + + switch (encoding) { + case Nan::ASCII: +#if NODE_MODULE_VERSION < 0x000C + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , toStr->WriteAscii(to, 0, static_cast(sz_ + term_len), flags)); + return to; +#endif + case Nan::BINARY: + case Nan::BUFFER: + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } +#if NODE_MODULE_VERSION < 0x000C + { + uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; + + size_t len = toStr->Write(twobytebuf, 0, + static_cast(sz_ + term_len), flags); + + for (size_t i = 0; i < sz_ + term_len && i < len + term_len; i++) { + unsigned char *b = reinterpret_cast(&twobytebuf[i]); + to[i] = *b; + } + + NanSetPointerSafe(datalen, len); + + delete[] twobytebuf; + return to; + } +#else + NanSetPointerSafe( + datalen, + toStr->WriteOneByte( + reinterpret_cast(to) + , 0 + , static_cast(sz_ + term_len) + , flags)); + return to; +#endif + case Nan::UTF8: + sz_ = toStr->Utf8Length(); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , toStr->WriteUtf8(to, static_cast(sz_ + term_len) + , NULL, flags) + - term_len); + return to; + case Nan::BASE64: + { + v8::String::Value value(toStr); + sz_ = _nan_base64_decoded_size(*value, value.length()); + if (to == NULL) { + to = new char[sz_ + term_len]; + } else { + assert(buflen >= sz_ + term_len); + } + NanSetPointerSafe( + datalen + , _nan_base64_decode(to, sz_, *value, value.length())); + if (term_len) { + to[sz_] = '\0'; + } + return to; + } + case Nan::UCS2: + { + sz_ = toStr->Length(); + if (to == NULL) { + to = new char[(sz_ + term_len) * 2]; + } else { + assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); + } + + int bc = 2 * toStr->Write( + reinterpret_cast(to) + , 0 + , static_cast(sz_ + term_len) + , flags); + NanSetPointerSafe(datalen, bc); + return to; + } + case Nan::HEX: + { + v8::String::Value value(toStr); + sz_ = value.length(); + assert(!(sz_ & 1) && "bad hex data"); + if (to == NULL) { + to = new char[sz_ / 2 + term_len]; + } else { + assert(buflen >= sz_ / 2 + term_len && "too small buffer"); + } + NanSetPointerSafe( + datalen + , _nan_hex_decode(to, sz_ / 2, *value, value.length())); + } + if (term_len) { + to[sz_ / 2] = '\0'; + } + return to; + default: + assert(0 && "unknown encoding"); + } + return to; +} + +NAN_DEPRECATED NAN_INLINE void* NanRawString( + v8::Handle from + , enum Nan::Encoding encoding + , size_t *datalen + , void *buf + , size_t buflen + , int flags +) { + return _NanRawString(from, encoding, datalen, buf, buflen, flags); +} + + +NAN_DEPRECATED NAN_INLINE char* NanCString( + v8::Handle from + , size_t *datalen + , char *buf = NULL + , size_t buflen = 0 + , int flags = v8::String::NO_OPTIONS +) { + return static_cast( + _NanRawString(from, Nan::UTF8, datalen, buf, buflen, flags) + ); +} + +NAN_INLINE void NanSetPrototypeTemplate( + v8::Local templ + , const char *name + , v8::Handle value +) { + NanSetTemplate(templ->PrototypeTemplate(), name, value); +} + +NAN_INLINE void NanSetPrototypeTemplate( + v8::Local templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes +) { + NanSetTemplate(templ->PrototypeTemplate(), name, value, attributes); +} + +NAN_INLINE void NanSetInstanceTemplate( + v8::Local templ + , const char *name + , v8::Handle value +) { + NanSetTemplate(templ->InstanceTemplate(), name, value); +} + +NAN_INLINE void NanSetInstanceTemplate( + v8::Local templ + , v8::Handle name + , v8::Handle value + , v8::PropertyAttribute attributes +) { + NanSetTemplate(templ->InstanceTemplate(), name, value, attributes); +} + +#endif // NAN_H_ diff --git a/node_modules/nan/package.json b/node_modules/nan/package.json new file mode 100644 index 00000000..203cc987 --- /dev/null +++ b/node_modules/nan/package.json @@ -0,0 +1,78 @@ +{ + "name": "nan", + "version": "1.3.0", + "description": "Native Abstractions for Node.js: C++ header for Node 0.8->0.12 compatibility", + "main": "include_dirs.js", + "repository": { + "type": "git", + "url": "git://github.com/rvagg/nan.git" + }, + "scripts": { + "test": "tap --gc test/js/*-test.js", + "rebuild-tests": "node-gyp rebuild --directory test" + }, + "contributors": [ + { + "name": "Rod Vagg", + "email": "r@va.gg", + "url": "https://github.com/rvagg" + }, + { + "name": "Benjamin Byholm", + "email": "bbyholm@abo.fi", + "url": "https://github.com/kkoopa/" + }, + { + "name": "Trevor Norris", + "email": "trev.norris@gmail.com", + "url": "https://github.com/trevnorris" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "https://github.com/TooTallNate" + }, + { + "name": "Brett Lawson", + "email": "brett19@gmail.com", + "url": "https://github.com/brett19" + }, + { + "name": "Ben Noordhuis", + "email": "info@bnoordhuis.nl", + "url": "https://github.com/bnoordhuis" + } + ], + "devDependencies": { + "bindings": "~1.2.1", + "node-gyp": "~1.0.1", + "tap": "~0.4.12", + "xtend": "~4.0.0" + }, + "license": "MIT", + "gitHead": "e482fbe142e58373d5a24f4e5a60c61e22a13f83", + "bugs": { + "url": "https://github.com/rvagg/nan/issues" + }, + "homepage": "https://github.com/rvagg/nan", + "_id": "nan@1.3.0", + "_shasum": "9a5b8d5ef97a10df3050e59b2c362d3baf779742", + "_from": "nan@", + "_npmVersion": "1.4.21", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "9a5b8d5ef97a10df3050e59b2c362d3baf779742", + "tarball": "http://registry.npmjs.org/nan/-/nan-1.3.0.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/nan/-/nan-1.3.0.tgz" +}