conversion.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #! /usr/bin/env node
  2. 'use strict';
  3. const fs = require('fs');
  4. const path = require('path');
  5. const args = process.argv.slice(2);
  6. const dir = args[0];
  7. if (!dir) {
  8. console.log('Usage: node ' + path.basename(__filename) + ' <target-dir>');
  9. process.exit(1);
  10. }
  11. const NodeApiVersion = require('../package.json').version;
  12. const disable = args[1];
  13. let ConfigFileOperations;
  14. if (disable !== '--disable' && dir !== '--disable') {
  15. ConfigFileOperations = {
  16. 'package.json': [
  17. [/([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'],
  18. [/[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '']
  19. ],
  20. 'binding.gyp': [
  21. [/([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'<!(node -p "require(\\\'node-addon-api\\\').include_dir")\','],
  22. [/([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!(node -p \\"require(\'node-addon-api\').include_dir\\")",'],
  23. [/[ ]*("|')<!\(node -e ("|'|\\"|\\')require\(("|'|\\"|\\')nan("|'|\\"|\\')\)("|'|\\"|\\')\)("|')(,|)[\r\n]/g, ''],
  24. [/([ ]*)("|')target_name("|'): ("|')(.+?)("|'),/g, '$1$2target_name$2: $4$5$6,\n $2cflags!$2: [ $2-fno-exceptions$2 ],\n $2cflags_cc!$2: [ $2-fno-exceptions$2 ],\n $2xcode_settings$2: { $2GCC_ENABLE_CPP_EXCEPTIONS$2: $2YES$2,\n $2CLANG_CXX_LIBRARY$2: $2libc++$2,\n $2MACOSX_DEPLOYMENT_TARGET$2: $210.7$2,\n },\n $2msvs_settings$2: {\n $2VCCLCompilerTool$2: { $2ExceptionHandling$2: 1 },\n },']
  25. ]
  26. };
  27. } else {
  28. ConfigFileOperations = {
  29. 'package.json': [
  30. [/([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'],
  31. [/[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '']
  32. ],
  33. 'binding.gyp': [
  34. [/([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'<!(node -p "require(\\\'node-addon-api\\\').include_dir")\','],
  35. [/([ ]*)"include_dirs": \[/g, '$1"include_dirs": [\n$1 "<!(node -p \'require(\\"node-addon-api\\").include_dir\')",'],
  36. [/[ ]*("|')<!\(node -e ("|'|\\"|\\')require\(("|'|\\"|\\')nan("|'|\\"|\\')\)("|'|\\"|\\')\)("|')(,|)[\r\n]/g, ''],
  37. [/([ ]*)("|')target_name("|'): ("|')(.+?)("|'),/g, '$1$2target_name$2: $4$5$6,\n $2cflags!$2: [ $2-fno-exceptions$2 ],\n $2cflags_cc!$2: [ $2-fno-exceptions$2 ],\n $2defines$2: [ $2NAPI_DISABLE_CPP_EXCEPTIONS$2 ],\n $2conditions$2: [\n [\'OS=="win"\', { $2defines$2: [ $2_HAS_EXCEPTIONS=1$2 ] }]\n ]']
  38. ]
  39. };
  40. }
  41. const SourceFileOperations = [
  42. [/Nan::SetMethod\(target,[\s]*"(.*)"[\s]*,[\s]*([^)]+)\)/g, 'exports.Set(Napi::String::New(env, "$1"), Napi::Function::New(env, $2))'],
  43. [/v8::Local<v8::FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'],
  44. [/Local<FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'],
  45. [/Local<FunctionTemplate>\s+(\w+)\s*=\s*Nan::New<FunctionTemplate>\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'],
  46. [/Nan::New<v8::FunctionTemplate>\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)'],
  47. [/Nan::New<FunctionTemplate>\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);'],
  48. [/Nan::New<v8::FunctionTemplate>\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'],
  49. [/Nan::New<FunctionTemplate>\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'],
  50. // FunctionTemplate to FunctionReference
  51. [/Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference'],
  52. [/Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference'],
  53. [/v8::Local<v8::FunctionTemplate>/g, 'Napi::FunctionReference'],
  54. [/Local<FunctionTemplate>/g, 'Napi::FunctionReference'],
  55. [/v8::FunctionTemplate/g, 'Napi::FunctionReference'],
  56. [/FunctionTemplate/g, 'Napi::FunctionReference'],
  57. [/([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),'],
  58. [/([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm,
  59. '});\n\n' +
  60. '$1constructor = Napi::Persistent($3);\n' +
  61. '$1constructor.SuppressDestruct();\n' +
  62. '$1target.Set("$2", $3);'],
  63. // TODO: Other attribute combinations
  64. [/static_cast<PropertyAttribute>\(ReadOnly\s*\|\s*DontDelete\)/gm,
  65. 'static_cast<napi_property_attributes>(napi_enumerable | napi_configurable)'],
  66. [/([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()'],
  67. [/\*Nan::Utf8String\(([^)]+)\)/g, '$1->As<Napi::String>().Utf8Value().c_str()'],
  68. [/Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As<Napi::String>()'],
  69. [/Nan::Utf8String/g, 'std::string'],
  70. [/v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'],
  71. [/String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'],
  72. [/\.length\(\)/g, '.Length()'],
  73. [/Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,'],
  74. [/class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>'],
  75. [/(\w+)\(([^)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3'],
  76. // HandleOKCallback to OnOK
  77. [/HandleOKCallback/g, 'OnOK'],
  78. // HandleErrorCallback to OnError
  79. [/HandleErrorCallback/g, 'OnError'],
  80. // ex. .As<Function>() to .As<Napi::Object>()
  81. [/\.As<v8::(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As<Napi::$1>()'],
  82. [/\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As<Napi::$1>()'],
  83. // ex. Nan::New<Number>(info[0]) to Napi::Number::New(info[0])
  84. [/Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)'],
  85. [/Nan::New\(([0-9.]+)\)/g, 'Napi::Number::New(env, $1)'],
  86. [/Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")'],
  87. [/Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")'],
  88. [/Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)'],
  89. [/Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)'],
  90. [/Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, '],
  91. [/Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, '],
  92. [/Nan::NewBuffer\(/g, 'Napi::Buffer<char>::New(env, '],
  93. // TODO: Properly handle this
  94. [/Nan::New\(/g, 'Napi::New(env, '],
  95. [/\.IsInt32\(\)/g, '.IsNumber()'],
  96. [/->IsInt32\(\)/g, '.IsNumber()'],
  97. [/(.+?)->BooleanValue\(\)/g, '$1.As<Napi::Boolean>().Value()'],
  98. [/(.+?)->Int32Value\(\)/g, '$1.As<Napi::Number>().Int32Value()'],
  99. [/(.+?)->Uint32Value\(\)/g, '$1.As<Napi::Number>().Uint32Value()'],
  100. [/(.+?)->IntegerValue\(\)/g, '$1.As<Napi::Number>().Int64Value()'],
  101. [/(.+?)->NumberValue\(\)/g, '$1.As<Napi::Number>().DoubleValue()'],
  102. // ex. Nan::To<bool>(info[0]) to info[0].Value()
  103. [/Nan::To<v8::(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To<Napi::$1>()'],
  104. [/Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To<Napi::$1>()'],
  105. // ex. Nan::To<bool>(info[0]) to info[0].As<Napi::Boolean>().Value()
  106. [/Nan::To<bool>\((.+?)\)/g, '$1.As<Napi::Boolean>().Value()'],
  107. // ex. Nan::To<int>(info[0]) to info[0].As<Napi::Number>().Int32Value()
  108. [/Nan::To<int>\((.+?)\)/g, '$1.As<Napi::Number>().Int32Value()'],
  109. // ex. Nan::To<int32_t>(info[0]) to info[0].As<Napi::Number>().Int32Value()
  110. [/Nan::To<int32_t>\((.+?)\)/g, '$1.As<Napi::Number>().Int32Value()'],
  111. // ex. Nan::To<uint32_t>(info[0]) to info[0].As<Napi::Number>().Uint32Value()
  112. [/Nan::To<uint32_t>\((.+?)\)/g, '$1.As<Napi::Number>().Uint32Value()'],
  113. // ex. Nan::To<int64_t>(info[0]) to info[0].As<Napi::Number>().Int64Value()
  114. [/Nan::To<int64_t>\((.+?)\)/g, '$1.As<Napi::Number>().Int64Value()'],
  115. // ex. Nan::To<float>(info[0]) to info[0].As<Napi::Number>().FloatValue()
  116. [/Nan::To<float>\((.+?)\)/g, '$1.As<Napi::Number>().FloatValue()'],
  117. // ex. Nan::To<double>(info[0]) to info[0].As<Napi::Number>().DoubleValue()
  118. [/Nan::To<double>\((.+?)\)/g, '$1.As<Napi::Number>().DoubleValue()'],
  119. [/Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())'],
  120. [/Nan::Has\(([^,]+),\s*/gm, '($1).Has('],
  121. [/\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)'],
  122. [/\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)'],
  123. [/Nan::Get\(([^,]+),\s*/gm, '($1).Get('],
  124. [/\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)'],
  125. [/\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)'],
  126. [/Nan::Set\(([^,]+),\s*/gm, '($1).Set('],
  127. [/\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,'],
  128. [/\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,'],
  129. // ex. node::Buffer::HasInstance(info[0]) to info[0].IsBuffer()
  130. [/node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()'],
  131. // ex. node::Buffer::Length(info[0]) to info[0].Length()
  132. [/node::Buffer::Length\((.+?)\)/g, '$1.As<Napi::Buffer<char>>().Length()'],
  133. // ex. node::Buffer::Data(info[0]) to info[0].Data()
  134. [/node::Buffer::Data\((.+?)\)/g, '$1.As<Napi::Buffer<char>>().Data()'],
  135. [/Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, '],
  136. // Nan::AsyncQueueWorker(worker)
  137. [/Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();'],
  138. [/Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()'],
  139. // Nan::ThrowError(error) to Napi::Error::New(env, error).ThrowAsJavaScriptException()
  140. [/([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();'],
  141. [/Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();'],
  142. [/Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n'],
  143. // Nan::RangeError(error) to Napi::RangeError::New(env, error)
  144. [/Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)'],
  145. [/Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)'],
  146. [/Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);'],
  147. [/Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope'],
  148. [/Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty('],
  149. [/\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", '],
  150. // [ /Nan::GetPropertyNames\(([^,]+)\)/, '$1->GetPropertyNames()' ],
  151. [/Nan::Equals\(([^,]+),/g, '$1.StrictEquals('],
  152. [/(.+)->Set\(/g, '$1.Set('],
  153. [/Nan::Callback/g, 'Napi::FunctionReference'],
  154. [/Nan::Persistent<Object>/g, 'Napi::ObjectReference'],
  155. [/Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target'],
  156. [/(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;'],
  157. [/Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();'],
  158. [/Nan::NAN_METHOD_RETURN_TYPE/g, 'void'],
  159. [/NAN_INLINE/g, 'inline'],
  160. [/Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&'],
  161. [/NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'],
  162. [/static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'],
  163. [/NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'],
  164. [/static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'],
  165. [/NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'],
  166. [/void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)'],
  167. [/NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);'],
  168. [/NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)'],
  169. [/::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)'],
  170. [/constructor_template/g, 'constructor'],
  171. [/Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2'],
  172. [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);'],
  173. [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&'],
  174. [/Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()'],
  175. [/info\[(\d+)\]->/g, 'info[$1].'],
  176. [/info\[([\w\d]+)\]->/g, 'info[$1].'],
  177. [/info\.This\(\)->/g, 'info.This().'],
  178. [/->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()'],
  179. [/info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()'],
  180. [/info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;'],
  181. // ex. Local<Value> to Napi::Value
  182. [/v8::Local<v8::(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1'],
  183. [/Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1'],
  184. // Declare an env in helper functions that take a Napi::Value
  185. [/(\w+)\(Napi::Value (\w+)(,\s*[^()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4'],
  186. // delete #include <node.h> and/or <v8.h>
  187. [/#include +(<|")(?:node|nan).h("|>)/g, '#include $1napi.h$2\n#include $1uv.h$2'],
  188. // NODE_MODULE to NODE_API_MODULE
  189. [/NODE_MODULE/g, 'NODE_API_MODULE'],
  190. [/Nan::/g, 'Napi::'],
  191. [/nan.h/g, 'napi.h'],
  192. // delete .FromJust()
  193. [/\.FromJust\(\)/g, ''],
  194. // delete .ToLocalCheck()
  195. [/\.ToLocalChecked\(\)/g, ''],
  196. [/^.*->SetInternalFieldCount\(.*$/gm, ''],
  197. // replace using node; and/or using v8; to using Napi;
  198. [/using (node|v8);/g, 'using Napi;'],
  199. [/using namespace (node|Nan|v8);/g, 'using namespace Napi;'],
  200. // delete using v8::Local;
  201. [/using v8::Local;\n/g, ''],
  202. // replace using v8::XXX; with using Napi::XXX
  203. [/using v8::([A-Za-z]+);/g, 'using Napi::$1;']
  204. ];
  205. const paths = listFiles(dir);
  206. paths.forEach(function (dirEntry) {
  207. const filename = dirEntry.split('\\').pop().split('/').pop();
  208. // Check whether the file is a source file or a config file
  209. // then execute function accordingly
  210. const sourcePattern = /.+\.h|.+\.cc|.+\.cpp/;
  211. if (sourcePattern.test(filename)) {
  212. convertFile(dirEntry, SourceFileOperations);
  213. } else if (ConfigFileOperations[filename] != null) {
  214. convertFile(dirEntry, ConfigFileOperations[filename]);
  215. }
  216. });
  217. function listFiles (dir, filelist) {
  218. const files = fs.readdirSync(dir);
  219. filelist = filelist || [];
  220. files.forEach(function (file) {
  221. if (file === 'node_modules') {
  222. return;
  223. }
  224. if (fs.statSync(path.join(dir, file)).isDirectory()) {
  225. filelist = listFiles(path.join(dir, file), filelist);
  226. } else {
  227. filelist.push(path.join(dir, file));
  228. }
  229. });
  230. return filelist;
  231. }
  232. function convert (content, operations) {
  233. for (let i = 0; i < operations.length; i++) {
  234. const operation = operations[i];
  235. content = content.replace(operation[0], operation[1]);
  236. }
  237. return content;
  238. }
  239. function convertFile (fileName, operations) {
  240. fs.readFile(fileName, 'utf-8', function (err, file) {
  241. if (err) throw err;
  242. file = convert(file, operations);
  243. fs.writeFile(fileName, file, function (err) {
  244. if (err) throw err;
  245. });
  246. });
  247. }