Update Files

This commit is contained in:
2025-01-22 16:18:30 +01:00
parent ed4603cf95
commit a36294b518
16718 changed files with 2960346 additions and 0 deletions

View File

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

View File

@ -0,0 +1,181 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js;
import haxe.Constraints.Function;
import haxe.extern.Rest;
import js.node.Module;
import js.node.Process;
import js.node.Timers.Immediate;
import js.node.Timers.Timeout;
import js.node.console.Console;
#if haxe4
import js.Syntax.code;
#end
/**
Node.js globals
**/
@:native("global")
extern class Node {
/**
This variable may appear to be global but is not. See [__dirname](https://nodejs.org/api/modules.html#modules_dirname).
**/
static var __dirname(get, never):String;
private static inline function get___dirname():String {
#if haxe4
return code("__dirname");
#else
return untyped __js__("__dirname");
#end
}
/**
This variable may appear to be global but is not. See [__filename](https://nodejs.org/api/modules.html#modules_filename).
**/
static var __filename(get, never):String;
private static inline function get___filename():String {
#if haxe4
return code("__filename");
#else
return untyped __js__("__filename");
#end
}
/**
`clearImmediate` is described in the [timers](https://nodejs.org/api/timers.html) section.
**/
static function clearImmediate(immediate:Immediate):Void;
/**
`clearInterval` is described in the [timers](https://nodejs.org/api/timers.html) section.
**/
static function clearInterval(timeout:Timeout):Void;
/**
`clearTimeout` is described in the [timers](https://nodejs.org/api/timers.html) section.
**/
static function clearTimeout(timeout:Timeout):Void;
/**
Used to print to stdout and stderr. See the [console](https://nodejs.org/api/console.html) section.
**/
static var console(get, never):Console;
private static inline function get_console():Console {
#if haxe4
return code("console");
#else
return untyped __js__("console");
#end
}
/**
This variable may appear to be global but is not. See [exports](https://nodejs.org/api/modules.html#modules_exports).
**/
static var exports(get, never):Dynamic<Dynamic>;
private static inline function get_exports():Dynamic<Dynamic> {
#if haxe4
return code("exports");
#else
return untyped __js__("exports");
#end
}
/**
In browsers, the top-level scope is the global scope.
This means that within the browser `var something` will define a new global variable.
In Node.js this is different. The top-level scope is not the global scope; `var something` inside a Node.js module
will be local to that module.
**/
static inline var global:Dynamic<Dynamic> = cast Node;
/**
This variable may appear to be global but is not. See [module](https://nodejs.org/api/modules.html#modules_module).
**/
static var module(get, never):Module;
private static inline function get_module():Module {
#if haxe4
return code("module");
#else
return untyped __js__("module");
#end
}
/**
The process object. See the [process object](https://nodejs.org/api/process.html#process_process) section.
**/
static var process(get, never):Process;
private static inline function get_process():Process {
#if haxe4
return code("process");
#else
return untyped __js__("process");
#end
}
/**
The `queueMicrotask()` method queues a microtask to invoke `callback`.
If `callback` throws an exception, the [process object](https://nodejs.org/api/process.html#process_process) 'uncaughtException' event will be emitted.
The microtask queue is managed by V8 and may be used in a similar manner to the `Process.nextTick()` queue,
which is managed by Node.js.
The `Process.nextTick()` queue is always processed before the microtask queue within each turn of the Node.js event loop.
**/
static function queueMicrotask(callback:Void->Void):Void;
/**
This variable may appear to be global but is not. See [require()](https://nodejs.org/api/modules.html#modules_require_id).
**/
static inline function require(module:String):Dynamic {
#if haxe4
return code("require({0})", module);
#else
return untyped __js__("require({0})", module);
#end
}
/**
`setImmediate` is described in the [timers](https://nodejs.org/api/timers.html) section.
**/
static function setImmediate(callback:Function, args:Rest<Dynamic>):Immediate;
/**
`setInterval` is described in the [timers](https://nodejs.org/api/timers.html) section.
**/
static function setInterval(callback:Function, delay:Int, args:Rest<Dynamic>):Timeout;
/**
`setTimeout` is described in the [timers](https://nodejs.org/api/timers.html) section.
**/
static function setTimeout(callback:Function, delay:Int, args:Rest<Dynamic>):Timeout;
}
@:deprecated typedef TimeoutObject = js.node.Timers.Timeout;
@:deprecated typedef IntervalObject = js.node.Timers.Timeout;
@:deprecated typedef ImmediateObject = js.node.Timers.Immediate;

View File

@ -0,0 +1,66 @@
![hxnodejs](hxnodejs.png)
# Haxe Node.JS
[![Build Status](https://badgen.net/travis/HaxeFoundation/hxnodejs?label=build)](https://travis-ci.org/HaxeFoundation/hxnodejs)
[![Haxelib Version](https://badgen.net/haxelib/v/hxnodejs)](https://lib.haxe.org/p/hxnodejs)
[![Haxelib Downloads](https://badgen.net/haxelib/d/hxnodejs?color=blue)](https://lib.haxe.org/p/hxnodejs)
[![Haxelib License](https://badgen.net/haxelib/license/hxnodejs)](LICENSE.md)
Extern type definitions for Node.JS. Haxe **3.4** or newer is required.
Haxe-generated API documentation is available at http://haxefoundation.github.io/hxnodejs/js/Node.html.
Original node.js documentation can be found at http://nodejs.org/api/index.html.
## Features
- Full node.js API with documentation.
- Strict typing for everything, fully leveraging Haxe type system.
- Optionally typed event listeners.
- Automatic insert of "require" statements for used modules.
- Clean output.
## Quick example
1. Install hxnodejs with `haxelib install hxnodejs` (released version) or `haxelib git hxnodejs https://github.com/HaxeFoundation/hxnodejs` (latest from GitHub).
2. Write some code and save to `Main.hx`:
```haxe
class Main {
static function main() {
var server = js.node.Net.createServer(function(socket) {
socket.write("Echo server\n\n");
socket.pipe(socket);
});
server.listen(1337, "127.0.0.1");
}
}
```
3. Compile it with with `haxe -lib hxnodejs -main Main -js main.js` (optionally add `-D js-es=6` for cleaner JavaScript output, since node.js is ES6-compliant)
4. Look at generated `main.js`:
```js
// Generated by Haxe 4.0.0-rc.2+63144f6db
(function ($global) { "use strict";
class Main {
static main() {
var server = js_node_Net.createServer(function(socket) {
socket.write("Echo server\n\n");
socket.pipe(socket);
});
server.listen(1337,"127.0.0.1");
}
}
var js_node_Net = require("net");
Main.main();
})({});
```
5. You're awesome! (See more [examples](examples))
## Status
This library is considered complete, but testing and contributions are welcome. See [current issues](https://github.com/HaxeFoundation/hxnodejs/issues) and [extern guidelines](https://github.com/HaxeFoundation/hxnodejs/blob/master/HOWTO.md).

View File

@ -0,0 +1,224 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
#if haxe4
import js.lib.Error;
import js.lib.Promise;
import js.lib.RegExp;
#else
import js.Error;
import js.Promise;
import js.RegExp;
#end
/**
The `assert module` provides a set of assertion functions for verifying invariants.
The module provides a recommended [strict mode](https://nodejs.org/api/assert.html#assert_strict_mode) and a more lenient legacy mode.
@see https://nodejs.org/api/assert.html#assert_assert
**/
@:jsRequire("assert")
extern class Assert {
/**
In strict mode, assert functions use the comparison in the corresponding strict functions.
For example, `Assert.deepEqual()` will behave like `Assert.deepStrictEqual()`.
@see https://nodejs.org/api/assert.html#assert_strict_mode
**/
static var strict(default, never):Assert;
/**
An alias of `Assert.ok()`.
@see https://nodejs.org/api/assert.html#assert_assert_value_message
**/
@:selfCall
@:overload(function(value:Dynamic, ?message:Error):Void {})
static function assert(value:Dynamic, ?message:String):Void;
/**
An alias of `Assert.deepStrictEqual()`.
@see https://nodejs.org/api/assert.html#assert_assert_deepequal_actual_expected_message
**/
@:deprecated
@:overload(function<T>(actual:T, expected:T, ?message:Error):Void {})
static function deepEqual<T>(actual:T, expected:T, ?message:String):Void;
/**
Tests for deep equality between the `actual` and `expected` parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules.
@see https://nodejs.org/api/assert.html#assert_assert_deepstrictequal_actual_expected_message
**/
@:overload(function<T>(actual:T, expected:T, ?message:Error):Void {})
static function deepStrictEqual<T>(actual:T, expected:T, ?message:String):Void;
/**
Awaits the `asyncFn` promise or, if `asyncFn` is a function,
immediately calls the function and awaits the returned promise to complete.
It will then check that the promise is not rejected.
@see https://nodejs.org/api/assert.html#assert_assert_doesnotreject_asyncfn_error_message
**/
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:Class<Dynamic>, ?message:String):Void {})
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:RegExp, ?message:String):Void {})
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:Dynamic->Bool, ?message:String):Void {})
@:overload(function(asyncFn:Promise<Dynamic>, ?error:Class<Dynamic>, ?message:String):Void {})
@:overload(function(asyncFn:Promise<Dynamic>, ?error:RegExp, ?message:String):Void {})
static function doesNotReject(asyncFn:Promise<Dynamic>, ?error:Dynamic->Bool, ?message:String):Void;
/**
Asserts that the function `fn` does not throw an error.
Using `Assert.doesNotThrow()` is actually not useful because there is no benefit
in catching an error and then rethrowing it.
Instead, consider adding a comment next to the specific code path that should not throw
and keep error messages as expressive as possible.
@see https://nodejs.org/api/assert.html#assert_assert_doesnotthrow_fn_error_message
**/
@:overload(function(fn:Void->Void, ?error:Class<Dynamic>, ?message:String):Void {})
@:overload(function(fn:Void->Void, ?error:RegExp, ?message:String):Void {})
static function doesNotThrow(fn:Void->Void, ?error:Dynamic->Bool, ?message:String):Void;
/**
An alias of `strictEqual`.
@see https://nodejs.org/api/assert.html#assert_assert_equal_actual_expected_message
**/
@:overload(function<T>(actual:T, expected:T, ?message:String):Void {})
static function equal<T>(actual:T, expected:T, ?message:Error):Void;
/**
Throws an `AssertionError` with the provided error message or a default error message.
If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`.
@see https://nodejs.org/api/assert.html#assert_assert_fail_message
**/
@:overload(function(?message:String):Void {})
static function fail(?message:Error):Void;
/**
Throws an `AssertionError`. If `message` is falsy, the error message is set as the values
of `actual` and `expected` separated by the provided `operator`.
Otherwise, the error message is the value of `message`.
@see https://nodejs.org/api/assert.html#assert_assert_fail_actual_expected_message_operator_stackstartfn
**/
@:deprecated
@:native("fail")
@:overload(function<T>(actual:T, expected:T, ?message:String, ?operator_:String, ?stackStartFn:haxe.Constraints.Function):Void {})
static function fail_<T>(actual:T, expected:T, ?message:Error, ?operator_:String, ?stackStartFn:haxe.Constraints.Function):Void;
/**
Throws `value` if `value` is not `undefined` or `null`.
This is useful when testing the `error` argument in callbacks.
The stack trace contains all frames from the error passed to `ifError()` including the potential new frames for `ifError()` itself.
@see https://nodejs.org/api/assert.html#assert_assert_iferror_value
**/
static function ifError(value:Dynamic):Void;
/**
An alias of `Assert.notDeepStrictEqual()`.
@see https://nodejs.org/api/assert.html#assert_assert_notdeepequal_actual_expected_message
**/
@:deprecated
@:overload(function<T>(actual:T, expected:T, ?message:Error):Void {})
static function notDeepEqual<T>(actual:T, expected:T, ?message:String):Void;
/**
Tests for deep strict inequality. Opposite of `Assert.deepStrictEqual()`.
@see https://nodejs.org/api/assert.html#assert_assert_notdeepstrictequal_actual_expected_message
**/
@:overload(function<T>(actual:T, expected:T, ?message:Error):Void {})
static function notDeepStrictEqual<T>(actual:T, expected:T, ?message:String):Void;
/**
An alias of `Assert.notStrictEqual()`.
@see https://nodejs.org/api/assert.html#assert_assert_notequal_actual_expected_message
**/
@:deprecated
@:overload(function<T>(actual:T, expected:T, ?message:Error):Void {})
static function notEqual<T>(actual:T, expected:T, ?message:String):Void;
/**
Tests strict inequality between the `actual` and `expected` parameters as determined by the SameValue Comparison.
@see https://nodejs.org/api/assert.html#assert_assert_notstrictequal_actual_expected_message
**/
@:overload(function<T>(actual:T, expected:T, ?message:Error):Void {})
static function notStrictEqual<T>(actual:T, expected:T, ?message:String):Void;
/**
Tests if `value` is truthy.
It is equivalent to `Assert.equal(!!value, true, message)`.
@see https://nodejs.org/api/assert.html#assert_assert_ok_value_message
**/
@:overload(function(value:Dynamic, ?message:Error):Void {})
static function ok(value:Dynamic, ?message:String):Void;
/**
Awaits the `asyncFn` promise or, if `asyncFn` is a function,
immediately calls the function and awaits the returned promise to complete.
It will then check that the promise is rejected.
@see https://nodejs.org/api/assert.html#assert_assert_rejects_asyncfn_error_message
**/
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:Class<Dynamic>, ?message:String):Void {})
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:RegExp, ?message:String):Void {})
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:Dynamic->Bool, ?message:String):Void {})
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:Dynamic, ?message:String):Void {})
@:overload(function(asyncFn:Void->Promise<Dynamic>, ?error:Error, ?message:String):Void {})
@:overload(function(asyncFn:Promise<Dynamic>, ?error:Class<Dynamic>, ?message:String):Void {})
@:overload(function(asyncFn:Promise<Dynamic>, ?error:RegExp, ?message:String):Void {})
@:overload(function(asyncFn:Promise<Dynamic>, ?error:Dynamic->Bool, ?message:String):Void {})
@:overload(function(asyncFn:Promise<Dynamic>, ?error:Dynamic, ?message:String):Void {})
static function rejects(asyncFn:Promise<Dynamic>, ?error:Error, ?message:String):Void;
/**
Tests strict equality between the `actual` and `expected` parameter as
determined by the SameValue Comparison.
@see https://nodejs.org/api/assert.html#assert_assert_strictequal_actual_expected_message
**/
@:overload(function<T>(actual:T, expected:T, ?message:Error):Void {})
static function strictEqual<T>(actual:T, expected:T, ?message:String):Void;
/**
Expects the function `fn` to throw an error.
@see https://nodejs.org/api/assert.html#assert_assert_throws_fn_error_message
**/
@:overload(function(fn:Void->Void, ?error:RegExp, ?message:String):Void {})
@:overload(function(fn:Void->Void, ?error:Dynamic->Bool, ?message:String):Void {})
@:overload(function(fn:Void->Void, ?error:Dynamic, ?message:String):Void {})
static function throws(fn:Void->Void, ?error:Error, ?message:String):Void;
}

View File

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

View File

@ -0,0 +1,418 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.DynamicAccess;
import haxe.extern.EitherType;
import js.node.child_process.ChildProcess as ChildProcessObject;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Common options for all `ChildProcess` methods.
**/
private typedef ChildProcessCommonOptions = {
/**
Current working directory of the child process.
**/
@:optional var cwd:String;
/**
Environment key-value pairs
**/
@:optional var env:DynamicAccess<String>;
/**
Sets the user identity of the process. See setuid(2).
**/
@:optional var uid:Int;
/**
Sets the group identity of the process. See setgid(2).
**/
@:optional var gid:Int;
/**
Shell to execute the command with.
Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows.
The shell should understand the -c switch on UNIX or /s /c on Windows.
On Windows, command line parsing should be compatible with cmd.exe.
**/
@:optional var shell:EitherType<Bool, String>;
}
/**
Common options for `spawn` and `spawnSync` methods.
**/
private typedef ChildProcessSpawnOptionsBase = {
> ChildProcessCommonOptions,
/**
Child's stdio configuration.
**/
@:optional var stdio:ChildProcessSpawnOptionsStdio;
}
/**
Options for the `spawn` method.
**/
typedef ChildProcessSpawnOptions = {
> ChildProcessSpawnOptionsBase,
/**
The child will be a process group leader.
**/
@:optional var detached:Bool;
}
/**
Options for the `spawnSync` method.
**/
typedef ChildProcessSpawnSyncOptions = {
> ChildProcessSpawnOptionsBase,
> ChildProcessExecOptionsBase,
@:optional var input:EitherType<String, Buffer>;
}
/**
The `stdio` option is an array where each index corresponds to a fd in the child.
The value is one of the following:
* 'pipe' - Create a pipe between the child process and the parent process.
The parent end of the pipe is exposed to the parent as a property on the child_process object as ChildProcess.stdio[fd].
Pipes created for fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout and ChildProcess.stderr, respectively.
* 'ipc' - Create an IPC channel for passing messages/file descriptors between parent and child.
A ChildProcess may have at most one IPC stdio file descriptor. Setting this option enables the ChildProcess.send() method.
If the child writes JSON messages to this file descriptor, then this will trigger ChildProcess.on('message').
If the child is a Node.js program, then the presence of an IPC channel will enable process.send() and process.on('message').
* 'ignore' - Do not set this file descriptor in the child. Note that Node will always open fd 0 - 2 for the processes it spawns.
When any of these is ignored node will open /dev/null and attach it to the child's fd.
* Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process.
The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index
in the stdio array. Note that the stream must have an underlying descriptor (file streams do not until the 'open'
event has occurred).
* Positive integer - The integer value is interpreted as a file descriptor that is is currently open in the parent process.
It is shared with the child process, similar to how Stream objects can be shared.
* null - Use default value. For stdio fds 0, 1 and 2 (in other words, stdin, stdout, and stderr) a pipe is created.
For fd 3 and up, the default is 'ignore'.
As a shorthand, the stdio argument may also be one of the following strings, rather than an array:
ignore - ['ignore', 'ignore', 'ignore']
pipe - ['pipe', 'pipe', 'pipe']
inherit - [process.stdin, process.stdout, process.stderr] or [0,1,2]
**/
typedef ChildProcessSpawnOptionsStdio = EitherType<ChildProcessSpawnOptionsStdioSimple, ChildProcessSpawnOptionsStdioFull>;
/**
A shorthand for the `stdio` argument in `ChildProcessSpawnOptions`
**/
@:enum abstract ChildProcessSpawnOptionsStdioSimple(String) from String to String {
/**
Equivalent to ['ignore', 'ignore', 'ignore']
**/
var Ignore = "ignore";
/**
Equivalent to ['pipe', 'pipe', 'pipe']
**/
var Pipe = "pipe";
/**
Equivalent to [process.stdin, process.stdout, process.stderr] or [0,1,2]
**/
var Inherit = "inherit";
}
/**
Enumeration of possible `stdio` behaviours.
**/
@:enum abstract ChildProcessSpawnOptionsStdioBehaviour(String) from String to String {
/**
Create a pipe between the child process and the parent process.
The parent end of the pipe is exposed to the parent as a property on the child_process object as ChildProcess.stdio[fd].
Pipes created for fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout and ChildProcess.stderr, respectively.
**/
var Pipe = "pipe";
/**
Create an IPC channel for passing messages/file descriptors between parent and child.
A ChildProcess may have at most one IPC stdio file descriptor.
Setting this option enables the ChildProcess.send() method.
If the child writes JSON messages to this file descriptor, then this will trigger
ChildProcess.on('message').
If the child is a Node.js program, then the presence of an IPC channel will
enable process.send() and process.on('message').
**/
var Ipc = "ipc";
/**
Do not set this file descriptor in the child.
Note that Node will always open fd 0 - 2 for the processes it spawns.
When any of these is ignored node will open /dev/null and attach it to the child's fd.
**/
var Ignore = "ignore";
}
// see https://github.com/HaxeFoundation/haxe/issues/3499
// typedef ChildProcessSpawnOptionsStdioFull = Array<EitherType<ChildProcessSpawnOptionsStdioBehaviour,EitherType<IStream,Int>>>;
typedef ChildProcessSpawnOptionsStdioFull = Array<Dynamic>;
/**
Common options for `exec` and `execFile` methods.
**/
private typedef ChildProcessExecOptionsBase = {
> ChildProcessCommonOptions,
/**
Default: 'utf8'
**/
@:optional var encoding:String;
/**
If greater than 0, then it will kill the child process if it runs longer than timeout milliseconds.
**/
@:optional var timeout:Int;
/**
The child process is killed with `killSignal` (default: 'SIGTERM').
**/
@:optional var killSignal:String;
/**
The largest amount of data allowed on stdout or stderr.
If this value is exceeded then the child process is killed.
Default: 200*1024
**/
@:optional var maxBuffer:Int;
}
/**
Options for the `exec` method.
**/
typedef ChildProcessExecOptions = {
> ChildProcessExecOptionsBase,
}
/**
Options for the `execFile` method.
**/
typedef ChildProcessExecFileOptions = {
> ChildProcessExecOptionsBase,
}
/**
Options for the `fork` method.
**/
typedef ChildProcessForkOptions = {
> ChildProcessCommonOptions,
/**
Executable used to create the child process
**/
@:optional var execPath:String;
/**
List of string arguments passed to the executable (Default: process.execArgv)
**/
@:optional var execArgv:Array<String>;
/**
If `true`, stdin, stdout, and stderr of the child will be piped to the parent,
otherwise they will be inherited from the parent, see the "pipe" and "inherit"
options for `ChildProcessSpawnOptions.stdio` for more details (default is `false`)
**/
@:optional var silent:Bool;
}
/**
An error passed to the `ChildProcess.exec` callback.
**/
@:native("Error")
extern class ChildProcessExecError extends Error {
/**
the exit code of the child proces.
**/
var code(default, null):Int;
/**
the signal that terminated the process.
**/
var signal(default, null):String;
}
/**
A callback type for `ChildProcess.exec`.
It receives three arguments: `error`, `stdout`, `stderr`.
On success, error will be `null`. On error, `error` will be an instance of `Error`
and `error.code` will be the exit code of the child process, and `error.signal` will be set
to the signal that terminated the process (see `ChildProcessExecError`).
**/
typedef ChildProcessExecCallback = #if (haxe_ver >= 4) (error : Null<ChildProcessExecError>, stdout : EitherType<Buffer, String>, stderr : EitherType<Buffer,
String>) -> Void; #else Null<ChildProcessExecError>->EitherType<Buffer, String>->EitherType<Buffer, String>->Void; #end
/**
Object returned from the `spawnSync` method.
**/
typedef ChildProcessSpawnSyncResult = {
/**
Pid of the child process
**/
var pid:Int;
/**
Array of results from stdio output
**/
var output:Array<EitherType<Buffer, String>>;
/**
The contents of output[1]
**/
var stdout:EitherType<Buffer, String>;
/**
The contents of output[2]
**/
var stderr:EitherType<Buffer, String>;
/**
The exit code of the child process
**/
var status:Int;
/**
The signal used to kill the child process
**/
var signal:String;
/**
The error object if the child process failed or timed out
**/
var error:Error;
}
@:jsRequire("child_process")
extern class ChildProcess {
/**
Launches a new process with the given `command`, with command line arguments in `args`.
If omitted, `args` defaults to an empty `Array`.
The third argument is used to specify additional options, which defaults to:
{ cwd: null,
env: process.env
}
Note that if spawn receives an empty options object, it will result in spawning the process with an empty
environment rather than using `process.env`. This due to backwards compatibility issues with a deprecated API.
**/
@:overload(function(command:String, ?options:ChildProcessSpawnOptions):ChildProcessObject {})
@:overload(function(command:String, args:Array<String>, ?options:ChildProcessSpawnOptions):ChildProcessObject {})
static function spawn(command:String, ?args:Array<String>):ChildProcessObject;
/**
Runs a command in a shell and buffers the output.
`command` is the command to run, with space-separated arguments.
The default `options` are:
{ encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null }
**/
@:overload(function(command:String, options:ChildProcessExecOptions, callback:ChildProcessExecCallback):ChildProcessObject {})
static function exec(command:String, callback:ChildProcessExecCallback):ChildProcessObject;
/**
This is similar to `exec` except it does not execute a subshell but rather the specified file directly.
This makes it slightly leaner than `exec`
**/
@:overload(function(file:String, args:Array<String>, options:ChildProcessExecFileOptions, ?callback:ChildProcessExecCallback):ChildProcessObject {})
@:overload(function(file:String, options:ChildProcessExecFileOptions, ?callback:ChildProcessExecCallback):ChildProcessObject {})
@:overload(function(file:String, args:Array<String>, ?callback:ChildProcessExecCallback):ChildProcessObject {})
static function execFile(file:String, ?callback:ChildProcessExecCallback):ChildProcessObject;
/**
This is a special case of the `spawn` functionality for spawning Node processes.
In addition to having all the methods in a normal `ChildProcess` instance,
the returned object has a communication channel built-in.
See `send` for details.
**/
@:overload(function(modulePath:String, args:Array<String>, options:ChildProcessForkOptions):ChildProcessObject {})
@:overload(function(modulePath:String, options:ChildProcessForkOptions):ChildProcessObject {})
static function fork(modulePath:String, ?args:Array<String>):ChildProcessObject;
/**
Synchronous version of `spawn`.
`spawnSync` will not return until the child process has fully closed.
When a timeout has been encountered and `killSignal` is sent, the method won't return until the process
has completely exited. That is to say, if the process handles the SIGTERM signal and doesn't exit,
your process will wait until the child process has exited.
**/
@:overload(function(command:String, args:Array<String>, ?options:ChildProcessSpawnSyncOptions):ChildProcessSpawnSyncResult {})
static function spawnSync(command:String, ?options:ChildProcessSpawnSyncOptions):ChildProcessSpawnSyncResult;
/**
Synchronous version of `execFile`.
`execFileSync` will not return until the child process has fully closed.
When a timeout has been encountered and `killSignal` is sent, the method won't return until the process
has completely exited. That is to say, if the process handles the SIGTERM signal and doesn't exit,
your process will wait until the child process has exited.
If the process times out, or has a non-zero exit code, this method will throw.
The Error object will contain the entire result from `spawnSync`
**/
@:overload(function(command:String, ?options:ChildProcessSpawnSyncOptions):EitherType<String, Buffer> {})
@:overload(function(command:String, args:Array<String>, ?options:ChildProcessSpawnSyncOptions):EitherType<String, Buffer> {})
static function execFileSync(command:String, ?args:Array<String>):EitherType<String, Buffer>;
/**
Synchronous version of `exec`.
`execSync` will not return until the child process has fully closed.
When a timeout has been encountered and `killSignal` is sent, the method won't return until the process
has completely exited. That is to say, if the process handles the SIGTERM signal and doesn't exit,
your process will wait until the child process has exited.
If the process times out, or has a non-zero exit code, this method will throw.
The Error object will contain the entire result from `spawnSync`
**/
static function execSync(command:String, ?options:ChildProcessSpawnSyncOptions):EitherType<String, Buffer>;
}

View File

@ -0,0 +1,266 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.DynamicAccess;
import js.node.cluster.Worker;
import js.node.events.EventEmitter;
@:enum abstract ClusterEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
When a new worker is forked the cluster module will emit a 'fork' event.
This can be used to log worker activity, and create your own timeout.
Listener arguments:
* worker:Worker
**/
var Fork:ClusterEvent<Worker->Void> = "fork";
/**
After forking a new worker, the worker should respond with an online message.
When the master receives an online message it will emit this event.
The difference between 'fork' and 'online' is that fork is emitted when the master forks a worker,
and 'online' is emitted when the worker is running.
Listener arguments:
* worker:Worker
**/
var Online:ClusterEvent<Worker->Void> = "online";
/**
After calling `listen` from a worker, when the 'listening' event is emitted on the server,
a listening event will also be emitted on cluster in the master.
The event handler is executed with two arguments, the `worker` contains the worker object and
the `address` object contains the following connection properties: address, port and addressType.
This is very useful if the worker is listening on more than one address.
Listener arguments:
* worker:Worker
* address:ListeningEventAddress
**/
var Listening:ClusterEvent<Worker->ListeningEventAddress->Void> = "listening";
/**
Emitted after the worker IPC channel has disconnected.
This can occur when a worker exits gracefully, is killed,
or is disconnected manually (such as with `Worker.disconnect`).
There may be a delay between the 'disconnect' and 'exit' events.
These events can be used to detect if the process is stuck in a cleanup
or if there are long-living connections.
Listener arguments:
* worker:Worker
**/
var Disconnect:ClusterEvent<Worker->Void> = "disconnect";
/**
When any of the workers die the cluster module will emit the 'exit' event.
This can be used to restart the worker by calling `Cluster.fork` again.
Listener arguments:
* worker:Worker
* code:Int - the exit code, if it exited normally.
* signal:String - the name of the signal (eg. 'SIGHUP') that caused the process to be killed.
**/
var Exit:ClusterEvent<Worker->Int->String->Void> = "exit";
/**
Emitted the first time that `Cluster.setupMaster` is called.
**/
var Setup:ClusterEvent<ClusterSettings->Void> = "setup";
}
/**
Structure emitted by 'listening' event.
**/
typedef ListeningEventAddress = {
var address:String;
var port:Int;
var addressType:ListeningEventAddressType;
}
@:enum abstract ListeningEventAddressType(haxe.extern.EitherType<Int, String>) to haxe.extern.EitherType<Int, String> {
var TCPv4 = 4;
var TCPv6 = 6;
var Unix = -1;
var UDPv4 = "udp4";
var UDPv6 = "udp6";
}
@:jsRequire("cluster")
@:enum extern abstract ClusterSchedulingPolicy(Int) {
var SCHED_NONE;
var SCHED_RR;
}
/**
A single instance of Node runs in a single thread.
To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load.
The cluster module allows you to easily create child processes that all share server ports.
This feature was introduced recently, and may change in future versions. Please try it out and provide feedback.
Also note that, on Windows, it is not yet possible to set up a named pipe server in a worker.
**/
@:jsRequire("cluster")
extern class Cluster extends EventEmitter<Cluster> {
/**
A reference to the `Cluster` object returned by node.js module.
It can be imported into module namespace by using: "import js.node.Cluster.instance in cluster"
**/
public static inline var instance:Cluster = cast Cluster;
/**
The scheduling policy, either `SCHED_RR` for round-robin
or `SCHED_NONE` to leave it to the operating system.
This is a global setting and effectively frozen once you spawn the first worker
or call `setupMaster`, whatever comes first.
`SCHED_RR` is the default on all operating systems except Windows.
Windows will change to `SCHED_RR` once libuv is able to effectively distribute IOCP handles
without incurring a large performance hit.
`schedulingPolicy` can also be set through the NODE_CLUSTER_SCHED_POLICY environment variable.
Valid values are "rr" and "none".
**/
var schedulingPolicy:ClusterSchedulingPolicy;
/**
After calling `setupMaster` (or `fork`) this settings object will contain the settings, including the default values.
It is effectively frozen after being set, because `setupMaster` can only be called once.
This object is not supposed to be changed or set manually, by you.
**/
var settings(default, null):ClusterSettings;
/**
True if the process is a master.
This is determined by the process.env.NODE_UNIQUE_ID.
If process.env.NODE_UNIQUE_ID is undefined, then `isMaster` is true.
**/
var isMaster(default, null):Bool;
/**
True if the process is not a master (it is the negation of `isMaster`).
**/
var isWorker(default, null):Bool;
/**
`setupMaster` is used to change the default `fork` behavior.
Once called, the `settings` will be present in `settings`.
Note that:
Only the first call to `setupMaster` has any effect, subsequent calls are ignored
That because of the above, the only attribute of a worker that may be customized per-worker
is the `env` passed to `fork`
`fork` calls `setupMaster` internally to establish the defaults, so to have any effect,
`setupMaster` must be called before any calls to `fork`
**/
function setupMaster(?settings:{?exec:String, ?args:Array<String>, ?silent:Bool}):Void;
/**
Spawn a new worker process.
This can only be called from the master process.
**/
function fork(?env:DynamicAccess<String>):Worker;
/**
Calls `disconnect` on each worker in `workers`.
When they are disconnected all internal handles will be closed,
allowing the master process to die gracefully if no other event is waiting.
The method takes an optional `callback` argument which will be called when finished.
This can only be called from the master process.
**/
function disconnect(?callback:Void->Void):Void;
/**
A reference to the current worker object.
Not available in the master process.
**/
var worker(default, null):Worker;
/**
A hash that stores the active worker objects, keyed by `id` field.
Makes it easy to loop through all the workers.
It is only available in the master process.
A worker is removed from `workers` just before the 'disconnect' or 'exit' event is emitted.
Should you wish to reference a worker over a communication channel, using the worker's unique `id`
is the easiest way to find the worker.
**/
var workers(default, null):DynamicAccess<Worker>;
}
typedef ClusterSettings = {
/**
list of string arguments passed to the node executable.
Default: process.execArgv
**/
@:optional var execArgv(default, null):Array<String>;
/**
file path to worker file.
Default: process.argv[1]
**/
@:optional var exec(default, null):String;
/**
string arguments passed to worker.
Default: process.argv.slice(2)
**/
@:optional var args(default, null):Array<String>;
/**
whether or not to send output to parent's stdio.
Default: false
**/
@:optional var silent(default, null):Bool;
/**
Sets the user identity of the process.
**/
@:optional var uid(default, null):Int;
/**
Sets the group identity of the process.
**/
@:optional var gid(default, null):Int;
}

View File

@ -0,0 +1,44 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
@:jsRequire("constants")
extern class Constants {
static var ENGINE_METHOD_RSA(default, null):Int;
static var ENGINE_METHOD_DSA(default, null):Int;
static var ENGINE_METHOD_DH(default, null):Int;
static var ENGINE_METHOD_RAND(default, null):Int;
static var ENGINE_METHOD_ECDH(default, null):Int;
static var ENGINE_METHOD_ECDSA(default, null):Int;
static var ENGINE_METHOD_CIPHERS(default, null):Int;
static var ENGINE_METHOD_DIGESTS(default, null):Int;
static var ENGINE_METHOD_STORE(default, null):Int;
static var ENGINE_METHOD_PKEY_METH(default, null):Int;
static var ENGINE_METHOD_PKEY_ASN1_METH(default, null):Int;
static var ENGINE_METHOD_ALL(default, null):Int;
static var ENGINE_METHOD_NONE(default, null):Int;
static var RSA_NO_PADDING(default, null):Int;
static var RSA_PKCS1_PADDING(default, null):Int;
static var RSA_PKCS1_OAEP_PADDING(default, null):Int;
}

View File

@ -0,0 +1,306 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.extern.EitherType;
import js.node.Buffer;
import js.node.crypto.*;
import js.node.crypto.DiffieHellman.IDiffieHellman;
import js.node.tls.SecureContext;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumerations of crypto algorighms to be used.
**/
@:enum abstract CryptoAlgorithm(String) from String to String {
var SHA1 = "sha1";
var MD5 = "md5";
var SHA256 = "sha256";
var SHA512 = "sha512";
}
/**
Enumeration of supported group names for `Crypto.getDiffieHellman`.
**/
@:enum abstract DiffieHellmanGroupName(String) from String to String {
var Modp1 = "modp1";
var Modp2 = "modp2";
var Modp5 = "modp5";
var Modp14 = "modp14";
var Modp15 = "modp15";
var Modp16 = "modp16";
var Modp17 = "modp17";
var Modp18 = "modp18";
}
/**
The crypto module offers a way of encapsulating secure credentials
to be used as part of a secure HTTPS net or http connection.
It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
**/
@:jsRequire("crypto")
extern class Crypto {
/**
Load and set engine for some/all OpenSSL functions (selected by `flags`).
`engine` could be either an id or a path to the to the engine's shared library.
`flags` is optional and has `Constants.ENGINE_METHOD_ALL` value by default.
It could take one of or mix of flags prefixed with `ENGINE_METHOD_` defined in `Constants` module.
**/
static function setEngine(engine:String, ?flags:Int):Void;
/**
The default encoding to use for functions that can take either strings or buffers.
The default value is 'buffer', which makes it default to using `Buffer` objects.
This is here to make the crypto module more easily compatible with legacy programs
that expected 'binary' to be the default encoding.
Note that new programs will probably expect buffers, so only use this as a temporary measure.
**/
@:deprecated
static var DEFAULT_ENCODING:String;
/**
Property for checking and controlling whether a FIPS compliant crypto provider is currently in use.
Setting to true requires a FIPS build of Node.js.
**/
static var fips:Bool;
/**
Returns an array with the names of the supported ciphers.
**/
static function getCiphers():Array<String>;
/**
Returns an array with the names of the supported hash algorithms.
**/
static function getHashes():Array<String>;
/**
Returns an array with the names of the supported elliptic curves.
**/
static function getCurves():Array<String>;
/**
Creates a credentials object
**/
@:deprecated("Use js.node.Tls.createSecureContext instead.")
static function createCredentials(?details:SecureContextOptions):SecureContext;
/**
Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.
`algorithm` is dependent on the available algorithms supported by the version of OpenSSL on the platform.
Examples are 'sha1', 'md5', 'sha256', 'sha512', etc.
On recent releases, openssl list-message-digest-algorithms will display the available digest algorithms.
**/
static function createHash(algorithm:CryptoAlgorithm):Hash;
/**
Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
`algorithm` is dependent on the available algorithms supported by OpenSSL - see `createHash` above.
`key` is the hmac key to be used.
**/
static function createHmac(algorithm:CryptoAlgorithm, key:EitherType<String, Buffer>):Hmac;
/**
Creates and returns a cipher object, with the given algorithm and password.
`algorithm` is dependent on OpenSSL, examples are 'aes192', etc.
On recent releases, openssl list-cipher-algorithms will display the available cipher algorithms.
`password` is used to derive key and IV, which must be a 'binary' encoded string or a buffer.
It is a stream that is both readable and writable. The written data is used to compute the hash.
Once the writable side of the stream is ended, use the `read` method to get the computed hash digest.
The legacy `update` and `digest` methods are also supported.
**/
static function createCipher(algorithm:String, password:EitherType<String, Buffer>):Cipher;
/**
Creates and returns a cipher object, with the given algorithm, key and iv.
`algorithm` is the same as the argument to `createCipher`.
`key` is the raw key used by the algorithm.
`iv` is an initialization vector.
`key` and `iv` must be 'binary' encoded strings or buffers.
**/
static function createCipheriv(algorithm:String, key:EitherType<String, Buffer>, iv:EitherType<String, Buffer>):Cipher;
/**
Creates and returns a decipher object, with the given algorithm and key.
This is the mirror of the `createCipher` above.
**/
static function createDecipher(algorithm:String, password:EitherType<String, Buffer>):Decipher;
/**
Creates and returns a decipher object, with the given algorithm, key and iv.
This is the mirror of the `createCipheriv` above.
**/
static function createDecipheriv(algorithm:String, key:EitherType<String, Buffer>, iv:EitherType<String, Buffer>):Decipher;
/**
Creates and returns a signing object, with the given algorithm.
On recent OpenSSL releases, openssl list-public-key-algorithms will display the available signing algorithms.
Example: 'RSA-SHA256'.
**/
static function createSign(algorithm:String):Sign;
/**
Creates and returns a verification object, with the given algorithm.
This is the mirror of the signing object above.
**/
static function createVerify(algorithm:String):Verify;
/**
Creates a Diffie-Hellman key exchange object using the supplied `prime` or generated prime of given bit `prime_length`.
The generator used is 2. `encoding` can be 'binary', 'hex', or 'base64'.
Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is 2.
**/
@:overload(function(prime_length:Int):DiffieHellman {})
@:overload(function(prime:Buffer):DiffieHellman {})
static function createDiffieHellman(prime:String, encoding:String):DiffieHellman;
/**
Creates a predefined Diffie-Hellman key exchange object.
The supported groups are: 'modp1', 'modp2', 'modp5' (defined in RFC 2412) and 'modp14', 'modp15', 'modp16', 'modp17', 'modp18' (defined in RFC 3526).
The returned object mimics the interface of objects created by `createDiffieHellman` above,
but will not allow to change the keys (with setPublicKey() for example).
The advantage of using this routine is that the parties don't have to generate nor exchange group modulus beforehand,
saving both processor and communication time.
**/
static function getDiffieHellman(group_name:DiffieHellmanGroupName):IDiffieHellman;
/**
Creates an Elliptic Curve (EC) Diffie-Hellman key exchange object using a predefined curve
specified by the `curve_name` string. Use `getCurves` to obtain a list of available curve names.
On recent releases, openssl ecparam -list_curves will also display the name
and description of each available elliptic curve.
**/
static function createECDH(curve_name:String):ECDH;
/**
Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length
from the given password, salt and iterations.
**/
@:overload(function(password:EitherType<String, Buffer>, salt:EitherType<String, Buffer>, iterations:Int, keylen:Int, digest:String,
callback:Error->Buffer->Void):Void {})
static function pbkdf2(password:EitherType<String, Buffer>, salt:EitherType<String, Buffer>, iterations:Int, keylen:Int,
callback:Error->Buffer->Void):Void;
/**
Synchronous PBKDF2 function. Returns derivedKey or throws error.
**/
static function pbkdf2Sync(password:EitherType<String, Buffer>, salt:EitherType<String, Buffer>, iterations:Int, keylen:Int, ?digest:String):Buffer;
/**
Generates cryptographically strong pseudo-random data.
If `callback` is specified, the function runs asynchronously, otherwise it will block and synchronously
return random bytes.
NOTE: Will throw error or invoke callback with error, if there is not enough accumulated entropy
to generate cryptographically strong data. In other words, `randomBytes` without callback will not
block even if all entropy sources are drained.
**/
@:overload(function(size:Int, callback:Error->Buffer->Void):Void {})
static function randomBytes(size:Int):Buffer;
/**
Decrypts `buffer` with `private_key`.
`private_key` can be an object or a string.
If `private_key` is a string, it is treated as the key with no passphrase
and will use `RSA_PKCS1_OAEP_PADDING`.
**/
@:overload(function(private_key:CryptoKeyOptions, buffer:Buffer):Buffer {})
static function privateDecrypt(private_key:String, buffer:Buffer):Buffer;
/**
Encrypts `buffer` with `private_key`.
`private_key` can be an object or a string.
If `private_key` is a string, it is treated as the key with no passphrase
and will use `RSA_PKCS1_PADDING`.
**/
@:overload(function(private_key:CryptoKeyOptions, buffer:Buffer):Buffer {})
static function privateEncrypt(private_key:String, buffer:Buffer):Buffer;
/**
Decrypts `buffer` with `public_key`.
`public_key` can be an object or a string.
If `public_key` is a string, it is treated as the key with no passphrase
and will use `RSA_PKCS1_PADDING`.
Because RSA public keys can be derived from private keys,
a private key may be passed instead of a public key.
**/
@:overload(function(public_key:CryptoKeyOptions, buffer:Buffer):Buffer {})
static function publicDecrypt(public_key:String, buffer:Buffer):Buffer;
/**
Encrypts `buffer` with `public_key`.
`public_key` can be an object or a string.
If `public_key` is a string, it is treated as the key with no passphrase
and will use `RSA_PKCS1_OAEP_PADDING`.
Because RSA public keys can be derived from private keys,
a private key may be passed instead of a public key.
**/
@:overload(function(public_key:CryptoKeyOptions, buffer:Buffer):Buffer {})
static function publicEncrypt(public_key:String, buffer:Buffer):Buffer;
}
/**
An options type for `privateEncrypt`, `privateDecrypt`, `publicEncrypt`, `publicDecrypt` methods of `Crypto`.
**/
typedef CryptoKeyOptions = {
/**
PEM encoded public key
**/
var key:String;
/**
Passphrase for the private key
**/
@:optional var passphrase:String;
/**
Padding value, one of the following:
* `Constants.RSA_NO_PADDING`
* `Constants.RSA_PKCS1_PADDING`
* `Constants.RSA_PKCS1_OAEP_PADDING`
**/
@:optional var padding:Int;
}

View File

@ -0,0 +1,43 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import js.node.dgram.Socket;
/**
Datagram sockets
**/
@:jsRequire("dgram")
extern class Dgram {
/**
Creates a datagram `Socket` of the specified types.
Takes an optional `callback` which is added as a listener for 'message' events.
Call `socket.bind` if you want to receive datagrams. `socket.bind` will bind to
the "all interfaces" address on a random port (it does the right thing for both `udp4` and `udp6` sockets).
You can then retrieve the address and port with `socket.address().address` and `socket.address().port`.
**/
@:overload(function(type:SocketType, ?callback:MessageListener):Socket {})
static function createSocket(options:SocketOptions, ?callback:MessageListener):Socket;
}

View File

@ -0,0 +1,431 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.extern.EitherType;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of possible Int `options` values for `Dns.lookup`.
**/
@:enum abstract DnsAddressFamily(Int) from Int to Int {
var IPv4 = 4;
var IPv6 = 6;
}
/**
Type of the `options` argument for `Dns.lookup`.
**/
typedef DnsLookupOptions = {
/**
The record family. If not provided, both IP v4 and v6 addresses are accepted.
**/
@:optional var family:DnsAddressFamily;
/**
If present, it should be one or more of the supported `getaddrinfo` flags.
If hints is not provided, then no flags are passed to `getaddrinfo`.
Multiple flags can be passed through hints by logically ORing their values.
**/
@:optional var hints:Int;
/**
When true, the callback returns all resolved addresses in an array, otherwise returns a single address.
Defaults to false.
**/
@:optional var all:Bool;
}
/**
Enumeration of possible `rrtype` value for `Dns.resolve`.
**/
@:enum abstract DnsRrtype(String) from String to String {
/**
IPV4 addresses, default
**/
var A = "A";
/**
IPV6 addresses
**/
var AAAA = "AAAA";
/**
mail exchange records
**/
var MX = "MX";
/**
text records
**/
var TXT = "TXT";
/**
SRV records
**/
var SRV = "SRV";
/**
used for reverse IP lookups
**/
var PTR = "PTR";
/**
name server records
**/
var NS = "NS";
/**
canonical name records
**/
var CNAME = "CNAME";
/**
start of authority record
**/
var SOA = "SOA";
}
/**
Types of address data returned by `resolve` functions.
**/
typedef DnsResolvedAddressMX = {priority:Int, exchange:String};
typedef DnsResolvedAddressSRV = {priority:Int, weight:Int, port:Int, name:String};
typedef DnsResolvedAddressSOA = {nsname:String, hostmaster:String, serial:Int, refresh:Int, retry:Int, expire:Int, minttl:Int};
typedef DnsResolvedAddress = EitherType<String, EitherType<DnsResolvedAddressMX, EitherType<DnsResolvedAddressSOA, DnsResolvedAddressSRV>>>;
/**
Error objects returned by dns lookups are of this type
**/
extern class DnsError extends Error {
/**
Values for error codes are listed in `Dns` class.
**/
var code(default, null):DnsErrorCode;
}
/**
Each DNS query can return one of the following error codes
**/
@:jsRequire("dns")
@:enum extern abstract DnsErrorCode(String) {
/**
DNS server returned answer with no data.
**/
var NODATA;
/**
DNS server claims query was misformatted.
**/
var FORMERR;
/**
DNS server returned general failure.
**/
var SERVFAIL;
/**
Domain name not found.
**/
var NOTFOUND;
/**
DNS server does not implement requested operation.
**/
var NOTIMP;
/**
DNS server refused query.
**/
var REFUSED;
/**
Misformatted DNS query.
**/
var BADQUERY;
/**
Misformatted domain name.
**/
var BADNAME;
/**
Unsupported address family.
**/
var BADFAMILY;
/**
Misformatted DNS reply.
**/
var BADRESP;
/**
Could not contact DNS servers.
**/
var CONNREFUSED;
/**
Timeout while contacting DNS servers.
**/
var TIMEOUT;
/**
End of file.
**/
var EOF;
/**
Error reading file.
**/
var FILE;
/**
Out of memory.
**/
var NOMEM;
/**
Channel is being destroyed.
**/
var DESTRUCTION;
/**
Misformatted string.
**/
var BADSTR;
/**
Illegal flags specified.
**/
var BADFLAGS;
/**
Given hostname is not numeric.
**/
var NONAME;
/**
Illegal hints flags specified.
**/
var BADHINTS;
/**
c-ares library initialization not yet performed.
**/
var NOTINITIALIZED;
/**
Error loading iphlpapi.dll.
**/
var LOADIPHLPAPI;
/**
Could not find GetNetworkParams function.
**/
var ADDRGETNETWORKPARAMS;
/**
DNS query cancelled.
**/
var CANCELLED;
}
typedef DnsLookupCallbackSingle = #if (haxe_ver >= 4) (err : DnsError, address : String, family : DnsAddressFamily) -> Void; #else DnsError->String->
DnsAddressFamily->Void #end
typedef DnsLookupCallbackAll = #if (haxe_ver >= 4) (err : DnsError, addresses : Array<DnsLookupCallbackAllEntry>) -> Void; #else DnsError->
Array<DnsLookupCallbackAllEntry>->Void; #end
typedef DnsLookupCallbackAllEntry = {address:String, family:DnsAddressFamily};
/**
This module contains functions that belong to two different categories:
1) Functions that use the underlying operating system facilities to perform name resolution,
and that do not necessarily do any network communication. This category contains only one function: `lookup`.
Developers looking to perform name resolution in the same way that other applications on the same operating
system behave should use `lookup`.
2) Functions that connect to an actual DNS server to perform name resolution,
and that always use the network to perform DNS queries. This category contains all functions in the dns module but `lookup`.
These functions do not use the same set of configuration files than what `lookup` uses. For instance,
they do not use the configuration from /etc/hosts. These functions should be used by developers who do not want
to use the underlying operating system's facilities for name resolution, and instead want to always perform DNS queries.
**/
@:jsRequire("dns")
extern class Dns {
/**
Resolves a `hostname` (e.g. 'google.com') into the first found A (IPv4) or AAAA (IPv6) record.
If `options` is not provided, then IP v4 and v6 addresses are both valid.
The `family` can be the integer 4 or 6. Defaults to null that indicates both Ip v4 and v6 address family.
The `callback` has arguments (err, address, family).
The `address` argument is a string representation of a IP v4 or v6 address.
The `family` argument is either the integer 4 or 6 and denotes the family
of address (not necessarily the value initially passed to lookup).
With the `all` option set, the arguments change to (err, addresses), with addresses being an array of objects
with the properties `address` and `family`.
Keep in mind that `err.code` will be set to 'ENOENT' not only when the hostname does not exist but
also when the lookup fails in other ways such as no available file descriptors.
`lookup` doesn't necessarily have anything to do with the DNS protocol. It's only an operating system facility
that can associate name with addresses, and vice versa.
**/
@:overload(function(hostname:String, options:EitherType<DnsAddressFamily, DnsLookupOptions>,
callback:EitherType<DnsLookupCallbackSingle, DnsLookupCallbackAll>):Void {})
static function lookup(hostname:String, callback:DnsLookupCallbackSingle):Void;
/**
A flag passed in the `hints` argument of `lookup` method.
Returned address types are determined by the types of addresses supported by the current system.
For example, IPv4 addresses are only returned if the current system has at least one IPv4 address configured.
Loopback addresses are not considered.
**/
static var ADDRCONFIG(default, null):Int;
/**
A flag passed in the `hints` argument of `lookup` method.
If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses.
Note that it is not supported on some operating systems (e.g FreeBSD 10.1).
**/
static var V4MAPPED(default, null):Int;
/**
Resolves the given `address` and `port` into a hostname and service using `getnameinfo`.
The `callback` has arguments (err, hostname, service).
The `hostname` and `service` arguments are strings (e.g. 'localhost' and 'http' respectively).
On error, `err` is an Error object, where `err.code` is the error code.
**/
static function lookupService(address:String, port:Int, callback:DnsError->String->String->Void):Void;
/**
Resolves a `hostname` (e.g. 'google.com') into an array of the record types specified by `rrtype`.
The `callback` has arguments (err, addresses).
The type of each item in `addresses` is determined by the record type,
and described in the documentation for the corresponding lookup methods below.
On error, `err` is an Error object, where `err.code` is the error code.
**/
@:overload(function(hostname:String, callback:DnsError->Array<DnsResolvedAddress>->Void):Void {})
static function resolve(hostname:String, rrtype:DnsRrtype, callback:DnsError->Array<DnsResolvedAddress>->Void):Void;
/**
The same as `resolve`, but only for IPv4 queries (A records).
`addresses` is an array of IPv4 addresses (e.g. ['74.125.79.104', '74.125.79.105', '74.125.79.106']).
**/
static function resolve4(hostname:String, callback:DnsError->Array<String>->Void):Void;
/**
The same as `resolve4` except for IPv6 queries (an AAAA query).
**/
static function resolve6(hostname:String, callback:DnsError->Array<String>->Void):Void;
/**
The same as `resolve`, but only for mail exchange queries (MX records).
`addresses` is an array of MX records, each with a priority
and an exchange attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).
**/
static function resolveMx(hostname:String, callback:DnsError->Array<DnsResolvedAddressMX>->Void):Void;
/**
The same as `resolve`, but only for text queries (TXT records).
`addresses` is a 2-d array of the text records available for hostname (e.g., [ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]).
Each sub-array contains TXT chunks of one record. Depending on the use case, the could be either joined together
or treated separately.
**/
static function resolveTxt(hostname:String, callback:DnsError->Array<Array<String>>->Void):Void;
/**
The same as `resolve`, but only for service records (SRV records).
`addresses` is an array of the SRV records available for `hostname`.
Properties of SRV records are priority, weight, port, and name
(e.g., [{'priority': 10, 'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).
**/
static function resolveSrv(hostname:String, callback:DnsError->Array<DnsResolvedAddressSRV>->Void):Void;
/**
Uses the DNS protocol to resolve pointer records (PTR records) for the `hostname`.
The addresses argument passed to the callback function will be an array of strings containing the reply records.
**/
static function resolvePtr(hostname:String, callback:DnsError->Array<String>->Void):Void;
/**
The same as `resolve`, but only for start of authority record queries (SOA record).
`addresses` is an object with the following structure:
{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
**/
static function resolveSoa(hostname:String, callback:DnsError->DnsResolvedAddressSOA->Void):Void;
/**
The same as `resolve`, but only for name server records (NS records).
`addresses` is an array of the name server records available for hostname (e.g., ['ns1.example.com', 'ns2.example.com']).
**/
static function resolveNs(hostname:String, callback:DnsError->Array<String>->Void):Void;
/**
The same as `resolve`, but only for canonical name records (CNAME records).
`addresses` is an array of the canonical name records available for hostname (e.g., ['bar.example.com']).
**/
static function resolveCname(hostname:String, callback:DnsError->Array<String>->Void):Void;
/**
Reverse resolves an `ip` address to an array of hostnames.
The `callback` has arguments (err, hostname).
**/
static function reverse(ip:String, callback:DnsError->Array<String>->Void):Void;
/**
Returns an array of IP addresses as strings that are currently being used for resolution.
**/
static function getServers():Array<String>;
/**
Given an array of IP addresses as strings, set them as the servers to use for resolving.
If you specify a port with the address it will be stripped, as the underlying library doesn't support that.
This will throw if you pass invalid input.
**/
static function setServers(servers:Array<String>):Void;
}

View File

@ -0,0 +1,41 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import js.node.domain.Domain as DomainObject;
/**
Domains provide a way to handle multiple different IO operations as a single group.
If any of the event emitters or callbacks registered to a domain emit an error event, or throw an error,
then the domain object will be notified, rather than losing the context of the error in the process.on('uncaughtException') handler,
or causing the program to exit immediately with an error code.
**/
@:deprecated
@:jsRequire("domain")
extern class Domain {
/**
Returns a new Domain object.
**/
static function create():DomainObject;
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.Constraints.Function;
import js.node.events.EventEmitter;
#if haxe4
import js.lib.Promise;
#else
import js.Promise;
#end
/**
Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture
in which certain kinds of objects (called "emitters") emit named events that cause `Function` objects
("listeners") to be called.
@see https://nodejs.org/api/events.html#events_events
*/
@:jsRequire("events")
extern class Events {
/**
Creates a `Promise` that is resolved when the `EventEmitter` emits the given
event or that is rejected when the `EventEmitter` emits `'error'`.
The `Promise` will resolve with an array of all the arguments emitted to the
given event.
@see https://nodejs.org/api/events.html#events_events_once_emitter_name
**/
static function once<T:Function>(emitter:IEventEmitter, name:Event<T>):Promise<Array<Dynamic>>;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,245 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.DynamicAccess;
import haxe.extern.EitherType;
import js.node.http.*;
import js.node.net.Socket;
import js.node.stream.Duplex;
import js.node.url.URL;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
The HTTP interfaces in Node are designed to support many features of the protocol
which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages.
The interface is careful to never buffer entire requests or responses--the user is able to stream data.
HTTP message headers are represented by an object like this:
{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive' }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, Node's HTTP API is very low-level.
It deals with stream handling and message parsing only. It parses a message into headers and body but
it does not parse the actual headers or the body.
**/
@:jsRequire("http")
extern class Http {
/**
A list of the HTTP methods that are supported by the parser.
**/
static var METHODS:Array<String>;
/**
A collection of all the standard HTTP response status codes, and the short description of each.
For example, `http.STATUS_CODES[404] === 'Not Found'`.
**/
static var STATUS_CODES(default, null):DynamicAccess<String>;
/**
Returns a new web server object.
The `requestListener` is a function which is automatically added to the `'request'` event.
**/
#if haxe4
@:overload(function(options:HttpCreateServerOptions, ?requestListener:(request:IncomingMessage, response:ServerResponse) -> Void):Server {})
static function createServer(?requestListener:(request:IncomingMessage, response:ServerResponse) -> Void):Server;
#else
@:overload(function(options:HttpCreateServerOptions, ?requestListener:IncomingMessage->ServerResponse->Void):Server {})
static function createServer(?requestListener:IncomingMessage->ServerResponse->Void):Server;
#end
/**
Since most requests are GET requests without bodies, Node.js provides this convenience method.
The only difference between this method and `request()` is that it sets the method to GET and calls `end()` automatically.
The callback must take care to consume the response data for reasons stated in `http.ClientRequest` section.
**/
@:overload(function(url:URL, ?options:HttpRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:String, ?options:HttpRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
static function get(options:HttpRequestOptions, ?callback:IncomingMessage->Void):ClientRequest;
/**
Global instance of Agent which is used as the default for all http client requests.
**/
static var globalAgent:Agent;
static var maxHeaderSize:Int;
/**
Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.
`url` can be a string or a URL object.
If `url` is a string, it is automatically parsed with `new URL()`.
If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence.
The optional `callback` parameter will be added as a one-time listener for the `'response'` event.
`request()` returns an instance of the `http.ClientRequest` class.
The `ClientRequest` instance is a writable stream.
If one needs to upload a file with a POST request, then write to the `ClientRequest` object.
**/
@:overload(function(url:URL, ?options:HttpRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:String, ?options:HttpRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
static function request(options:HttpRequestOptions, ?callback:IncomingMessage->Void):ClientRequest;
}
typedef HttpCreateServerOptions = {
/**
Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`.
Default: `js.node.http.IncomingMessage`.
**/
@:optional var IncomingMessage:Class<Dynamic>;
/**
Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`.
Default: `ServerResponse`.
**/
@:optional var ServerResponse:Class<Dynamic>;
}
/**
Type of the options object passed to `Http.request`.
**/
typedef HttpRequestOptions = {
/**
Controls Agent behavior.
Possible values:
- `undefined` (default): use http.globalAgent for this host and port.
- `Agent` object: explicitly use the passed in `Agent`.
- `false` : causes a new `Agent` with default values to be used.
**/
@:optional var agent:EitherType<Agent, Bool>;
/**
Basic authentication i.e. `'user:password'` to compute an Authorization header.
**/
@:optional var auth:String;
/**
A function that produces a socket/stream to use for the request when the `agent` option is not used.
This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function.
See [agent.createConnection()](https://nodejs.org/api/http.html#http_agent_createconnection_options_callback) for more details.
Any `Duplex` stream is a valid return value.
**/
#if haxe4
@:optional var createConnection:(options:SocketConnectOptionsTcp, ?callabck:(err:Error, stream:IDuplex) -> Void) -> IDuplex;
#else
@:optional var createConnection:SocketConnectOptionsTcp->?(Error->IDuplex->Void)->IDuplex;
#end
/**
Default port for the protocol.
Default: `agent.defaultPort` if an Agent is used, else `undefined`.
**/
@:optional var defaultPort:Int;
/**
IP address family to use when resolving `host` or `hostname`.
Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used.
**/
@:optional var family:js.node.Dns.DnsAddressFamily;
/**
An object containing request headers.
**/
@:optional var headers:DynamicAccess<EitherType<String, Array<String>>>;
/**
A domain name or IP address of the server to issue the request to.
Default: `'localhost'`.
**/
@:optional var host:String;
/**
Alias for `host`.
To support `url.parse()`, hostname will be used if both `host` and `hostname` are specified.
**/
@:optional var hostname:String;
/**
Local interface to bind for network connections.
**/
@:optional var localAddress:String;
/**
A string specifying the HTTP request method.
Default: `'GET'`.
**/
@:optional var method:Method;
/**
Request path. Should include query string if any. E.G. `'/index.html?page=12'`.
An exception is thrown when the request path contains illegal characters.
Currently, only spaces are rejected but that may change in the future.
Default: `'/'`.
**/
@:optional var path:String;
/**
Port of remote server.
Default: `defaultPort` if set, else `80`.
**/
@:optional var port:Int;
/**
Protocol to use.
Default: `'http:'`.
**/
@:optional var protocol:String;
/**
Specifies whether or not to automatically add the Host header.
Defaults to `true`.
**/
@:optional var setHost:Bool;
/**
Unix Domain Socket (cannot be used if one of host or port is specified, those specify a TCP Socket).
**/
@:optional var socketPath:String;
/**
A number specifying the socket timeout in milliseconds.
This will set the timeout before the socket is connected.
**/
@:optional var timeout:Int;
}

View File

@ -0,0 +1,94 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import js.node.http.ClientRequest;
import js.node.http.IncomingMessage;
import js.node.http.ServerResponse;
import js.node.https.*;
import js.node.url.URL;
/**
HTTPS is the HTTP protocol over TLS/SSL.
In Node.js this is implemented as a separate module.
**/
@:jsRequire("https")
extern class Https {
/**
Returns a new HTTPS web server object.
**/
#if haxe4
@:overload(function(options:HttpsCreateServerOptions, ?requestListener:(request:IncomingMessage, response:ServerResponse) -> Void):Server {})
static function createServer(?requestListener:(request:IncomingMessage, response:ServerResponse) -> Void):Server;
#else
@:overload(function(options:HttpsCreateServerOptions, ?requestListener:IncomingMessage->ServerResponse->Void):Server {})
static function createServer(?requestListener:IncomingMessage->ServerResponse->Void):Server;
#end
/**
Like `Http.get` but for HTTPS.
`options` can be an object, a string, or a `URL` object.
If `options` is a string, it is automatically parsed with `new URL()`.
If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
**/
@:overload(function(url:URL, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:URL, options:HttpsRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:String, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:String, options:HttpsRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
static function get(options:HttpsRequestOptions, ?callback:IncomingMessage->Void):ClientRequest;
/**
Global instance of `https.Agent` for all HTTPS client requests.
**/
static var globalAgent:Agent;
/**
Makes a request to a secure web server.
The following additional `options` from `tls.connect()` are also accepted:
`ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, `pfx`,
`rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`.
`options` can be an object, a string, or a `URL` object.
If `options` is a string, it is automatically parsed with `new URL()`.
If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
**/
@:overload(function(url:URL, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:URL, options:HttpsRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:String, ?callback:IncomingMessage->Void):ClientRequest {})
@:overload(function(url:String, options:HttpsRequestOptions, ?callback:IncomingMessage->Void):ClientRequest {})
static function request(options:HttpsRequestOptions, ?callback:IncomingMessage->Void):ClientRequest;
}
typedef HttpsCreateServerOptions = {
> js.node.Tls.TlsCreateServerOptions,
> js.node.tls.SecureContext.SecureContextOptions,
> js.node.Http.HttpCreateServerOptions,
}
typedef HttpsRequestOptions = {
> js.node.Http.HttpRequestOptions,
> js.node.Tls.TlsConnectOptions,
// TODO: clean those options up
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
#if haxe4
typedef Iterator<T> = js.lib.Iterator<T>;
typedef IteratorStep<T> = js.lib.Iterator.IteratorStep<T>;
#else
typedef Iterator<T> = {
function next():IteratorStep<T>;
}
typedef IteratorStep<T> = {
done:Bool,
?value:T
}
#end

View File

@ -0,0 +1,39 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
/**
Key/value access helper.
**/
abstract KeyValue<K, V>(Array<Any>) {
public var key(get, never):K;
public var value(get, never):V;
inline function get_key():K {
return this[0];
}
inline function get_value():V {
return this[1];
}
}

View File

@ -0,0 +1,120 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import js.node.url.URL;
/**
In each module, the `module` free variable is a reference to the object representing the current module.
For convenience, `module.exports` is also accessible via the `exports` module-global.
`module` is not actually a global but rather local to each module.
@see https://nodejs.org/api/modules.html#modules_the_module_object
**/
@:jsRequire("module")
extern class Module {
/**
The module objects required for the first time by this one.
@see https://nodejs.org/api/modules.html#modules_module_children
**/
var children(default, null):Array<Module>;
/**
The `module.exports` object is created by the Module system.
Sometimes this is not acceptable; many want their module to be an instance of some class.
To do this, assign the desired export object to `module.exports`.
Assigning the desired object to `exports` will simply rebind the local `exports` variable, which is probably not
what is desired.
@see https://nodejs.org/api/modules.html#modules_module_exports
**/
var exports:Dynamic;
/**
The fully resolved filename of the module.
@see https://nodejs.org/api/modules.html#modules_module_filename
**/
var filename(default, null):String;
/**
The identifier for the module.
Typically this is the fully resolved filename.
@see https://nodejs.org/api/modules.html#modules_module_id
**/
var id(default, null):String;
/**
Whether or not the module is done loading, or is in the process of loading.
@see https://nodejs.org/api/modules.html#modules_module_loaded
**/
var loaded(default, null):Bool;
/**
The module that first required this one.
@see https://nodejs.org/api/modules.html#modules_module_parent
**/
var parent(default, null):Module;
/**
The search paths for the module.
@see https://nodejs.org/api/modules.html#modules_module_paths
**/
var paths(default, null):Array<String>;
/**
The `module.require()` method provides a way to load a module as if `require()` was called from the original
module.
@see https://nodejs.org/api/modules.html#modules_module_require_id
**/
function require(id:String):Dynamic;
/**
A list of the names of all modules provided by Node.js.
Can be used to verify if a module is maintained by a third party or not.
@see https://nodejs.org/api/modules.html#modules_module_builtinmodules
**/
static var builtinModules(default, null):Array<String>;
/**
@see https://nodejs.org/api/modules.html#modules_module_createrequire_filename
**/
@:overload(function(filename:URL):String->Dynamic {})
static function createRequire(filename:String):String->Dynamic;
/**
The `module.syncBuiltinESMExports()` method updates all the live bindings for builtin ES Modules to match the
properties of the CommonJS exports.
It does not add or remove exported names from the ES Modules.
@see https://nodejs.org/api/modules.html#modules_module_syncbuiltinesmexports
**/
static function syncBuiltinESMExports():Void;
}

View File

@ -0,0 +1,125 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.extern.EitherType;
import js.node.net.Server;
import js.node.net.Socket;
typedef NetCreateServerOptions = {
> SocketOptionsBase,
/**
If true, then the socket associated with each incoming connection will be paused,
and no data will be read from its handle.
This allows connections to be passed between processes without any data being read by the original process.
To begin reading data from a paused socket, call `resume`.
Default: false
**/
@:optional var pauseOnConnect:Bool;
}
/**
Options for the `Net.connect` method (TCP version).
**/
typedef NetConnectOptionsTcp = {
> SocketOptions,
> SocketConnectOptionsTcp,
}
/**
Options for the `Net.connect` method (Local domain socket version).
**/
typedef NetConnectOptionsUnix = {
> SocketOptions,
> SocketConnectOptionsUnix,
}
/**
Enumeration of possible values for `Net.isIP` return.
**/
@:enum abstract NetIsIPResult(Int) to Int {
var Invalid = 0;
var IPv4 = 4;
var IPv6 = 6;
}
/**
The net module provides you with an asynchronous network wrapper.
It contains methods for creating both servers and clients (called streams).
**/
@:jsRequire("net")
extern class Net {
/**
Creates a new TCP server.
The `connectionListener` argument is automatically set as a listener for the 'connection' event.
**/
@:overload(function(options:NetCreateServerOptions, ?connectionListener:Socket->Void):Server {})
static function createServer(?connectionListener:Socket->Void):Server;
/**
A factory function, which returns a new `Socket` and automatically connects with the supplied `options`.
The `options` are passed to both the `Socket` constructor and the `socket.connect` method.
The `connectListener` parameter will be added as a listener for the `connect` event once.
If `port` is provided, creates a TCP connection to `port` on `host`.
If `host` is omitted, 'localhost' will be assumed.
If `path` is provided, creates unix socket connection to `path`.
Otherwise `options` argument should be provided.
**/
@:overload(function(path:String, ?connectListener:Void->Void):Socket {})
@:overload(function(port:Int, ?connectListener:Void->Void):Socket {})
@:overload(function(port:Int, host:String, ?connectListener:Void->Void):Socket {})
static function connect(options:EitherType<NetConnectOptionsTcp, NetConnectOptionsUnix>, ?connectListener:Void->Void):Socket;
/**
Same as `connect`.
**/
@:overload(function(path:String, ?connectListener:Void->Void):Socket {})
@:overload(function(port:Int, ?connectListener:Void->Void):Socket {})
@:overload(function(port:Int, host:String, ?connectListener:Void->Void):Socket {})
static function createConnection(options:EitherType<NetConnectOptionsTcp, NetConnectOptionsUnix>, ?connectListener:Void->Void):Socket;
/**
Tests if input is an IP address.
Returns 0 for invalid strings, returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
**/
static function isIP(input:String):NetIsIPResult;
/**
Returns true if input is a version 4 IP address, otherwise returns false.
**/
static function isIPv4(input:String):Bool;
/**
Returns true if input is a version 6 IP address, otherwise returns false.
**/
static function isIPv6(input:String):Bool;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,196 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
/**
The `path` module provides utilities for working with file and directory paths.
@see https://nodejs.org/api/path.html#path_path
**/
@:jsRequire("path")
extern class Path {
/**
The `path.basename()` methods returns the last portion of a `path`, similar to the Unix `basename` command. Trailing directory separators are ignored, see path.sep.
@see https://nodejs.org/api/path.html#path_path_basename_path_ext
**/
static function basename(path:String, ?ext:String):String;
/**
Platform-specific path delimiter:
`;` for Windows
`:` for POSIX
@see https://nodejs.org/api/path.html#path_path_delimiter
**/
static var delimiter(default, null):String;
/**
The `path.dirname()` method returns the directory name of a `path`, similar to the Unix `dirname` command. Trailing directory separators are ignored, see path.sep.
@see https://nodejs.org/api/path.html#path_path_dirname_path
**/
static function dirname(path:String):String;
/**
The `path.extname()` method returns the extension of the `path`, from the last occurrence of the `.` (period) character to end of string in the last portion of the `path`.
If there is no `.` in the last portion of the `path`, or if there are no `.` characters other than the first character of the basename of `path` (see `path.basename()`) ,
an empty string is returned.
@see https://nodejs.org/api/path.html#path_path_extname_path
**/
static function extname(path:String):String;
/**
The path.format() method returns a path string from an object. This is the opposite of path.parse().
@see https://nodejs.org/api/path.html#path_path_format_pathobject
**/
static function format(pathObject:PathObject):String;
/**
The `path.isAbsolute()` method determines if `path` is an absolute path.
@see https://nodejs.org/api/path.html#path_path_isabsolute_path
**/
static function isAbsolute(path:String):Bool;
/**
The `path.join()` method joins all given `path` segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.
@see https://nodejs.org/api/path.html#path_path_join_paths
**/
static function join(paths:haxe.extern.Rest<String>):String;
/**
The `path.normalize()` method normalizes the given `path`, resolving `'..'` and `'.'` segments.
@see https://nodejs.org/api/path.html#path_path_normalize_path
**/
static function normalize(path:String):String;
/**
The `path.parse()` method returns an object whose properties represent significant elements of the `path`. Trailing directory separators are ignored, see path.sep.
@see https://nodejs.org/api/path.html#path_path_parse_path
**/
static function parse(path:String):PathObject;
/**
The `path.posix` property provides access to POSIX specific implementations of the `path` methods.
@see https://nodejs.org/api/path.html#path_path_posix
**/
static var posix(default, null):PathModule;
/**
The `path.relative()` method returns the relative path from `from` to `to` based on the current working directory.
If `from` and `to` each resolve to the same path (after calling path.resolve() on each), a zero-length string is returned.
@see https://nodejs.org/api/path.html#path_path_relative_from_to
**/
static function relative(from:String, to:String):String;
/**
The `path.resolve()` method resolves a sequence of paths or path segments into an absolute path.
@see https://nodejs.org/api/path.html#path_path_resolve_paths
**/
static function resolve(paths:haxe.extern.Rest<String>):String;
/**
Provides the platform-specific path segment separator:
`\` on Windows
`/` on POSIX
@see https://nodejs.org/api/path.html#path_path_sep
**/
static var sep(default, null):String;
/**
On Windows systems only, returns an equivalent namespace-prefixed path for the given `path`. If `path` is not a string, `path` will be returned without modifications.
@see https://nodejs.org/api/path.html#path_path_tonamespacedpath_path
**/
static function toNamespacedPath(path:String):String;
/**
The path.win32 property provides access to Windows-specific implementations of the path methods.
@see https://nodejs.org/api/path.html#path_path_win32
**/
static var win32(default, null):PathModule;
}
/**
Path object returned from `Path.parse` and taken by `Path.format`.
@see https://nodejs.org/api/path.html#path_path_format_pathobject
**/
typedef PathObject = {
/**
E.g. "C:\path\dir" for "C:\path\dir\index.html"
**/
var dir:String;
/**
E.g. "C:\" for "C:\path\dir\index.html"
**/
var root:String;
/**
E.g. "index.html" for "C:\path\dir\index.html"
**/
var base:String;
/**
E.g. "index" for "C:\path\dir\index.html"
**/
var name:String;
/**
E.g. ".html" for "C:\path\dir\index.html"
**/
var ext:String;
}
// IMPORTANT: this structure should contain a set of fields
// matching statics of the `Path` class and is used as a type
// for `posix` and `win32` fields of `Path` class.
// We should probably generate this from a macro, but let's keep
// things simple for now.
private typedef PathModule = {
function normalize(path:String):String;
function join(paths:haxe.extern.Rest<String>):String;
function resolve(paths:haxe.extern.Rest<String>):String;
function isAbsolute(path:String):Bool;
function relative(from:String, to:String):String;
function dirname(path:String):String;
function basename(path:String, ?ext:String):String;
function extname(path:String):String;
var sep(default, null):String;
var delimiter(default, null):String;
function parse(pathString:String):PathObject;
function format(pathObject:PathObject):String;
}

View File

@ -0,0 +1,351 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.DynamicAccess;
import haxe.extern.EitherType;
import haxe.extern.Rest;
import js.node.child_process.ChildProcess.ChildProcessSendOptions;
import js.node.events.EventEmitter;
import js.node.stream.Readable;
import js.node.stream.Writable;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by the Process class.
**/
@:enum abstract ProcessEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when the process is about to exit.
There is no way to prevent the exiting of the event loop at this point,
and once all exit listeners have finished running the process will exit.
Therefore you must only perform synchronous operations in this handler.
This is a good hook to perform checks on the module's state (like for unit tests).
The callback takes one argument, the code the process is exiting with.
**/
var Exit:ProcessEvent<Int->Void> = "exit";
/**
Emitted when node empties it's event loop and has nothing else to schedule.
Normally, node exits when there is no work scheduled, but a listener for `beforeExit`
can make asynchronous calls, and cause node to continue.
`beforeExit` is not emitted for conditions causing explicit termination, such as `process.exit()`
or uncaught exceptions, and should not be used as an alternative to the `exit` event
unless the intention is to schedule more work.
**/
var BeforeExit:ProcessEvent<Int->Void> = "beforeExit";
/**
Emitted when an exception bubbles all the way back to the event loop.
If a listener is added for this exception, the default action (which is to print a stack trace and exit)
will not occur.
**/
var UncaughtException:ProcessEvent<Error->Void> = "uncaughtException";
}
extern class Process extends EventEmitter<Process> {
/**
A Writable Stream to stdout.
`stderr` and `stdout` are unlike other streams in Node in that writes to them are usually blocking.
**/
var stdout:IWritable;
/**
A writable stream to stderr.
`stderr` and `stdout` are unlike other streams in Node in that writes to them are usually blocking.
**/
var stderr:IWritable;
/**
A Readable Stream for stdin.
**/
var stdin:IReadable;
/**
An array containing the command line arguments.
The first element will be `node`, the second element will be the name of the JavaScript file.
The next elements will be any additional command line arguments.
E.g:
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
**/
var argv:Array<String>;
/**
This is the absolute pathname of the executable that started the process.
**/
var execPath:String;
/**
This is the set of node-specific command line options from the executable that started the process.
These options do not show up in `argv`, and do not include the node executable, the name of the script,
or any options following the script name.
These options are useful in order to spawn child processes with the same execution environment as the parent.
**/
var execArgv:Array<String>;
/**
This causes node to emit an abort. This will cause node to exit and generate a core file.
**/
function abort():Void;
/**
Changes the current working directory of the process or throws an exception if that fails.
**/
function chdir(directory:String):Void;
/**
Returns the current working directory of the process.
**/
function cwd():String;
/**
An object containing the user environment. See environ(7).
**/
var env:DynamicAccess<String>;
/**
Ends the process with the specified `code`. If the `code` is omitted, exit uses either the
'success' code `0` or the value of `process.exitCode` if specified.
**/
function exit(?code:Int):Void;
/**
A number which will be the process exit code, when the process either exits gracefully,
or is exited via `process.exit()` without specifying a code.
Specifying a code to `process.exit(code)` will override any previous setting of `process.exitCode`.
**/
var exitCode:Null<Int>;
/**
Gets the group identity of the process. See getgid(2).
Note: this function is only available on POSIX platforms (i.e. not Windows)
**/
function getgid():Int;
/**
Sets the group identity of the process. See setgid(2).
This accepts either a numerical ID or a groupname string.
If a groupname is specified, this method blocks while resolving it to a numerical ID.
Note: this function is only available on POSIX platforms (i.e. not Windows)
**/
@:overload(function(id:String):Void {})
function setgid(id:Int):Void;
/**
Gets the user identity of the process. See getuid(2).
Note: this function is only available on POSIX platforms (i.e. not Windows)
**/
function getuid():Int;
/**
Sets the user identity of the process. See setuid(2).
This accepts either a numerical ID or a username string.
If a username is specified, this method blocks while resolving it to a numerical ID.
Note: this function is only available on POSIX platforms (i.e. not Windows)
**/
@:overload(function(id:String):Void {})
function setuid(id:Int):Void;
/**
Returns an array with the supplementary group IDs.
POSIX leaves it unspecified if the effective group ID is included but node.js ensures it always is.
Note: this function is only available on POSIX platforms (i.e. not Windows)
**/
function getgroups():Array<Int>;
/**
Sets the supplementary group IDs.
This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability.
Note: this function is only available on POSIX platforms (i.e. not Windows)
The list can contain group IDs, group names or both.
**/
function setgroups(groups:Array<EitherType<String, Int>>):Void;
/**
Reads /etc/group and initializes the group access list, using all groups of which the user is a member.
This is a privileged operation, meaning you need to be root or have the CAP_SETGID capability.
Note: this function is only available on POSIX platforms (i.e. not Windows)
**/
function initgroups(user:EitherType<String, Int>, extra_group:EitherType<String, Int>):Void;
/**
A compiled-in property that exposes NODE_VERSION.
**/
var version(default, null):String;
/**
A property exposing version strings of node and its dependencies.
**/
var versions:DynamicAccess<String>;
/**
An Object containing the JavaScript representation of the configure options that were used to compile the current node executable.
This is the same as the "config.gypi" file that was produced when running the ./configure script.
**/
var config:Dynamic<Dynamic>;
/**
Send a signal to a process.
`pid` is the process id and `signal` is the string describing the signal to send. Signal names are strings like 'SIGINT' or 'SIGHUP'.
If omitted, the `signal` will be 'SIGTERM'. See Signal Events and kill(2) for more information.
Will throw an error if target does not exist, and as a special case,
a signal of 0 can be used to test for the existence of a process.
Note that just because the name of this function is `kill`, it is really just a signal sender, like the kill system call.
The signal sent may do something other than kill the target process.
**/
function kill(pid:Int, ?signal:String):Void;
/**
The PID of the process.
**/
var pid(default, null):Int;
/**
Getter/setter to set what is displayed in 'ps'.
When used as a setter, the maximum length is platform-specific and probably short.
On Linux and OS X, it's limited to the size of the binary name plus the length of the
command line arguments because it overwrites the argv memory.
**/
var title:String;
/**
What processor architecture you're running on: 'arm', 'ia32', or 'x64'.
**/
var arch:String;
/**
What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
**/
var platform:String;
/**
Returns an object describing the memory usage of the Node process measured in bytes.
**/
function memoryUsage():MemoryUsage;
/**
On the next loop around the event loop call this callback.
This is not a simple alias to setTimeout(fn, 0), it's much more efficient.
It typically runs before any other I/O events fire, but there are some exceptions.
This is important in developing APIs where you want to give the user the chance to
assign event handlers after an object has been constructed, but before any I/O has occurred.
**/
function nextTick(callback:Void->Void, args:Rest<Dynamic>):Void;
/**
Sets or reads the process's file mode creation mask.
Child processes inherit the mask from the parent process.
Returns the old mask if mask argument is given, otherwise returns the current mask.
**/
function umask(?mask:Int):Int;
/**
Number of seconds Node has been running.
**/
function uptime():Float;
/**
Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.
It is relative to an arbitrary time in the past.
It is not related to the time of day and therefore not subject to clock drift.
The primary use is for measuring performance between intervals.
You may pass in the result of a previous call to `hrtime` to get a diff reading,
useful for benchmarks and measuring intervals
**/
@:overload(function(prev:Array<Float>):Array<Float> {})
function hrtime():Array<Float>;
/**
Alternate way to retrieve require.main. The difference is that if the main module changes at runtime,
require.main might still refer to the original main module in modules that were required
before the change occurred. Generally it's safe to assume that the two refer to the same module.
As with require.main, it will be undefined if there was no entry script.
**/
var mainModule(default, null):Module;
/**
Send a message to the parent process.
Only available for child processes. See `ChildProcess.send`.
**/
@:overload(function(message:Dynamic, sendHandle:Dynamic, options:ChildProcessSendOptions, ?callback:Error->Void):Bool {})
@:overload(function(message:Dynamic, sendHandle:Dynamic, ?callback:Error->Void):Bool {})
function send(message:Dynamic, ?callback:Error->Void):Bool;
/**
Close the IPC channel to parent process.
Only available for child processes. See `ChildProcess.disconnect`.
**/
function disconnect():Void;
/**
Disable run-time deprecation warnings.
See `Util.deprecate`.
**/
var noDeprecation:Bool;
/**
Enable logging of deprecation warnings.
See `Util.deprecate`.
**/
var traceDeprecation:Bool;
/**
Throw on deprecated API usage.
See `Util.deprecate`.
**/
var throwDeprecation:Bool;
}
typedef MemoryUsage = {
rss:Float,
heapTotal:Float,
heapUsed:Float
}

View File

@ -0,0 +1,75 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
@:deprecated("In a future major version of Node.js punycode module will be removed")
@:jsRequire("punycode")
extern class Punycode {
/**
Converts a Punycode string of ASCII code points to a string of Unicode code points.
**/
static function decode(string:String):String;
/**
Converts a string of Unicode code points to a Punycode string of ASCII code points.
**/
static function encode(string:String):String;
/**
Converts a Punycode string representing a domain name to Unicode.
Only the Punycoded parts of the domain name will be converted, i.e. it doesn't matter
if you call it on a string that has already been converted to Unicode.
**/
static function toUnicode(domain:String):String;
/**
Converts a Unicode string representing a domain name to Punycode.
Only the non-ASCII parts of the domain name will be converted, i.e. it doesn't matter
if you call it with a domain that's already in ASCII.
**/
static function toASCII(domain:String):String;
static var ucs2(default, null):PunycodeUcs2;
/**
The current Punycode.js version number.
**/
static var version(default, null):String;
}
@:deprecated
extern class PunycodeUcs2 {
/**
Creates an array containing the decimal code points of each Unicode character in the string.
While JavaScript uses UCS-2 internally, this function will convert a pair of surrogate halves (each of which
UCS-2 exposes as separate characters) into a single code point, matching UTF-16.
**/
function decode(string:String):Array<Int>;
/**
Creates a string based on an array of decimal code points.
**/
function encode(codePoints:Array<Int>):String;
}

View File

@ -0,0 +1,119 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.DynamicAccess;
import haxe.extern.EitherType;
/**
The `querystring` module provides utilities for parsing and formatting URL query strings.
@see https://nodejs.org/api/querystring.html#querystring_query_string
**/
@:jsRequire("querystring")
extern class Querystring {
/**
The `querystring.decode()` function is an alias for `querystring.parse()`.
@see https://nodejs.org/api/querystring.html#querystring_querystring_decode
**/
@:overload(function(str:String):QuerystringParseResult {})
static function decode(str:String, ?sep:String, ?eq:String, ?options:QuerystringParseOptions):QuerystringParseResult;
/**
The `querystring.encode()` function is an alias for `querystring.stringify()`.
@see https://nodejs.org/api/querystring.html#querystring_querystring_decode
**/
@:overload(function(obj:{}):String {})
static function encode(obj:{}, ?sep:String, ?eq:String, ?options:QuerystringStringifyOptions):String;
/**
The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL query strings.
@see https://nodejs.org/api/querystring.html#querystring_querystring_escape_str
**/
static dynamic function escape(str:String):String;
/**
The `querystring.parse()` method parses a URL query string (`str`) into a collection of key and value pairs.
@see https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
**/
@:overload(function(str:String):QuerystringParseResult {})
static function parse(str:String, ?sep:String, ?eq:String, ?options:QuerystringParseOptions):QuerystringParseResult;
/**
The `querystring.stringify()` method produces a URL query string from a given `obj` by iterating through the object's "own properties".
@see https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options
**/
@:overload(function(obj:{}):String {})
static function stringify(obj:{}, ?sep:String, ?eq:String, ?options:QuerystringStringifyOptions):String;
/**
The `querystring.unescape()` method performs decoding of URL percent-encoded characters on the given `str`.
@see https://nodejs.org/api/querystring.html#querystring_querystring_unescape_str
**/
static dynamic function unescape(str:String):Dynamic;
}
/**
Options used for `Querystring.parse` method.
@see https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
**/
typedef QuerystringParseOptions = {
/**
The function to use when decoding percent-encoded characters in the query string. Default: `querystring.unescape()`.
**/
@:optional var decodeURIComponent:String->String;
/**
Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. Default: `1000`.
**/
@:optional var maxKeys:Int;
}
/**
The result type of `Querystring.parse`. Is a collection of either strings or array of strings.
The object returned by the `querystring.parse()` method does not prototypically inherit from the JavaScript `Object`.
This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others are not defined and will not work.
@see https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
**/
typedef QuerystringParseResult = DynamicAccess<EitherType<String, Array<String>>>;
/**
Options for `Querystring.stringify` method.
@see https://nodejs.org/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options
**/
typedef QuerystringStringifyOptions = {
/**
The function to use when converting URL-unsafe characters to percent-encoding in the query string. Default: `querystring.escape()`.
**/
@:optional var encodeURIComponent:String->String;
}

View File

@ -0,0 +1,188 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.extern.EitherType;
import js.node.readline.*;
import js.node.stream.Readable.IReadable;
import js.node.stream.Writable.IWritable;
/**
The readline module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) one
line at a time.
@see https://nodejs.org/api/readline.html#readline_readline
**/
@:jsRequire("readline")
extern class Readline {
/**
The `readline.clearLine()` method Clears current line of given `TTY` stream
in a specified direction identified by `dir`.
@see https://nodejs.org/api/readline.html#readline_readline_clearline_stream_dir_callback
**/
static function clearLine(stream:IWritable, dir:ClearLineDirection, ?callback:Void->Void):Bool;
/**
The `readline.clearScreenDown()` method clears the given `TTY` stream
from the current position of the cursor down.
@see https://nodejs.org/api/readline.html#readline_readline_clearscreendown_stream_callback
**/
static function clearScreenDown(stream:IWritable, ?callback:Void->Void):Bool;
/**
The `readline.createInterface()` method creates a new `readline.Interface` instance.
@see https://nodejs.org/api/readline.html#readline_readline_createinterface_options
**/
@:overload(function(input:IReadable, ?output:IWritable, ?completer:ReadlineCompleterCallback, ?terminal:Bool):Interface {})
static function createInterface(options:ReadlineOptions):Interface;
/**
The `readline.cursorTo()` method moves cursor to the specified position in a given `TTY` `stream`.
@see https://nodejs.org/api/readline.html#readline_readline_cursorto_stream_x_y_callback
**/
static function cursorTo(stream:IWritable, x:Int, ?y:Int, ?callback:Void->Void):Bool;
/**
The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'`
events corresponding to received input.
@see https://nodejs.org/api/readline.html#readline_readline_emitkeypressevents_stream_interface
**/
static function emitKeypressEvents(stream:IReadable, ?iface:Interface):Void;
/**
The `readline.moveCursor()` method moves the cursor relative to its current position in a given `TTY` `stream`.
@see https://nodejs.org/api/readline.html#readline_readline_movecursor_stream_dx_dy_callback
**/
static function moveCursor(stream:IWritable, dx:Int, dy:Int, ?callback:Void->Void):Bool;
}
/**
Options object used by `Readline.createInterface`.
@see https://nodejs.org/api/readline.html#readline_readline_createinterface_options
**/
typedef ReadlineOptions = {
/**
The `Readable` stream to listen to.
**/
var input:IReadable;
/**
The `Writable` stream to write readline data to.
**/
@:optional var output:IWritable;
/**
An optional function used for Tab autocompletion.
@see https://nodejs.org/api/readline.html#readline_use_of_the_completer_function
**/
@:optional var completer:ReadlineCompleterCallback;
/**
`true` if the `input` and `output` streams should be treated like a TTY, and have ANSI/VT100 escape codes
written to it.
Default: checking `isTTY` on the `output` stream upon instantiation.
**/
@:optional var terminal:Bool;
/**
Maximum number of history lines retained.
To disable the history set this value to `0`.
This option makes sense only if `terminal` is set to `true` by the user or by an internal `output` check,
otherwise the history caching mechanism is not initialized at all.
Default: `30`.
**/
@:optional var historySize:Int;
/**
The prompt string to use.
Default: `'> '`.
**/
@:optional var prompt:String;
/**
If the delay between `\r` and `\n` exceeds `crlfDelay` milliseconds, both `\r` and `\n` will be treated as
separate end-of-line input.
`crlfDelay` will be coerced to a number no less than `100`.
It can be set to `Infinity`, in which case `\r` followed by `\n` will always be considered a single newline
(which may be reasonable for reading files with `\r\n` line delimiter).
Default: `100`.
**/
@:optional var crlfDelay:Int;
/**
If `true`, when a new input line added to the history list duplicates an older one, this removes the older line
from the list.
Default: `false`.
**/
@:optional var removeHistoryDuplicates:Bool;
/**
The duration `readline` will wait for a character (when reading an ambiguous key sequence in milliseconds one
that can both form a complete key sequence using the input read so far and can take additional input to complete
a longer key sequence).
Default: `500`.
**/
@:optional var escapeCodeTimeout:Int;
}
#if haxe4
typedef ReadlineCompleterCallback = (line:String) -> Array<EitherType<Array<String>, String>>;
#else
typedef ReadlineCompleterCallback = String->Array<EitherType<Array<String>, String>>;
#end
/**
Enumeration of possible directions for `Readline.clearLine`.
@see https://nodejs.org/api/readline.html#readline_readline_clearline_stream_dir_callback
**/
@:enum abstract ClearLineDirection(Int) from Int to Int {
/**
to the left from cursor.
**/
var Left = -1;
/**
to the right from cursor.
**/
var Right = 1;
/**
the entire line.
**/
var EntireLine = 0;
}

View File

@ -0,0 +1,176 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.DynamicAccess;
import js.node.repl.REPLServer;
import js.node.stream.Readable.IReadable;
import js.node.stream.Writable.IWritable;
#if haxe4
import js.lib.Error;
import js.lib.Symbol;
#else
import js.Error;
#end
/**
The `repl` module provides a Read-Eval-Print-Loop (REPL) implementation that is available both as a standalone
program or includible in other applications.
@see https://nodejs.org/api/repl.html#repl_repl
**/
@:jsRequire("repl")
extern class Repl {
/**
The `repl.start()` method creates and starts a `repl.REPLServer` instance.
@see https://nodejs.org/api/repl.html#repl_repl_start_options
**/
@:overload(function(prompt:String):REPLServer {})
static function start(options:ReplOptions):REPLServer;
/**
Evaluates expressions in sloppy mode.
@see https://nodejs.org/api/repl.html#repl_repl_start_options
**/
#if haxe4
static final REPL_MODE_SLOPPY:Symbol;
#else
static var REPL_MODE_SLOPPY(default, never):Dynamic;
#end
/**
Evaluates expressions in strict mode.
This is equivalent to prefacing every repl statement with `'use strict'`.
@see https://nodejs.org/api/repl.html#repl_repl_start_options
**/
#if haxe4
static final REPL_MODE_STRICT:Symbol;
#else
static var REPL_MODE_STRICT(default, never):Dynamic;
#end
}
/**
Options object used by `Repl.start`.
@see https://nodejs.org/api/repl.html#repl_repl_start_options
**/
typedef ReplOptions = {
/**
The input prompt to display.
Default: `'> '` (with a trailing space).
**/
@:optional var prompt:String;
/**
The `Readable` stream from which REPL input will be read.
Default: `process.stdin`.
**/
@:optional var input:IReadable;
/**
The `Writable` stream to which REPL output will be written.
Default: `process.stdout`.
**/
@:optional var output:IWritable;
/**
If `true`, specifies that the `output` should be treated as a TTY terminal.
Default: checking the value of the `isTTY` property on the `output` stream upon instantiation.
**/
@:optional var terminal:Bool;
/**
The function to be used when evaluating each given line of input.
Default: an async wrapper for the JavaScript `eval()` function.
**/
#if haxe4
@:optional var eval:(code:String, context:DynamicAccess<Dynamic>, file:String, cb:(error:Null<Error>, ?result:Dynamic) -> Void) -> Void;
#else
@:optional var eval:String->DynamicAccess<Dynamic>->String->(Null<Error>->?Dynamic->Void)->Void;
#end
/**
If `true`, specifies that the default `writer` function should include ANSI color styling to REPL output.
If a custom `writer` function is provided then this has no effect.
Default: checking color support on the `output` stream if the REPL instance's `terminal` value is `true`.
**/
@:optional var useColors:Bool;
/**
If `true`, specifies that the default evaluation function will use the JavaScript `global` as the context as
opposed to creating a new separate context for the REPL instance.
The node CLI REPL sets this value to `true`.
Default: `false`.
**/
@:optional var useGlobal:Bool;
/**
If `true`, specifies that the default writer will not output the return value of a command if it evaluates to
`undefined`.
Default: `false`.
**/
@:optional var ignoreUndefined:Bool;
/**
The function to invoke to format the output of each command before writing to `output`.
Default: `util.inspect()`.
**/
@:optional var writer:Dynamic->Void;
/**
An optional function used for custom Tab auto completion.
**/
@:optional var completer:Readline.ReadlineCompleterCallback;
/**
A flag that specifies whether the default evaluator executes all JavaScript commands in strict mode or default
(sloppy) mode.
Acceptable values are `repl.REPL_MODE_SLOPPY` or `repl.REPL_MODE_STRICT`.
**/
#if haxe4
@:optional var replMode:Symbol;
#else
@:optional var replMode:Dynamic;
#end
/**
Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is pressed.
This cannot be used together with a custom `eval` function.
Default: `false`.
**/
@:optional var breakEvalOnSigint:Bool;
}

View File

@ -0,0 +1,108 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.DynamicAccess;
@:native("require")
extern class Require {
/**
Used to import modules, `JSON`, and local files.
Modules can be imported from `node_modules`.
Local modules and JSON files can be imported using a relative path (e.g. `./`, .`/foo`, `./bar/baz`, `../foo`)
that will be resolved against the directory named by `__dirname` (if defined) or the current working directory.
@see https://nodejs.org/api/modules.html#modules_module_id
**/
@:selfCall
static function require(id:String):Dynamic;
/**
Modules are cached in this object when they are required.
By deleting a key value from this object, the next `require` will reload the module.
This does not apply to native addons, for which reloading will result in an error.
@see https://nodejs.org/api/modules.html#modules_require_cache
**/
static var cache(default, null):DynamicAccess<Module>;
/**
Instruct require on how to handle certain file extensions.
Deprecated: In the past, this list has been used to load non-JavaScript modules into Node by compiling them on-demand.
However, in practice, there are much better ways to do this, such as loading modules via some other Node program,
or compiling them to JavaScript ahead of time.
Since the `Module` system is locked, this feature will probably never go away. However, it may have subtle bugs
and complexities that are best left untouched.
**/
@:deprecated
static var extensions(default, null):DynamicAccess<Dynamic>;
/**
The `Module` object representing the entry script loaded when the Node.js process launched.
See ["Accessing the main module"](https://nodejs.org/api/modules.html#modules_accessing_the_main_module).
@see https://nodejs.org/api/modules.html#modules_require_main
**/
static var main(default, null):Module;
/**
Use the internal `require()` machinery to look up the location of a module,
but rather than loading the module, just return the resolved filename.
@see https://nodejs.org/api/modules.html#modules_require_resolve_request_options
**/
static function resolve(module:String, ?options:RequireResolveOptions):String;
}
@:native("require.resolve")
extern class RequireResolve {
/**
Use the internal `require()` machinery to look up the location of a module,
but rather than loading the module, just return the resolved filename.
@see https://nodejs.org/api/modules.html#modules_require_resolve_request_options
**/
@:selfCall
static function resolve(module:String, ?options:RequireResolveOptions):String;
/**
Returns an array containing the paths searched during resolution of `request` or `null`
if the `request` string references a core module, for example `http` or `fs`.
@see https://nodejs.org/api/modules.html#modules_require_resolve_paths_request
**/
static function paths(request:String):Null<Array<String>>;
}
typedef RequireResolveOptions = {
/**
Paths to resolve module location from.
If present, these paths are used instead of the default resolution paths,
with the exception of `GLOBAL_FOLDERS` like $HOME/.node_modules, which are always included.
Each of these paths is used as a starting point for the module resolution algorithm,
meaning that the node_modules hierarchy is checked from this location.
**/
@:optional var paths:Array<String>;
}

View File

@ -0,0 +1,73 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.extern.Rest;
import js.node.events.EventEmitter;
import js.node.stream.Readable.IReadable;
import js.node.stream.Writable.IWritable;
#if haxe4
import js.lib.Error;
import js.lib.Promise;
#else
import js.Error;
import js.Promise;
#end
/**
Base class for all streams.
**/
@:jsRequire("stream") // the module itself is also a class
extern class Stream<TSelf:Stream<TSelf>> extends EventEmitter<TSelf> implements IStream {
private function new();
/**
A module method to pipe between streams forwarding errors and properly cleaning up
and provide a callback when the pipeline is complete.
@see https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback
**/
@:overload(function(readable:IReadable, callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, writable2:IWritable, callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, writable2:IWritable, writable3:IWritable, callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, writable2:IWritable, writable3:IWritable, writable4:IWritable,
callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, writable2:IWritable, writable3:IWritable, writable4:IWritable, writable5:IWritable,
callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, writable2:IWritable, writable3:IWritable, writable4:IWritable, writable5:IWritable,
writable6:IWritable, callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, writable2:IWritable, writable3:IWritable, writable4:IWritable, writable5:IWritable,
writable6:IWritable, writable7:IWritable, callback:Null<Error>->Void):Void {})
@:overload(function(readable:IReadable, writable1:IWritable, writable2:IWritable, writable3:IWritable, writable4:IWritable, writable5:IWritable,
writable6:IWritable, writable7:IWritable, writable8:IWritable, callback:Null<Error>->Void):Void {})
static function pipeline(readable:IReadable, streams:Rest<IWritable>):Promise<Void>;
}
/**
`IStream` interface is used as "any Stream".
See `Stream` for actual class.
**/
@:remove
extern interface IStream extends IEventEmitter {}

View File

@ -0,0 +1,66 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
#if haxe4
import js.lib.ArrayBufferView;
#else
import js.html.ArrayBufferView;
#end
/**
The `string_decoder` module provides an API for decoding `Buffer` objects into strings in a manner that preserves
encoded multi-byte UTF-8 and UTF-16 characters.
@see https://nodejs.org/api/string_decoder.html#string_decoder_string_decoder
**/
@:jsRequire("string_decoder", "StringDecoder")
extern class StringDecoder {
/**
Creates a new `StringDecoder` instance.
@see https://nodejs.org/api/string_decoder.html#string_decoder_new_stringdecoder_encoding
**/
function new(?encoding:String);
/**
Returns any remaining input stored in the internal buffer as a string.
Bytes representing incomplete UTF-8 and UTF-16 characters will be replaced
with substitution characters appropriate for the character encoding.
@see https://nodejs.org/api/string_decoder.html#string_decoder_stringdecoder_end_buffer
**/
@:overload(function(buffer:Buffer):String {})
@:overload(function(buffer:ArrayBufferView):String {})
function end():String;
/**
Returns a decoded string, ensuring that any incomplete multibyte characters at the end of the `Buffer`, or
`TypedArray`, or `DataViewor` are omitted from the returned string and stored in an internal buffer for the next
call to `stringDecoder.write()` or `stringDecoder.end()`.
@see https://nodejs.org/api/string_decoder.html#string_decoder_stringdecoder_write_buffer
**/
@:overload(function(buffer:ArrayBufferView):String {})
function write(buffer:Buffer):String;
}

View File

@ -0,0 +1,138 @@
package js.node;
import haxe.Constraints.Function;
import haxe.extern.Rest;
/**
The `timer` module exposes a global API for scheduling functions to be called at some future period of time.
Because the timer functions are globals, there is no need to call `require('timers')` to use the API.
The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers
but use a different internal implementation that is built around the Node.js Event Loop.
**/
@:jsRequire("timers")
extern class Timers {
/**
Schedules the "immediate" execution of the callback after I/O events' callbacks.
When multiple calls to `setImmediate()` are made, the `callback` functions are queued for execution
in the order in which they are created. The entire callback queue is processed every event loop iteration.
If an immediate timer is queued from inside an executing callback, that timer will not be triggered until
the next event loop iteration.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `util.promisify()`.
**/
static function setImmediate(callback:Function, args:Rest<Dynamic>):Immediate;
/**
Schedules repeated execution of `callback` every `delay` milliseconds.
When delay is larger than `2147483647` or less than `1`, the `delay` will be set to `1`.
Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `util.promisify()`.
**/
static function setInterval(callback:Function, delay:Int, args:Rest<Dynamic>):Timeout;
/**
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering.
The callback will be called as close as possible to the time specified.
When delay is larger than `2147483647` or less than `1`, the delay will be set to `1`.
Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `util.promisify()`.
**/
static function setTimeout(callback:Function, delay:Int, args:Rest<Dynamic>):Timeout;
/**
Cancels an Immediate object created by `setImmediate()`.
**/
static function clearImmediate(immediate:Immediate):Void;
/**
Cancels a Timeout object created by `setInterval()`.
**/
static function clearInterval(timeout:Timeout):Void;
/**
Cancels a Timeout object created by `setTimeout()`.
**/
static function clearTimeout(timeout:Timeout):Void;
}
/**
This object is created internally and is returned from `setImmediate()`.
It can be passed to `clearImmediate()` in order to cancel the scheduled actions.
**/
extern class Immediate {
/**
If true, the `Immediate` object will keep the Node.js event loop active.
**/
function hasRef():Bool;
/**
When called, requests that the Node.js event loop not exit so long as the `Immediate` is active.
Calling `immediate.ref()` multiple times will have no effect.
By default, all `Immediate` objects are "ref'ed", making it normally unnecessary to call `immediate.ref()`
unless `immediate.unref()` had been called previously.
**/
function ref():Immediate;
/**
When called, the active `Immediate` object will not require the Node.js event loop to remain active.
If there is no other activity keeping the event loop running, the process may exit before the `Immediate` object's
callback is invoked. Calling immediate.unref() multiple times will have no effect.
**/
function unref():Immediate;
}
/**
This object is created internally and is returned from `setTimeout()` and `setInterval()`.
It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the scheduled actions.
**/
extern class Timeout {
/**
If true, the `Timeout` object will keep the Node.js event loop active.
**/
function hasRef():Bool;
/**
When called, the active `Timeout` object will not require the Node.js event loop to remain active.
If there is no other activity keeping the event loop running, the process may exit before the `Timeout` object's
callback is invoked. Calling `timeout.unref()` multiple times will have no effect.
Calling `timeout.unref()` creates an internal timer that will wake the Node.js event loop.
Creating too many of these can adversely impact performance of the Node.js application.
**/
function ref():Timeout;
/**
Sets the timer's start time to the current time, and reschedules the timer to call its callback at the previously
specified duration adjusted to the current time. This is useful for refreshing a timer without allocating
a new JavaScript object.
Using this on a timer that has already called its callback will reactivate the timer.
**/
function refresh():Timeout;
/**
When called, the active `Timeout` object will not require the Node.js event loop to remain active.
If there is no other activity keeping the event loop running, the process may exit before the `Timeout` object's
callback is invoked. Calling `timeout.unref()` multiple times will have no effect.
Calling `timeout.unref()` creates an internal timer that will wake the Node.js event loop.
Creating too many of these can adversely impact performance of the Node.js application.
**/
function unref():Timeout;
}

View File

@ -0,0 +1,212 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.extern.EitherType;
import js.node.Buffer;
import js.node.tls.SecureContext;
import js.node.tls.SecurePair;
import js.node.tls.Server;
import js.node.tls.TLSSocket;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
typedef TlsOptionsBase = {
/**
If true the server will reject any connection which is not authorized with the list of supplied CAs.
This option only has an effect if `requestCert` is true.
Default: false.
**/
@:optional var rejectUnauthorized:Bool;
/**
possible NPN protocols. (Protocols should be ordered by their priority).
**/
@:optional var NPNProtocols:EitherType<Array<String>, Buffer>;
}
typedef TlsServerOptionsBase = {
> TlsOptionsBase,
/**
If true the server will request a certificate from clients that connect
and attempt to verify that certificate.
Default: false.
**/
@:optional var requestCert:Bool;
/**
A function that will be called if client supports SNI TLS extension.
Two argument will be passed to it: `servername`, and `cb`.
SNICallback should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance.
(You can use tls.createSecureContext(...) to get proper `SecureContext`).
If `SNICallback` wasn't provided - default callback with high-level API will be used.
**/
@:optional var SNICallback:#if (haxe_ver >= 4)(servername:String, cb:(Error->SecureContext)) -> Void #else String->(Error->SecureContext)->Void #end;
}
typedef TlsClientOptionsBase = {
> TlsOptionsBase,
/**
A Buffer instance, containing TLS session.
**/
@:optional var session:Buffer;
/**
If true - OCSP status request extension would be added to client hello,
and OCSPResponse event will be emitted on socket before establishing secure communication
**/
@:optional var requestOCSP:Bool;
}
/**
Base structure for options object used in tls methods.
**/
typedef TlsCreateServerOptions = {
> TlsServerOptionsBase,
> SecureContextOptions,
/**
Abort the connection if the SSL/TLS handshake does not finish in this many milliseconds.
The default is 120 seconds.
A 'clientError' is emitted on the `tls.Server` object whenever a handshake times out.
**/
@:optional var handshakeTimeout:Int;
/**
An integer specifying the seconds after which TLS session identifiers
and TLS session tickets created by the server are timed out.
See SSL_CTX_set_timeout for more details.
**/
@:optional var sessionTimeout:Int;
/**
A 48-byte `Buffer` instance consisting of 16-byte prefix, 16-byte hmac key, 16-byte AES key.
You could use it to accept tls session tickets on multiple instances of tls server.
NOTE: Automatically shared between cluster module workers.
**/
@:optional var ticketKeys:Buffer;
}
typedef TlsConnectOptions = {
> TlsClientOptionsBase,
> SecureContextOptions,
/**
Host the client should connect to.
Defaults to 'localhost'
**/
@:optional var host:String;
/**
Port the client should connect to
**/
@:optional var port:Int;
/**
Establish secure connection on a given socket rather than creating a new socket.
If this option is specified, `host` and `port` are ignored.
**/
@:optional var socket:js.node.net.Socket;
/**
Creates unix socket connection to path.
If this option is specified, host and port are ignored.
**/
@:optional var path:String;
/**
Servername for SNI (Server Name Indication) TLS extension.
**/
@:optional var servername:String;
/**
An override for checking server's hostname against the certificate.
Should return an error if verification fails. Return `js.Lib.undefined` if passing.
**/
@:optional var checkServerIdentity:String -> {}->Dynamic; // TODO: peer cerficicate structure
}
/**
The tls module uses OpenSSL to provide Transport Layer Security
and/or Secure Socket Layer: encrypted stream communication.
**/
@:jsRequire("tls")
extern class Tls {
/**
renegotiation limit, default is 3.
**/
static var CLIENT_RENEG_LIMIT:Int;
/**
renegotiation window in seconds, default is 10 minutes.
**/
static var CLIENT_RENEG_WINDOW:Int;
/**
Size of slab buffer used by all tls servers and clients. Default: 10 * 1024 * 1024.
Don't change the defaults unless you know what you are doing.
**/
static var SLAB_BUFFER_SIZE:Int;
/**
Returns an array with the names of the supported SSL ciphers.
**/
static function getCiphers():Array<String>;
/**
Creates a new `Server`.
The `connectionListener` argument is automatically set as a listener for the 'secureConnection' event.
**/
static function createServer(options:TlsCreateServerOptions, ?secureConnectionListener:TLSSocket->Void):Server;
/**
Creates a new client connection to the given `port` and `host` (old API) or `options.port` and `options.host`.
If `host` is omitted, it defaults to 'localhost'.
**/
@:overload(function(port:Int, ?callback:Void->Void):TLSSocket {})
@:overload(function(port:Int, options:TlsConnectOptions, ?callback:Void->Void):TLSSocket {})
@:overload(function(port:Int, host:String, ?callback:Void->Void):TLSSocket {})
@:overload(function(port:Int, host:String, options:TlsConnectOptions, ?callback:Void->Void):TLSSocket {})
static function connect(options:TlsConnectOptions, ?callback:Void->Void):TLSSocket;
/**
Creates a credentials object.
**/
static function createSecureContext(?details:SecureContextOptions):SecureContext;
/**
Creates a new secure pair object with two streams, one of which reads/writes encrypted data,
and one reads/writes cleartext data.
Generally the encrypted one is piped to/from an incoming encrypted data stream,
and the cleartext one is used as a replacement for the initial encrypted stream.
**/
static function createSecurePair(?context:SecureContext, ?isServer:Bool, ?requestCert:Bool, ?rejectUnauthorized:Bool):SecurePair;
}

View File

@ -0,0 +1,42 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
/**
The tty module houses the tty.ReadStream and tty.WriteStream classes.
In most cases, you will not need to use this module directly.
When node detects that it is being run inside a TTY context, then process.stdin will be a tty.ReadStream
instance and process.stdout will be a tty.WriteStream instance. The preferred way to check if node is being
run in a TTY context is to check process.stdout.isTTY.
**/
@:jsRequire("tty")
extern class Tty {
/**
Returns true or false depending on if the `fd` is associated with a terminal.
**/
static function isatty(fd:Int):Bool;
@:deprecated("Use tty.ReadStream#setRawMode() instead.")
static function setRawMode(mode:Bool):Void;
}

View File

@ -0,0 +1,239 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import js.node.url.URL;
/**
The `url` module provides utilities for URL resolution and parsing.
**/
@:jsRequire("url")
extern class Url {
/**
Returns the Punycode ASCII serialization of the `domain`. If `domain` is an invalid domain, the empty string is returned.
It performs the inverse operation to `url.domainToUnicode()`.
**/
static function domainToASCII(domain:String):String;
/**
Returns the Unicode serialization of the `domain`. If `domain` is an invalid domain, the empty string is returned.
It performs the inverse operation to `url.dmainToASCII()`.
**/
static function domainToUnicode(domain:String):String;
/**
This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.
**/
@:overload(function(url:String):String {})
static function fileURLToPath(url:URL):String;
/**
Returns a customizable serialization of a URL `String` representation of a [WHATWG URL](https://nodejs.org/api/url.html#url_the_whatwg_url_api) object.
The URL object has both a `toString()` method and href property that return string serializations of the URL.
These are not, however, customizable in any way.
The `url.format(URL[, options])` method allows for basic customization of the output.
`format(urlObject:UrlObject)` and `format(urlObject:String)` are deprecated.
**/
@:overload(function(urlObject:UrlObject):String {})
@:overload(function(urlObject:String):String {})
static function format(url:URL, ?options:UrlFormatOptions):String;
/**
This function ensures that `path` is resolved absolutely,
and that the URL control characters are correctly encoded when converting into a File URL.
**/
static function pathToFileURL(path:String):URL;
/**
Takes a URL string, parses it, and returns a URL object.
If `parseQueryString` is true, the `query` property will always be set to an object returned by the `Querystring.parse` method.
If false, the `query` property on the returned URL object will be an unparsed, undecoded string.
Defaults to false.
If `slashesDenoteHost` is true, the first token after the literal string `//` and preceding the next `/` will be interpreted as the host.
For instance, given `//foo/bar`, the result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`.
Defaults to false.
**/
@:deprecated
static function parse(urlString:String, ?parseQueryString:Bool, ?slashesDenoteHost:Bool):UrlObject;
/**
Resolves a target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF.
Examples:
```haxe
resolve('/one/two/three', 'four') // '/one/two/four'
resolve('http://example.com/', '/one') // 'http://example.com/one'
resolve('http://example.com/one', '/two') // 'http://example.com/two'
```
**/
@:deprecated
static function resolve(from:String, to:String):String;
}
typedef UrlFormatOptions = {
/**
`true` if the serialized URL string should include the username and password, `false` otherwise.
Default: `true`.
**/
@:optional var auth:Bool;
/**
`true` if the serialized URL string should include the fragment, `false` otherwise.
Default: `true`.
**/
@:optional var fragment:Bool;
/**
`true` if the serialized URL string should include the search query, `false` otherwise.
Default: `true`.
**/
@:optional var search:Bool;
/**
`true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded.
Default: `false`.
**/
@:optional var unicode:Bool;
}
/**
Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string.
Any parts that are not in the URL string will not be in the parsed object.
**/
@:deprecated
typedef UrlObject = {
/**
The full URL string that was parsed with both the `protocol` and `host` components converted to lower-case.
For example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
**/
@:optional var href:String;
/**
The URL's lower-cased protocol scheme.
For example: 'http:'
**/
@:optional var protocol:String;
/**
True if two ASCII forward-slash characters (`/`) are required following the colon in the `protocol`.
**/
@:optional var slashes:Bool;
/**
The full lower-cased host portion of the URL, including the `port` if specified.
For example: 'host.com:8080'
**/
@:optional var host:String;
/**
The username and password portion of the URL, also referred to as "userinfo".
This string subset follows the `protocol` and double slashes (if present) and precedes the `host` component,
delimited by an ASCII "at sign" (`@`).
The format of the string is `{username}[:{password}]`, with the `[:{password}]` portion being optional.
For example: 'user:pass'
**/
@:optional var auth:String;
/**
The lower-cased host name portion of the `host` component without the `port` included.
For example: 'host.com'
**/
@:optional var hostname:String;
/**
The numeric port portion of the `host` component.
For example: '8080'
**/
@:optional var port:String;
/**
The entire path section of the URL. This is everything following the `host` (including the `port`) and
before the start of the `query` or `hash` components, delimited by either the ASCII question mark (`?`) or
hash (`#`) characters.
For example '/p/a/t/h'
No decoding of the path string is performed.
**/
@:optional var pathname:String;
/**
The entire "query string" portion of the URL, including the leading ASCII question mark (`?`) character.
For example: '?query=string'
No decoding of the query string is performed.
**/
@:optional var search:String;
/**
Concatenation of the `pathname` and `search` components.
For example: '/p/a/t/h?query=string'
No decoding of the path is performed.
**/
@:optional var path:String;
/**
Either the query string without the leading ASCII question mark (`?`),
or an object returned by the `Querystring.parse` method.
Whether the `query` property is a string or object is determined by the `parseQueryString` argument passed to `Url.parse`.
For example: 'query=string' or {'query': 'string'}
If returned as a string, no decoding of the query string is performed.
If returned as an object, both keys and values are decoded.
The type of this field can be implicitly converted to `String` or `DynamicAccess<String>`,
where either one is expected, so if you know the actual type, just assign it
to properly typed variable (e.g. var s:String = url.query)
**/
@:optional var query:haxe.extern.EitherType<String, haxe.DynamicAccess<String>>;
/**
The "fragment" portion of the URL including the leading ASCII hash (`#`) character.
For example: '#hash'
**/
@:optional var hash:String;
}

View File

@ -0,0 +1,352 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.Constraints.Function;
import haxe.extern.EitherType;
import haxe.extern.Rest;
import js.node.stream.Readable;
import js.node.stream.Writable;
#if haxe4
import js.lib.Error;
import js.lib.Promise;
#else
import js.Error;
import js.Promise;
#end
/**
The `util` module is primarily designed to support the needs of Node.js' own internal APIs.
@see https://nodejs.org/api/util.html#util_util
**/
@:jsRequire("util")
extern class Util {
/**
Takes an `async` function (or a function that returns a `Promise`) and returns a function following the
error-first callback style, i.e. taking an `(err, value) => ...` callback as the last argument.
@see https://nodejs.org/api/util.html#util_util_callbackify_original
**/
static function callbackify(original:Function, args:Rest<Dynamic>):Null<Error>->Null<Dynamic>->Void;
/**
The `util.debuglog()` method is used to create a function that conditionally writes debug messages to `stderr`
based on the existence of the `NODE_DEBUG` environment variable.
@see https://nodejs.org/api/util.html#util_util_debuglog_section
**/
static function debuglog(section:String):Rest<Dynamic>->Void;
/**
The `util.deprecate()` method wraps `fn` (which may be a function or class) in such a way that it is marked
asdeprecated.
@see https://nodejs.org/api/util.html#util_util_deprecate_fn_msg_code
**/
static function deprecate<T:haxe.Constraints.Function>(fun:T, msg:String, ?code:String):T;
/**
The `util.format()` method returns a formatted string using the first argument as a `printf`-like format string
which can contain zero or more format specifiers.
@see https://nodejs.org/api/util.html#util_util_format_format_args
**/
@:overload(function(args:Rest<Dynamic>):String {})
static function format(format:String, args:Rest<Dynamic>):String;
/**
This function is identical to `util.format()`, except in that it takes an `inspectOptions` argument which
specifies options that are passed along to `util.inspect()`.
@see https://nodejs.org/api/util.html#util_util_formatwithoptions_inspectoptions_format_args
**/
@:overload(function(inspectOptions:InspectOptions, args:Rest<Dynamic>):String {})
static function formatWithOptions(inspectOptions:InspectOptions, format:String, args:Rest<Dynamic>):String;
/**
Returns the string name for a numeric error code that comes from a Node.js API.
@see https://nodejs.org/api/util.html#util_util_getsystemerrorname_err
**/
static function getSystemErrorName(err:Int):String;
/**
Inherit the prototype methods from one `constructor` into another.
@see https://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor
**/
@:deprecated
static function inherits(constructor:Class<Dynamic>, superConstructor:Class<Dynamic>):Void;
/**
The `util.inspect()` method returns a string representation of `object` that is intended for debugging.
@see https://nodejs.org/api/util.html#util_util_inspect_object_options
**/
@:overload(function(object:Dynamic, ?showHidden:Bool, ?depth:Int, ?colors:Bool):String {})
static function inspect(object:Dynamic, ?options:InspectOptions):String;
/**
Returns `true` if there is deep strict equality between `val1` and `val2`.
@see https://nodejs.org/api/util.html#util_util_isdeepstrictequal_val1_val2
**/
static function isDeepStrictEqual(val1:Dynamic, val2:Dynamic):Bool;
/**
Takes a function following the common error-first callback style, i.e. taking an `(err, value) => ...` callback
as the last argument, and returns a version that returns promises.
@see https://nodejs.org/api/util.html#util_util_promisify_original
**/
static function promisify(original:Function):Rest<Dynamic>->Promise<Dynamic>;
/**
Deprecated predecessor of `Console.error`.
**/
@:deprecated("Use js.Node.console.error instead")
static function debug(string:String):Void;
/**
Deprecated predecessor of console.error.
**/
@:deprecated("Use js.Node.console.error instead")
static function error(args:Rest<Dynamic>):Void;
/**
Returns true if the given "object" is an Array. false otherwise.
**/
@:deprecated
static function isArray(object:Dynamic):Bool;
/**
Returns true if the given "object" is a Bool. false otherwise.
**/
@:deprecated
static function isBoolean(object:Dynamic):Bool;
/**
Returns true if the given "object" is a Buffer. false otherwise.
**/
@:deprecated
static function isBuffer(object:Dynamic):Bool;
/**
Returns true if the given "object" is a Date. false otherwise.
**/
@:deprecated
static function isDate(object:Dynamic):Bool;
/**
Returns true if the given "object" is an Error. false otherwise.
**/
@:deprecated
static function isError(object:Dynamic):Bool;
/**
Returns true if the given "object" is a Function. false otherwise.
**/
@:deprecated
static function isFunction(object:Dynamic):Bool;
/**
Returns true if the given "object" is strictly null. false otherwise.
**/
@:deprecated
static function isNull(object:Dynamic):Bool;
/**
Returns true if the given "object" is null or undefined. false otherwise.
**/
@:deprecated
static function isNullOrUndefined(object:Dynamic):Bool;
/**
Returns true if the given "object" is a Float. false otherwise.
**/
@:deprecated
static function isNumber(object:Dynamic):Bool;
/**
Returns true if the given "object" is strictly an Object and not a Function. false otherwise.
**/
@:deprecated
static function isObject(object:Dynamic):Bool;
/**
Returns true if the given "object" is a primitive type. false otherwise.
**/
@:deprecated
static function isPrimitive(object:Dynamic):Bool;
/**
Returns true if the given "object" is a RegExp. false otherwise.
**/
@:deprecated
static function isRegExp(object:Dynamic):Bool;
/**
Returns true if the given "object" is a String. false otherwise.
**/
@:deprecated
static function isString(object:Dynamic):Bool;
/**
Returns true if the given "object" is a Symbol. false otherwise.
**/
@:deprecated
static function isSymbol(object:Dynamic):Bool;
/**
Returns true if the given "object" is undefined. false otherwise.
**/
@:deprecated
static function isUndefined(object:Dynamic):Bool;
/**
Output with timestamp on stdout.
**/
@:deprecated
static function log(args:Rest<Dynamic>):Void;
/**
Deprecated predecessor of console.log.
**/
@:deprecated("Use js.Node.console.log instead")
static function print(args:Rest<Dynamic>):Void;
/**
Deprecated predecessor of console.log.
**/
@:deprecated("Use js.Node.console.log instead")
static function puts(args:Rest<Dynamic>):Void;
/**
Deprecated predecessor of stream.pipe().
**/
@:deprecated("Use `readableStream.pipe(writableStream)` instead")
static function pump(readableStream:IReadable, writableStream:IWritable, ?callback:Error->Void):Void;
}
/**
Options object used by `Console.dir`.
**/
typedef InspectOptionsBase = {
/**
If `true`, `object`'s non-enumerable symbols and properties are included in the formatted result.
`WeakMap` and `WeakSet` entries are also included.
Default: `false`.
**/
@:optional var showHidden:Bool;
/**
Specifies the number of times to recurse while formatting `object`.
This is useful for inspecting large objects. To recurse up to the maximum call stack size pass `Infinity` or
`null`.
Default: `2`.
**/
@:optional var depth:Null<Int>;
/**
If `true`, the output is styled with ANSI color codes.
Colors are customizable.
See Customizing `util.inspect` colors.
Default: `false`.
**/
@:optional var colors:Bool;
}
/**
Options object used by `Util.inspect`.
**/
typedef InspectOptions = {
> InspectOptionsBase,
/**
If `false`, `[util.inspect.custom](depth, opts)` functions are not invoked.
Default: `true`.
**/
@:optional var customInspect:Bool;
/**
If `true`, `Proxy` inspection includes the `target` and `handler` objects.
Default: `false`.
**/
@:optional var showProxy:Bool;
/**
Specifies the maximum number of `Array`, `TypedArray`, `WeakMap` and `WeakSet` elements to include when
formatting.
Set to `null` or `Infinity` to show all elements.
Set to `0` or negative to show no elements.
Default: `100`.
**/
@:optional var maxArrayLength:Null<Int>;
/**
The length at which input values are split across multiple lines.
Set to `Infinity` to format the input as a single line (in combination with `compact` set to `true` or any
number >= `1`).
Default: `80`.
**/
@:optional var breakLength:Float;
/**
Setting this to `false` causes each object key to be displayed on a new line.
It will also add new lines to text that is longer than `breakLength`.
If set to a number, the most `n` inner elements are united on a single line as long as all properties fit into
`breakLength`.
Short array elements are also grouped together.
No text will be reduced below 16 characters, no matter the `breakLength` size.
For more information, see the example below.
Default: `3`.
**/
@:optional var compact:EitherType<Bool, Int>;
/**
If set to `true` or a function, all properties of an object, and `Set` and `Map` entries are sorted in the
resulting string.
If set to `true` the default sort is used.
If set to a function, it is used as a compare function.
**/
@:optional var sorted:EitherType<Bool, Dynamic->Dynamic->Int>;
/**
If set to `true`, getters are inspected.
If set to `'get'`, only getters without a corresponding setter are inspected.
If set to `'set'`, only getters with a corresponding setter are inspected.
This might cause side effects depending on the getter function.
Default: `false`.
**/
@:optional var getters:EitherType<Bool, String>;
}

View File

@ -0,0 +1,73 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
/**
The v8 module exposes APIs that are specific to the version of V8 built into the Node.js binary.
Note: The APIs and implementation are subject to change at any time.
**/
@:jsRequire("v8")
extern class V8 {
static function getHeapStatistics():V8HeapStatistics;
/**
Returns statistics about the V8 heap spaces, i.e. the segments which make up the V8 heap.
Neither the ordering of heap spaces, nor the availability of a heap space can be guaranteed
as the statistics are provided via the V8 `GetHeapSpaceStatistics` function and may change
from one V8 version to the next.
**/
static function getHeapSpaceStatistics():Array<V8HeapSpaceStatistics>;
/**
This method can be used to programmatically set V8 command line flags. This method should be used with care.
Changing settings after the VM has started may result in unpredictable behavior, including crashes and data loss;
or it may simply do nothing.
The V8 options available for a version of Node.js may be determined by running `node --v8-options`.
**/
static function setFlagsFromString(string:String):Void;
}
/**
Object returned by `V8.getHeapStatistics` method.
**/
typedef V8HeapStatistics = {
var total_heap_size:Int;
var total_heap_size_executable:Int;
var total_physical_size:Int;
var total_available_size:Int;
var used_heap_size:Int;
var heap_size_limit:Int;
}
/**
Object returned by `V8.getHeapSpaceStatistics` method.
**/
typedef V8HeapSpaceStatistics = {
var space_name:String;
var space_size:Int;
var space_used_size:Int;
var space_available_size:Int;
var physical_space_size:Int;
}

View File

@ -0,0 +1,113 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import js.node.vm.Script;
/**
Options object used by Vm.run* methods.
**/
typedef VmRunOptions = {
> ScriptOptions,
> ScriptRunOptions,
}
/**
Using this class JavaScript code can be compiled and
run immediately or compiled, saved, and run later.
**/
@:jsRequire("vm")
extern class Vm {
/**
Compiles `code`, runs it and returns the result.
Running code does not have access to local scope.
`filename` is optional, it's used only in stack traces.
In case of syntax error in `code` emits the syntax error to stderr and throws an exception.
**/
static function runInThisContext(code:String, ?options:VmRunOptions):Dynamic;
/**
Compiles `code`, contextifies `sandbox` if passed or creates a new contextified sandbox if it's omitted,
and then runs the code with the sandbox as the global object and returns the result.
`runInNewContext` takes the same options as `runInThisContext`.
Note that running untrusted code is a tricky business requiring great care. `runInNewContext` is quite useful,
but safely running untrusted code requires a separate process.
**/
@:overload(function(code:String, ?sandbox:{}):Dynamic {})
static function runInNewContext(code:String, sandbox:{}, ?options:VmRunOptions):Dynamic;
/**
Compiles `code`, then runs it in `contextifiedSandbox` and returns the result.
Running code does not have access to local scope. The `contextifiedSandbox` object must have been previously
contextified via `createContext`; it will be used as the global object for code.
`runInContext` takes the same options as `runInThisContext`.
Note that running untrusted code is a tricky business requiring great care. `runInContext` is quite useful,
but safely running untrusted code requires a separate process.
**/
static function runInContext(code:String, contextifiedSandbox:VmContext<Dynamic>, ?options:VmRunOptions):Dynamic;
/**
If given a sandbox object, will "contextify" that sandbox so that it can be used in calls to `runInContext` or
`Script.runInContext`. Inside scripts run as such, sandbox will be the global object, retaining all its existing
properties but also having the built-in objects and functions any standard global object has. Outside of scripts
run by the vm module, sandbox will be unchanged.
If not given a sandbox object, returns a new, empty contextified sandbox object you can use.
This function is useful for creating a sandbox that can be used to run multiple scripts, e.g. if you were
emulating a web browser it could be used to create a single sandbox representing a window's global object,
then run all <script> tags together inside that sandbox.
**/
static function createContext<T:{}>(?sandbox:T):VmContext<T>;
/**
Returns whether or not a sandbox object has been contextified by calling `createContext` on it.
**/
static function isContext(sandbox:{}):Bool;
/**
Compiles and executes `code` inside the V8 debug context.
The primary use case is to get access to the V8 debug object:
Note that the debug context and object are intrinsically tied to V8's debugger implementation
and may change (or even get removed) without prior warning.
**/
static function runInDebugContext(code:String):Dynamic;
@:deprecated("use new js.node.vm.Script(...) instead")
static function createScript(code:String, ?options:ScriptOptions):Script;
}
/**
Type of context objects returned by `Vm.createContext`.
**/
@:forward
abstract VmContext<T:{}>(T) from T to T {}

View File

@ -0,0 +1,250 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node;
import haxe.extern.EitherType;
import js.node.Buffer;
import js.node.zlib.*;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
typedef ZlibOptions = {
/**
default: `Zlib.Z_NO_FLUSH`
**/
@:optional var flush:Int;
/**
default: 16*1024
**/
@:optional var chunkSize:Int;
@:optional var windowBits:Int;
/**
compression only
**/
@:optional var level:Int;
/**
compression only
**/
@:optional var memLevel:Int;
/**
compression only
**/
@:optional var strategy:Int;
/**
deflate/inflate only, empty dictionary by default
**/
@:optional var dictionary:Buffer;
}
/**
This provides bindings to Gzip/Gunzip, Deflate/Inflate, and DeflateRaw/InflateRaw classes.
Each class takes the same options, and is a readable/writable Stream.
**/
@:jsRequire("zlib")
extern class Zlib {
/**
Allowed `flush` values.
**/
static var Z_NO_FLUSH(default, null):Int;
static var Z_PARTIAL_FLUSH(default, null):Int;
static var Z_SYNC_FLUSH(default, null):Int;
static var Z_FULL_FLUSH(default, null):Int;
static var Z_FINISH(default, null):Int;
static var Z_BLOCK(default, null):Int;
static var Z_TREES(default, null):Int;
/**
Return codes for the compression/decompression functions.
Negative values are errors, positive values are used for special but normal events.
**/
static var Z_OK(default, null):Int;
static var Z_STREAM_END(default, null):Int;
static var Z_NEED_DICT(default, null):Int;
static var Z_ERRNO(default, null):Int;
static var Z_STREAM_ERROR(default, null):Int;
static var Z_DATA_ERROR(default, null):Int;
static var Z_MEM_ERROR(default, null):Int;
static var Z_BUF_ERROR(default, null):Int;
static var Z_VERSION_ERROR(default, null):Int;
/**
Compression levels.
**/
static var Z_NO_COMPRESSION(default, null):Int;
static var Z_BEST_SPEED(default, null):Int;
static var Z_BEST_COMPRESSION(default, null):Int;
static var Z_DEFAULT_COMPRESSION(default, null):Int;
/**
Compression strategy.
**/
static var Z_FILTERED(default, null):Int;
static var Z_HUFFMAN_ONLY(default, null):Int;
static var Z_RLE(default, null):Int;
static var Z_FIXED(default, null):Int;
static var Z_DEFAULT_STRATEGY(default, null):Int;
/**
Possible values of the data_type field.
**/
static var Z_BINARY(default, null):Int;
static var Z_TEXT(default, null):Int;
static var Z_ASCII(default, null):Int;
static var Z_UNKNOWN(default, null):Int;
/**
The deflate compression method (the only one supported in this version).
**/
static var Z_DEFLATED(default, null):Int;
/**
For initializing zalloc, zfree, opaque.
**/
static var Z_NULL(default, null):Int;
/**
Returns a new `Gzip` object with an `options`.
**/
static function createGzip(?options:ZlibOptions):Gzip;
/**
Returns a new `Gunzip` object with an `options`.
**/
static function createGunzip(?options:ZlibOptions):Gunzip;
/**
Returns a new `Deflate` object with an `options`.
**/
static function createDeflate(?options:ZlibOptions):Deflate;
/**
Returns a new `Inflate` object with an `options`.
**/
static function createInflate(?options:ZlibOptions):Inflate;
/**
Returns a new `DeflateRaw` object with an `options`.
**/
static function createDeflateRaw(?options:ZlibOptions):DeflateRaw;
/**
Returns a new `InflateRaw` object with an `options`.
**/
static function createInflateRaw(?options:ZlibOptions):InflateRaw;
/**
Returns a new `Unzip` object with an `options`.
**/
static function createUnzip(?options:ZlibOptions):Unzip;
/**
Compress a string with `Deflate`.
**/
@:overload(function(buf:EitherType<String, Buffer>, options:ZlibOptions, callback:Error->Buffer->Void):Void {})
static function deflate(buf:EitherType<String, Buffer>, callback:Error->Buffer->Void):Void;
/**
Compress a string with `Deflate` (synchronous version).
**/
static function deflateSync(buf:EitherType<String, Buffer>, ?options:ZlibOptions):Buffer;
/**
Compress a string with `DeflateRaw`.
**/
@:overload(function(buf:EitherType<String, Buffer>, options:ZlibOptions, callback:Error->Buffer->Void):Void {})
static function deflateRaw(buf:EitherType<String, Buffer>, callback:Error->Buffer->Void):Void;
/**
Compress a string with `DeflateRaw` (synchronous version).
**/
static function deflateRawSync(buf:EitherType<String, Buffer>, ?options:ZlibOptions):Buffer;
/**
Compress a string with `Gzip`.
**/
@:overload(function(buf:EitherType<String, Buffer>, options:ZlibOptions, callback:Error->Buffer->Void):Void {})
static function gzip(buf:EitherType<String, Buffer>, callback:Error->Buffer->Void):Void;
/**
Compress a string with `Gzip` (synchronous version).
**/
static function gzipSync(buf:EitherType<String, Buffer>, ?options:ZlibOptions):Buffer;
/**
Decompress a raw Buffer with `Gunzip`.
**/
@:overload(function(buf:EitherType<String, Buffer>, options:ZlibOptions, callback:Error->Buffer->Void):Void {})
static function gunzip(buf:EitherType<String, Buffer>, callback:Error->Buffer->Void):Void;
/**
Decompress a raw Buffer with `Gunzip` (synchronous version).
**/
static function gunzipSync(buf:EitherType<String, Buffer>, ?options:ZlibOptions):Buffer;
/**
Decompress a raw Buffer with `Inflate`.
**/
@:overload(function(buf:EitherType<String, Buffer>, options:ZlibOptions, callback:Error->Buffer->Void):Void {})
static function inflate(buf:EitherType<String, Buffer>, callback:Error->Buffer->Void):Void;
/**
Decompress a raw Buffer with `Inflate` (synchronous version).
**/
static function inflateSync(buf:EitherType<String, Buffer>, ?options:ZlibOptions):Buffer;
/**
Decompress a raw Buffer with `InflateRaw`.
**/
@:overload(function(buf:EitherType<String, Buffer>, options:ZlibOptions, callback:Error->Buffer->Void):Void {})
static function inflateRaw(buf:EitherType<String, Buffer>, callback:Error->Buffer->Void):Void;
/**
Decompress a raw Buffer with `InflateRaw` (synchronous version).
**/
static function inflateRawSync(buf:EitherType<String, Buffer>, ?options:ZlibOptions):Buffer;
/**
Decompress a raw Buffer with `Unzip`.
**/
@:overload(function(buf:EitherType<String, Buffer>, options:ZlibOptions, callback:Error->Buffer->Void):Void {})
static function unzip(buf:EitherType<String, Buffer>, callback:Error->Buffer->Void):Void;
/**
Decompress a raw Buffer with `Unzip` (synchronous version).
**/
static function unzipSync(buf:EitherType<String, Buffer>, ?options:ZlibOptions):Buffer;
}

View File

@ -0,0 +1,99 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.assert;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Indicates the failure of an assertion. All errors thrown by the `Assert` module will be instances of the `AssertionError` class.
@see https://nodejs.org/api/assert.html#assert_class_assert_assertionerror
**/
@:jsRequire("assert", "AssertionError")
extern class AssertionError extends Error {
/**
A subclass of Error that indicates the failure of an assertion.
**/
function new(options:AssertionErrorOptions);
/**
Set to the `actual` argument for methods such as `Assert.strictEqual()`.
**/
var actual:Dynamic;
/**
Set to the `expected` value for methods such as `Assert.strictEqual()`.
**/
var expected:Dynamic;
/**
Indicates if the message was auto-generated (`true`) or not.
**/
var generatedMessage:Bool;
/**
Value is always `ERR_ASSERTION` to show that the error is an assertion error.
**/
var code:String;
/**
Set to the passed in operator value.
**/
@:native("operator") var operator_:String;
}
/**
An options type for `new` of `AssertionError`.
**/
typedef AssertionErrorOptions = {
/**
If provided, the error message is set to this value.
**/
@:optional var message:String;
/**
The `actual` property on the error instance.
**/
@:optional var actual:Dynamic;
/**
The `expected` property on the error instance.
**/
@:optional var expected:Dynamic;
#if (haxe_ver < 4)
/**
The `operator` property on the error instance.
**/
@:optional var operator:String;
#end
/**
If provided, the generated stack trace omits frames before this function.
**/
@:optional var stackStartFunction:Dynamic;
}

View File

@ -0,0 +1,763 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.buffer;
import haxe.io.Bytes;
import haxe.io.UInt8Array;
#if haxe4
import js.lib.ArrayBuffer;
import js.lib.ArrayBufferView;
import js.lib.Object;
import js.lib.Uint8Array;
#else
import js.html.ArrayBuffer;
import js.html.ArrayBufferView;
import js.html.Uint8Array;
#end
/**
The `Buffer` class is a global type for dealing with binary data directly. It can be constructed in a variety of ways.
@see https://nodejs.org/api/buffer.html#buffer_class_buffer
**/
@:jsRequire("buffer", "Buffer")
extern class Buffer extends Uint8Array {
/**
Allocates a new buffer.
@see https://nodejs.org/api/buffer.html#buffer_new_buffer_array
@see https://nodejs.org/api/buffer.html#buffer_new_buffer_arraybuffer_byteoffset_length
@see https://nodejs.org/api/buffer.html#buffer_new_buffer_buffer
@see https://nodejs.org/api/buffer.html#buffer_new_buffer_size
@see https://nodejs.org/api/buffer.html#buffer_new_buffer_string_encoding
**/
@:deprecated
@:overload(function(array:Array<Int>):Void {})
@:overload(function(arrayBuffer:ArrayBuffer, ?byteOffset:Int, ?length:Int):Void {})
@:overload(function(buffer:UInt8Array):Void {})
@:overload(function(size:Int):Void {})
function new(string:String, ?encoding:String):Void;
/**
Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be zero-filled.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding
**/
@:overload(function(size:Int, fill:String, ?encoding:String):Buffer {})
@:overload(function(size:Int, fill:Uint8Array):Buffer {})
@:overload(function(size:Int, fill:Int):Buffer {})
static function alloc(size:Int):Buffer;
/**
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
`buffer.constants.MAX_LENGTH` or smaller than 0, `ERR_INVALID_OPT_VALUE`
is thrown. A zero-length `Buffer` is created if `size` is 0.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_allocunsafe_size
**/
static function allocUnsafe(size:Int):Buffer;
/**
Allocates a new `Buffer` of `size` bytes. If `size` is larger than
`buffer.constants.MAX_LENGTH` or smaller than 0, `ERR_INVALID_OPT_VALUE`
is thrown. A zero-length `Buffer` is created if `size` is 0.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_allocunsafeslow_size
**/
static function allocUnsafeSlow(size:Int):Buffer;
/**
Returns the actual byte length of a string. This is not the same as
`String.prototype.length` since that returns the number of characters in
a string.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_bytelength_string_encoding
**/
#if (haxe_ver >= 3.3)
// it need extern SharedArrayBuffer for Node
// @:overload(function(string:SharedArrayBuffer):Int {})
@:overload(function(string:String, ?encoding:String):Int {})
@:overload(function(string:ArrayBufferView):Int {})
@:overload(function(string:ArrayBuffer):Int {})
static function byteLength(string:Buffer):Int;
#end
#if (haxe_ver >= 3.3)
@:deprecated("In haxe 3.3+, use Buffer.byteLength instead!")
#end
inline static function _byteLength(string:String, ?encoding:String):Int
return untyped Buffer['byteLength'](string, encoding);
/**
Compares `buf1` to `buf2` typically for the purpose of sorting arrays of
`Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_compare_buf1_buf2
**/
@:native("compare")
static function compareBuffers(buf1:Uint8Array, buf2:Uint8Array):Int;
/**
Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
**/
static function concat<T:Uint8Array>(list:Array<T>, ?totalLength:Int):Buffer;
/**
Allocates a new `Buffer`.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_array
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_buffer
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_object_offsetorencoding_length
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding
**/
// it need extern SharedArrayBuffer for node
// @:overload(function(arrayBuffer:SharedArrayBuffer, ?byteOffset:Int, ?length:Int):Buffer {})
@:overload(function(array:Array<Int>):Buffer {})
@:overload(function(arrayBuffer:ArrayBuffer, ?byteOffset:Int, ?length:Int):Buffer {})
@:overload(function(buffer:Uint8Array):Buffer {})
@:overload(function(object:{}, ?offset:Int, ?length:Int):Buffer {})
@:overload(function(object:{}, ?encoding:String, ?length:Int):Buffer {})
static function from(string:String, ?encoding:String):Buffer;
/**
Returns `true` if `obj` is a `Buffer`, `false` otherwise.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_isbuffer_obj
**/
static function isBuffer(obj:Dynamic):Bool;
/**
Returns `true` if `encoding` contains a supported character encoding, or `false` otherwise.
@see https://nodejs.org/api/buffer.html#buffer_class_method_buffer_isencoding_encoding
**/
static function isEncoding(encoding:String):Bool;
/**
This is the size (in bytes) of pre-allocated internal `Buffer` instances used for pooling. This value may be modified.
@see https://nodejs.org/api/buffer.html#buffer_class_property_buffer_poolsize
**/
static var poolSize:Int;
// buf[index]
// var buffer:ArrayBuffer;
/**
When setting `byteOffset` in `Buffer.from(ArrayBuffer, byteOffset, length)`
or sometimes when allocating a buffer smaller than `Buffer.poolSize` the
buffer doesn't start from a zero offset on the underlying `ArrayBuffer`.
@see https://nodejs.org/api/buffer.html#buffer_buf_byteoffset
**/
static var byteOffset(default, null):Int;
/**
Compares `buf` with `target` and returns a number indicating whether `buf` comes before, after,
or is the same as `target` in sort order. Comparison is based on the actual sequence of bytes in each `Buffer`.
@see https://nodejs.org/api/buffer.html#buffer_buf_compare_target_targetstart_targetend_sourcestart_sourceend
**/
@:overload(function(target:Uint8Array):Int {})
function compare(target:Uint8Array, ?targetStart:Int, ?targetEnd:Int, ?sourceStart:Int, ?sourceEnd:Int):Int;
/**
Copies data from a region of `buf` to a region in `target` even if the `target` memory region overlaps with `buf`.
@see https://nodejs.org/api/buffer.html#buffer_buf_copy_target_targetstart_sourcestart_sourceend
**/
@:overload(function(target:Uint8Array):Void {})
function copy(target:Uint8Array, ?targetStart:Int, ?sourceStart:Int, ?sourceEnd:Int):Void;
/**
Creates and returns an iterator of `[index, byte]` pairs from the contents of `buf`.
@see https://nodejs.org/api/buffer.html#buffer_buf_entries
**/
function entries():js.node.Iterator<js.node.KeyValue<Int, Int>>;
/**
Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes, `false` otherwise.
@see https://nodejs.org/api/buffer.html#buffer_buf_equals_otherbuffer
**/
function equals(otherBuffer:Uint8Array):Bool;
/**
Fills `buf` with the specified `value`. If the `offset` and `end` are not given, the entire `buf` will be filled:
@see https://nodejs.org/api/buffer.html#buffer_buf_fill_value_offset_end_encoding
**/
@:overload(function(value:Uint8Array, ?offset:Int, ?end:Int):Buffer {})
@:overload(function(value:Int, ?offset:Int, ?end:Int):Buffer {})
function fill(value:String, ?offset:Int, ?end:Int, ?encoding:String):Buffer;
/**
Equivalent to `buf.indexOf() !== -1`.
@see https://nodejs.org/api/buffer.html#buffer_buf_includes_value_byteoffset_encoding
**/
@:overload(function(value:Uint8Array, ?byteOffset:Int):Bool {})
@:overload(function(value:Int, ?byteOffset:Int):Bool {})
function includes(value:String, ?byteOffset:Int, ?encoding:String):Bool;
/**
If `value` is:
- a string, `value` is interpreted according to the character encoding in `encoding`.
- a `Buffer` or Uint8Array, `value` will be used in its entirety. To compare a partial `Buffer`, use buf.slice().
- a number, `value` will be interpreted as an unsigned 8-bit integer value between `0` and `255`.
@see https://nodejs.org/api/buffer.html#buffer_buf_indexof_value_byteoffset_encoding
**/
@:overload(function(value:Uint8Array, ?byteOffset:Int):Int {})
@:overload(function(value:Int, ?byteOffset:Int):Int {})
function indexOf(value:String, ?byteOffset:Int, ?encoding:String):Int;
/**
Creates and returns an iterator of `buf` keys (indices).
@see https://nodejs.org/api/buffer.html#buffer_buf_keys
**/
function keys():js.node.Iterator<Int>;
/**
Identical to `buf.indexOf()`, except the last occurrence of `value` is found
rather than the first occurrence.
@see https://nodejs.org/api/buffer.html#buffer_buf_lastindexof_value_byteoffset_encoding
**/
@:overload(function(value:Uint8Array, ?byteOffset:Int):Int {})
@:overload(function(value:Int, ?byteOffset:Int):Int {})
function lastIndexOf(value:String, ?byteOffset:Int, ?encoding:String):Int;
// var length(default, null):Int;
// these functions need BigInt implementation.
// /**
// Reads a signed 64-bit integer from `buf` at the specified `offset` with the specified endian format
// (`readBigInt64BE()` returns big endian, `readBigInt64LE()` returns little endian).
// @see https://nodejs.org/api/buffer.html#buffer_buf_readbigint64be_offset
// **/
// function readBigInt64BE(?offset:Int):BigInt;
// /**
// Reads a signed 64-bit integer from `buf` at the specified `offset` with the specified endian format
// (`readBigInt64BE()` returns big endian, `readBigInt64LE()` returns little endian).
// @see https://nodejs.org/api/buffer.html#buffer_buf_readbigint64le_offset
// **/
// function readBigInt64LE(?offset:Int):BigInt;
// /**
// Reads an unsigned 64-bit integer from `buf` at the specified `offset` with specified endian format
// (`readBigUInt64BE()` returns big endian, `readBigUInt64LE()` returns little endian).
// @see https://nodejs.org/api/buffer.html#buffer_buf_readbiguint64be_offset
// **/
// function readBigUInt64BE(?offset:Int):BigInt;
// /**
// Reads an unsigned 64-bit integer from `buf` at the specified `offset` with specified endian format
// (`readBigUInt64BE()` returns big endian, `readBigUInt64LE()` returns little endian).
// @see https://nodejs.org/api/buffer.html#buffer_buf_readbiguint64le_offset
// **/
// function readBigUInt64LE(?offset:Int):BigInt;
/**
Reads a 64-bit double from `buf` at the specified `offset` with specified endian format
(`readDoubleBE()` returns big endian, `readDoubleLE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readdoublebe_offset
**/
function readDoubleBE(?offset:Int):Float;
/**
Reads a 64-bit double from `buf` at the specified `offset` with specified endian format
(`readDoubleBE()` returns big endian, `readDoubleLE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readdoublele_offset
**/
function readDoubleLE(?offset:Int):Float;
/**
Reads a 32-bit float from `buf` at the specified `offset` with specified endian format
(`readFloatBE()` returns big endian, `readFloatLE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readfloatbe_offset
**/
function readFloatBE(?offset:Int):Float;
/**
Reads a 32-bit float from `buf` at the specified `offset` with specified endian format
(`readFloatBE()` returns big endian, `readFloatLE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readfloatle_offset
**/
function readFloatLE(?offset:Int):Float;
/**
Reads a signed 8-bit integer from `buf` at the specified `offset`.
https://nodejs.org/api/buffer.html#buffer_buf_readint8_offset
**/
function readInt8(?offset:Int):Int;
/**
Reads a signed 16-bit integer from `buf` at the specified `offset` with the specified endian format
(`readInt16BE()` returns big endian, `readInt16LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readint16be_offset
**/
function readInt16BE(?offset:Int):Int;
/**
Reads a signed 16-bit integer from `buf` at the specified `offset` with the specified endian format
(`readInt16BE()` returns big endian, `readInt16LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readint16le_offset
**/
function readInt16LE(?offset:Int):Int;
/**
Reads a signed 32-bit integer from buf at the specified offset with the specified endian format
(`readInt32BE()` returns big endian, `readInt32LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readint32be_offset
**/
function readInt32BE(?offset:Int):Int;
/**
Reads a signed 32-bit integer from buf at the specified offset with the specified endian format
(`readInt32BE()` returns big endian, `readInt32LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readint32be_offset
**/
function readInt32LE(?offset:Int):Int;
/**
Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result
as a two's complement signed value. Supports up to 48 bits of accuracy.
@see https://nodejs.org/api/buffer.html#buffer_buf_readintbe_offset_bytelength
**/
function readIntBE(offset:Int, byteLength:Int):Int;
/**
Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result
as a two's complement signed value. Supports up to 48 bits of accuracy.
@see https://nodejs.org/api/buffer.html#buffer_buf_readintle_offset_bytelength
**/
function readIntLE(offset:Int, byteLength:Int):Int;
/**
Reads an unsigned 8-bit integer from `buf` at the specified `offset`.
@see https://nodejs.org/api/buffer.html#buffer_buf_readuint8_offset
**/
function readUInt8(?offset:Int):Int;
/**
Reads an unsigned 16-bit integer from `buf` at the specified `offset` with specified endian format
`readUInt16BE()` returns big endian, `readUInt16LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset
**/
function readUInt16BE(?offset:Int):Int;
/**
Reads an unsigned 16-bit integer from `buf` at the specified `offset` with specified endian format
(`readUInt16BE()` returns big endian, `readUInt16LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readuint16le_offset
**/
function readUInt16LE(?offset:Int):Int;
/**
Reads an unsigned 32-bit integer from `buf` at the specified `offset` with specified endian format
(`readUInt32BE()` returns big endian, `readUInt32LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readuint32be_offset
**/
function readUInt32BE(?offset:Int):Int;
/**
Reads an unsigned 32-bit integer from `buf` at the specified `offset` with specified endian format
(`readUInt32BE()` returns big endian, `readUInt32LE()` returns little endian).
@see https://nodejs.org/api/buffer.html#buffer_buf_readuint32be_offset
**/
function readUInt32LE(?offset:Int):Int;
/**
Returns a new `Buffer` that references the same memory as the original,
but offset and cropped by the `start` and `end` indices.
@see https://nodejs.org/api/buffer.html#buffer_buf_subarray_start_end
**/
#if haxe4
function subarray(?start:Int, ?end:Int):Buffer;
#else
override function subarray(start:Int, ?end:Int):Buffer;
#end
/**
Returns a new `Buffer` that references the same memory as the original,
but offset and cropped by the `start` and `end` indices.
@see https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end
**/
function slice(?start:Int, ?end:Int):Buffer;
/**
Interprets `buf` as an array of unsigned 16-bit integers and swaps the
byte order in-place. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length`
is not a multiple of 2.
@see https://nodejs.org/api/buffer.html#buffer_buf_swap16
**/
function swap16():Buffer;
/**
Interprets `buf` as an array of unsigned 32-bit integers and swaps the
byte order in-place. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length`
is not a multiple of 4.
@see https://nodejs.org/api/buffer.html#buffer_buf_swap32
**/
function swap32():Buffer;
/**
Interprets `buf` as an array of 64-bit numbers and swaps byte order in-place.
Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8.
@see https://nodejs.org/api/buffer.html#buffer_buf_swap64
**/
function swap64():Buffer;
/**
Returns a JSON representation of `buf`. `JSON.stringify()` implicitly calls
this function when stringifying a `Buffer` instance.
@see https://nodejs.org/api/buffer.html#buffer_buf_tojson
**/
function toJSON():Dynamic;
/**
Decodes `buf` to a string according to the specified character encoding in `encoding`.
`start` and `end` may be passed to decode only a subset of `buf`.
@see https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end
**/
@:overload(function(?encoding:String, ?start:Int, ?end:Int):String {})
function toString():String;
/**
Creates and returns an iterator for `buf` values (bytes). This function is called automatically
when a `Buffer` is used in a `for..of` statement.
@see https://nodejs.org/api/buffer.html#buffer_buf_values
**/
function values():js.node.Iterator<Int>;
/**
Writes `string` to `buf` at `offset` according to the character encoding in `encoding`.
The `length` parameter is the number of bytes to write.
If `buf` did not contain enough space to fit the entire `string`, only part of string will be written.
However, partially encoded characters will not be written.
@see https://nodejs.org/api/buffer.html#buffer_buf_write_string_offset_length_encoding
**/
function write(string:String, ?offset:Int, ?length:Int, ?encoding:String):Int;
// these functions need BigInt Implementation.
// /**
// Writes `value` to `buf` at the specified `offset` with specified endian format (`writeBigInt64BE()` writes big endian, `writeBigInt64LE()` writes little endian).
// @see https://nodejs.org/api/buffer.html#buffer_buf_writebigint64be_value_offset
// **/
// function writeBigInt64BE(value:Int, ?offset:Int):BigInt;
// /**
// Writes `value` to `buf` at the specified `offset` with specified endian format (`writeBigInt64BE()` writes big endian, `writeBigInt64LE()` writes little endian).
// @see https://nodejs.org/api/buffer.html#buffer_buf_writebigint64le_value_offset
// **/
// function writeBigInt64LE(value:Int, ?offset:Int):BigInt;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeDoubleBE()` writes big endian, `writeDoubleLE()` writes little endian).
`value` should be a valid 64-bit double. Behavior is undefined when `value` is anything other than a 64-bit double.
@see https://nodejs.org/api/buffer.html#buffer_buf_writedoublebe_value_offset
**/
function writeDoubleBE(value:Float, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeDoubleBE()` writes big endian, `writeDoubleLE()` writes little endian).
`value` should be a valid 64-bit double. Behavior is undefined when `value` is anything other than a 64-bit double.
@see https://nodejs.org/api/buffer.html#buffer_buf_writedoublele_value_offset
**/
function writeDoubleLE(value:Float, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeFloatBE()` writes big endian, `writeFloatLE()` writes little endian).
`value` should be a valid 32-bit float. Behavior is undefined when `value` is anything other than a 32-bit float.
@see https://nodejs.org/api/buffer.html#buffer_buf_writefloatbe_value_offset
**/
function writeFloatBE(value:Float, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeFloatBE()` writes big endian, `writeFloatLE()` writes little endian).
`value` should be a valid 32-bit float. Behavior is undefined when `value` is anything other than a 32-bit float.
@see https://nodejs.org/api/buffer.html#buffer_buf_writefloatle_value_offset
**/
function writeFloatLE(value:Float, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset`. `value` should be a valid signed 8-bit integer.
Behavior is undefined when `value` is anything other than a signed 8-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeint8_value_offset
**/
function writeInt8(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeInt16BE()` writes big endian, `writeInt16LE()` writes little endian).
`value` should be a valid signed 16-bit integer.
Behavior is undefined when value is anything other than a signed 16-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeint16be_value_offset
**/
function writeInt16BE(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeInt16BE()` writes big endian, `writeInt16LE()` writes little endian).
`value` should be a valid signed 16-bit integer.
Behavior is undefined when value is anything other than a signed 16-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeint16le_value_offset
**/
function writeInt16LE(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeInt32BE()` writes big endian, `writeInt32LE()` writes little endian).
`value` should be a valid signed 32-bit integer.
Behavior is undefined when `value` is anything other than a signed 32-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeint32be_value_offset
**/
function writeInt32BE(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeInt32BE()` writes big endian, `writeInt32LE()` writes little endian).
`value` should be a valid signed 32-bit integer.
Behavior is undefined when `value` is anything other than a signed 32-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeint32le_value_offset
**/
function writeInt32LE(value:Int, ?offset:Int):Void;
/**
Writes `byteLength` bytes of `value` to `buf` at the specified `offset`.
Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than a signed integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeintbe_value_offset_bytelength
**/
function writeIntBE(value:Int, offset:Int, byteLength:Int):Int;
/**
Writes `byteLength` bytes of `value` to `buf` at the specified `offset`.
Supports up to 48 bits of accuracy. Behavior is undefined when `value` is anything other than a signed integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeintle_value_offset_bytelength
**/
function writeIntLE(value:Int, offset:Int, byteLength:Int):Int;
/**
Writes `value` to `buf` at the specified `offset`. `value` should be a valid unsigned 8-bit integer.
Behavior is undefined when `value` is anything other than an unsigned 8-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeuint8_value_offset
**/
function writeUInt8(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeUInt16BE()` writes big endian, `writeUInt16LE()` writes little endian).
`value` should be a valid unsigned 16-bit integer.
Behavior is undefined when `value` is anything other than an unsigned 16-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeuint16be_value_offset
**/
function writeUInt16BE(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeUInt16BE()` writes big endian, `writeUInt16LE()` writes little endian).
`value` should be a valid unsigned 16-bit integer.
Behavior is undefined when `value` is anything other than an unsigned 16-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeuint16le_value_offset
**/
function writeUInt16LE(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeUInt32BE()` writes big endian, `writeUInt32LE()` writes little endian).
`value` should be a valid unsigned 32-bit integer.
Behavior is undefined when `value` is anything other than an unsigned 32-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeuint32be_value_offset
**/
function writeUInt32BE(value:Int, ?offset:Int):Void;
/**
Writes `value` to `buf` at the specified `offset` with specified endian format
(`writeUInt32BE()` writes big endian, `writeUInt32LE()` writes little endian).
`value` should be a valid unsigned 32-bit integer.
Behavior is undefined when `value` is anything other than an unsigned 32-bit integer.
@see https://nodejs.org/api/buffer.html#buffer_buf_writeuint32le_value_offset
**/
function writeUInt32LE(value:Int, ?offset:Int):Void;
/**
Default: `50`
Returns the maximum number of bytes that will be returned when `buf.inspect()` is called.
This can be overridden by user modules.
See `util.inspect()` for more details on `buf.inspect()` behavior.
This is a property on the `buffer` module returned by `require('buffer')`, not on the `Buffer` global or a `Buffer` instance.
@see https://nodejs.org/api/buffer.html#buffer_buffer_inspect_max_bytes
**/
static var INSPECT_MAX_BYTES(get, set):Int;
private static inline function get_INSPECT_MAX_BYTES():Int {
return BufferModule.INSPECT_MAX_BYTES;
}
private static inline function set_INSPECT_MAX_BYTES(bytes:Int):Int {
return BufferModule.INSPECT_MAX_BYTES = bytes;
}
/**
An alias for `buffer.constants.MAX_LENGTH`.
This is a property on the `buffer` module returned by `require('buffer')`, not on the `Buffer` global or a `Buffer` instance.
@see https://nodejs.org/api/buffer.html#buffer_buffer_kmaxlength
**/
static var kMaxLength(get, never):Int;
private static inline function get_kMaxLength():Int {
return BufferModule.kMaxLength;
}
/**
Re-encodes the given `Buffer` or `Uint8Array` instance from one character encoding to another.
Returns a new `Buffer` instance.
@see https://nodejs.org/api/buffer.html#buffer_buffer_transcode_source_fromenc_toenc
**/
static inline function transcode(source:Uint8Array, fromEnc:String, toEnc:String):Buffer {
return BufferModule.transcode(source, fromEnc, toEnc);
};
/**
`buffer.constants` is a property on the `buffer` module returned by `require('buffer')`,
not on the `Buffer` global or a `Buffer` instance.
@see https://nodejs.org/api/buffer.html#buffer_buffer_constants
**/
static var constants(default, never):BufferConstants;
private static inline function get_constants():BufferConstants {
return BufferModule.constants;
}
/**
Create `haxe.io.Bytes` object that uses the same underlying data storage as `this` buffer.
Any modifications done using the returned object will be reflected in the `this` buffer.
**/
inline function hxToBytes():Bytes {
return Helper.bytesOfBuffer(this);
}
/**
Create `Buffer` object from `haxe.io.Bytes` using the same underlying data storage.
Any modifications done using the returned object will be reflected in given `haxe.io.Bytes` object.
**/
static inline function hxFromBytes(b:Bytes):Buffer {
var data = @:privateAccess b.b;
return Buffer.from(data.buffer, data.byteOffset, b.length);
}
}
@:dce
private class Helper {
public static function bytesOfBuffer(b:Buffer):haxe.io.Bytes untyped {
var o = Object.create(haxe.io.Bytes.prototype);
// the following is basically a haxe.io.Bytes constructor,
// but using given buffer instead of creating new Uint8Array
o.length = b.byteLength;
o.b = b;
b.bufferValue = b;
b.hxBytes = o;
b.bytes = b;
return o;
}
}
@:jsRequire("buffer")
private extern class BufferModule {
static var INSPECT_MAX_BYTES:Int;
static var kMaxLength(default, never):Int;
static function transcode(source:Uint8Array, fromEnc:String, toEnc:String):Buffer;
static var constants(default, never):BufferConstants;
}
typedef BufferConstants = {
/**
On 32-bit architectures, this value is `(2^30)-1` (`~1GB`).
On 64-bit architectures, this value is `(2^31)-1` (`~2GB`).
@see https://nodejs.org/api/buffer.html#buffer_buffer_constants_max_length
**/
var MAX_LENGTH(default, never):Int;
/**
Represents the largest `length` that a `string` primitive can have, counted
in UTF-16 code units.
@see https://nodejs.org/api/buffer.html#buffer_buffer_constants_max_string_length
**/
var MAX_STRING_LENGTH(default, never):Int;
}

View File

@ -0,0 +1,52 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.buffer;
/**
Returns an un-pooled `Buffer`.
In order to avoid the garbage collection overhead of creating many individually allocated Buffer instances,
by default allocations under 4KB are sliced from a single larger allocated object.
This approach improves both performance and memory usage since v8 does not need to track
and cleanup as many Persistent objects.
In the case where a developer may need to retain a small chunk of memory from a pool
for an indeterminate amount of time, it may be appropriate to create an un-pooled `Buffer` instance
using `SlowBuffer` then copy out the relevant bits.
Use of `SlowBuffer` should be used only as a last resort after a developer has observed
undue memory retention in their applications.
**/
@:deprecated("SlowBuffer is deprecated, use Buffer.allocUnsafeSlow() instead")
@:jsRequire("buffer", "SlowBuffer")
extern class SlowBuffer extends Buffer {
/**
Allocates a new `SlowBuffer` of `size` bytes.
The `size` must be less than or equal to the value of `Buffer.kMaxLength`. Otherwise, a `RangeError` is thrown.
A zero-length Buffer will be created if size <= 0.
The underlying memory for `SlowBuffer` instances is not initialized. The contents of a newly created `SlowBuffer`
are unknown and could contain sensitive data. Use `buf.fill(0)` to initialize a `SlowBuffer` to zeroes.
**/
function new(size:Int);
}

View File

@ -0,0 +1,220 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.child_process;
import js.node.Stream;
import js.node.events.EventEmitter;
import js.node.stream.Readable;
import js.node.stream.Writable;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by `ChildProcess` objects.
**/
@:enum abstract ChildProcessEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when:
1. The process could not be spawned, or
2. The process could not be killed, or
3. Sending a message to the child process failed for whatever reason.
Note that the exit-event may or may not fire after an error has occured.
If you are listening on both events to fire a function, remember to guard against calling your function twice.
See also `ChildProcess.kill` and `ChildProcess.send`.
**/
var Error:ChildProcessEvent<Error->Void> = "error";
/**
This event is emitted after the child process ends.
Listener arguments:
code - the exit code, if it exited normally.
signal - the signal passed to kill the child process, if it was killed by the parent.
If the process terminated normally, `code` is the final exit code of the process, otherwise null.
If the process terminated due to receipt of a signal, `signal` is the string name of the signal, otherwise null.
Note that the child process stdio streams might still be open.
Also, note that node establishes signal handlers for 'SIGINT' and 'SIGTERM',
so it will not terminate due to receipt of those signals, it will exit.
See waitpid(2).
**/
var Exit:ChildProcessEvent<Int->String->Void> = "exit";
/**
This event is emitted when the stdio streams of a child process have all terminated.
This is distinct from `Exit`, since multiple processes might share the same stdio streams.
Listener arguments:
code - the exit code, if it exited normally.
signal - the signal passed to kill the child process, if it was killed by the parent.
**/
var Close:ChildProcessEvent<Int->String->Void> = "close";
/**
This event is emitted after calling the `disconnect` method in the parent or in the child.
After disconnecting it is no longer possible to send messages, and the `connected` property is false.
**/
var Disconnect:ChildProcessEvent<Void->Void> = "disconnect";
/**
Messages send by `send` are obtained using the message event.
This event can also be listened on the `process` object to receive messages from the parent.
Listener arguments:
message - a parsed JSON object or primitive value
sendHandle - a Socket or Server object
**/
var Message:ChildProcessEvent<Dynamic->Dynamic->Void> = "message";
}
typedef ChildProcessSendOptions = {
/**
Can be used when passing instances of `js.node.net.Socket`.
When true, the socket is kept open in the sending process.
Defaults to false.
**/
@:optional var keepOpen:Bool;
}
/**
An object representing a child process.
The `ChildProcess` class is not intended to be used directly. Use the spawn() or fork() module methods
to create a `ChildProcess` instance.
**/
extern class ChildProcess extends EventEmitter<ChildProcess> {
/**
A Writable Stream that represents the child process's stdin.
Closing this stream via `end` often causes the child process to terminate.
If the child stdio streams are shared with the parent, then this will not be set.
**/
var stdin(default, null):IWritable;
/**
A Readable Stream that represents the child process's stdout.
If the child stdio streams are shared with the parent, then this will not be set.
**/
var stdout(default, null):IReadable;
/**
A Readable Stream that represents the child process's stderr.
If the child stdio streams are shared with the parent, then this will not be set.
**/
var stderr(default, null):IReadable;
/**
The parent end of the stdio pipes.
**/
var stdio(default, null):Array<IStream>;
/**
The PID of the child process.
**/
var pid(default, null):Int;
/**
Set to false after `disconnect' is called
If `connected` is false, it is no longer possible to send messages.
**/
var connected(default, null):Bool;
/**
Send a signal to the child process.
If no argument is given, the process will be sent 'SIGTERM'.
See signal(7) for a list of available signals.
May emit an 'error' event when the signal cannot be delivered.
Sending a signal to a child process that has already exited is not an error
but may have unforeseen consequences: if the PID (the process ID) has been reassigned to another process,
the signal will be delivered to that process instead. What happens next is anyone's guess.
Note that while the function is called `kill`, the signal delivered to the child process may not actually kill it.
`kill` really just sends a signal to a process. See kill(2)
**/
function kill(?signal:String):Void;
/**
When using `fork` you can write to the child using `send` and messages are received by a 'message' event on the child.
In the child the `Process` object will have a `send` method, and process will emit objects each time it receives
a message on its channel.
Please note that the `send` method on both the parent and child are synchronous - sending large chunks of data is
not advised (pipes can be used instead, see `spawn`).
There is a special case when sending a {cmd: 'NODE_foo'} `message`. All messages containing a `NODE_` prefix in
its cmd property will not be emitted in the 'message' event, since they are internal messages used by node core.
Messages containing the prefix are emitted in the 'internalMessage' event, you should by all means avoid using
this feature, it is subject to change without notice.
The `sendHandle` option is for sending a TCP server or socket object to another process.
The child will receive the object as its second argument to the message event.
The `callback` option is a function that is invoked after the message is sent but before the target may have received it.
It is called with a single argument: null on success, or an `Error` object on failure.
Emits an 'error' event if the message cannot be sent, for example because the child process has already exited.
Returns true under normal circumstances or false when the backlog of unsent messages exceeds a threshold that
makes it unwise to send more. Use the callback mechanism to implement flow control.
**/
@:overload(function(message:Dynamic, sendHandle:Dynamic, options:ChildProcessSendOptions, ?callback:Error->Void):Bool {})
@:overload(function(message:Dynamic, sendHandle:Dynamic, ?callback:Error->Void):Bool {})
function send(message:Dynamic, ?callback:Error->Void):Bool;
/**
Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other
connections keeping it alive.
After calling this method the `connected` flag will be set to false in both the parent and child,
and it is no longer possible to send messages.
The 'disconnect' event will be emitted when there are no messages in the process of being received,
most likely immediately.
Note that you can also call `process.disconnect` in the child process.
**/
function disconnect():Void;
/**
By default, the parent will wait for the detached child to exit.
To prevent the parent from waiting for a given child, use the `unref` method,
and the parent's event loop will not include the child in its reference count.
**/
function unref():Void;
}

View File

@ -0,0 +1,124 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.cluster;
import js.node.Cluster.ListeningEventAddress;
import js.node.child_process.ChildProcess;
import js.node.events.EventEmitter;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
@:enum abstract WorkerEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
var Message:WorkerEvent<Dynamic->Dynamic->Void> = "message";
var Online:WorkerEvent<Void->Void> = "online";
var Listening:WorkerEvent<ListeningEventAddress->Void> = "listening";
var Disconnect:WorkerEvent<Void->Void> = "disconnect";
var Exit:WorkerEvent<Int->String->Void> = "exit";
var Error:WorkerEvent<Error->Void> = "error";
}
/**
A Worker object contains all public information and method about a worker.
In the master it can be obtained using `Cluster.workers`.
In a worker it can be obtained using `Cluster.worker`.
**/
extern class Worker extends EventEmitter<Worker> {
/**
Each new worker is given its own unique id, this id is stored in the `id`.
While a worker is alive, this is the key that indexes it in `Cluster.workers`
**/
var id(default, null):String;
/**
All workers are created using `ChildProcess.fork`, the returned object from this function is stored as `process`.
In a worker, the global process is stored.
Note that workers will call `process.exit(0)` if the 'disconnect' event occurs on process
and `suicide` is not true. This protects against accidental disconnection.
**/
var process:ChildProcess;
/**
Set by calling `kill` or `disconnect`, until then it is undefined.
Lets you distinguish between voluntary and accidental exit, the master may choose
not to respawn a worker based on this value.
(an alias to `exitedAfterDisconnect` in newer node.js versions)
**/
var suicide:Null<Bool>;
/**
Set by calling `kill` or `disconnect`. Until then, it is undefined.
Lets you distinguish between voluntary and accidental exit, the master may choose
not to respawn a worker based on this value.
**/
var exitedAfterDisconnect:Null<Bool>;
/**
This function is equal to the `send` methods provided by `ChildProcess.fork`.
In the master you should use this function to send a `message` to a specific worker.
In a worker you can also use `process.send`, it is the same function.
**/
@:overload(function(message:Dynamic, sendHandle:Dynamic, ?callback:Error->Void):Bool {})
function send(message:Dynamic, ?callback:Error->Void):Bool;
/**
This function will kill the worker. In the master, it does this by disconnecting the `worker.process`,
and once disconnected, killing with `signal`. In the worker, it does it by disconnecting the channel,
and then exiting with code 0.
Causes `suicide` to be set.
**/
function kill(?signal:String):Void;
/**
In a worker, this function will close all servers, wait for the 'close' event on those servers,
and then disconnect the IPC channel.
In the master, an internal message is sent to the worker causing it to call `disconnect` on itself.
Causes `suicide` to be set.
**/
function disconnect():Void;
/**
This function returns true if the worker is connected to its master via its IPC channel, false otherwise
A worker is connected to its master after it's been created.
It is disconnected after the 'disconnect' event is emitted.
**/
function isConnected():Bool;
/**
This function returns true if the worker's process has terminated (either because of exiting or being signaled).
Otherwise, it returns false.
**/
function isDead():Bool;
}

View File

@ -0,0 +1,262 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.console;
import haxe.extern.EitherType;
import haxe.extern.Rest;
import js.node.stream.Writable;
/**
The `Console` class can be used to create a simple logger with configurable output streams
and can be accessed using either `require('console').Console` or `console.Console` (or their destructured counterparts):
@see https://nodejs.org/api/console.html#console_class_console
**/
@:jsRequire("console", "Console")
extern class Console {
/**
Creates a new `Console` with one or two writable stream instances. `stdout` is a writable stream to print log or info output.
`stderr` is used for warning or error output. If `stderr` is not provided, `stdout` is used for stderr.
@see https://nodejs.org/api/console.html#console_new_console_stdout_stderr_ignoreerrors
**/
@:overload(function(options:ConsoleOptions):Void {})
function new(stdout:IWritable, ?stderr:IWritable, ?ignoreerrors:Bool):Void;
/**
A simple assertion test that verifies whether `value` is truthy. If it is not, `Assertion` failed is logged.
If provided, the error `message` is formatted using `util.format()` by passing along all message arguments. The output is used as the error message.
@see https://nodejs.org/api/console.html#console_console_assert_value_message
**/
function assert(value:Dynamic, message:Rest<Dynamic>):Void;
/**
When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. When `stdout` is not a TTY, this method does nothing.
@see https://nodejs.org/api/console.html#console_console_clear
**/
function clear():Void;
/**
Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`.
@see https://nodejs.org/api/console.html#console_console_count_label
**/
function count(?label:String):Void;
/**
Resets the internal counter specific to `label`.
@see https://nodejs.org/api/console.html#console_console_countreset_label
**/
function countReset(?label:String):Void;
/**
The `console.debug()` function is an alias for `console.log()`.
@see https://nodejs.org/api/console.html#console_console_debug_data_args
**/
function debug(data:Dynamic, args:Rest<Dynamic>):Void;
/**
Uses util.inspect() on `obj` and prints the resulting string to `stdout`. This function bypasses any custom `inspect()` function defined on `obj`.
@see https://nodejs.org/api/console.html#console_console_dir_obj_options
**/
function dir(obj:Dynamic, ?options:Util.InspectOptionsBase):Void;
/**
This method calls `console.log()` passing it the arguments received. This method does not produce any XML formatting.
@see https://nodejs.org/api/console.html#console_console_dirxml_data
**/
function dirxml(data:Rest<Dynamic>):Void;
/**
Prints to `stderr` with newline. Multiple arguments can be passed,
with the first used as the primary message and all additional used as substitution values similar to printf(3)
(the arguments are all passed to util.format()).
@see https://nodejs.org/api/console.html#console_console_error_data_args
**/
function error(data:Dynamic, args:Rest<Dynamic>):Void;
/**
If one or more `label`s are provided, those are printed first without the additional indentation.
@see https://nodejs.org/api/console.html#console_console_group_label
**/
function group(label:Rest<Dynamic>):Void;
/**
An alias for console.group().
@see https://nodejs.org/api/console.html#console_console_groupcollapsed
**/
function groupCollapsed():Void;
/**
Decreases indentation of subsequent lines by two spaces.
@see https://nodejs.org/api/console.html#console_console_groupend
**/
function groupEnd():Void;
/**
The `console.info()` function is an alias for console.log().
@see https://nodejs.org/api/console.html#console_console_info_data_args
**/
function info(data:Dynamic, args:Rest<Dynamic>):Void;
/**
Prints to `stdout` with newline. Multiple arguments can be passed,
with the first used as the primary message and all additional used as substitution values similar to printf(3)
(the arguments are all passed to util.format()).
@see https://nodejs.org/api/console.html#console_console_log_data_args
**/
function log(data:Dynamic, args:Rest<Dynamic>):Void;
/**
Try to construct a table with the columns of the properties of `tabularData` (or use `properties`)
and rows of `tabularData` and log it. Falls back to just logging the argument if it cant be parsed as tabular.
@see https://nodejs.org/api/console.html#console_console_table_tabulardata_properties
**/
function table(tabularData:Dynamic, ?properties:Array<String>):Void;
/**
Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`.
Use the same `label` when calling console.timeEnd() to stop the timer and output the elapsed time in milliseconds to `stdout`.
Timer durations are accurate to the sub-millisecond.
@see https://nodejs.org/api/console.html#console_console_time_label
**/
function time(?label:String):Void;
/**
Stops a timer that was previously started by calling console.time() and prints the result to `stdout`:
@see https://nodejs.org/api/console.html#console_console_timeend_label
**/
function timeEnd(?label:String):Void;
/**
For a timer that was previously started by calling console.time(), prints the elapsed time and other `data` arguments to `stdout`:
@see https://nodejs.org/api/console.html#console_console_timelog_label_data
**/
function timeLog(?label:String, data:Rest<Dynamic>):Void;
/**
Prints to `stderr` the string `'Trace: '`, followed by the util.format() formatted message and stack trace to the current position in the code.
@see https://nodejs.org/api/console.html#console_console_trace_message_args
**/
function trace(message:Dynamic, args:Rest<Dynamic>):Void;
/**
The `console.warn()` function is an alias for console.error().
@see https://nodejs.org/api/console.html#console_console_warn_data_args
**/
function warn(data:Dynamic, args:Rest<Dynamic>):Void;
/**
This method does not display anything unless used in the inspector. The `console.markTimeline()` method is the deprecated form of console.timeStamp().
@see https://nodejs.org/api/console.html#console_console_marktimeline_label
**/
function markTimeline(?label:String):Void;
/**
This method does not display anything unless used in the inspector.
The `console.profile()` method starts a JavaScript CPU profile with an optional label until console.profileEnd() is called.
The profile is then added to the Profile panel of the inspector.
@see https://nodejs.org/api/console.html#console_console_profile_label
**/
function profile(?label:String):Void;
/**
This method does not display anything unless used in the inspector.
Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector.
See console.profile() for an example.
@see https://nodejs.org/api/console.html#console_console_profileend_label
**/
function profileEnd(?label:String):Void;
/**
This method does not display anything unless used in the inspector.
The `console.timeStamp()` method adds an event with the label `'label'` to the Timeline panel of the inspector.
@see https://nodejs.org/api/console.html#console_console_timestamp_label
**/
function timeStamp(?label:String):Void;
/**
This method does not display anything unless used in the inspector. The `console.timeline()` method is the deprecated form of console.time().
@see https://nodejs.org/api/console.html#console_console_timeline_label
**/
function timeline(?label:String):Void;
/**
This method does not display anything unless used in the inspector. The `console.timelineEnd()` method is the deprecated form of console.timeEnd().
@see https://nodejs.org/api/console.html#console_console_timelineend_label
**/
function timelineEnd(?label:String):Void;
}
typedef ConsoleOptions = {
/**
`stdout` is a writable stream to print log or info output.
**/
var stdout:IWritable;
/**
`stderr` is used for warning or error output. If stderr is not provided, stdout is used for stderr.
**/
@optional var stderr:IWritable;
/**
Ignore errors when writing to the underlying streams. Default: `true`.
**/
@optional var ignoreErrors:Bool;
/**
Set color support for this `Console` instance. Setting to `true` enables coloring while inspecting values,
setting to `'auto'` will make color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream.
This option can not be used, if `inspectOptions.colors` is set as well. Default: `'auto'`.
**/
@optional var colorMode:EitherType<Bool, String>;
/**
Specifies options that are passed along to util.inspect().
**/
@optional var inspectOptions:Util.InspectOptions;
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import js.node.Buffer;
/**
SPKAC is a Certificate Signing Request mechanism originally implemented by Netscape
and now specified formally as part of HTML5's keygen element.
**/
@:jsRequire("crypto", "Certificate")
extern class Certificate {
function new();
/**
Returns the challenge component in the form of a Node.js `Buffer`.
The `spkac` data structure includes a public key and a challenge.
**/
@:overload(function(spkac:String):Buffer {})
function exportChallenge(spkac:Buffer):Buffer;
/**
Returns the public key component in the form of a Node.js `Buffer`.
The `spkac` data structure includes a public key and a challenge.
**/
@:overload(function(spkac:String):Buffer {})
function exportPublicKey(spkac:Buffer):Buffer;
/**
Returns true if the given `spkac` data structure is valid, false otherwise.
**/
function verifySpkac(spkac:Buffer):Bool;
}

View File

@ -0,0 +1,84 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import js.node.Buffer;
/**
Class for encrypting data.
Returned by `Crypto.createCipher` and `Crypto.createCipheriv`.
Cipher objects are streams that are both readable and writable.
The written plain text data is used to produce the encrypted data on the readable side.
The legacy `update` and `final` methods are also supported.
**/
extern class Cipher extends js.node.stream.Transform<Cipher> {
/**
Updates the cipher with `data`, the encoding of which is given in `input_encoding`
and can be 'utf8', 'ascii' or 'binary'. If no encoding is provided, then a buffer is expected.
If data is a Buffer then `input_encoding` is ignored.
The `output_encoding` specifies the output format of the enciphered data,
and can be 'binary', 'base64' or 'hex'. If no encoding is provided, then a buffer is returned.
Returns the enciphered contents, and can be called many times with new data as it is streamed.
**/
@:overload(function(data:Buffer):Buffer {})
@:overload(function(data:String, input_encoding:String):Buffer {})
function update(data:String, input_encoding:String, output_encoding:String):String;
/**
Returns any remaining enciphered contents, with `output_encoding` being one of: 'binary', 'base64' or 'hex'.
If no encoding is provided, then a buffer is returned.
Note: cipher object can not be used after `final` method has been called.
**/
@:native("final") @:overload(function():Buffer {})
function finalContents(output_encoding:String):String;
/**
You can disable automatic padding of the input data to block size.
If `auto_padding` is false, the length of the entire input data
must be a multiple of the cipher's block size or `final` will fail.
Useful for non-standard padding, e.g. using 0x0 instead of PKCS padding.
You must call this before `final`.
**/
@:overload(function():Void {})
function setAutoPadding(auto_padding:Bool):Void;
/**
For authenticated encryption modes (currently supported: GCM), this method returns a `Buffer`
that represents the authentication tag that has been computed from the given data.
Should be called after encryption has been completed using the `final` method!
**/
function getAuthTag():Buffer;
/**
For authenticated encryption modes (currently supported: GCM), this method sets the value
used for the additional authenticated data (AAD) input parameter.
**/
function setAAD(buffer:Buffer):Void;
}

View File

@ -0,0 +1,83 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import js.node.Buffer;
/**
Class for decrypting data.
Returned by `Crypto.createDecipher` and `Crypto.createDecipheriv`.
Decipher objects are streams that are both readable and writable.
The written enciphered data is used to produce the plain-text data on the the readable side.
The legacy `update` and `final` methods are also supported.
**/
extern class Decipher extends js.node.stream.Transform<Decipher> {
/**
Updates the decipher with `data`, which is encoded in 'binary', 'base64' or 'hex'.
If no encoding is provided, then a buffer is expected.
The `output_decoding` specifies in what format to return the deciphered plaintext: 'binary', 'ascii' or 'utf8'.
If no encoding is provided, then a buffer is returned.
**/
@:overload(function(data:Buffer):Buffer {})
@:overload(function(data:String, input_encoding:String):Buffer {})
function update(data:String, input_encoding:String, output_encoding:String):String;
/**
Returns any remaining plaintext which is deciphered,
with `output_encoding` being one of: 'binary', 'ascii' or 'utf8'.
If no encoding is provided, then a buffer is returned.
Note: decipher object can not be used after `final` method has been called.
**/
@:native("final") @:overload(function():Buffer {})
function finalContents(output_encoding:String):String;
/**
You can disable auto padding if the data has been encrypted without standard block padding
to prevent `final` from checking and removing it.
Can only work if the input data's length is a multiple of the ciphers block size.
You must call this before streaming data to `update`.
**/
@:overload(function():Void {})
function setAutoPadding(auto_padding:Bool):Void;
/**
For authenticated encryption modes (currently supported: GCM), this method must be used
to pass in the received authentication tag. If no tag is provided or if the ciphertext
has been tampered with, `final` will throw, thus indicating that the ciphertext should be
discarded due to failed authentication.
**/
function setAuthTag(buffer:Buffer):Void;
/**
For authenticated encryption modes (currently supported: GCM), this method sets the value
used for the additional authenticated data (AAD) input parameter.
**/
function setAAD(buffer:Buffer):Void;
}

View File

@ -0,0 +1,121 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import js.node.Buffer;
/**
Common interface for `DiffieHellman` and a mimic object returned by `Crypto.getDiffieHellman`.
See `DiffieHellman` documentation.
**/
@:remove
extern interface IDiffieHellman {
@:overload(function():Buffer {})
function generateKeys(encoding:String):String;
@:overload(function(other_public_key:Buffer):Buffer {})
@:overload(function(other_public_key:String, input_encoding:String):Buffer {})
function computeSecret(other_public_key:String, input_encoding:String, output_encoding:String):String;
@:overload(function():Buffer {})
function getPrime(encoding:String):String;
@:overload(function():Buffer {})
function getGenerator(encoding:String):String;
@:overload(function():Buffer {})
function getPublicKey(encoding:String):String;
@:overload(function():Buffer {})
function getPrivateKey(encoding:String):String;
}
/**
The class for creating Diffie-Hellman key exchanges.
Returned by `Crypto.createDiffieHellman`.
**/
extern class DiffieHellman implements IDiffieHellman {
/**
Generates private and public Diffie-Hellman key values, and returns the public key in the specified `encoding`.
This key should be transferred to the other party. `encoding` can be 'binary', 'hex', or 'base64'.
**/
@:overload(function():Buffer {})
function generateKeys(encoding:String):String;
/**
Computes the shared secret using `other_public_key` as the other party's public key
and returns the computed shared secret.
Supplied key is interpreted using specified `input_encoding`,
and secret is encoded using specified `output_encoding`.
Encodings can be 'binary', 'hex', or 'base64'.
If the input encoding is not provided, then a buffer is expected.
**/
@:overload(function(other_public_key:Buffer):Buffer {})
@:overload(function(other_public_key:String, input_encoding:String):Buffer {})
function computeSecret(other_public_key:String, input_encoding:String, output_encoding:String):String;
/**
Returns the Diffie-Hellman prime in the specified encoding, which can be 'binary', 'hex', or 'base64'.
If no encoding is provided, then a buffer is returned.
**/
@:overload(function():Buffer {})
function getPrime(encoding:String):String;
/**
Returns the Diffie-Hellman generator in the specified encoding, which can be 'binary', 'hex', or 'base64'.
If no encoding is provided, then a buffer is returned.
**/
@:overload(function():Buffer {})
function getGenerator(encoding:String):String;
/**
Returns the Diffie-Hellman public key in the specified encoding, which can be 'binary', 'hex', or 'base64'.
If no encoding is provided, then a buffer is returned.
**/
@:overload(function():Buffer {})
function getPublicKey(encoding:String):String;
/**
Returns the Diffie-Hellman private key in the specified encoding, which can be 'binary', 'hex', or 'base64'.
If no encoding is provided, then a buffer is returned.
**/
@:overload(function():Buffer {})
function getPrivateKey(encoding:String):String;
/**
Sets the Diffie-Hellman public key. Key encoding can be 'binary', 'hex' or 'base64'.
If no `encoding` is provided, then a `Buffer` is expected.
**/
@:overload(function(public_key:Buffer):Void {})
function setPublicKey(public_key:String, encoding:String):Void;
/**
Sets the Diffie-Hellman private key. Key encoding can be 'binary', 'hex' or 'base64'.
If no `encoding` is provided, then a `Buffer` is expected.
**/
@:overload(function(private_key:Buffer):Void {})
function setPrivateKey(private_key:String, encoding:String):Void;
}

View File

@ -0,0 +1,99 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import haxe.extern.EitherType;
import js.node.Buffer;
@:enum abstract ECDHFormat(String) from String to String {
var Compressed = "compressed";
var Uncompressed = "uncompressed";
var Hybrid = "hybrid";
}
/**
The class for creating EC Diffie-Hellman key exchanges.
Returned by `Crypto.createECDH`.
**/
extern class ECDH {
/**
Generates private and public EC Diffie-Hellman key values, and returns the public key
in the specified `format` and `encoding`. This key should be transferred to the other party.
Format specifies point encoding and can be 'compressed', 'uncompressed', or 'hybrid'.
If no format is provided - the point will be returned in 'uncompressed' format.
Encoding can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.
**/
function generateKeys(?encoding:String, ?format:ECDHFormat):EitherType<String, Buffer>;
/**
Computes the shared secret using `other_public_key` as the other party's public key
and returns the computed shared secret. Supplied key is interpreted using specified `input_encoding`,
and secret is encoded using specified `output_encoding`.
Encodings can be 'binary', 'hex', or 'base64'.
If the input encoding is not provided, then a buffer is expected.
If no output encoding is given, then a buffer is returned.
**/
@:overload(function(other_public_key:String, input_encoding:String, output_encoding:String):String {})
@:overload(function(other_public_key:String, input_encoding:String):Buffer {})
function computeSecret(other_public_key:Buffer):Buffer;
/**
Returns the EC Diffie-Hellman public key in the specified `encoding` and `format`.
Format specifies point encoding and can be 'compressed', 'uncompressed', or 'hybrid'.
If no format is provided - the point will be returned in 'uncompressed' format.
Encoding can be 'binary', 'hex', or 'base64'. If no encoding is provided, then a buffer is returned.
**/
function getPublicKey(?encoding:String, ?format:ECDHFormat):EitherType<String, Buffer>;
/**
Returns the EC Diffie-Hellman private key in the specified encoding, which can be 'binary', 'hex', or 'base64'.
If no `encoding` is provided, then a buffer is returned.
**/
@:overload(function():Buffer {})
function getPrivateKey(encoding:String):String;
/**
Sets the EC Diffie-Hellman public key.
Key encoding can be 'binary', 'hex' or 'base64'.
If no encoding is provided, then a buffer is expected.
**/
@:overload(function(public_key:Buffer):Void {})
function setPublicKey(public_key:String, encoding:String):Void;
/**
Sets the EC Diffie-Hellman private key.
Key encoding can be 'binary', 'hex' or 'base64'.
If no encoding is provided, then a buffer is expected.
**/
@:overload(function(private_key:Buffer):Void {})
function setPrivateKey(private_key:String, encoding:String):Void;
}

View File

@ -0,0 +1,60 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import js.node.Buffer;
/**
The class for creating hash digests of data.
It is a stream that is both readable and writable.
The written data is used to compute the hash.
Once the writable side of the stream is ended, use the `read` method to get the computed hash digest.
The legacy `update` and `digest` methods are also supported.
Returned by `Crypto.createHash`.
**/
extern class Hash extends js.node.stream.Transform<Hash> {
/**
Updates the hash content with the given `data`,
the `encoding` of which is given in `input_encoding` and can be 'utf8', 'ascii' or 'binary'.
If no `encoding` is provided and the input is a string an encoding of 'binary' is enforced.
If `data` is a `Buffer` then `input_encoding` is ignored.
This can be called many times with new data as it is streamed.
**/
@:overload(function(data:Buffer):Hash {})
function update(data:String, ?input_encoding:String):Hash;
/**
Calculates the digest of all of the passed data to be hashed.
The `encoding` can be 'hex', 'binary' or 'base64'.
If no `encoding` is provided, then a buffer is returned.
Note: hash object can not be used after `digest` method has been called.
**/
@:overload(function():Buffer {})
function digest(encoding:String):String;
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import js.node.Buffer;
/**
Class for creating cryptographic hmac content.
It is a stream that is both readable and writable. The written data is used to compute the hmac.
Once the writable side of the stream is ended, use the `read` method to get the computed digest.
The legacy `update` and `digest` methods are also supported.
Returned by `Crypto.createHmac`.
**/
extern class Hmac extends js.node.stream.Transform<Hmac> {
/**
Update the hmac content with the given data.
This can be called many times with new data as it is streamed.
**/
@:overload(function(data:Buffer):Hmac {})
function update(data:String, ?input_encoding:String):Hmac;
/**
Calculates the digest of all of the passed data to the hmac.
The `encoding` can be 'hex', 'binary' or 'base64'.
If no `encoding` is provided, then a buffer is returned.
Note: hmac object can not be used after `digest` method has been called.
**/
@:overload(function():Buffer {})
function digest(encoding:String):String;
}

View File

@ -0,0 +1,57 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import haxe.extern.EitherType;
import js.node.Buffer;
import js.node.stream.Writable;
/**
Class for generating signatures.
Returned by `Crypto.createSign`.
Sign objects are writable streams. The written data is used to generate the signature.
Once all of the data has been written, the sign method will return the signature.
The legacy `update` method is also supported.
**/
extern class Sign extends Writable<Sign> {
/**
Updates the sign object with data.
This can be called many times with new data as it is streamed.
**/
@:overload(function(data:Buffer):Void {})
function update(data:String, ?encoding:String):Void;
/**
Calculates the signature on all the updated data passed through the sign.
`private_key` is a string containing the PEM encoded private key for signing.
Returns the signature in `output_format` which can be 'binary', 'hex' or 'base64'.
If no encoding is provided, then a buffer is returned.
Note: sign object can not be used after `sign` method has been called.
**/
@:overload(function(private_key:EitherType<String, {key:String, passphrase:String}>):Buffer {})
function sign(private_key:EitherType<String, {key:String, passphrase:String}>, output_format:String):String;
}

View File

@ -0,0 +1,60 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.crypto;
import js.node.Buffer;
import js.node.stream.Writable;
/**
Class for verifying signatures.
Returned by `Crypto.createVerify`.
Verify objects are writable streams. The written data is used to validate against the supplied signature.
Once all of the data has been written, the verify method will return true if the supplied signature is valid.
The legacy `update` method is also supported.
**/
extern class Verify extends Writable<Sign> {
/**
Updates the verifier object with data. This can be called many times with new data as it is streamed.
**/
@:overload(function(data:Buffer):Void {})
function update(data:String, ?encoding:String):Void;
/**
Verifies the signed data by using the object and signature.
`object` is a string containing a PEM encoded object, which can be one of RSA public key,
DSA public key, or X.509 certificate.
`signature` is the previously calculated signature for the data,
in the `signature_format` which can be 'binary', 'hex' or 'base64'.
If no encoding is specified, then a buffer is expected.
Returns true or false depending on the validity of the signature for the data and public key.
Note: verifier object can not be used after `verify` method has been called.
**/
@:overload(function(object:String, signature:Buffer):Bool {})
function verify(object:String, signature:String, signature_format:String):Bool;
}

View File

@ -0,0 +1,230 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.dgram;
import js.node.events.EventEmitter;
import js.node.net.Socket.SocketAdress;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events for the `Socket` object.
**/
@:enum abstract SocketEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when a new datagram is available on a socket.
Listener arguments:
msg - received data
rinfo - sender's address information and the number of bytes in the datagram
**/
var Message:SocketEvent<MessageListener> = "message";
/**
Emitted when a socket starts listening for datagrams.
This happens as soon as UDP sockets are created.
**/
var Listening:SocketEvent<Void->Void> = "listening";
/**
Emitted when a socket is closed with `close`.
No new message events will be emitted on this socket.
**/
var Close:SocketEvent<Void->Void> = "close";
/**
Emitted when an error occurs.
**/
var Error:SocketEvent<Error->Void> = "error";
}
/**
Remote address information for the `SocketEvent.Message` event.
**/
typedef MessageRemoteInfo = {
> SocketAdress,
/**
The message size.
**/
var size:Int;
}
typedef MessageListener = Buffer->MessageRemoteInfo->Void;
/**
Enumeration of possible datagram socket types
**/
@:enum abstract SocketType(String) from String to String {
var Udp4 = "udp4";
var Udp6 = "udp6";
}
/**
Options passed to the Socket consturctor.
**/
typedef SocketOptions = {
/**
Type of the socket. Either udp4 or udp6.
**/
var type:SocketType;
/**
When true, `Socket.bind` will reuse the address, even if another process has already bound a socket on it.
Defaults to false.
**/
@:optional var reuseAddr:Bool;
}
/**
Options for `Socket.bind` method.
**/
typedef SocketBindOptions = {
var port:Int;
@:optional var address:String;
/**
If false (default), then cluster workers will use the same underlying handle, allowing connection handling
duties to be shared. When true, the handle is not shared, and attempted port sharing results in an error.
**/
@:optional var exclusive:Bool;
}
/**
Encapsulates the datagram functionality.
It should be created via `Dgram.createSocket`.
**/
@:jsRequire("dgram", "Socket")
extern class Socket extends EventEmitter<Socket> {
@:overload(function(type:SocketType, ?callback:MessageListener):Void {})
private function new(options:SocketOptions, ?callback:MessageListener);
/**
The destination `port` and `address` must be specified.
A string may be supplied for the `address` parameter, and it will be resolved with DNS.
If the `address` is omitted or is an empty string, '0.0.0.0' or '::0' is used instead.
Depending on the network configuration, those defaults may or may not work; it's best to be
explicit about the destination address.
If the socket has not been previously bound with a call to `bind`, it gets assigned a random
port number and is bound to the "all interfaces" address ('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)
An optional `callback` may be specified to detect DNS errors or for determining when it's safe
to reuse the buf object. Note that DNS lookups delay the time to send for at least one tick.
The only way to know for sure that the datagram has been sent is by using a `callback`.
**/
function send(buf:Buffer, offset:Int, length:Int, port:Int, address:String, ?callback:Error->Int->Void):Void;
/**
Listen for datagrams on a named `port` and optional `address`.
If `port` is not specified, the OS will try to bind to a random port.
If `address` is not specified, the OS will try to listen on all addresses.
After binding is done, a "listening" event is emitted and the `callback` (if specified) is called.
Specifying both a "listening" event listener and `callback` is not harmful but not very useful.
A bound datagram socket keeps the node process running to receive datagrams.
If binding fails, an "error" event is generated. In rare case (e.g. binding a closed socket),
an `Error` may be thrown by this method.
**/
@:overload(function(options:SocketBindOptions, ?callback:Void->Void):Void {})
@:overload(function(port:Int, address:String, ?callback:Void->Void):Void {})
@:overload(function(port:Int, ?callback:Void->Void):Void {})
function bind(?callback:Void->Void):Void;
/**
Close the underlying socket and stop listening for data on it.
If a `callback` is provided, it is added as a listener for the 'close' event.
**/
function close(?callback:Void->Void):Void;
/**
Returns an object containing the address information for a socket.
**/
function address():SocketAdress;
/**
Sets or clears the SO_BROADCAST socket option.
When this option is set, UDP packets may be sent to a local interface's broadcast address.
**/
function setBroadcast(flag:Bool):Void;
/**
Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it specifies
the number of IP hops that a packet is allowed to go through. Each router or gateway that forwards
a packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
Changing TTL values is typically done for network probes or when multicasting.
The argument to `setTTL` is a number of hops between 1 and 255. The default on most systems is 64.
**/
function setTTL(ttl:Int):Void;
/**
Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this context it specifies
the number of IP hops that a packet is allowed to go through, specifically for multicast traffic.
Each router or gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a router,
it will not be forwarded.
The argument to `setMulticastTTL` is a number of hops between 0 and 255. The default on most systems is 1.
**/
function setMulticastTTL(ttl:Int):Void;
/**
Sets or clears the IP_MULTICAST_LOOP socket option.
When this option is set, multicast packets will also be received on the local interface.
**/
function setMulticastLoopback(flag:Bool):Void;
/**
Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.
If `multicastInterface` is not specified, the OS will try to add membership to all valid interfaces.
**/
function addMembership(multicastAddress:String, ?multicastInterface:String):Void;
/**
Opposite of `addMembership` - tells the kernel to leave a multicast group with IP_DROP_MEMBERSHIP socket option.
This is automatically called by the kernel when the socket is closed or process terminates,
so most apps will never need to call this.
If `multicastInterface` is not specified, the OS will try to drop membership to all valid interfaces.
**/
function dropMembership(multicastAddress:String, ?multicastInterface:String):Void;
/**
Calling `unref` on a socket will allow the program to exit if this is the only active socket in the event system.
If the socket is already `unref`d calling `unref` again will have no effect.
**/
function unref():Void;
/**
Opposite of `unref`, calling `ref` on a previously `unref`d socket will not let
the program exit if it's the only socket left (the default behavior).
If the socket is `ref`d calling `ref` again will have no effect.
**/
function ref():Void;
}

View File

@ -0,0 +1,170 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.domain;
import haxe.Constraints.Function;
import js.node.Timers.Timeout;
import js.node.events.EventEmitter;
/**
Enumeration of events emitted by `Domain` objects.
**/
@:deprecated
@:enum abstract DomainEvent<T:Function>(Event<T>) to Event<T> {
var Error:DomainEvent<DomainError->Void> = "error";
var Dispose:DomainEvent<Void->Void> = "dispose";
}
/**
Any time an Error object is routed through a domain, a few extra fields are added to it.
**/
@:deprecated
typedef DomainError = {
/**
The domain that first handled the error.
**/
var domain:Domain;
/**
The event emitter that emitted an 'error' event with the error object.
**/
var domainEmitter:IEventEmitter;
/**
The callback function which was bound to the domain, and passed an error as its first argument.
**/
var domainBound:Function;
/**
A boolean indicating whether the error was thrown, emitted, or passed to a bound callback function.
**/
var domainThrown:Bool;
}
/**
The Domain class encapsulates the functionality of routing errors
and uncaught exceptions to the active Domain object.
**/
@:deprecated
extern class Domain extends EventEmitter<Domain> {
/**
Run the supplied function in the context of the domain, implicitly binding all event emitters, timers,
and lowlevel requests that are created in that context.
This is the most basic way to use a domain.
**/
function run(fn:Void->Void):Void;
/**
An array of timers and event emitters that have been explicitly added to the domain.
**/
var members(default, null):Array<haxe.extern.EitherType<IEventEmitter, Timeout>>;
/**
Explicitly adds an `emitter` to the domain.
If any event handlers called by the emitter throw an error, or if the emitter emits an error event,
it will be routed to the domain's error event, just like with implicit binding.
This also works with timers that are returned from `setInterval` and `setTimeout`.
If their callback function throws, it will be caught by the domain 'error' handler.
If the Timer or EventEmitter was already bound to a domain, it is removed from that one,
and bound to this one instead.
**/
@:overload(function(emitter:Timeout):Void {})
function add(emitter:IEventEmitter):Void;
/**
The opposite of `add`. Removes domain handling from the specified emitter.
**/
@:overload(function(emitter:Timeout):Void {})
function remove(emitter:IEventEmitter):Void;
/**
The returned function will be a wrapper around the supplied `callback` function.
When the returned function is called, any errors that are thrown will be routed to the domain's error event.
**/
function bind<T:Function>(callback:T):T;
/**
This method is almost identical to `bind`. However, in addition to catching thrown errors, it will also
intercept `Error` objects sent as the first argument to the function.
In this way, the common if (er != null) return callback(er); pattern
can be replaced with a single error handler in a single place.
**/
function intercept<T:Function>(callback:T):T;
/**
The `enter` method is plumbing used by the `run`, `bind`, and `intercept` methods to set the active domain.
It sets `domain.active` and `process.domain` to the domain, and implicitly pushes the domain onto
the domain stack managed by the domain module (see `exit` for details on the domain stack).
The call to `enter` delimits the beginning of a chain of asynchronous calls and I/O operations bound to a domain.
Calling `enter` changes only the active domain, and does not alter the domain itself.
Enter and exit can be called an arbitrary number of times on a single domain.
If the domain on which `enter` is called has been disposed, `enter` will return without setting the domain.
**/
function enter():Void;
/**
The `exit` method exits the current domain, popping it off the domain stack.
Any time execution is going to switch to the context of a different chain of asynchronous calls,
it's important to ensure that the current domain is exited. The call to `exit` delimits either the end of
or an interruption to the chain of asynchronous calls and I/O operations bound to a domain.
If there are multiple, nested domains bound to the current execution context,
`exit` will exit any domains nested within this domain.
Calling `exit` changes only the active domain, and does not alter the domain itself.
Enter and exit can be called an arbitrary number of times on a single domain.
If the domain on which `exit` is called has been disposed, `exit` will return without exiting the domain.
**/
function exit():Void;
/**
The `dispose` method destroys a domain, and makes a best effort attempt
to clean up any and all IO that is associated with the domain.
Streams are aborted, ended, closed, and/or destroyed. Timers are cleared.
Explicitly bound callbacks are no longer called.
Any error events that are raised as a result of this are ignored.
The intention of calling `dispose` is generally to prevent cascading errors when a critical part of
the Domain context is found to be in an error state.
Once the domain is disposed the 'dispose' event will emit.
Note that IO might still be performed. However, to the highest degree possible, once a domain is disposed,
further errors from the emitters in that set will be ignored. So, even if some remaining actions are still
in flight, Node.js will not communicate further about them.
**/
function dispose():Void;
}

View File

@ -0,0 +1,264 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.events;
import haxe.Constraints.Function;
import haxe.extern.Rest;
#if haxe4
import haxe.extern.EitherType;
import js.lib.Symbol;
#end
/**
Enumeration of events emitted by all `EventEmitter` instances.
**/
@:enum abstract EventEmitterEvent<T:Function>(Event<T>) to Event<T> {
/**
The `EventEmitter` instance will emit its own `'newListener'` event before
a listener is added to its internal array of listeners.
@see https://nodejs.org/api/events.html#events_event_newlistener
**/
#if haxe4
var NewListener:EventEmitterEvent<(eventName:EitherType<String, Symbol>, listener:Function) -> Void> = "newListener";
#else
var NewListener:EventEmitterEvent<String->Function->Void> = "newListener";
#end
/**
The `'removeListener'` event is emitted after the `listener` is removed.
@see https://nodejs.org/api/events.html#events_event_removelistener
**/
#if haxe4
var RemoveListener:EventEmitterEvent<(eventName:EitherType<String, Symbol>, listener:Function) -> Void> = "removeListener";
#else
var RemoveListener:EventEmitterEvent<String->Function->Void> = "removeListener";
#end
}
/**
The `EventEmitter` class is defined and exposed by the `events` module:
@see https://nodejs.org/api/events.html#events_class_eventemitter
**/
@:jsRequire("events", "EventEmitter")
extern class EventEmitter<TSelf:EventEmitter<TSelf>> implements IEventEmitter {
function new();
/**
By default, a maximum of `10` listeners can be registered for any single
event. This limit can be changed for individual `EventEmitter` instances
using the `emitter.setMaxListeners(n)` method. To change the default
for all `EventEmitter` instances, the `EventEmitter.defaultMaxListeners`
property can be used. If this value is not a positive number, a `TypeError`
will be thrown.
@see https://nodejs.org/api/events.html#events_eventemitter_defaultmaxlisteners
**/
static var defaultMaxListeners:Int;
/**
Alias for `emitter.on(eventName, listener)`.
@see https://nodejs.org/api/events.html#events_emitter_addlistener_eventname_listener
**/
function addListener<T:Function>(eventName:Event<T>, listener:T):TSelf;
/**
Synchronously calls each of the listeners registered for the event named
`eventName`, in the order they were registered, passing the supplied arguments
to each.
@see https://nodejs.org/api/events.html#events_emitter_emit_eventname_args
**/
function emit<T:Function>(eventName:Event<T>, args:Rest<Dynamic>):Bool;
/**
Returns an array listing the events for which the emitter has registered
listeners. The values in the array will be strings or `Symbol`s.
@see https://nodejs.org/api/events.html#events_emitter_eventnames
**/
#if haxe4
function eventNames():Array<EitherType<String, Symbol>>;
#else
function eventNames():Array<String>;
#end
/**
Returns the current max listener value for the `EventEmitter` which is either
set by `emitter.setMaxListeners(n)` or defaults to
`EventEmitter.defaultMaxListeners`.
@see https://nodejs.org/api/events.html#events_emitter_getmaxlisteners
**/
function getMaxListeners():Int;
/**
Returns the number of listeners listening to the event named `eventName`.
@see https://nodejs.org/api/events.html#events_emitter_listenercount_eventname
**/
function listenerCount<T:Function>(eventName:Event<T>):Int;
/**
Returns a copy of the array of listeners for the event named `eventName`.
@see https://nodejs.org/api/events.html#events_emitter_listeners_eventname
**/
function listeners<T:Function>(eventName:Event<T>):Array<T>;
/**
Alias for `emitter.removeListener()`.
@see https://nodejs.org/api/events.html#events_emitter_off_eventname_listener
**/
function off<T:Function>(eventName:Event<T>, listener:T):TSelf;
/**
Adds the `listener` function to the end of the listeners array for the
event named `eventName`. No checks are made to see if the `listener` has
already been added. Multiple calls passing the same combination of `eventName`
and `listener` will result in the `listener` being added, and called, multiple
times.
@see https://nodejs.org/api/events.html#events_emitter_on_eventname_listener
**/
function on<T:Function>(eventName:Event<T>, listener:T):TSelf;
/**
Adds a one-time `listener` function for the event named `eventName`. The
next time `eventName` is triggered, this listener is removed and then invoked.
@see https://nodejs.org/api/events.html#events_emitter_once_eventname_listener
**/
function once<T:Function>(eventName:Event<T>, listener:T):TSelf;
/**
Adds the `listener` function to the beginning of the listeners array for the
event named `eventName`. No checks are made to see if the `listener` has
already been added. Multiple calls passing the same combination of `eventName`
and `listener` will result in the `listener` being added, and called, multiple
times.
@see https://nodejs.org/api/events.html#events_emitter_prependlistener_eventname_listener
**/
function prependListener<T:Function>(eventName:Event<T>, listener:T):TSelf;
/**
Adds a one-time `listener` function for the event named `eventName` to the
beginning of the listeners array. The next time `eventName` is triggered, this
listener is removed, and then invoked.
@see https://nodejs.org/api/events.html#events_emitter_prependoncelistener_eventname_listener
**/
function prependOnceListener<T:Function>(eventName:Event<T>, listener:T):TSelf;
/**
Removes all listeners, or those of the specified `eventName`.
@see https://nodejs.org/api/events.html#events_emitter_removealllisteners_eventname
**/
function removeAllListeners<T:Function>(?eventName:Event<T>):TSelf;
/**
Removes the specified `listener` from the listener array for the event named
`eventName`.
@see https://nodejs.org/api/events.html#events_emitter_removelistener_eventname_listener
**/
function removeListener<T:Function>(eventName:Event<T>, listener:T):TSelf;
/**
By default `EventEmitter`s will print a warning if more than `10` listeners are
added for a particular event. This is a useful default that helps finding
memory leaks. Obviously, not all events should be limited to just 10 listeners.
The `emitter.setMaxListeners()` method allows the limit to be modified for this
specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`)
to indicate an unlimited number of listeners.
@see https://nodejs.org/api/events.html#events_emitter_setmaxlisteners_n
**/
function setMaxListeners(n:Int):Void;
/**
Returns a copy of the array of listeners for the event named `eventName`,
including any wrappers (such as those created by `.once()`).
@see https://nodejs.org/api/events.html#events_emitter_rawlisteners_eventname
**/
function rawListeners<T:Function>(eventName:Event<T>):Array<T>;
}
/**
`IEventEmitter` interface is used as "any EventEmitter".
See `EventEmitter` for actual class documentation.
**/
@:remove
extern interface IEventEmitter {
function addListener<T:Function>(eventName:Event<T>, listener:T):IEventEmitter;
function emit<T:Function>(eventName:Event<T>, args:Rest<Dynamic>):Bool;
#if haxe4
function eventNames():Array<EitherType<String, Symbol>>;
#else
function eventNames():Array<String>;
#end
function getMaxListeners():Int;
function listenerCount<T:Function>(eventName:Event<T>):Int;
function listeners<T:Function>(eventName:Event<T>):Array<T>;
function off<T:Function>(eventName:Event<T>, listener:T):IEventEmitter;
function on<T:Function>(eventName:Event<T>, listener:T):IEventEmitter;
function once<T:Function>(eventName:Event<T>, listener:T):IEventEmitter;
function prependListener<T:Function>(eventName:Event<T>, listener:T):IEventEmitter;
function prependOnceListener<T:Function>(eventName:Event<T>, listener:T):IEventEmitter;
function removeAllListeners<T:Function>(?eventName:Event<T>):IEventEmitter;
function removeListener<T:Function>(eventName:Event<T>, listener:T):IEventEmitter;
function setMaxListeners(n:Int):Void;
function rawListeners<T:Function>(eventName:Event<T>):Array<T>;
}
/**
Abstract type for events. Its type parameter is a signature
of a listener for a concrete event.
**/
#if haxe4
abstract Event<T:Function>(Dynamic) from String to String from Symbol to Symbol {}
#else
abstract Event<T:Function>(Dynamic) from String to String {}
#end

View File

@ -0,0 +1,68 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.fs;
import js.node.Fs.FsPath;
import js.node.events.EventEmitter;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of possible types of changes for 'change' event.
**/
@:enum abstract FSWatcherChangeType(String) from String to String {
var Change = "change";
var Rename = "rename";
}
/**
Enumeration of the events emitted by `FSWatcher`.
**/
@:enum abstract FSWatcherEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when something changes in a watched directory or file. See more details in `Fs.watch`.
Listener arguments:
event - The type of fs change
filename - The filename that changed (if relevant/available)
**/
var Change:FSWatcherEvent<FSWatcherChangeType->FsPath->Void> = "change";
/**
Emitted when an error occurs.
**/
var Error:FSWatcherEvent<Error->Void> = "error";
}
/**
Objects returned from `Fs.watch` are of this type.
**/
extern class FSWatcher extends EventEmitter<FSWatcher> {
/**
Stop watching for changes on the given `FSWatcher`.
**/
function close():Void;
}

View File

@ -0,0 +1,49 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.fs;
import js.node.Fs.FsPath;
import js.node.events.EventEmitter.Event;
@:enum abstract ReadStreamEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when the `ReadStream`'s file is opened.
Listener arguments:
fd - file descriptor used by the `ReadStream`.
**/
var Open:ReadStreamEvent<Int->Void> = "open";
}
/**
Readable file stream.
**/
extern class ReadStream extends js.node.stream.Readable<ReadStream> {
/**
The path to the file the stream is reading from as specified in the first argument to `Fs.createReadStream`.
If path is passed as a string, then readStream.path will be a string.
If path is passed as a Buffer, then readStream.path will be a Buffer.
**/
var path:FsPath;
}

View File

@ -0,0 +1,82 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.fs;
/**
Objects returned from `Fs.stat`, `Fs.lstat` and `Fs.fstat` and their synchronous counterparts are of this type.
**/
extern class Stats {
var dev:Int;
var ino:Float;
var mode:Int;
var nlink:Int;
var uid:Int;
var gid:Int;
var rdev:Int;
var size:Float;
var blksize:Null<Int>;
var blocks:Null<Float>;
/**
"Access Time" - Time when file data last accessed.
Changed by the mknod(2), utimes(2), and read(2) system calls.
**/
var atime:Date;
/**
"Modified Time" - Time when file data last modified.
Changed by the mknod(2), utimes(2), and write(2) system calls.
**/
var mtime:Date;
/**
"Change Time" - Time when file status was last changed (inode data modification).
Changed by the chmod(2), chown(2), link(2), mknod(2), rename(2), unlink(2), utimes(2), read(2), and write(2) system calls.
**/
var ctime:Date;
/**
"Birth Time" - Time of file creation. Set once when the file is created.
On filesystems where birthtime is not available, this field may instead hold either the ctime or 1970-01-01T00:00Z (ie, unix epoch timestamp 0).
Note that this value may be greater than `atime` or `mtime` in this case. On Darwin and other FreeBSD variants,
also set if the `atime` is explicitly set to an earlier value than the current birthtime using the utimes(2) system call.
**/
var birthtime:Date;
function isFile():Bool;
function isDirectory():Bool;
function isBlockDevice():Bool;
function isCharacterDevice():Bool;
/**
Only valid with `Fs.lstat`.
**/
function isSymbolicLink():Bool;
function isFIFO():Bool;
function isSocket():Bool;
}

View File

@ -0,0 +1,54 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.fs;
import js.node.Fs.FsPath;
import js.node.events.EventEmitter.Event;
@:enum abstract WriteStreamEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when the `WriteStream`'s file is opened.
Listener arguments:
fd - file descriptor used by the `WriteStream`.
**/
var Open:WriteStreamEvent<Int->Void> = "open";
}
/**
Writable file stream.
**/
extern class WriteStream extends js.node.stream.Writable<WriteStream> {
/**
The path to the file the stream is writing to as specified in the first argument to `Fs.createWriteStream`.
If path is passed as a string, then writeStream.path will be a string.
If path is passed as a Buffer, then writeStream.path will be a Buffer.
**/
var path:FsPath;
/**
The number of bytes written so far.
Does not include data that is still queued for writing.
**/
var bytesWritten:Int;
}

View File

@ -0,0 +1,189 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.http;
import haxe.DynamicAccess;
import js.node.net.Socket;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
An `Agent` is responsible for managing connection persistence and reuse for HTTP clients.
It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty,
at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port.
Whether it is destroyed or pooled depends on the `keepAlive` option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may still close idle connections, in which case they will be removed
from the pool and a new connection will be made when a new HTTP request is made for that host and port.
Servers may also refuse to allow multiple requests over the same connection, in which case the connection will have to be remade for every
request and cannot be pooled.
The `Agent` will still make the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed from the pool.
Any unused sockets in the pool will be unrefed so as not to keep the Node.js process running when there are no outstanding requests.
(see [socket.unref()](https://nodejs.org/api/net.html#net_socket_unref)).
It is good practice, to `destroy()` an Agent instance when it is no longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either a `'close'` event or an `'agentRemove'` event.
When intending to keep one HTTP request open for a long time without keeping it in the agent, something like the following may be done.
An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions,
a one-time use `Agent` with default options will be used for the client connection.
**/
@:jsRequire("http", "Agent")
extern class Agent {
/**
`options` in socket.connect() are also supported.
The default `http.globalAgent` that is used by `http.request()` has all of these values set to their respective defaults.
To configure any of them, a custom `http.Agent` instance must be created.
**/
function new(?options:HttpAgentOptions);
/**
Produces a socket/stream to be used for HTTP requests.
By default, this function is the same as `net.createConnection()`.
However, custom agents may override this method in case greater flexibility is desired.
A socket/stream can be supplied in one of two ways: by returning the socket/stream from this function,
or by passing the socket/stream to `callback`.
`callback` has a signature of `(err, stream)`.
**/
#if haxe4
function createConnection(options:SocketConnectOptionsTcp, ?callback:(err:Error, stream:Socket) -> Void):Socket;
#else
function createConnection(options:SocketConnectOptionsTcp, ?callback:Error->Socket->Void):Socket;
#end
/**
Called when `socket` is detached from a request and could be persisted by the `Agent`.
This method can be overridden by a particular `Agent` subclass.
If this method returns a falsy value, the socket will be destroyed instead of persisting it for use with the next request.
**/
function keepSocketAlive(socket:Socket):Void;
/**
Called when `socket` is attached to `request` after being persisted because of the keep-alive options.
This method can be overridden by a particular `Agent` subclass.
**/
function reuseSocket(socket:Socket, request:ClientRequest):Void;
/**
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an agent with `keepAlive` enabled,
then it is best to explicitly shut down the agent when it will no longer be used. Otherwise,
sockets may hang open for quite a long time before the server terminates them.
**/
function destroy():Void;
/**
An object which contains arrays of sockets currently awaiting use by the agent when keepAlive is enabled.
Do not modify.
*/
var freeSockets(default, null):DynamicAccess<Array<Socket>>;
/**
Get a unique name for a set of request options, to determine whether a connection can be reused.
For an HTTP agent, this returns `host:port:localAddress` or `host:port:localAddress:family`.
For an HTTPS agent, the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options that determine socket reusability.
**/
function getName(options:js.node.Http.HttpRequestOptions):String;
/**
By default set to `256`.
For agents with `keepAlive` enabled, this sets the maximum number of sockets that will be left open in the free state.
**/
var maxFreeSockets:Float;
/**
By default set to `Infinity`.
Determines how many concurrent sockets the agent can have open per origin. Origin is the returned value of `getName()`.
**/
var maxSockets:Float;
/**
An object which contains queues of requests that have not yet been assigned to sockets.
Do not modify.
**/
var requests(default, null):DynamicAccess<Array<ClientRequest>>;
/**
An object which contains arrays of sockets currently in use by the agent.
Do not modify.
**/
var sockets(default, null):DynamicAccess<Array<Socket>>;
}
/**
Options for `Agent` constructor.
**/
typedef HttpAgentOptions = {
/**
Keep sockets around even when there are no outstanding requests, so they can be used for future requests
without having to reestablish a TCP connection.
Not to be confused with the `keep-alive` value of the `Connection` header.
The `Connection: keep-alive` header is always sent when using an agent except when the `Connection` header
is explicitly specified or when the `keepAlive` and `maxSockets` options are respectively set to `false` and `Infinity`,
in which case `Connection: close` will be used.
Default: `false`
**/
@:optional var keepAlive:Bool;
/**
When using the `keepAlive` option, specifies the [initial delay](https://nodejs.org/api/net.html#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets.
Ignored when the `keepAlive` option is `false` or `undefined`.
Default: `1000`.
**/
@:optional var keepAliveMsecs:Int;
/**
Maximum number of sockets to allow per host. Each request will use a new socket until the maximum is reached.
Default: `Infinity`.
**/
@:optional var maxSockets:Int;
/**
Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`.
Default: `256`.
**/
@:optional var maxFreeSockets:Int;
/**
Socket timeout in milliseconds. This will set the timeout when the socket is created.
**/
@:optional var timeout:Int;
}

View File

@ -0,0 +1,223 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.http;
import haxe.DynamicAccess;
import js.node.Buffer;
import js.node.events.EventEmitter.Event;
import js.node.net.Socket;
import js.node.stream.Writable;
/**
Enumeration of events emitted by `ClientRequest`
**/
@:enum abstract ClientRequestEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when the request has been aborted by the client.
This event is only emitted on the first call to `abort()`.
**/
var Abort:ClientRequestEvent<Void->Void> = "abort";
/**
Emitted each time a server responds to a request with a `CONNECT` method.
If this event is not being listened for, clients receiving a `CONNECT` method will have their connections closed.
**/
#if haxe4
var Connect:ClientRequestEvent<(response:IncomingMessage, socket:Socket, head:Buffer) -> Void> = "connect";
#else
var Connect:ClientRequestEvent<IncomingMessage->Socket->Buffer->Void> = "connect";
#end
/**
Emitted when the server sends a '100 Continue' HTTP response,
usually because the request contained 'Expect: 100-continue'.
This is an instruction that the client should send the request body.
**/
var Continue:ClientRequestEvent<Void->Void> = "continue";
/**
Emitted when the server sends a 1xx intermediate response (excluding 101 Upgrade).
The listeners of this event will receive an object containing the HTTP version, status code, status message,
key-value headers object, and array with the raw header names followed by their respective values.
**/
var Information:ClientRequestEvent<InformationEventData->Void> = "information";
/**
Emitted when a response is received to this request. This event is emitted only once.
**/
var Response:ClientRequestEvent<IncomingMessage->Void> = "response";
/**
Emitted after a socket is assigned to this request.
**/
var Socket:ClientRequestEvent<Socket->Void> = "socket";
/**
Emitted when the underlying socket times out from inactivity.
This only notifies that the socket has been idle. The request must be aborted manually.
See also: [request.setTimeout()](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
**/
var Timeout:ClientRequestEvent<Socket->Void> = "timeout";
/**
Emitted each time a server responds to a request with an upgrade.
If this event is not being listened for and the response status code is 101 Switching Protocols,
clients receiving an upgrade header will have their connections closed.
**/
#if haxe4
var Upgrade:ClientRequestEvent<(response:IncomingMessage, socket:Socket, head:Buffer) -> Void> = "upgrade";
#else
var Upgrade:ClientRequestEvent<IncomingMessage->Socket->Buffer->Void> = "upgrade";
#end
}
/**
This object is created internally and returned from http.request().
It represents an in-progress request whose header has already been queued.
The header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API.
The actual header will be sent along with the first data chunk or when calling `request.end()`.
To get the response, add a listener for `'response'` to the request object.
`'response'` will be emitted from the request object when the response headers have been received.
The `'response'` event is executed with one argument which is an instance of `http.IncomingMessage`.
During the `'response'` event, one can add listeners to the response object; particularly to listen for the `'data'` event.
If no `'response'` handler is added, then the response will be entirely discarded. However,
if a `'response'` event handler is added, then the data from the response object *must* be consumed,
either by calling `response.read()` whenever there is a `'readable'` event, or by adding a `'data'` handler,
or by calling the `.resume()` method. Until the data is consumed, the `'end'` event will not fire.
Also, until the data is read it will consume memory that can eventually lead to a 'process out of memory' error.
Unlike the `request` object, if the response closes prematurely, the response object does not emit an `'error'` event
but instead emits the `'aborted'` event.
Node.js does not check whether Content-Length and the length of the body which has been transmitted are equal or not.
**/
@:jsRequire("http", "ClientRequest")
extern class ClientRequest extends Writable<ClientRequest> {
/**
Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.
**/
function abort():Void;
/**
The request.aborted property will be true if the request has been aborted.
**/
var aborted(default, null):Bool;
/**
See `request.socket`.
**/
var connection(default, null):Socket;
/**
The `response.finished` property will be true if `response.end()` has been called.
**/
var finished(default, null):Bool;
/**
Flush the request headers.
For efficiency reasons, node.js normally buffers the request headers until you call `request.end()`
or write the first chunk of request data. It then tries hard to pack the request headers and data
into a single TCP packet.
That's usually what you want (it saves a TCP round-trip) but not when the first data isn't sent
until possibly much later. `flushHeaders` lets you bypass the optimization and kickstart the request.
**/
function flushHeaders():Void;
/**
Reads out a header on the request. The name is case-insensitive.
The type of the return value depends on the arguments provided to `request.setHeader()`.
**/
function getHeader(name:String):haxe.extern.EitherType<String, Array<String>>;
/**
Limits maximum response headers count. If set to 0, no limit will be applied.
Default: `2000`
**/
var maxHeadersCount:Null<Int>;
/**
The request path.
**/
var path(default, null):String;
/**
Removes a header that's already defined into headers object.
**/
function removeHeader(name:String):Void;
/**
Sets a single header value for headers object.
If this header already exists in the to-be-sent headers, its value will be replaced.
Use an array of strings here to send multiple headers with the same name.
Non-string values will be stored without modification. Therefore, `request.getHeader()` may return non-string values.
However, the non-string values will be converted to strings for network transmission.
**/
@:overload(function(name:String, value:Array<String>):Void {})
function setHeader(name:String, value:String):Void;
/**
Once a socket is assigned to this request and is connected
`socket.setNoDelay` will be called.
**/
function setNoDelay(?noDelay:Bool):Void;
/**
Once a socket is assigned to this request and is connected
`socket.setKeepAlive`() will be called.
**/
@:overload(function(?initialDelay:Int):Void {})
function setSocketKeepAlive(enable:Bool, ?initialDelay:Int):Void;
/**
Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called.
**/
function setTimeout(timeout:Int, ?callback:Socket->Void):ClientRequest;
/**
Reference to the underlying socket. Usually users will not want to access this property.
In particular, the socket will not emit `'readable'` events because of how the protocol parser attaches to the socket.
The `socket` may also be accessed via `request.connection`.
*/
var socket(default, null):Socket;
// This field is defined in super class.
// var writableEnded(default, null):Bool;
// var writableFinished(default, null):Bool;
}
typedef InformationEventData = {
var httpVersion:String;
var httpVersionMajor:Int;
var httpVersionMinor:Int;
var statusCode:Int;
var statusMessage:String;
var headers:DynamicAccess<String>;
var rawHeaders:Array<String>;
}

View File

@ -0,0 +1,171 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.http;
import haxe.DynamicAccess;
import js.node.events.EventEmitter.Event;
import js.node.net.Socket;
import js.node.stream.Readable;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by the `IncomingMessage` objects in addition to its parent class events.
**/
@:enum abstract IncomingMessageeEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when the request has been aborted.
**/
var Aborted:IncomingMessageeEvent<Void->Void> = "aborted";
/**
Indicates that the underlying connection was closed.
**/
var Close:IncomingMessageeEvent<Void->Void> = "close";
}
/**
An `IncomingMessage` object is created by `http.Server` or `http.ClientRequest` and passed as the first argument to the `'request'` and `'response'` event respectively.
It may be used to access response status, headers and data.
It implements the `Readable Stream` interface, as well as the following additional events, methods, and properties.
**/
@:jsRequire("http", "IncomingMessage")
extern class IncomingMessage extends Readable<IncomingMessage> {
/**
The `aborted` property will be `true` if the request has been aborted.
**/
var aborted(default, null):Bool;
/**
The `complete` property will be `true` if a complete HTTP message has been received and successfully parsed.
**/
var complete(default, null):Bool;
/**
Calls `destroy()` on the socket that received the `IncomingMessage`.
If `error` is provided, an `'error'` event is emitted and `error` is passed as an argument to any listeners on the event.
**/
override function destroy(?error:Error):IncomingMessage;
/**
The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.
Duplicates in raw headers are handled in the following ways, depending on the header name:
- Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`,
`last-modified`, `location`, `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, or `user-agent` are discarded.
- `set-cookie` is always an array. Duplicates are added to the array.
- For duplicate `cookie` headers, the values are joined together with '; '.
- For all other headers, the values are joined together with ', '.
**/
var headers(default, null):DynamicAccess<haxe.extern.EitherType<String, Array<String>>>;
/**
In case of server request, the HTTP version sent by the client.
In the case of client response, the HTTP version of the connected-to server.
Probably either `'1.1'` or `'1.0'`.
**/
var httpVersion(default, null):String;
/**
HTTP Version first integer
**/
var httpVersionMajor(default, null):Int;
/**
HTTP Version second integer
**/
var httpVersionMinor(default, null):Int;
/**
*Only valid for request obtained from* `Server`.
The request method as a string.
Read only. Example: `'GET'`, `'DELETE'`.
**/
var method(default, null):Method;
/**
The raw request/response headers list exactly as they were received.
The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values,
and the odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
**/
var rawHeaders(default, null):Array<String>;
/**
The raw request/response trailer keys and values exactly as they were received.
Only populated at the `'end'` event.
**/
var rawTrailers(default, null):Array<String>;
/**
Calls `connection.setTimeout(msecs, callback)`.
**/
function setTimeout(msecs:Int, ?callback:Void->Void):Void;
/**
The `Socket` object associated with the connection.
With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the client's authentication details.
**/
var socket(default, null):Socket;
/**
Alias for `socket`.
**/
var connection(default, null):Socket;
/**
*Only valid for response obtained from* `ClientRequest`.
The 3-digit HTTP response status code. E.G. `404`.
**/
var statusCode(default, null):Int;
/**
*Only valid for response obtained from* `ClientRequest`.
The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`.
**/
var statusMessage(default, null):String;
/**
The request/response trailers object.
Only populated after the `'end'` event.
**/
var trailers(default, null):DynamicAccess<String>;
/**
*Only valid for request obtained from* `Server`.
Request URL string. This contains only the URL that is present in the actual HTTP request.
**/
var url(default, null):String;
}

View File

@ -0,0 +1,63 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.http;
/**
Enumeration of possible HTTP methods as described in
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
**/
@:enum abstract Method(String) from String to String {
var Acl = "ACL";
var Bind = "BIND";
var Checkout = "CHECKOUT";
var Connect = "CONNECT";
var Copy = "COPY";
var Delete = "DELETE";
var Get = "GET";
var Head = "HEAD";
var Link = "LINK'";
var Lock = "LOCK'";
var MSearch = "M-SEARCH'";
var Merge = "MERGE'";
var Mkactivity = "MKACTIVITY'";
var Mkcalendar = "MKCALENDAR'";
var Mkcol = "MKCOL'";
var Move = "MOVE'";
var Notify = "NOTIFY'";
var Options = "OPTIONS";
var Patch = "PATCH";
var Post = "POST";
var Propfind = "PROPFIND";
var Proppatch = "PROPPATCH";
var Purge = "PURGE";
var Put = "PUT";
var Rebind = "REBIND";
var Report = "REPORT";
var Search = "SEARCH";
var Subscribe = "SUBSCRIBE";
var Trace = "TRACE";
var Unbind = "UNBIND";
var Unlink = "UNLINK";
var Unlock = "UNLOCK";
var Unsubscribe = "UNSUBSCRIBE";
}

View File

@ -0,0 +1,204 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.http;
import js.node.Buffer;
import js.node.events.EventEmitter.Event;
import js.node.net.Socket;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by `http.Server` class in addition to
its parent `net.Server` class.
**/
@:enum abstract ServerEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted each time a request with an HTTP Expect: `100-continue` is received.
If this event is not listened for, the server will automatically respond with a `100 Continue` as appropriate.
Handling this event involves calling `response.writeContinue` if the client should continue
to send the request body, or generating an appropriate HTTP response (e.g. 400 Bad Request) if the client
should not continue to send the request body.
When this event is emitted and handled, the 'request' event will not be emitted.
**/
#if haxe4
var CheckContinue:ServerEvent<(request:IncomingMessage, response:ServerResponse) -> Void> = "checkContinue";
#else
var CheckContinue:ServerEvent<IncomingMessage->ServerResponse->Void> = "checkContinue";
#end
/**
Emitted each time a request with an HTTP `Expect` header is received, where the value is not `100-continue`.
If this event is not listened for, the server will automatically respond with a `417 Expectation Failed` as appropriate.
When this event is emitted and handled, the `'request'` event will not be emitted.
**/
#if haxe4
var CheckExpectation:ServerEvent<(request:IncomingMessage, response:ServerResponse) -> Void> = "checkExpectation";
#else
var CheckExpectation:ServerEvent<IncomingMessage->ServerResponse->Void> = "checkExpectation";
#end
/**
If a client connection emits an `'error'` event, it will be forwarded here.
Listener of this event is responsible for closing/destroying the underlying socket.
For example, one may wish to more gracefully close the socket with a custom HTTP response instead of abruptly severing the connection.
Default behavior is to try close the socket with a HTTP '400 Bad Request', or a HTTP '431 Request Header Fields Too Large'
in the case of a `HPE_HEADER_OVERFLOW` error. If the socket is not writable it is immediately destroyed.
**/
#if haxe4
var ClientError:ServerEvent<(exception:Error, socket:Socket) -> Void> = "clientError";
#else
var ClientError:ServerEvent<Error->Socket->Void> = "clientError";
#end
/**
Emitted when the server closes.
**/
var Close:ServerEvent<Void->Void> = "close";
/**
Emitted each time a client requests an HTTP `CONNECT` method.
If this event is not listened for, then clients requesting a `CONNECT` method will have their connections closed.
After this event is emitted, the request's socket will not have a `'data'` event listener,
meaning it will need to be bound in order to handle data sent to the server on that socket.
**/
#if haxe4
var Connect:ServerEvent<(request:IncomingMessage, socekt:Socket, head:Buffer) -> Void> = "connect";
#else
var Connect:ServerEvent<IncomingMessage->Socket->Buffer->Void> = "connect";
#end
/**
This event is emitted when a new TCP stream is established.
`socket` is typically an object of type net.Socket. Usually users will not want to access this event.
In particular, the socket will not emit `'readable'` events because of how the protocol parser attaches to the socket.
The `socket` can also be accessed at `request.connection`.
This event can also be explicitly emitted by users to inject connections into the HTTP server. In that case,
any `Duplex` stream can be passed.
If `socket.setTimeout()` is called here, the timeout will be replaced with `server.keepAliveTimeout`
when the socket has served a request (if `server.keepAliveTimeout` is non-zero).
**/
var Connection:ServerEvent<Socket->Void> = "connection";
/**
Emitted each time there is a request.
There may be multiple requests per connection (in the case of HTTP Keep-Alive connections).
**/
#if haxe4
var Request:ServerEvent<(request:IncomingMessage, response:ServerResponse) -> Void> = "request";
#else
var Request:ServerEvent<IncomingMessage->ServerResponse->Void> = "request";
#end
/**
Emitted each time a client requests an HTTP upgrade.
Listening to this event is optional and clients cannot insist on a protocol change.
After this event is emitted, the request's socket will not have a `'data'` event listener,
meaning it will need to be bound in order to handle data sent to the server on that socket.
**/
#if haxe4
var Upgrade:ServerEvent<(request:IncomingMessage, socket:Socket, buffer:Buffer) -> Void> = "upgrade";
#else
var Upgrade:ServerEvent<IncomingMessage->Socket->Buffer->Void> = "upgrade";
#end
}
/**
This class inherits `from net.Server`.
**/
@:jsRequire("http", "Server")
extern class Server extends js.node.net.Server {
/**
Limit the amount of time the parser will wait to receive the complete HTTP headers.
In case of inactivity, the rules defined in `server.timeout` apply.
However, that inactivity based timeout would still allow the connection to be kept open
if the headers are being sent very slowly (by default, up to a byte per 2 minutes).
In order to prevent this, whenever header data arrives an additional check is made that
more than `server.headersTimeout` milliseconds has not passed since the connection was established.
If the check fails, a `'timeout'` event is emitted on the server object, and (by default) the socket is destroyed.
See [server.timeout](https://nodejs.org/api/http.html#http_server_timeout) for more information on how timeout behavior can be customized.
Default: `40000`
**/
var headersTimeout:Int;
/**
Limits maximum incoming headers count. If set to 0, no limit will be applied.
Default: `2000`
**/
var maxHeadersCount:Null<Int>;
/**
Sets the timeout value for sockets, and emits a `'timeout'` event on the Server object,
passing the socket as an argument, if a timeout occurs.
If there is a `'timeout'` event listener on the Server object, then it will be called with the timed-out socket as an argument.
By default, the Server's timeout value is 2 minutes, and sockets are destroyed automatically if they time out.
However, if a callback is assigned to the Server's `'timeout'` event, timeouts must be handled explicitly.
To change the default timeout use the `--http-server-default-timeout` flag.
**/
function setTimeout(msecs:Int, ?callback:js.node.net.Socket->Void):Void;
/**
The number of milliseconds of inactivity before a socket is presumed to have timed out.
A value of `0` will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this value only affects new connections to the server,
not any existing connections.
To change the default timeout use the `--http-server-default-timeout` flag.
Default: `120000` (2 minutes)
**/
var timeout:Int;
/**
The number of milliseconds of inactivity a server needs to wait for additional incoming data,
after it has finished writing the last response, before a socket will be destroyed.
If the server receives new data before the keep-alive timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`.
A value of `0` will disable the keep-alive timeout behavior on incoming connections
A value of 0 makes the http server behave similarly to Node.js versions prior to 8.0.0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.
Default: `5000` (5 seconds).
**/
var keepAliveTimeout:Int;
}

View File

@ -0,0 +1,210 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.http;
import haxe.DynamicAccess;
import js.node.events.EventEmitter.Event;
import js.node.net.Socket;
import js.node.stream.Writable;
/**
Enumeration of events emitted by the `ServerResponse` objects in addition to its parent class events.
**/
@:enum abstract ServerResponseEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Indicates that the underlying connection was terminated.
**/
var Close:ServerResponseEvent<Void->Void> = "close";
/**
Emitted when the response has been sent.
More specifically, this event is emitted when the last segment of the response header
and body have been handed off to the operating system for transmission over the network.
It does not imply that the client has received anything yet.
**/
var Finish:ServerResponseEvent<Void->Void> = "finish";
}
/**
This object is created internally by an HTTP server — not by the user.
It is passed as the second parameter to the 'request' event.
**/
@:jsRequire("http", "ServerResponse")
extern class ServerResponse extends Writable<ServerResponse> {
/**
This method adds HTTP trailing headers (a header but at the end of the message) to the response.
Trailers will only be emitted if chunked encoding is used for the response;
if it is not (e.g., if the request was HTTP/1.0), they will be silently discarded.
Note that HTTP requires the 'Trailer' header to be sent if you intend to emit trailers,
with a list of the header fields in its value.
**/
@:overload(function(headers:Array<Array<String>>):Void {})
function addTrailers(headers:DynamicAccess<String>):Void;
/**
See `socket`.
**/
var connection(default, null):Socket;
/**
The `finished` property will be true if `end()` has been called.
**/
var finished(default, null):Bool;
/**
Flushes the response headers.
See also: [request.flushHeaders()](https://nodejs.org/api/http.html#http_request_flushheaders).
**/
function flushHeaders():Void;
/**
Reads out a header that's already been queued but not sent to the client.
The name is case-insensitive. The type of the return value depends on the arguments provided to `setHeader()`.
**/
function getHeader(name:String):haxe.extern.EitherType<String, Array<String>>;
/**
Returns an array containing the unique names of the current outgoing headers. All header names are lowercase.
**/
function getHeaderNames():Array<String>;
/**
Returns a shallow copy of the current outgoing headers. Since a shallow copy is used,
array values may be mutated without additional calls to various header-related http module methods.
The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The object returned by the `getHeaders()` method does not prototypically inherit from the JavaScript Object.
This means that typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, and others are not defined and will not work.
*/
function getHeaders():DynamicAccess<haxe.extern.EitherType<String, Array<String>>>;
/**
Returns true if the header identified by `name` is currently set in the outgoing headers.
The header name matching is case-insensitive.
**/
function hasHeader(name:String):Bool;
/**
Boolean (read-only). True if headers were sent, false otherwise.
**/
var headersSent(default, null):Bool;
/**
Removes a header that's queued for implicit sending.
**/
function removeHeader(name:String):Void;
/**
When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers.
Defaults to true.
This should only be disabled for testing; HTTP requires the Date header in responses.
**/
var sendDate:Bool;
/**
Sets a single header value for implicit headers.
If this header already exists in the to-be-sent headers, its value will be replaced.
Use an array of strings here to send multiple headers with the same name.
Non-string values will be stored without modification.
Therefore, `getHeader()` may return non-string values.
However, the non-string values will be converted to strings for network transmission.
**/
@:overload(function(name:String, value:Array<String>):Void {})
function setHeader(name:String, value:String):Void;
/**
Sets the Socket's timeout value to `msecs`.
If a callback is provided, then it is added as a listener on the `'timeout'` event on the response object.
If no `'timeout'` listener is added to the request, the response, or the server, then sockets are destroyed when they time out.
If a handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly.
**/
function setTimeout(msecs:Int, ?callback:Void->Void):Void;
/**
Reference to the underlying socket. Usually users will not want to access this property.
In particular, the socket will not emit `'readable'` events because of how the protocol parser attaches to the socket.
After `end()`, the property is nulled. The `socket` may also be accessed via `connection`.
**/
var socket(default, null):Socket;
/**
When using implicit headers (not calling `writeHead` explicitly), this property controls the status code
that will be sent to the client when the headers get flushed.
After response header was sent to the client, this property indicates the status code which was sent out.
**/
var statusCode:Int;
/**
When using implicit headers (not calling `writeHead()` explicitly),
this property controls the status message that will be sent to the client when the headers get flushed.
If this is left as `undefined` then the standard message for the status code will be used.
After response header was sent to the client, this property indicates the status message which was sent out.
**/
var statusMessage:String;
/**
Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.
See the `'checkContinue'` event on `Server`.
*/
function writeContinue():Void;
/**
Sends a response header to the request.
The status code is a 3-digit HTTP status code, like `404`. The last argument, `headers`, are the response headers.
Optionally one can give a human-readable `statusMessage` as the second argument.
This method must only be called once on a message and it must be called before `end()` is called.
If `write()` or `end()` are called before calling this, the implicit/mutable headers will be calculated and call this function.
When headers have been set with `setHeader()`, they will be merged with any headers passed to `writeHead()`, with the headers passed to `writeHead()` given precedence.
If this method is called and `setHeader()` has not been called, it will directly write the supplied header values onto the network channel without caching internally,
and the `getHeader()` on the header will not yield the expected result.
If progressive population of headers is desired with potential future retrieval and modification, use `setHeader()` instead.
`Content-Length` is given in bytes not characters.
The above example works because the string `'hello world'` contains only single byte characters.
If the body contains higher coded characters then `Buffer.byteLength()` should be used to determine the number of bytes in a given encoding.
And Node.js does not check whether `Content-Length` and the length of the body which has been transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters will result in a `TypeError` being thrown.
**/
@:overload(function(statusCode:Int, ?headers:DynamicAccess<String>):Void {})
function writeHead(statusCode:Int, reasonPhrase:String, ?headers:DynamicAccess<String>):Void;
/**
Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.
**/
function writeProcessing():Void;
// This field is defined in super class.
// var writableEnded(default, null):Bool;
// var writableFinished(default, null):Bool;
}

View File

@ -0,0 +1,51 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.https;
/**
An Agent object for HTTPS similar to `http.Agent`.
See [https.request](https://nodejs.org/api/http.html#http_http_request_options_callback) for more information.
**/
@:jsRequire("https", "Agent")
extern class Agent extends js.node.http.Agent {
function new(?options:HttpsAgentOptions);
}
typedef HttpsAgentOptions = {
> js.node.http.Agent.HttpAgentOptions,
/**
maximum number of TLS cached sessions. Use `0` to disable TLS session caching.
Default: `100`.
**/
@:optional var maxCachedSessions:Int;
/**
the value of [Server Name Indication extension](https://en.wikipedia.org/wiki/Server_Name_Indication) to be sent to the server.
Use empty string `''` to disable sending the extension.
Default: hostname of the target server, unless the target server is specified using an IP address, in which case the default is `''` (no extension).
**/
@:optional var servername:String;
}

View File

@ -0,0 +1,30 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.https;
/**
This class is a subclass of `tls.Server` and emits events same as `http.Server`.
See [http.Server](https://nodejs.org/api/http.html#http_class_http_server) for more information.
**/
@:jsRequire("https", "Server")
extern class Server extends js.node.tls.Server {}

View File

@ -0,0 +1,173 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.net;
import haxe.extern.EitherType;
import js.node.events.EventEmitter;
import js.node.net.Socket.SocketAdress;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by the `Server` objects
**/
@:enum abstract ServerEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted when the server has been bound after calling `Server.listen`.
**/
var Listening:ServerEvent<Void->Void> = "listening";
/**
Emitted when a new connection is made.
**/
var Connection:ServerEvent<Socket->Void> = "connection";
/**
Emitted when the server closes.
Note that if connections exist, this event is not emitted until all connections are ended.
**/
var Close:ServerEvent<Void->Void> = "close";
/**
Emitted when an error occurs.
The 'close' event will be called directly following this event. See example in discussion of server.listen.
**/
var Error:ServerEvent<Error->Void> = "error";
}
private typedef ServerListenOptionsBase = {
@:optional var exclusive:Bool;
}
/**
Options for the `Server.listen` method (TCP version).
**/
typedef ServerListenOptionsTcp = {
> ServerListenOptionsBase,
@:optional var port:Int;
@:optional var host:String;
@:optional var backlog:Int;
}
/**
Options for the `Server.listen` method (UNIX version).
**/
typedef ServerListenOptionsUnix = {
> ServerListenOptionsBase,
@:optional var path:String;
}
/**
This class is used to create a TCP or local server.
**/
@:jsRequire("net", "Server")
extern class Server extends EventEmitter<Server> {
/**
Begin accepting connections on the specified `port` and `hostname`.
If the `hostname` is omitted, the server will accept connections on any IPv6 address (::) when IPv6 is available,
or any IPv4 address (0.0.0.0) otherwise.
A `port` value of zero will assign a random port.
`backlog` is the maximum length of the queue of pending connections. The actual length will be determined
by your OS through sysctl settings such as tcp_max_syn_backlog and somaxconn on linux.
The default value of this parameter is 511 (not 512).
When `path` is provided, start a local socket server listening for connections on the given path.
When `handle` is provided, it should be either a server or socket (anything with an underlying `_handle` member),
or a {fd: <n>} object. This will cause the server to accept connections on the specified handle,
but it is presumed that the file descriptor or handle has already been bound to a port or domain socket.
Listening on a file descriptor is not supported on Windows.
This function is asynchronous. When the server has been bound, 'listening' event will be emitted.
The last parameter `callback` will be added as an listener for the 'listening' event.
**/
@:overload(function(path:String, ?callback:Void->Void):Void {})
@:overload(function(handle:EitherType<Dynamic, {fd:Int}>, ?callback:Void->Void):Void {})
@:overload(function(port:Int, ?callback:Void->Void):Void {})
@:overload(function(port:Int, backlog:Int, ?callback:Void->Void):Void {})
@:overload(function(port:Int, hostname:String, ?callback:Void->Void):Void {})
@:overload(function(port:Int, hostname:String, backlog:Int, ?callback:Void->Void):Void {})
function listen(options:EitherType<ServerListenOptionsTcp, ServerListenOptionsUnix>, ?callback:Void->Void):Void;
/**
Stops the server from accepting new connections and keeps existing connections.
This function is asynchronous, the server is finally closed when all connections are ended
and the server emits a 'close' event.
The optional callback will be called once the 'close' event occurs. Unlike that event,
it will be called with an Error as its only argument if the server was not open when it was closed.
**/
@:overload(function(callback:Error->Void):Void {})
function close(?callback:Void->Void):Void;
/**
Returns the bound address, the address family name and port of the server as reported by the operating system.
Useful to find which port was assigned when giving getting an OS-assigned address.
**/
function address():SocketAdress;
/**
Calling `unref` on a server will allow the program to exit if this is the only active server in the event system.
If the server is already `unref`d calling `unref` again will have no effect.
**/
function unref():Void;
/**
Opposite of `unref`, calling `ref` on a previously `unref`d server
will not let the program exit if it's the only server left (the default behavior).
If the server is `ref`d calling `ref` again will have no effect.
**/
function ref():Void;
/**
A boolean indicating whether or not the server is listening for connections.
**/
var listening(default, null):Bool;
/**
Set this property to reject connections when the server's connection count gets high.
It is not recommended to use this option once a socket has been sent to a child with child_process.fork().
**/
var maxConnections:Int;
/**
The number of concurrent connections on the server.
This becomes null when sending a socket to a child with child_process.fork().
To poll forks and get current number of active connections use asynchronous `getConnections` instead.
**/
@:deprecated("please use `getConnections` instead")
var connections(default, null):Null<Int>;
/**
Asynchronously get the number of concurrent connections on the server.
Works when sockets were sent to forks.
**/
function getConnections(callback:Error->Int->Void):Void;
}

View File

@ -0,0 +1,367 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.net;
import haxe.extern.EitherType;
import js.node.Dns;
import js.node.events.EventEmitter.Event;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events for `Socket` objects.
**/
@:enum abstract SocketEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted after resolving the hostname but before connecting.
Not applicable to UNIX sockets.
**/
var Lookup:SocketEvent<Null<Error>->String->DnsAddressFamily->Void> = "lookup";
/**
Emitted when a socket connection is successfully established. See `Socket.connect`.
**/
var Connect:SocketEvent<Void->Void> = "connect";
/**
Emitted when data is received.
The argument data will be a `Buffer` or `String`.
Encoding of data is set by `Socket.setEncoding`.
Note that the data will be lost if there is no listener when a Socket emits a 'data' event.
**/
var Data:SocketEvent<EitherType<Buffer, String>->Void> = "data";
/**
Emitted when the other end of the socket sends a FIN packet.
By default (allowHalfOpen == false) the socket will destroy its file descriptor once
it has written out its pending write queue. However, by setting allowHalfOpen == true
the socket will not automatically `end` its side allowing the user to write arbitrary amounts of data,
with the caveat that the user is required to `end` their side now.
**/
var End:SocketEvent<Void->Void> = "end";
/**
Emitted if the socket times out from inactivity.
This is only to notify that the socket has been idle
The user must manually close the connection.
See also: `Socket.setTimeout`
**/
var Timeout:SocketEvent<Void->Void> = "timeout";
/**
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
See also: the return values of `Socket.write`
**/
var Drain:SocketEvent<Void->Void> = "drain";
/**
Emitted when an error occurs. The 'close' event will be called directly following this event.
**/
var Error:SocketEvent<Error->Void> = "error";
/**
Emitted once the socket is fully closed.
The argument `had_error` is a boolean which says if the socket was closed due to a transmission error.
Listener arguments:
had_error - true if the socket had a transmission error
**/
var Close:SocketEvent<Bool->Void> = "close";
}
typedef SocketOptionsBase = {
/**
If true, then the socket won't automatically send a FIN packet
when the other end of the socket sends a FIN packet.
The socket becomes non-readable, but still writable. You should call the `end` method explicitly.
See `end` event for more information.
Default: false
**/
@:optional var allowHalfOpen:Bool;
}
/**
Options for creating new `Socket` object.
**/
typedef SocketOptions = {
> SocketOptionsBase,
/**
allows you to specify the existing file descriptor of socket.
**/
@:optional var fd:Null<Int>;
/**
allow reads on this socket (NOTE: Works only when `fd` is passed)
**/
@:optional var readable:Bool;
/**
allow writes on this socket (NOTE: Works only when `fd` is passed)
**/
@:optional var writable:Bool;
}
/**
Options for the `Socket.connect` method (TCP version).
**/
typedef SocketConnectOptionsTcp = {
/**
Port the client should connect to
**/
var port:Int;
/**
Host the client should connect to.
Defaults to 'localhost'.
**/
@:optional var host:String;
/**
Local interface to bind to for network connections.
**/
@:optional var localAddress:String;
/**
Local port to bind to for network connections.
**/
@:optional var localPort:Int;
/**
Version of IP stack. Defaults to 4.
**/
@:optional var family:DnsAddressFamily;
/**
Custom lookup function. Defaults to `Dns.lookup`.
**/
@:optional var lookup:String->DnsLookupOptions->DnsLookupCallbackSingle->Void;
}
/**
Options for the `Socket.connect` method (Local domain socket version).
**/
typedef SocketConnectOptionsUnix = {
/**
Path the client should connect to
**/
var path:String;
}
/**
Bound address, the address family name and port of the socket as reported by the operating system.
**/
typedef SocketAdress = {
/**
Connection port.
**/
var port:Int;
/**
IP Family.
**/
var family:SocketAdressFamily;
/**
IP Address.
**/
var address:String;
}
/**
Enumeration of possible socket family values.
**/
@:enum abstract SocketAdressFamily(String) to String {
var IPv4 = "IPv4";
var IPv6 = "IPv6";
}
@:jsRequire("net", "Socket")
extern class Socket extends js.node.stream.Duplex<Socket> {
/**
Construct a new socket object.
**/
function new(?options:SocketOptions);
/**
Opens the connection for a given socket.
If `port` and `host` are given, then the socket will be opened as a TCP socket,
if `host` is omitted, localhost will be assumed.
If a `path` is given, the socket will be opened as a unix socket to that path.
Normally this method is not needed, as `Net.createConnection` opens the socket.
Use this only if you are implementing a custom `Socket`.
This function is asynchronous. When the 'connect' event is emitted the socket is established.
If there is a problem connecting, the 'connect' event will not be emitted,
the 'error' event will be emitted with the exception
The `connectListener` parameter will be added as an listener for the 'connect' event.
**/
@:overload(function(path:String, ?connectListener:Void->Void):Socket {})
@:overload(function(port:Int, ?connectListener:Void->Void):Socket {})
@:overload(function(port:Int, host:String, ?connectListener:Void->Void):Socket {})
function connect(options:EitherType<SocketConnectOptionsTcp, SocketConnectOptionsUnix>, ?connectListener:Void->Void):Socket;
/**
`Socket` has the property that `socket.write` always works. This is to help users get up and running quickly.
The computer cannot always keep up with the amount of data that is written to a socket - the network connection
simply might be too slow. Node will internally queue up the data written to a socket and send it out over the
wire when it is possible. (Internally it is polling on the socket's file descriptor for being writable).
The consequence of this internal buffering is that memory may grow. This property shows the number of characters
currently buffered to be written. (Number of characters is approximately equal to the number of bytes to be written,
but the buffer may contain strings, and the strings are lazily encoded, so the exact number of bytes is not known.)
Users who experience large or growing `bufferSize` should attempt to "throttle" the data flows
in their program with `pause` and `resume`.
**/
var bufferSize:Int;
/**
A boolean value that indicates if the connection is destroyed or not.
Once a connection is destroyed no further data can be transferred using it.
define in Stream/Readable.hx
**/
// var destroyed(default, null):Bool;
#if haxe4
/**
Ensures that no more I/O activity happens on this socket.
Only necessary in case of errors (parse error or so).
If `exception` is specified, an 'error' event will be emitted and
any listeners for that event will receive exception as an argument.
**/
function destroy(?exception:Error):Void;
#end
/**
Sets the socket to timeout after `timeout` milliseconds of inactivity on the socket.
By default `Socket` do not have a timeout.
When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed.
The user must manually `end` or `destroy` the socket.
If `timeout` is 0, then the existing idle timeout is disabled.
The optional `callback` parameter will be added as a one time listener for the 'timeout' event.
**/
function setTimeout(timeout:Int, ?callback:Void->Void):Void;
/**
Disables the Nagle algorithm.
By default TCP connections use the Nagle algorithm, they buffer data before sending it off.
Setting true for `noDelay` will immediately fire off data each time `write` is called.
`noDelay` defaults to true.
**/
function setNoDelay(?noDelay:Bool):Void;
/**
Enable/disable keep-alive functionality, and optionally set the initial delay
before the first keepalive probe is sent on an idle socket.
`enable` defaults to false.
Set `initialDelay` (in milliseconds) to set the delay between the last data packet received and
the first keepalive probe.
Setting 0 for `initialDelay` will leave the value unchanged from the default (or previous) setting.
Defaults to 0.
**/
@:overload(function(?initialDelay:Int):Void {})
function setKeepAlive(enable:Bool, ?initialDelay:Int):Void;
/**
Returns the bound address, the address family name and port of the socket as reported by the operating system.
**/
function address():SocketAdress;
/**
Calling `unref` on a socket will allow the program to exit if this is the only active socket in the event system.
If the socket is already `unref`d calling `unref` again will have no effect.
**/
function unref():Socket;
/**
Opposite of `unref`, calling `ref` on a previously `unref`d socket will not let the program exit
if it's the only socket left (the default behavior).
If the socket is `ref`d calling `ref` again will have no effect.
**/
function ref():Socket;
/**
The string representation of the remote IP address.
For example, '74.125.127.100' or '2001:4860:a005::68'.
**/
var remoteAddress(default, null):String;
/**
The string representation of the remote IP family.
'IPv4' or 'IPv6'.
**/
var remoteFamily(default, null):SocketAdressFamily;
/**
The numeric representation of the remote port. For example, 80 or 21.
**/
var remotePort(default, null):Int;
/**
The string representation of the local IP address the remote client is connecting on.
For example, if you are listening on '0.0.0.0' and the client connects on '192.168.1.1',
the value would be '192.168.1.1'.
**/
var localAddress(default, null):String;
/**
The numeric representation of the local port. For example, 80 or 21.
**/
var localPort(default, null):Int;
/**
The amount of received bytes.
**/
var bytesRead(default, null):Int;
/**
The amount of bytes sent.
**/
var bytesWritten(default, null):Int;
/**
Always true for TLSSocket instances.
May be used to distinguish TLS sockets from regular ones.
**/
var encrypted(default, null):Bool;
}

View File

@ -0,0 +1,170 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.readline;
import js.node.Buffer;
import js.node.events.EventEmitter;
/**
Enumeration of events emitted by the `Interface` objects.
**/
@:enum abstract InterfaceEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
The `'close'` event is emitted when one of the following occur:
@see https://nodejs.org/api/readline.html#readline_event_close
**/
var Close:InterfaceEvent<Void->Void> = "close";
/**
The `'line'` event is emitted whenever the `input` stream receives an end-of-line input (`\n`, `\r`, or `\r\n`).
@see https://nodejs.org/api/readline.html#readline_event_line
**/
var Line:InterfaceEvent<String->Void> = "line";
/**
The `'pause'` event is emitted when one of the following occur:
@see https://nodejs.org/api/readline.html#readline_event_pause
**/
var Pause:InterfaceEvent<Void->Void> = "pause";
/**
The `'resume'` event is emitted whenever the `input` stream is resumed.
@see https://nodejs.org/api/readline.html#readline_event_resume
**/
var Resume:InterfaceEvent<Void->Void> = "resume";
/**
The `'SIGCONT'` event is emitted when a Node.js process previously moved into the background using `<ctrl>-Z`
(i.e. `SIGTSTP`) is then brought back to the foreground using `fg(1p)`.
@see https://nodejs.org/api/readline.html#readline_event_sigcont
**/
var SIGCONT:InterfaceEvent<Void->Void> = "SIGCONT";
/**
The `'SIGINT'` event is emitted whenever the `input` stream receives a `<ctrl>-C` input, known typically as
`SIGINT`.
@see https://nodejs.org/api/readline.html#readline_event_sigint
**/
var SIGINT:InterfaceEvent<Void->Void> = "SIGINT";
/**
The `'SIGTSTP'` event is emitted when the `input` stream receives a `<ctrl>-Z` input, typically known as
`SIGTSTP`.
@see https://nodejs.org/api/readline.html#readline_event_sigtstp
**/
var SIGTSTP:InterfaceEvent<Void->Void> = "SIGTSTP";
}
/**
Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method.
@see https://nodejs.org/api/readline.html#readline_class_interface
**/
extern class Interface extends EventEmitter<Interface> {
/**
The `rl.close()` method closes the `readline.Interface` instance and relinquishes control over the `input` and
`output` streams.
@see https://nodejs.org/api/readline.html#readline_rl_close
**/
function close():Void;
/**
The `rl.pause()` method pauses the `input` stream, allowing it to be resumed later if necessary.
@see https://nodejs.org/api/readline.html#readline_rl_pause
**/
function pause():Void;
/**
The `rl.prompt()` method writes the `readline.Interface` instances configured `prompt` to a new line in `output`
in order to provide a user with a new location at which to provide input.
@see https://nodejs.org/api/readline.html#readline_rl_prompt_preservecursor
**/
function prompt(?preserveCursor:Bool):Void;
/**
The `rl.question()` method displays the `query` by writing it to the `output`, waits for user `input` to be
provided on input, then invokes the `callback` function passing the provided input as the first argument.
@see https://nodejs.org/api/readline.html#readline_rl_question_query_callback
**/
function question(query:String, callback:String->Void):Void;
/**
The `rl.resume()` method resumes the `input` stream if it has been paused.
@see https://nodejs.org/api/readline.html#readline_rl_resume
**/
function resume():Void;
/**
The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called.
@see https://nodejs.org/api/readline.html#readline_rl_setprompt_prompt
**/
function setPrompt(prompt:String):Void;
/**
The `rl.write()` method write either `data` or a key sequence identified by `key` to the `output`.
@see https://nodejs.org/api/readline.html#readline_rl_write_data_key
**/
@:overload(function(data:Buffer, ?key:InterfaceWriteKey):Void {})
function write(data:String, ?key:InterfaceWriteKey):Void;
}
/**
Key sequence passed as the `key` argument to `Interface.write`.
@see https://nodejs.org/api/readline.html#readline_rl_write_data_key
**/
typedef InterfaceWriteKey = {
/**
`true` to indicate the <ctrl> key.
**/
@:optional var ctrl:Bool;
/**
`true` to indicate the <Meta> key.
*/
@:optional var meta:Bool;
/**
`true` to indicate the <Shift> key.
**/
@:optional var shift:Bool;
/**
The name of the a key.
**/
var name:String;
}

View File

@ -0,0 +1,135 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.repl;
import haxe.DynamicAccess;
import js.node.events.EventEmitter;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by the `REPLServer` objects.
**/
@:enum abstract REPLServerEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
The `'exit'` event is emitted when the REPL is exited either by receiving the `.exit` command as input,
the user pressing `<ctrl>-C` twice to signal `SIGINT`, or by pressing `<ctrl>-D` to signal 'end' on the input stream.
The listener callback is invoked without any arguments.
@see https://nodejs.org/api/repl.html#repl_event_exit
**/
var Exit:REPLServerEvent<Void->Void> = "exit";
/**
The `'reset'` event is emitted when the REPL's context is reset.
This occurs whenever the `.clear` command is received as input unless the REPL is using the default evaluator
and the `repl.REPLServer` instance was created with the `useGlobal` option set to `true`.
The listener callback will be called with a reference to the `context` object as the only argument.
@see https://nodejs.org/api/repl.html#repl_event_reset
**/
#if haxe4
var Reset:REPLServerEvent<(context:DynamicAccess<Dynamic>) -> Void> = "reset";
#else
var Reset:REPLServerEvent<DynamicAccess<Dynamic>->Void> = "reset";
#end
}
/**
Instances of `repl.REPLServer` are created using the `repl.start()` method and should not be created directly using
the JavaScript `new` keyword.
@see https://nodejs.org/api/repl.html#repl_class_replserver
**/
@:jsRequire("repl", "REPLServer")
extern class REPLServer extends EventEmitter<REPLServer> {
/**
It is possible to expose a variable to the REPL explicitly by assigning it to the `context` object associated
with each `REPLServer`.
@see https://nodejs.org/api/repl.html#repl_global_and_local_scope
**/
var context(default, null):DynamicAccess<Dynamic>;
/**
The `replServer.defineCommand()` method is used to add new `.`-prefixed commands to the REPL instance.
@see https://nodejs.org/api/repl.html#repl_replserver_definecommand_keyword_cmd
**/
#if haxe4
@:overload(function(keyword:String, cmd:(rest:String) -> Void):Void {})
#else
@:overload(function(keyword:String, cmd:String->Void):Void {})
#end
function defineCommand(keyword:String, cmd:REPLServerOptions):Void;
/**
The `replServer.displayPrompt()` method readies the REPL instance for input from the user, printing the
configured `prompt` to a new line in the `output` and resuming the `input` to accept new input.
@see https://nodejs.org/api/repl.html#repl_replserver_displayprompt_preservecursor
**/
function displayPrompt(?preserveCursor:Bool):Void;
/**
The `replServer.clearBufferedCommand()` method clears any command that has been buffered but not yet executed.
@see https://nodejs.org/api/repl.html#repl_replserver_clearbufferedcommand
**/
function clearBufferedCommand():Void;
/**
Initializes a history log file for the REPL instance.
@see https://nodejs.org/api/repl.html#repl_replserver_setuphistory_historypath_callback
**/
#if haxe4
function setupHistory(historyPath:String, callback:(err:Null<Error>, repl:Null<REPLServer>) -> Void):Void;
#else
function setupHistory(historyPath:String, callback:Null<Error>->Null<REPLServer>->Void):Void;
#end
}
/**
Options object used by `REPLServer.defineCommand`.
@see https://nodejs.org/api/repl.html#repl_class_replserver
**/
typedef REPLServerOptions = {
/**
Help text to be displayed when `.help` is entered.
**/
@:optional var help:String;
/**
The function to execute.
**/
#if haxe4
var action:(rest:String) -> Void;
#else
var action:String->Void;
#end
}

View File

@ -0,0 +1,344 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.stream;
import haxe.extern.EitherType;
import js.node.events.EventEmitter.Event;
import js.node.stream.Readable.IReadable;
import js.node.stream.Writable.IWritable;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Writable streams are an abstraction for a destination to which data is written.
@see https://nodejs.org/api/stream.html#stream_writable_streams
**/
@:enum abstract DuplexEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
// Writable stream events -------------------------------------------------
// var Close:DuplexEvent<Void->Void> = "close";
/**
If a call to stream.write(chunk) returns `false`, the `'drain'` event will be emitted
when it is appropriate to resume writing data to the stream.
@see https://nodejs.org/api/stream.html#stream_event_drain
**/
var Drain:DuplexEvent<Void->Void> = "drain";
// var Error:DuplexEvent<Error->Void> = "error";
/**
The `'finish'` event is emitted after the stream.end() method has been called,
and all data has been flushed to the underlying system.
@see https://nodejs.org/api/stream.html#stream_event_finish
**/
var Finish:DuplexEvent<Void->Void> = "finish";
/**
The `'pipe'` event is emitted when the stream.pipe() method is called on a readable stream,
adding this writable to its set of destinations.
@see https://nodejs.org/api/stream.html#stream_event_pipe
**/
var Pipe:DuplexEvent<IReadable->Void> = "pipe";
/**
The `'unpipe'` event is emitted when the stream.unpipe() method is called on a Readable stream,
removing this Writable from its set of destinations.
@see https://nodejs.org/api/stream.html#stream_event_unpipe
**/
var Unpipe:DuplexEvent<IReadable->Void> = "unpipe";
// Readable stream events -------------------------------------------------
// var Close:DuplexEvent<Void->Void> = "close";
/**
The `'data'` event is emitted whenever the stream is relinquishing ownership of
a chunk of data to a consumer. This may occur whenever the stream is switched
in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by
attaching a listener callback to the `'data'` event. The `'data'` event will
also be emitted whenever the `readable.read()` method is called and a chunk of
data is available to be returned.
@see https://nodejs.org/api/stream.html#stream_event_data
**/
var Data:DuplexEvent<Dynamic->Void> = "data";
/**
The `'end'` event is emitted when there is no more data to be consumed from
the stream.
@see https://nodejs.org/api/stream.html#stream_event_end
**/
var End:DuplexEvent<Void->Void> = "end";
// var Error:DuplexEvent<Error->Void> = "error";
/**
The `'pause'` event is emitted when `stream.pause()` is called
and `readableFlowing` is not `false`.
@see https://nodejs.org/api/stream.html#stream_event_pause
**/
var Pause:DuplexEvent<Void->Void> = "pause";
/**
The `'readable'` event is emitted when there is data available to be read from
the stream. In some cases, attaching a listener for the `'readable'` event will
cause some amount of data to be read into an internal buffer.
@see https://nodejs.org/api/stream.html#stream_event_readable
**/
var Readable:DuplexEvent<Void->Void> = "readable";
/**
The `'resume'` event is emitted when `stream.resume()` is
called and `readableFlowing` is not `true`.
@see https://nodejs.org/api/stream.html#stream_event_resume
**/
var Resume:DuplexEvent<Void->Void> = "resume";
// Overlapped events ------------------------------------------------------
/**
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed.
The event indicates that no more events will be emitted, and no further computation will occur.
@see https://nodejs.org/api/stream.html#stream_event_close
@see https://nodejs.org/api/stream.html#stream_event_close_1
**/
var Close:DuplexEvent<Void->Void> = "close";
/**
@see https://nodejs.org/api/stream.html#stream_event_error
@see https://nodejs.org/api/stream.html#stream_event_error_1
**/
var Error:DuplexEvent<Error->Void> = "error";
}
/**
Duplex streams are streams that implement both the `Readable` and `Writable` interfaces.
@see https://nodejs.org/api/stream.html#stream_class_stream_duplex
**/
@:jsRequire("stream", "Duplex")
extern class Duplex<TSelf:Duplex<TSelf>> extends Readable<TSelf> implements IDuplex {
// --------- Writable interface implementation ----------------------------
/**
The `writable.cork()` method forces all written data to be buffered in memory.
The buffered data will be flushed when either the `stream.uncork()` or `stream.end()` methods are called.
@see https://nodejs.org/api/stream.html#stream_writable_cork
**/
function cork():Void;
// This field is defined in super class.
// function destroy(?error:Error):TSelf;
// var destroyed(default, null):Bool;
/**
Calling the `writable.end()` method signals that no more data will be written to the Writable.
The optional `chunk` and `encoding` arguments allow one final additional chunk of data to be written immediately before closing the stream.
If provided, the optional `callback` function is attached as a listener for the 'finish' event.
@see https://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback
**/
@:overload(function(?callback:EitherType<Void->Void, Null<Error>->Void>):Void {})
function end(chunk:Dynamic, ?encoding:String, ?callback:EitherType<Void->Void, Null<Error>->Void>):Void;
/**
The `writable.setDefaultEncoding()` method sets the default `encoding` for a Writable stream.
@see https://nodejs.org/api/stream.html#stream_writable_setdefaultencoding_encoding
**/
function setDefaultEncoding(encoding:String):TSelf;
/**
The `writable.uncork()` method flushes all data buffered since `stream.cork()` was called.
@see https://nodejs.org/api/stream.html#stream_writable_uncork
**/
function uncork():Void;
/**
Is `true` if it is safe to call `writable.write()`.
@see https://nodejs.org/api/stream.html#stream_writable_writable
**/
var writable(default, null):Bool;
/**
Is `true` after `writable.end()` has been called. This property
does not indicate whether the data has been flushed, for this use
`writable.writableFinished` instead.
@see https://nodejs.org/api/stream.html#stream_writable_writableended
**/
var writableEnded(default, null):Bool;
/**
Is set to `true` immediately before the 'finish' event is emitted.
@see https://nodejs.org/api/stream.html#stream_writable_writablefinished
**/
var writableFinished(default, null):Bool;
/**
Return the value of `highWaterMark` passed when constructing this `Writable`.
@see https://nodejs.org/api/stream.html#stream_writable_writablehighwatermark
**/
var writablehighWaterMark(default, null):Int;
/**
This property contains the number of bytes (or objects) in the queue ready to be written.
The value provides introspection data regarding the status of the `highWaterMark`.
@see https://nodejs.org/api/stream.html#stream_writable_writablelength
**/
var writableLength(default, null):Int;
/**
Getter for the property `objectMode` of a given `Writable` stream.
@see https://nodejs.org/api/stream.html#stream_writable_writableobjectmode
**/
var writableObjectMode(default, null):Bool;
/**
The `writable.write()` method writes some data to the stream, and calls the supplied `callback` once the data has been fully handled.
If an error occurs, the `callback` may or may not be called with the error as its first argument.
To reliably detect write errors, add a listener for the `'error'` event.
@see https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback
**/
function write(chunk:Dynamic, ?encoding:String, ?callback:EitherType<Void->Void, Null<Error>->Void>):Bool;
// --------- API for implementing a Writable Stream -----------------------
// function new(?options:DuplexNewOptions);
/**
All `Writable` stream implementations must provide a `writable._write()` method to send data to the underlying resource.
@see https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback_1
**/
private function _write(chunk:Dynamic, encoding:String, callback:Null<Error>->Void):Void;
/**
This function MUST NOT be called by application code directly.
It should be implemented by child classes, and called by the internal `Writable` class methods only.
@see https://nodejs.org/api/stream.html#stream_writable_writev_chunks_callback
**/
private function _writev(chunks:Array<Writable.Chunk>, callback:Null<Error>->Void):Void;
// This field is defined in super class.
// private function _destroy(err:Null<Error>, ?callback:Null<Error>->Void):Void;
/**
The `_final()` method must not be called directly.
t may be implemented by child classes, and if so, will be called by the internal `Writable` class methods only.
@see https://nodejs.org/api/stream.html#stream_writable_final_callback
**/
private function _final(callback:Null<Error>->Void):Void;
// --------- Overlapped interface -----------------------------------------
/**
Destroy the stream.
Optionally emit an `'error'` event, and emit a `'close'` event unless `emitClose` is set in `false`.
@see https://nodejs.org/api/stream.html#stream_writable_destroy_error
@see https://nodejs.org/api/stream.html#stream_readable_destroy_error
**/
override function destroy(?error:Error):TSelf;
// This field is defined in super class.
// var destroyed(default, null):Bool;
/**
@see https://nodejs.org/api/stream.html#stream_constructor_new_stream_writable_options
@see https://nodejs.org/api/stream.html#stream_new_stream_readable_options
**/
function new(?options:DuplexNewOptions);
/**
The `_destroy()` method is called by `destroy()`.
It can be overridden by child classes but it **must not** be called directly.
@see https://nodejs.org/api/stream.html#stream_writable_destroy_err_callback
@see https://nodejs.org/api/stream.html#stream_readable_destroy_err_callback
**/
private override function _destroy(err:Null<Error>, callback:Null<Error>->Void):Void;
// This field is defined in super class.
// var isTTY(default, null):Bool;
}
/**
Passed to both `Writable` and `Readable` constructors. Also has the following fields:
@see https://nodejs.org/api/stream.html#stream_new_stream_duplex_options
**/
typedef DuplexNewOptions = {
> Readable.ReadableNewOptions,
> Writable.WritableNewOptions,
/**
If set to `false`, then the stream will automatically end the writable side when the readable side ends. Default: `true`.
**/
@:optional var allowHalfOpen:Bool;
/**
Sets `objectMode` for readable side of the stream. Has no effect if `objectMode` is `true`. Default: `false`.
**/
@:optional var readableObjectMode:Bool;
/**
Sets `objectMode` for writable side of the stream. Has no effect if `objectMode` is `true`. Default: `false`.
**/
@:optional var writableObjectMode:Bool;
/**
Sets `highWaterMark` for the readable side of the stream. Has no effect if `highWaterMark` is provided.
**/
@:optional var readableHighWaterMark:Int;
/**
Sets `highWaterMark` for the writable side of the stream. Has no effect if `highWaterMark` is provided.
**/
@:optional var writableHighWaterMark:Int;
}
@:remove
extern interface IDuplex extends IReadable extends IWritable {}

View File

@ -0,0 +1,36 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.stream;
/**
The `stream.PassThrough` class is a trivial implementation of a `Transform` stream
that simply passes the input bytes across to the output.
Its purpose is primarily for examples and testing, but there are some use cases
where `stream.PassThrough` is useful as a building block for novel sorts of streams.
@see https://nodejs.org/api/stream.html#stream_class_stream_passthrough
**/
@:jsRequire("stream", "PassThrough")
extern class PassThrough extends Transform<PassThrough> {
function new();
}

View File

@ -0,0 +1,386 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.stream;
import js.node.Iterator;
import js.node.Stream;
import js.node.events.EventEmitter.Event;
import js.node.stream.Writable.IWritable;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Readable streams are an abstraction for a source from which data is consumed.
@see https://nodejs.org/api/stream.html#stream_readable_streams
**/
@:enum abstract ReadableEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
The `'close'` event is emitted when the stream and any of its underlying
resources (a file descriptor, for example) have been closed.
The event indicates that no more events will be emitted, and no further computation will occur.
@see https://nodejs.org/api/stream.html#stream_event_close_1
**/
var Close:ReadableEvent<Void->Void> = "close";
/**
The `'data'` event is emitted whenever the stream is relinquishing ownership of
a chunk of data to a consumer. This may occur whenever the stream is switched
in flowing mode by calling `readable.pipe()`, `readable.resume()`, or by
attaching a listener callback to the `'data'` event. The `'data'` event will
also be emitted whenever the `readable.read()` method is called and a chunk of
data is available to be returned.
@see https://nodejs.org/api/stream.html#stream_event_data
**/
var Data:ReadableEvent<Dynamic->Void> = "data";
/**
The `'end'` event is emitted when there is no more data to be consumed from
the stream.
@see https://nodejs.org/api/stream.html#stream_event_end
**/
var End:ReadableEvent<Void->Void> = "end";
/**
The `'error'` event may be emitted by a `Readable` implementation at any time.
Typically, this may occur if the underlying stream is unable to generate data
due to an underlying internal failure, or when a stream implementation attempts
to push an invalid chunk of data.
@see https://nodejs.org/api/stream.html#stream_event_error_1
**/
var Error:ReadableEvent<Error->Void> = "error";
/**
The `'pause'` event is emitted when `stream.pause()` is called
and `readableFlowing` is not `false`.
@see https://nodejs.org/api/stream.html#stream_event_pause
**/
var Pause:ReadableEvent<Void->Void> = "pause";
/**
The `'readable'` event is emitted when there is data available to be read from
the stream. In some cases, attaching a listener for the `'readable'` event will
cause some amount of data to be read into an internal buffer.
@see https://nodejs.org/api/stream.html#stream_event_readable
**/
var Readable:ReadableEvent<Void->Void> = "readable";
/**
The `'resume'` event is emitted when `stream.resume()` is
called and `readableFlowing` is not `true`.
@see https://nodejs.org/api/stream.html#stream_event_resume
**/
var Resume:ReadableEvent<Void->Void> = "resume";
}
/**
@see https://nodejs.org/api/stream.html#stream_class_stream_readable
**/
@:jsRequire("stream", "Readable")
extern class Readable<TSelf:Readable<TSelf>> extends Stream<TSelf> implements IReadable {
/**
Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event unless `emitClose` is set in `false`.
After this call, the readable stream will release any internal resources and subsequent calls to `push()` will be ignored.
Implementors should not override this method, but instead implement `readable._destroy()`.
@see https://nodejs.org/api/stream.html#stream_readable_destroy_error
**/
function destroy(?error:Error):TSelf;
/**
Is `true` after `readable.destroy()` has been called.
@see https://nodejs.org/api/stream.html#stream_readable_destroyed
**/
var destroyed(default, null):Bool;
/**
The `readable.isPaused()` method returns the current operating state of the `Readable`.
This is used primarily by the mechanism that underlies the `readable.pipe()` method.
In most typical cases, there will be no reason to use this method directly.
@see https://nodejs.org/api/stream.html#stream_readable_ispaused
**/
function isPaused():Bool;
/**
The `readable.pause()` method will cause a stream in flowing mode to stop emitting `'data'` events,
switching out of flowing mode. Any data that becomes available will remain in the internal buffer.
@see https://nodejs.org/api/stream.html#stream_readable_pause
**/
function pause():TSelf;
/**
The `readable.pipe()` method attaches a `Writable` stream to the `readable`,
causing it to switch automatically into flowing mode and push all of its data to the attached `Writable`.
The flow of data will be automatically managed so that the destination `Writable` stream
is not overwhelmed by a faster `Readable` stream.
@see https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
**/
function pipe<T:IWritable>(destination:T, ?options:{?end:Bool}):T;
/**
The `readable.read()` method pulls some data out of the internal buffer and returns it.
If no data available to be read, `null` is returned. By default,
the data will be returned as a `Buffer` object unless an encoding has been specified using
the `readable.setEncoding()` method or the stream is operating in object mode.
@see https://nodejs.org/api/stream.html#stream_readable_read_size
**/
function read(?size:Int):Null<Dynamic>;
/**
Is `true` if it is safe to call `readable.read()`.
@see https://nodejs.org/api/stream.html#stream_readable_readable
**/
var readable(default, null):Bool;
/**
Getter for the property `encoding` of a given `Readable` stream.
The `encoding` property can be set using the `readable.setEncoding()` method.
@see https://nodejs.org/api/stream.html#stream_readable_readableencoding
**/
var readableEncoding(default, null):Null<String>;
/**
Becomes `true` when `'end'` event is emitted.
@see https://nodejs.org/api/stream.html#stream_readable_readableended
**/
var readableEnded(default, null):Bool;
/**
Returns the value of `highWaterMark` passed when constructing this `Readable`.
@see https://nodejs.org/api/stream.html#stream_readable_readablehighwatermark
**/
var readableHighWaterMark(default, null):Int;
/**
This property contains the number of bytes (or objects) in the queue ready to be read.
The value provides introspection data regarding the status of the `highWaterMark`.
@see https://nodejs.org/api/stream.html#stream_readable_readablelength
**/
var readableLength(default, null):Int;
/**
Getter for the property `objectMode` of a given `Readable` stream.
@see https://nodejs.org/api/stream.html#stream_readable_readableobjectmode
**/
var readableObjectMode(default, null):Bool;
/**
The `readable.resume()` method causes an explicitly paused `Readable` stream to resume emitting `'data'` events,
switching the stream into flowing mode.
@see https://nodejs.org/api/stream.html#stream_readable_resume
**/
function resume():TSelf;
/**
The `readable.setEncoding()` method sets the character encoding for data read from the `Readable` stream.
@see https://nodejs.org/api/stream.html#stream_readable_setencoding_encoding
**/
function setEncoding(encoding:String):TSelf;
/**
The `readable.unpipe()` method detaches a `Writable` stream previously attached using the `stream.pipe()` method.
@see https://nodejs.org/api/stream.html#stream_readable_unpipe_destination
**/
function unpipe(?destination:IWritable):TSelf;
/**
Passing `chunk` as `null` signals the end of the stream (EOF), after which no more data can be written.
@see https://nodejs.org/api/stream.html#stream_readable_unshift_chunk_encoding
**/
function unshift(chunk:Null<Dynamic>, ?encoding:String):Void;
/**
Prior to Node.js 0.10, streams did not implement the entire `stream` module API as it is currently defined.
(See Compatibility for more information.)
@see https://nodejs.org/api/stream.html#stream_readable_wrap_stream
**/
function wrap(stream:Dynamic):IReadable;
// --------- API for implementing a Readable Stream -----------------------
/**
@see https://nodejs.org/api/stream.html#stream_new_stream_readable_options
**/
function new(?options:ReadableNewOptions);
/**
This function **MUST NOT** be called by application code directly.
It should be implemented by child classes, and called by the internal `Readable` class methods only.
@see https://nodejs.org/api/stream.html#stream_readable_read_size_1
**/
private function _read(size:Int):Void;
/**
The `_destroy()` method is called by `readable.destroy()`.
It can be overridden by child classes but it **must not** be called directly.
@see https://nodejs.org/api/stream.html#stream_readable_destroy_err_callback
**/
private function _destroy(err:Null<Error>, callback:Null<Error>->Void):Void;
/**
The `readable.push()` method is intended be called only by `Readable` implementers,
and only from within the `readable._read()` method.
@see https://nodejs.org/api/stream.html#stream_readable_push_chunk_encoding
**/
private function push(chunk:Null<Dynamic>, ?encoding:String):Bool;
// --------- TTY module API ----------------------------------------------
/**
Terminal read streams (i.e. process.stdin) have this property set to true.
It is false for any other read streams.
@see https://nodejs.org/api/tty.html#tty_readstream_istty
**/
var isTTY(default, null):Bool;
// --------- static API --------------------------------------------------
// TODO @:overload(function<T>(iterable:AsyncIterator<T>, ?options:ReadableNewOptions):IReadable {})
static function from<T>(iterable:Iterator<T>, ?options:ReadableNewOptions):IReadable;
}
/**
Options for `Readable` private constructor.
For stream implementors only, see node.js API documentation
**/
typedef ReadableNewOptions = {
/**
The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
Default: `16384` (16kb), or `16` for `objectMode` streams.
**/
@:optional var highWaterMark:Int;
/**
If specified, then buffers will be decoded to strings using the specified encoding.
Default: `null`.
**/
@:optional var encoding:String;
/**
Whether this stream should behave as a stream of objects.
Meaning that `stream.read(n)` returns a single value instead of a `Buffer` of size `n`.
Default: `false`.
**/
@:optional var objectMode:Bool;
/**
Whether or not the stream should emit `'close'` after it has been destroyed.
Default: `true`.
**/
@:optional var emitClose:Bool;
/**
Implementation for the `stream._read()` method.
**/
#if haxe4
@:optional var read:(size:Int) -> Void;
#else
@:optional var read:Int->Void;
#end
/**
Implementation for the `stream._destroy()` method.
**/
#if haxe4
@:optional var destroy:(err:Null<Error>, callback:Null<Error>->Void) -> Void;
#else
@:optional var destroy:Null<Error>->(Null<Error>->Void)->Void;
#end
/**
Whether this stream should automatically call `.destroy()` on itself after ending.
Default: `false`.
**/
@:optional var autoDestroy:Bool;
}
/**
`IReadable` interface is used as "any Readable".
See `Readable` for actual class documentation.
**/
@:remove
extern interface IReadable extends IStream {
function destroy(?error:Error):IReadable;
var destroyed(default, null):Bool;
function isPaused():Bool;
function pause():IReadable;
function pipe<T:IWritable>(destination:T, ?options:{?end:Bool}):T;
function read(?size:Int):Null<Dynamic>;
var readable(default, null):Bool;
var readableEncoding(default, null):Null<String>;
var readableEnded(default, null):Bool;
var readableHighWaterMark(default, null):Int;
var readableLength(default, null):Int;
var readableObjectMode(default, null):Bool;
function resume():IReadable;
function setEncoding(encoding:String):IReadable;
function unpipe(?destination:IWritable):IReadable;
function unshift(chunk:Null<Dynamic>, ?encoding:String):Void;
function wrap(stream:Dynamic):IReadable;
}

View File

@ -0,0 +1,84 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.stream;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
A `Transform` stream is a `Duplex` stream where the output is computed in some way from the input.
Examples include `zlib` streams or `crypto` streams that compress, encrypt, or decrypt data.
@see https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream
**/
@:jsRequire("stream", "Transform")
extern class Transform<TSelf:Transform<TSelf>> extends Duplex<TSelf> implements ITransform {
function new(?options:TransformNewOptions);
/**
This function **MUST NOT** be called by application code directly.
It should be implemented by child classes, and called by the internal `Readable` class methods only.
@see https://nodejs.org/api/stream.html#stream_transform_flush_callback
**/
private function _flush(callback:Null<Error>->Void):Void;
/**
This function **MUST NOT** be called by application code directly.
It should be implemented by child classes, and called by the internal `Readable` class methods only.
@see https://nodejs.org/api/stream.html#stream_transform_transform_chunk_encoding_callback
**/
#if haxe4
private function _transform(chunk:Dynamic, encoding:String, callback:(error:Null<Error>, data:Dynamic) -> Void):Void;
#else
private function _transform(chunk:Dynamic, encoding:String, callback:Null<Error>->Dynamic->Void):Void;
#end
}
/**
@see https://nodejs.org/api/stream.html#stream_new_stream_transform_options
**/
typedef TransformNewOptions = {
> Duplex.DuplexNewOptions,
/**
Implementation for the `stream._transform()` method.
**/
#if haxe4
@:optional var transform:(chunk:Dynamic, encoding:String, callback:(error:Null<Error>, data:Dynamic) -> Void) -> Void;
#else
@:optional var transform:Dynamic->String->(Null<Error>->Dynamic->Void)->Void;
#end
/**
Implementation for the `stream._flush()` method.
**/
@:optional var flush:Null<Error>->Void;
}
@:remove
extern interface ITransform extends Duplex.IDuplex {}

View File

@ -0,0 +1,396 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.stream;
import haxe.extern.EitherType;
import js.node.Stream;
import js.node.events.EventEmitter.Event;
import js.node.stream.Readable.IReadable;
#if haxe4
import js.lib.Error;
import js.lib.Object;
import js.lib.Uint8Array;
#else
import js.Error;
import js.html.Uint8Array;
#end
/**
Writable streams are an abstraction for a destination to which data is written.
@see https://nodejs.org/api/stream.html#stream_writable_streams
**/
@:enum abstract WritableEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
The `'close'` event is emitted when the stream and any of its underlying resources
(a file descriptor, for example) have been closed.
The event indicates that no more events will be emitted, and no further computation will occur.
@see https://nodejs.org/api/stream.html#stream_event_close
**/
var Close:WritableEvent<Void->Void> = "close";
/**
If a call to stream.write(chunk) returns `false`, the `'drain'` event will be emitted
when it is appropriate to resume writing data to the stream.
@see https://nodejs.org/api/stream.html#stream_event_drain
**/
var Drain:WritableEvent<Void->Void> = "drain";
/**
The `'error'` event is emitted if an `error` occurred while writing or piping data.
The listener callback is passed a single Error argument when called.
@see https://nodejs.org/api/stream.html#stream_event_error
**/
var Error:WritableEvent<Error->Void> = "error";
/**
The `'finish'` event is emitted after the stream.end() method has been called,
and all data has been flushed to the underlying system.
@see https://nodejs.org/api/stream.html#stream_event_finish
**/
var Finish:WritableEvent<Void->Void> = "finish";
/**
The `'pipe'` event is emitted when the stream.pipe() method is called on a readable stream,
adding this writable to its set of destinations.
@see https://nodejs.org/api/stream.html#stream_event_pipe
**/
var Pipe:WritableEvent<IReadable->Void> = "pipe";
/**
The `'unpipe'` event is emitted when the stream.unpipe() method is called on a Readable stream,
removing this Writable from its set of destinations.
@see https://nodejs.org/api/stream.html#stream_event_unpipe
**/
var Unpipe:WritableEvent<IReadable->Void> = "unpipe";
}
/**
The Writable stream interface is an abstraction for a destination that you are writing data to.
Examples of writable streams include:
- http requests, on the client
- http responses, on the server
- fs write streams
- zlib streams
- crypto streams
- tcp sockets
- child process stdin
- process.stdout, process.stderr
**/
@:jsRequire("stream", "Writable")
extern class Writable<TSelf:Writable<TSelf>> extends Stream<TSelf> implements IWritable {
/**
The `writable.cork()` method forces all written data to be buffered in memory.
The buffered data will be flushed when either the `stream.uncork()` or `stream.end()` methods are called.
@see https://nodejs.org/api/stream.html#stream_writable_cork
**/
function cork():Void;
/**
Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event unless `emitClose` is set in `false`.
After this call, the writable stream has ended and subsequent calls to `write()` or `end()` will result in an `ERR_STREAM_DESTROYED` error.
This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error.
Use `end()` instead of destroy if data should flush before close, or wait for the `'drain'` event before destroying the stream.
Implementors should not override this method, but instead implement `writable._destroy()`.
@see https://nodejs.org/api/stream.html#stream_writable_destroy_error
**/
function destroy(?error:Error):TSelf;
/**
Is `true` after `writable.destroy()` has been called.
@see https://nodejs.org/api/stream.html#stream_writable_destroyed
**/
var destroyed(default, null):Bool;
/**
Calling the `writable.end()` method signals that no more data will be written to the Writable.
The optional `chunk` and `encoding` arguments allow one final additional chunk of data to be written immediately before closing the stream.
If provided, the optional `callback` function is attached as a listener for the 'finish' event.
@see https://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback
**/
@:overload(function(?callback:EitherType<Void->Void, Null<Error>->Void>):Void {})
function end(chunk:Dynamic, ?encoding:String, ?callback:EitherType<Void->Void, Null<Error>->Void>):Void;
/**
The `writable.setDefaultEncoding()` method sets the default `encoding` for a Writable stream.
@see https://nodejs.org/api/stream.html#stream_writable_setdefaultencoding_encoding
**/
function setDefaultEncoding(encoding:String):TSelf;
/**
The `writable.uncork()` method flushes all data buffered since `stream.cork()` was called.
@see https://nodejs.org/api/stream.html#stream_writable_uncork
**/
function uncork():Void;
/**
Is `true` if it is safe to call `writable.write()`.
@see https://nodejs.org/api/stream.html#stream_writable_writable
**/
var writable(default, null):Bool;
/**
Is `true` after `writable.end()` has been called. This property
does not indicate whether the data has been flushed, for this use
`writable.writableFinished` instead.
@see https://nodejs.org/api/stream.html#stream_writable_writableended
**/
var writableEnded(default, null):Bool;
/**
Is set to `true` immediately before the 'finish' event is emitted.
@see https://nodejs.org/api/stream.html#stream_writable_writablefinished
**/
var writableFinished(default, null):Bool;
/**
Return the value of `highWaterMark` passed when constructing this `Writable`.
@see https://nodejs.org/api/stream.html#stream_writable_writablehighwatermark
**/
var writablehighWaterMark(default, null):Int;
/**
This property contains the number of bytes (or objects) in the queue ready to be written.
The value provides introspection data regarding the status of the `highWaterMark`.
@see https://nodejs.org/api/stream.html#stream_writable_writablelength
**/
var writableLength(default, null):Int;
/**
Getter for the property `objectMode` of a given `Writable` stream.
@see https://nodejs.org/api/stream.html#stream_writable_writableobjectmode
**/
var writableObjectMode(default, null):Bool;
/**
The `writable.write()` method writes some data to the stream, and calls the supplied `callback` once the data has been fully handled.
If an error occurs, the `callback` may or may not be called with the error as its first argument.
To reliably detect write errors, add a listener for the `'error'` event.
@see https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback
**/
function write(chunk:Dynamic, ?encoding:String, ?callback:EitherType<Void->Void, Null<Error>->Void>):Bool;
// --------- API for implementing a Writable Stream -----------------------
/**
@see https://nodejs.org/api/stream.html#stream_constructor_new_stream_writable_options
**/
function new(?options:WritableNewOptionsAdapter);
/**
All `Writable` stream implementations must provide a `writable._write()` method to send data to the underlying resource.
@see https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback_1
**/
private function _write(chunk:Dynamic, encoding:String, callback:Null<Error>->Void):Void;
/**
This function **MUST NOT** be called by application code directly.
It should be implemented by child classes, and called by the internal `Writable` class methods only.
@see https://nodejs.org/api/stream.html#stream_writable_writev_chunks_callback
**/
private function _writev(chunks:Array<Chunk>, callback:Null<Error>->Void):Void;
/**
The `_destroy()` method is called by `writable.destroy()`.
It can be overridden by child classes but it **must not** be called directly.
@see https://nodejs.org/api/stream.html#stream_writable_destroy_err_callback
**/
private function _destroy(err:Null<Error>, callback:Null<Error>->Void):Void;
/**
The `_final()` method **must not** be called directly.
t may be implemented by child classes, and if so, will be called by the internal `Writable` class methods only.
@see https://nodejs.org/api/stream.html#stream_writable_final_callback
**/
private function _final(callback:Null<Error>->Void):Void;
// --------- TTY module API ----------------------------------------------
/**
Terminal write streams (i.e. process.stdout) have this property set to true.
It is false for any other write streams.
@see https://nodejs.org/api/tty.html#tty_writestream_istty
**/
var isTTY(default, null):Bool;
}
/**
@see https://nodejs.org/api/stream.html#stream_constructor_new_stream_writable_options
**/
typedef WritableNewOptions = {
/**
`highWaterMark` <number> Buffer level when stream.write() starts returning `false`. Default: `16384` (16kb), or 16 for `objectMode` streams.
**/
@:optional var highWaterMark:Int;
/**
`decodeStrings` <boolean> Whether to encode `string`s passed to stream.write() to `Buffer`s (with the encoding specified in the stream.write() call) before passing them to stream._write().
Other types of data are not converted (i.e. `Buffer`s are not decoded into `string`s). Setting to false will prevent strings from being converted.
Default: `true`.
**/
@:optional var decodeStrings:Bool;
/**
`defaultEncoding` <string> The default encoding that is used when no encoding is specified as an argument to stream.write().
Default: `'utf8'`.
**/
@:optional var defaultEncoding:String;
/**
`objectMode` <boolean> Whether or not the stream.write(anyObj) is a valid operation. When set,
it becomes possible to write JavaScript values other than string, `Buffer` or `Uint8Array` if supported by the stream implementation.
Default: `false`.
**/
@:optional var objectMode:Bool;
/**
`emitClose` <boolean> Whether or not the stream should emit `'close'` after it has been destroyed.
Default: `true`.
**/
@:optional var emitClose:Bool;
/**
`write` <Function> Implementation for the stream._write() method.
**/
#if haxe4
@:optional var write:(chunk:Dynamic, encoding:String, callback:Null<Error>->Void) -> Void;
#else
@:optional var write:Dynamic->String->Null<Error>->Void->Void;
#end
/**
`writev` <Function> Implementation for the stream._writev() method.
**/
#if haxe4
@:optional var writev:(chunks:Array<Chunk>, callback:Null<Error>->Void) -> Void;
#else
@:optional var writev:Array<Chunk>->(Null<Error>->Void)->Void;
#end
/**
`destroy` <Function> Implementation for the stream._destroy() method.
**/
#if haxe4
@:optional var destroy:(error:Null<Error>, callback:Null<Error>->Void) -> Void;
#else
@:optional var destroy:Null<Error>->(Null<Error>->Void)->Void;
#end
/**
`final` <Function> Implementation for the stream._final() method.
**/
// TODO @native in typedef cannot work now
// @:native("final")
#if haxe4
@:optional var final_:(error:Null<Error>) -> Void;
#else
@:optional var final_:Null<Error>->Void;
#end
/**
`autoDestroy` <boolean> Whether this stream should automatically call .destroy() on itself after ending. Default: false.
**/
@:optional var autoDestroy:Bool;
}
@:forward
abstract WritableNewOptionsAdapter(WritableNewOptions) {
@:from
public static function from(options:WritableNewOptions):WritableNewOptionsAdapter {
if (!Reflect.hasField(options, "final")) {
#if haxe4
Object.defineProperty(options, "final", {get: function() return options.final_});
#else
untyped __js__("Object.defineProperty({0}, {1}, {2})", options, "final", {get: function() return options.final_});
#end
}
return cast options;
}
}
/**
Writable interface used for type parameter constraints.
See `Writable` for actual class documentation.
**/
@:remove
extern interface IWritable extends IStream {
function cork():Void;
function destroy(?error:Error):IWritable;
var destroyed(default, null):Bool;
@:overload(function(?callback:EitherType<Void->Void, Null<Error>->Void>):Void {})
function end(chunk:Dynamic, ?encoding:String, ?callback:EitherType<Void->Void, Null<Error>->Void>):Void;
function setDefaultEncoding(encoding:String):IWritable;
function uncork():Void;
var writable(default, null):Bool;
var writableEnded(default, null):Bool;
var writableFinished(default, null):Bool;
var writablehighWaterMark(default, null):Int;
var writableLength(default, null):Int;
var writableObjectMode(default, null):Bool;
function write(chunk:Dynamic, ?encoding:String, ?callback:EitherType<Void->Void, Null<Error>->Void>):Bool;
var isTTY(default, null):Bool;
}
typedef Chunk = {
var chunk:Dynamic;
var encoding:String;
}

View File

@ -0,0 +1,111 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.tls;
import haxe.extern.EitherType;
typedef SecureContextOptions = {
/**
private key, certificate and CA certs of the server in PFX or PKCS12 format.
**/
@:optional var pfx:EitherType<String, Buffer>;
/**
passphrase for the private key or pfx.
**/
@:optional var passphrase:String;
/**
private key of the server in PEM format.
**/
@:optional var key:EitherType<String, Buffer>;
/**
certificate key of the server in PEM format.
**/
@:optional var cert:EitherType<String, Buffer>;
/**
trusted certificates in PEM format.
If this is omitted several well known "root" CAs will be used, like VeriSign.
These are used to authorize connections.
**/
@:optional var ca:Array<EitherType<String, Buffer>>;
/**
PEM encoded CRLs (Certificate Revocation List)
**/
@:optional var crl:EitherType<String, Array<String>>;
/**
ciphers to use or exclude.
To mitigate BEAST attacks it is recommended that you use this option in conjunction with the `honorCipherOrder`
option described below to prioritize the non-CBC cipher.
Defaults to AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH.
Consult the OpenSSL cipher list format documentation for details on the format.
ECDH (Elliptic Curve Diffie-Hellman) ciphers are not yet supported.
**/
@:optional var ciphers:String;
/**
named curve to use for ECDH key agreement or false to disable ECDH.
Defaults to prime256v1 (NIST P-256). Use `Crypto.getCurves` to obtain a list of available curve names.
On recent releases, openssl ecparam -list_curves will also display the name and description
of each available elliptic curve.
**/
@:optional var ecdhCurve:String;
/**
Diffie Hellman parameters, required for Perfect Forward Secrecy.
Use openssl dhparam to create it. Its key length should be greater than or equal to 1024 bits,
otherwise it throws an error. It is strongly recommended to use 2048 bits or more for stronger security.
If omitted or invalid, it is silently discarded and DHE ciphers won't be available.
**/
@:optional var dhparam:EitherType<String, Buffer>;
/**
The SSL method to use, e.g. SSLv3_method to force SSL version 3.
The possible values depend on your installation of OpenSSL and are defined in the constant SSL_METHODS.
**/
@:optional var secureProtocol:String;
/**
opaque identifier for session resumption.
If `requestCert` is true, the default is MD5 hash value generated from command-line.
Otherwise, the default is not provided.
**/
@:optional var sessionIdContext:String;
/**
When choosing a cipher, use the server's preferences instead of the client preferences.
Default: true.
**/
@:optional var honorCipherOrder:Bool;
}
extern class SecureContext {}

View File

@ -0,0 +1,47 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.tls;
import js.node.events.EventEmitter;
/**
Events emitted by `SecurePair`.
**/
@:enum abstract SecurePairEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
The event is emitted from the `SecurePair` once the pair has successfully established a secure connection.
Similarly to the checking for the server 'secureConnection' event,
`SecurePair.cleartext.authorized` should be checked to confirm whether
the certificate used properly authorized.
**/
var Secure:SecurePairEvent<Void->Void> = "secure";
}
/**
Returned by `Tls.createSecurePair`.
**/
extern class SecurePair extends EventEmitter<SecurePair> {
var cleartext(default, null):TLSSocket;
var encrypted(default, null):js.node.stream.Duplex.IDuplex;
}

View File

@ -0,0 +1,124 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.tls;
import js.node.Buffer;
import js.node.events.EventEmitter.Event;
import js.node.tls.SecureContext.SecureContextOptions;
import js.node.tls.TLSSocket;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by `Server` in addition to its parent classes.
**/
@:enum abstract ServerEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
This event is emitted after a new connection has been successfully handshaked.
**/
var SecureConnection:ServerEvent<TLSSocket->Void> = "secureConnection";
/**
When a client connection emits an 'error' event before secure connection is established -
it will be forwarded here.
Listener arguments:
exception - error object
securePair - the `TLSSocket` that the error originated from
**/
var ClientError:ServerEvent<Error->TLSSocket->Void> = "clientError";
/**
Emitted on creation of TLS session.
May be used to store sessions in external storage.
`callback` must be invoked eventually, otherwise no data will be sent or received from secure connection.
Listener arguments:
sessionId
sessionData
callback
**/
var NewSession:ServerEvent<Buffer->Buffer->(Void->Void)->Void> = "newSession";
/**
Emitted when client wants to resume previous TLS session.
Event listener may perform lookup in external storage using given sessionId,
and invoke callback(null, sessionData) once finished.
If session can't be resumed (i.e. doesn't exist in storage) one may call callback(null, null).
Calling callback(err) will terminate incoming connection and destroy socket.
Listener arguments:
sessionId
callback
**/
var ResumeSession:ServerEvent<Buffer->(Error->?Buffer->Void)->Void> = "resumeSession";
/**
Emitted when the client sends a certificate status request.
You could parse server's current certificate to obtain OCSP url and certificate id,
and after obtaining OCSP response invoke `callback(null, resp)`, where `resp` is a `Buffer` instance.
Both certificate and issuer are a Buffer DER-representations of the primary and issuer's certificates.
They could be used to obtain OCSP certificate id and OCSP endpoint url.
Alternatively, `callback(null, null)` could be called, meaning that there is no OCSP response.
Calling `callback(err)` will result in a `socket.destroy(err)` call.
**/
var OCSPRequest:ServerEvent<Buffer->Buffer->(Error->?Buffer->Void)->Void> = "OCSPRequest";
}
/**
This class is a subclass of `net.Server` and has the same methods on it.
Instead of accepting just raw TCP connections, this accepts encrypted connections using TLS or SSL.
**/
@:jsRequire("tls", "Server")
extern class Server extends js.node.net.Server {
/**
Returns `Buffer` instance holding the keys currently used for encryption/decryption of the TLS Session Tickets.
**/
function getTicketKeys():Buffer;
/**
Updates the keys for encryption/decryption of the TLS Session Tickets.
NOTE: the buffer should be 48 bytes long. See server `ticketKeys` option for
more information on how it is going to be used.
NOTE: the change is effective only for the future server connections. Existing or currently pending
server connections will use previous keys.
**/
function setTicketKeys(keys:Buffer):Void;
/**
Add secure context that will be used if client request's SNI hostname
is matching passed hostname (wildcards can be used).
**/
function addContext(hostname:String, credentials:SecureContextOptions):Void;
}

View File

@ -0,0 +1,174 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.tls;
import haxe.Constraints.Function;
import js.node.Buffer;
import js.node.Tls.TlsClientOptionsBase;
import js.node.Tls.TlsServerOptionsBase;
import js.node.events.EventEmitter.Event;
#if haxe4
import js.lib.Error;
#else
import js.Error;
#end
/**
Enumeration of events emitted by `TLSSocket` objects in addition to its parent class events.
**/
@:enum abstract TLSSocketEvent<T:Function>(Event<T>) to Event<T> {
/**
This event is emitted after a new connection has been successfully handshaked.
The listener will be called no matter if the server's certificate was authorized or not.
It is up to the user to test `TLSSocket.authorized` to see if the server certificate
was signed by one of the specified CAs. If `TLSSocket.authorized` is false then the error
can be found in `TLSSocket.authorizationError`. Also if NPN was used - you can
check `TLSSocket.npnProtocol` for negotiated protocol.
**/
var SecureConnect:TLSSocketEvent<Void->Void> = "secureConnect";
/**
This event will be emitted if `requestOCSP` option was set.
`response` is a `Buffer` object, containing server's OCSP response.
Traditionally, the response is a signed object from the server's CA
that contains information about server's certificate revocation status.
**/
var OCSPResponse:TLSSocketEvent<Buffer->Void> = "OCSPResponse";
}
typedef TLSSocketOptions = {
> TlsServerOptionsBase,
> TlsClientOptionsBase,
/**
An optional TLS context object from `Tls.createSecureContext`
**/
@:optional var secureContext:SecureContext;
/**
If true - TLS socket will be instantiated in server-mode
**/
@:optional var isServer:Bool;
@:optional var server:js.node.net.Server;
}
/**
This is a wrapped version of `net.Socket` that does transparent encryption
of written data and all required TLS negotiation.
Its `encrypted` field is always true.
**/
@:jsRequire("tls", "TLSSocket")
extern class TLSSocket extends js.node.net.Socket {
/**
Construct a new TLSSocket object from existing TCP socket.
**/
function new(socket:js.node.net.Socket, options:TLSSocketOptions);
/**
true if the peer certificate was signed by one of the specified CAs, otherwise false
**/
var authorized(default, null):Bool;
/**
The reason why the peer's certificate has not been verified.
This property becomes available only when `authorized` is false.
**/
var authorizationError(default, null):Null<String>;
/**
Negotiated protocol name.
**/
var npnProtocol(default, null):String;
/**
Returns an object representing the peer's certificate.
The returned object has some properties corresponding to the field of the certificate.
If `detailed` argument is true - the full chain with issuer property will be returned,
if false - only the top certificate without issuer property.
**/
function getPeerCertificate(?detailed:Bool):Dynamic; // TODO: is there a well defined structure for this?
/**
Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection.
Example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more information.
**/
function getCipher():{name:String, version:String};
/**
Initiate TLS renegotiation process.
The `options` may contain the following fields: rejectUnauthorized, requestCert (See `Tls.createServer` for details).
`callback(err)` will be executed with null as err, once the renegotiation is successfully completed.
NOTE: Can be used to request peer's certificate after the secure connection has been established.
ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout.
**/
function renegotiate(options:{?rejectUnauthorized:Bool, ?requestCert:Bool}, ?callback:Error->Void):Bool;
/**
Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512).
Returns true on success, false otherwise.
Smaller fragment size decreases buffering latency on the client: large fragments are buffered by the TLS layer
until the entire fragment is received and its integrity is verified; large fragments can span multiple roundtrips,
and their processing can be delayed due to packet loss or reordering. However, smaller fragments add
extra TLS framing bytes and CPU overhead, which may decrease overall server throughput.
**/
function setMaxSendFragment(size:Int):Bool;
/**
Returns a string containing the negotiated SSL/TLS protocol version of the current connection.
'unknown' will be returned for connected sockets that have not completed the handshaking process.
`null` will be returned for server sockets or disconnected client sockets.
**/
function getProtocol():String;
/**
Return ASN.1 encoded TLS session or null if none was negotiated.
Could be used to speed up handshake establishment when reconnecting to the server.
**/
function getSession():Null<Buffer>;
/**
NOTE: Works only with client TLS sockets.
Useful only for debugging, for session reuse provide session option to tls.connect.
Return TLS session ticket or null if none was negotiated.
**/
function getTLSTicket():Null<Buffer>;
}

View File

@ -0,0 +1,44 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.tty;
/**
A net.Socket subclass that represents the readable portion of a tty.
In normal circumstances, process.stdin will be the only tty.ReadStream instance
in any node program (only when isatty(0) is true).
**/
@:jsRequire("tty", "ReadStream")
extern class ReadStream extends js.node.net.Socket {
/**
A boolean that is initialized to false.
It represents the current "raw" state of the tty.ReadStream instance.
**/
var isRaw(default, null):Bool;
/**
`mode` should be true or false.
This sets the properties of the tty.ReadStream to act either as a raw device or default.
`isRaw` will be set to the resulting mode.
**/
function setRawMode(mode:Bool):Void;
}

View File

@ -0,0 +1,55 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.tty;
import js.node.events.EventEmitter;
/**
Enumeration of events emitted by `WriteStream` objects in addition to its parents.
**/
@:enum abstract WriteStreamEvent<T:haxe.Constraints.Function>(Event<T>) to Event<T> {
/**
Emitted by refreshSize() when either of the columns or rows properties has changed.
**/
var Resize:WriteStreamEvent<Void->Void> = "resize";
}
/**
A net.Socket subclass that represents the writable portion of a tty.
In normal circumstances, process.stdout will be the only tty.WriteStream instance
ever created (and only when isatty(1) is true).
**/
@:jsRequire("tty", "WriteStream")
extern class WriteStream extends js.node.net.Socket {
/**
The number of columns the TTY currently has.
This property gets updated on "resize" events.
**/
var columns(default, null):Int;
/**
The number of rows the TTY currently has.
This property gets updated on "resize" events.
**/
var rows(default, null):Int;
}

View File

@ -0,0 +1,120 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.url;
/**
Browser-compatible URL class, implemented by following the WHATWG URL Standard.
[Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself.
**/
@:jsRequire("url", "URL")
extern class URL {
/**
Creates a new `URL` object by parsing the `input` relative to the `base`.
If `base` is passed as a string, it will be parsed equivalent to `new URL(base)`.
**/
@:overload(function(input:String, ?base:URL):Void {})
function new(input:String, ?base:String):Void;
/**
Gets and sets the fragment portion of the URL.
**/
var hash:String;
/**
Gets and sets the host portion of the URL.
**/
var host:String;
/**
Gets and sets the hostname portion of the URL
The key difference between `url.host` and `url.hostname` is that `url.hostname` does not include the port.
**/
var hostname:String;
/**
Gets and sets the serialized URL.
**/
var href:String;
/**
Gets the read-only serialization of the URL's origin.
**/
var origin(default, null):String;
/**
Gets and sets the password portion of the URL.
**/
var password:String;
/**
Gets and sets the path portion of the URL.
**/
var pathname:String;
/**
Gets and sets the port portion of the URL.
The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive).
Setting the value to the default port of the `URL` objects given `protocol` will result in the port value becoming the empty string (`''`).
**/
var port:String;
/**
Gets and sets the protocol portion of the URL.
**/
var protocol:String;
/**
Gets and sets the serialized query portion of the URL.
**/
var search:String;
/**
Gets the `URLSearchParams` object representing the query parameters of the URL.
This property is read-only; to replace the entirety of query parameters of the URL, use the `url.search` setter.
See [URLSearchParams](https://nodejs.org/api/url.html#url_class_urlsearchparams) documentation for details.
**/
var searchParams(default, null):URLSearchParams;
/**
Gets and sets the username portion of the URL.
**/
var username:String;
/**
The `toString()` method on the `URL` object returns the serialized URL.
The value returned is equivalent to that of `url.href` and `url.toJSON()`.
Because of the need for standard compliance, this method does not allow users to customize the serialization process of the URL.
For more flexibility, `require('url').format()` method might be of interest.
**/
function toString():String;
/**
The `toJSON()` method on the `URL` object returns the serialized URL.
The value returned is equivalent to that of `url.href` and `url.toString()`.
This method is automatically called when an `URL` object is serialized with `JSON.stringify()`.
**/
function toJSON():String;
}

View File

@ -0,0 +1,139 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.url;
import js.node.Iterator;
/**
The `URLSearchParams` API provides read and write access to the query of a `URL`.
The `URLSearchParams` class can also be used standalone with one of the four following constructors.
The `URLSearchParams` class is also available on the global object.
The WHATWG `URLSearchParams` interface and the `querystring` module have similar purpose,
but the purpose of the querystring module is more general, as it allows the customization of delimiter characters (`&` and` `=`). On the other hand, this API is designed purely for URL query strings.
**/
@:jsRequire("url", "URLSearchParams")
extern class URLSearchParams {
@:overload(function(init:String):Void {})
@:overload(function(obj:Dynamic<String>):Void {})
@:overload(function(array:Array<URLSearchParamsEntry>):Void {})
@:overload(function(iter:Iterator<URLSearchParamsEntry>):Void {})
function new():Void;
/**
Append a new name-value pair to the query string.
**/
function append(name:String, value:String):Void;
/**
Remove all name-value pairs whose name is `name`.
**/
function delete(name:String):Void;
/**
Returns an ES6 `Iterator` over each of the name-value pairs in the query.
Each item of the iterator is a JavaScript `Array`.
The first item of the `Array` is the `name`, the second item of the `Array` is the `value`.
**/
function entries():Iterator<URLSearchParamsEntry>;
/**
Iterates over each name-value pair in the query and invokes the given function.
**/
#if haxe4
@:overload(function(fn:(value:String) -> Void, ?thisArg:Dynamic):Void {})
@:overload(function(fn:(value:String, name:String) -> Void, ?thisArg:Dynamic):Void {})
function forEach(fn:(value:String, name:String, searchParams:URLSearchParams) -> Void, ?thisArg:Dynamic):Void;
#else
@:overload(function(fn:String->Void, ?thisArg:Dynamic):Void {})
@:overload(function(fn:String->String->Void, ?thisArg:Dynamic):Void {})
function forEach(fn:String->String->URLSearchParams->Void, ?thisArg:Dynamic):Void;
#end
/**
Returns the value of the first name-value pair whose name is `name`.
If there are no such pairs, `null` is returned.
**/
function get(name:String):String;
/**
Returns the values of all name-value pairs whose name is `name`.
If there are no such pairs, an empty array is returned.
**/
function getAll(name:String):Array<String>;
/**
Returns `true` if there is at least one name-value pair whose name is `name`.
**/
function has(name:String):Bool;
/**
Returns an ES6 `Iterator` over the names of each name-value pair.
**/
function keys():Iterator<String>;
/**
Sets the value in the `URLSearchParams` object associated with `name` to `value`.
If there are any pre-existing name-value pairs whose names are `name`, set the first such pair's value to `value` and remove all others.
If not, append the name-value pair to the query string.
**/
function set(name:String, value:String):Void;
/**
Sort all existing name-value pairs in-place by their names. Sorting is done with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability),
so relative order between name-value pairs with the same name is preserved.
This method can be used, in particular, to increase cache hits.
**/
function sort():Void;
/**
Returns the search parameters serialized as a string, with characters percent-encoded where necessary.
**/
function toString():String;
/**
Returns an ES6 `Iterator` over the values of each name-value pair.
**/
function values():Iterator<String>;
}
/**
The name-value pair access helper for `js.node.url.URLSearchParams.entries()`.
**/
abstract URLSearchParamsEntry(Array<String>) {
public var name(get, never):String;
public var value(get, never):String;
public function new(name:String, value:String) {
this = [name, value];
}
inline function get_name():String {
return this[0];
}
inline function get_value():String {
return this[1];
}
}

View File

@ -0,0 +1,70 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.util;
import haxe.DynamicAccess;
import js.node.Util.InspectOptions;
@:jsRequire("util", "inspect")
extern class Inspect {
/**
The `util.inspect()` method returns a string representation of `object` that is intended for debugging.
@see https://nodejs.org/api/util.html#util_util_inspect_object_options
**/
@:selfCall
@:overload(function(object:Dynamic, ?showHidden:Bool, ?depth:Int, ?colors:Bool):String {})
static function inspect(object:Dynamic, ?options:InspectOptions):String;
/**
`util.inspect.styles` is a map associating a style name to a color from `util.inspect.colors` properties.
@see https://nodejs.org/api/util.html#util_customizing_util_inspect_colors
**/
static var styles:DynamicAccess<String>;
/**
The predefined color codes are: `white`, `grey`, `black`, `blue`, `cyan`, `green`, `magenta`, `red` and
`yellow`.
**/
static var colors:DynamicAccess<Array<Int>>;
/**
In addition to being accessible through `util.inspect.custom`, this symbol is registered globally and can be
accessed in any environment as `Symbol.for('nodejs.util.inspect.custom')`.
@see https://nodejs.org/api/util.html#util_util_inspect_custom
**/
#if haxe4
static final custom:js.lib.Symbol;
#else
static var custom(default, never):Dynamic;
#end
/**
The `defaultOptions` value allows customization of the default options used by `util.inspect`.
@see https://nodejs.org/api/util.html#util_util_inspect_defaultoptions
**/
static var defaultOptions:InspectOptions;
}

View File

@ -0,0 +1,54 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.util;
import haxe.Constraints.Function;
import haxe.extern.Rest;
#if haxe4
import js.lib.Promise;
#else
import js.Promise;
#end
@:jsRequire("util", "promisify")
extern class Promisify {
/**
Takes a function following the common error-first callback style, i.e. taking an `(err, value) => ...` callback
as the last argument, and returns a version that returns promises.
@see https://nodejs.org/api/util.html#util_util_promisify_original
**/
@:selfCall
static function promisify(original:Function):Rest<Dynamic>->Promise<Dynamic>;
/**
That can be used to declare custom promisified variants of functions, see Custom promisified functions.
@see https://nodejs.org/api/util.html#util_util_promisify_custom
**/
#if haxe4
static final custom:js.lib.Symbol;
#else
static var custom(default, never):Dynamic;
#end
}

View File

@ -0,0 +1,111 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.util;
import haxe.extern.EitherType;
#if haxe4
import js.lib.ArrayBuffer;
import js.lib.ArrayBufferView;
#else
import js.html.ArrayBuffer;
import js.html.ArrayBufferView;
#end
/**
An implementation of the WHATWG Encoding Standard `TextDecoder` API.
@see https://nodejs.org/api/util.html#util_class_util_textdecoder
**/
@:jsRequire("util", "TextDecoder")
extern class TextDecoder {
/**
Creates an new `TextDecoder` instance.
@see https://nodejs.org/api/util.html#util_new_textdecoder_encoding_options
**/
function new(?encoding:String, ?options:TextDecoderOptions);
/**
Decodes the `input` and returns a string.
@see https://nodejs.org/api/util.html#util_textdecoder_decode_input_options
**/
function decode(?input:EitherType<ArrayBuffer, ArrayBufferView>, ?options:TextDecodeOptions):String;
/**
The encoding supported by the `TextDecoder` instance.
@see https://nodejs.org/api/util.html#util_textdecoder_encoding
**/
var encoding(default, null):String;
/**
The value will be `true` if decoding errors result in a `TypeError` being thrown.
@see https://nodejs.org/api/util.html#util_textdecoder_fatal
**/
var fatal(default, null):Bool;
/**
The value will be `true` if the decoding result will include the byte order mark.
@see https://nodejs.org/api/util.html#util_textdecoder_ignorebom
**/
var ignoreBOM(default, null):Bool;
}
/**
Options object used by `new TextDecoder()`.
@see https://nodejs.org/api/util.html#util_new_textdecoder_encoding_options
**/
typedef TextDecoderOptions = {
/**
`true` if decoding failures are fatal.
This option is only supported when ICU is enabled (see Internationalization).
Default: `false`.
**/
@:optional var fatal:Bool;
/**
When `true`, the `TextDecoder` will include the byte order mark in the decoded result.
When `false`, the byte order mark will be removed from the output.
This option is only used when `encoding` is `'utf-8'`, `'utf-16be'` or `'utf-16le'`.
Default: `false`.
**/
@:optional var ignoreBOM:Bool;
}
/**
Options object used by `TextDecoder.decode`.
**/
typedef TextDecodeOptions = {
/**
`true` if additional chunks of data are expected.
Default: `false`.
**/
@:optional var stream:Bool;
}

View File

@ -0,0 +1,53 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.util;
#if haxe4
import js.lib.Uint8Array;
#else
import js.html.Uint8Array;
#end
/**
An implementation of the WHATWG Encoding Standard `TextEncoder` API.
@see https://nodejs.org/api/util.html#util_class_util_textencoder
**/
@:jsRequire("util", "TextEncoder")
extern class TextEncoder {
function new();
/**
UTF-8 encodes the `input` string and returns a `Uint8Array` containing the encoded bytes.
@see https://nodejs.org/api/util.html#util_textencoder_encode_input
**/
function encode(?input:String):Uint8Array;
/**
The encoding supported by the `TextEncoder` instance.
@see https://nodejs.org/api/util.html#util_textencoder_encoding
**/
var encoding(default, null):String;
}

View File

@ -0,0 +1,305 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.util;
/**
`util.types` provides a number of type checks for different kinds of built-in objects.
@see https://nodejs.org/api/util.html#util_util_types
**/
@:jsRequire("util", "types")
extern class Types {
/**
Returns `true` if the value is a built-in `ArrayBuffer` or `SharedArrayBuffer` instance.
@see https://nodejs.org/api/util.html#util_util_types_isanyarraybuffer_value
**/
static function isAnyArrayBuffer(value:Dynamic):Bool;
/**
Returns `true` if the value is an `arguments` object.
@see https://nodejs.org/api/util.html#util_util_types_isargumentsobject_value
**/
static function isArgumentsObject(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `ArrayBuffer` instance.
@see https://nodejs.org/api/util.html#util_util_types_isarraybuffer_value
**/
static function isArrayBuffer(value:Dynamic):Bool;
/**
Returns `true` if the value is an async function.
@see https://nodejs.org/api/util.html#util_util_types_isasyncfunction_value
**/
static function isAsyncFunction(value:Dynamic):Bool;
/**
Returns `true` if the value is a `BigInt64Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isbigint64array_value
**/
static function isBigInt64Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a `BigUint64Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isbiguint64array_value
**/
static function isBigUint64Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a boolean object, e.g. created by `new Boolean()`.
@see https://nodejs.org/api/util.html#util_util_types_isbooleanobject_value
**/
static function isBooleanObject(value:Dynamic):Bool;
/**
Returns `true` if the value is any boxed primitive object, e.g. created by `new Boolean()`, `new String()` or
`Object(Symbol())`.
@see https://nodejs.org/api/util.html#util_util_types_isboxedprimitive_value
**/
static function isBoxedPrimitive(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `DataView` instance.
@see https://nodejs.org/api/util.html#util_util_types_isdataview_value
**/
static function isDataView(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Date` instance.
@see https://nodejs.org/api/util.html#util_util_types_isdate_value
**/
static function isDate(value:Dynamic):Bool;
/**
Returns `true` if the value is a native `External` value.
@see https://nodejs.org/api/util.html#util_util_types_isexternal_value
**/
static function isExternal(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Float32Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isfloat32array_value
**/
static function isFloat32Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Float64Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isfloat64array_value
**/
static function isFloat64Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a generator function.
@see https://nodejs.org/api/util.html#util_util_types_isgeneratorfunction_value
**/
static function isGeneratorFunction(value:Dynamic):Bool;
/**
Returns `true` if the value is a generator object as returned from a built-in generator function.
@see https://nodejs.org/api/util.html#util_util_types_isgeneratorobject_value
**/
static function isGeneratorObject(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Int8Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isint8array_value
**/
static function isInt8Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Int16Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isint16array_value
**/
static function isInt16Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Int32Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isint32array_value
**/
static function isInt32Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Map` instance.
@see https://nodejs.org/api/util.html#util_util_types_ismap_value
**/
static function isMap(value:Dynamic):Bool;
/**
Returns `true` if the value is an iterator returned for a built-in `Map` instance.
@see https://nodejs.org/api/util.html#util_util_types_ismapiterator_value
**/
static function isMapIterator(value:Dynamic):Bool;
/**
Returns `true` if the value is an instance of a Module Namespace Object.
@see https://nodejs.org/api/util.html#util_util_types_ismodulenamespaceobject_value
**/
static function isModuleNamespaceObject(value:Dynamic):Bool;
/**
Returns `true` if the value is an instance of a built-in `Error` type.
@see https://nodejs.org/api/util.html#util_util_types_isnativeerror_value
**/
static function isNativeError(value:Dynamic):Bool;
/**
Returns `true` if the value is a number object, e.g. created by `new Number()`.
@see https://nodejs.org/api/util.html#util_util_types_isnumberobject_value
**/
static function isNumberObject(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Promise`.
@see https://nodejs.org/api/util.html#util_util_types_ispromise_value
**/
static function isPromise(value:Dynamic):Bool;
/**
Returns `true` if the value is a `Proxy` instance.
@see https://nodejs.org/api/util.html#util_util_types_isproxy_value
**/
static function isProxy(value:Dynamic):Bool;
/**
Returns `true` if the value is a regular expression object.
@see https://nodejs.org/api/util.html#util_util_types_isregexp_value
**/
static function isRegExp(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Set` instance.
@see https://nodejs.org/api/util.html#util_util_types_isset_value
**/
static function isSet(value:Dynamic):Bool;
/**
Returns `true` if the value is an iterator returned for a built-in `Set` instance.
@see https://nodejs.org/api/util.html#util_util_types_issetiterator_value
**/
static function isSetIterator(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `SharedArrayBuffer` instance.
@see https://nodejs.org/api/util.html#util_util_types_issharedarraybuffer_value
**/
static function isSharedArrayBuffer(value:Dynamic):Bool;
/**
Returns `true` if the value is a string object, e.g. created by `new String()`.
@see https://nodejs.org/api/util.html#util_util_types_isstringobject_value
**/
static function isStringObject(value:Dynamic):Bool;
/**
Returns `true` if the value is a symbol object, created by calling `Object()` on a `Symbol` primitive.
@see https://nodejs.org/api/util.html#util_util_types_issymbolobject_value
**/
static function isSymbolObject(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `TypedArray` instance.
@see https://nodejs.org/api/util.html#util_util_types_istypedarray_value
**/
static function isTypedArray(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Uint8Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isuint8array_value
**/
static function isUint8Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Uint8ClampedArray` instance.
@see https://nodejs.org/api/util.html#util_util_types_isuint8clampedarray_value
**/
static function isUint8ClampedArray(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Uint16Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isuint16array_value
**/
static function isUint16Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `Uint32Array` instance.
@see https://nodejs.org/api/util.html#util_util_types_isuint32array_value
**/
static function isUint32Array(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `WeakMap` instance.
@see https://nodejs.org/api/util.html#util_util_types_isweakmap_value
**/
static function isWeakMap(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `WeakSet` instance.
@see https://nodejs.org/api/util.html#util_util_types_isweakset_value
**/
static function isWeakSet(value:Dynamic):Bool;
/**
Returns `true` if the value is a built-in `WebAssembly.Module` instance.
@see https://nodejs.org/api/util.html#util_util_types_iswebassemblycompiledmodule_value
**/
static function isWebAssemblyCompiledModule(value:Dynamic):Bool;
}

View File

@ -0,0 +1,99 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.vm;
import js.node.Vm.VmContext;
typedef ScriptOptions = {
/**
The filename that shows up in any stack traces produced.
**/
@:optional var filename:String;
/**
Whether or not to print any errors to stderr, with the line of code that caused them highlighted,
before throwing an exception.
Will capture both syntax errors from compiling code and runtime errors thrown by executing the compiled code.
Defaults to true.
**/
@:optional var displayErrors:Bool;
}
typedef ScriptRunOptions = {
/**
Whether or not to print any errors to stderr, with the line of code that caused them highlighted,
before throwing an exception.
Will capture both syntax errors from compiling code and runtime errors thrown by executing the compiled code.
Defaults to true.
**/
@:optional var displayErrors:Bool;
/**
Number of milliseconds to execute code before terminating execution.
If execution is terminated, an Error will be thrown.
**/
@:optional var timeout:Int;
}
/**
A class for holding precompiled scripts, and running them in specific sandboxes.
**/
@:jsRequire("vm", "Script")
extern class Script {
/**
Creating a new `Script` compiles `code` but does not run it. Instead, the created `Script` object
represents this compiled code.
This script can be run later many times using methods below.
The returned script is not bound to any global object. It is bound before each run, just for that run.
**/
function new(code:String, ?options:ScriptOptions);
/**
Similar to `Vm.runInThisContext` but a method of a precompiled `Script` object.
`runInThisContext` runs the code of script and returns the result.
Running code does not have access to local scope, but does have access to the current global object.
**/
function runInThisContext(?options:ScriptRunOptions):Dynamic;
/**
Similar to `Vm.runInContext` but a method of a precompiled `Script` object.
`runInContext` runs script's compiled code in `contextifiedSandbox` and returns the result.
Running code does not have access to local scope.
**/
function runInContext(contextifiedSandbox:VmContext<Dynamic>, ?options:ScriptRunOptions):Dynamic;
/**
Similar to `Vm.runInNewContext` but a method of a precompiled `Script` object.
`runInNewContext` contextifies sandbox if passed or creates a new contextified sandbox if it's omitted,
and then runs script's compiled code with the sandbox as the global object and returns the result.
Running code does not have access to local scope.
**/
@:overload(function(sandbox:{}, ?options:ScriptRunOptions):Dynamic {})
function runInNewContext(?sandbox:{}):Dynamic;
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.zlib;
/**
Compress data using deflate.
**/
@:jsRequire("zlib", "Deflate")
extern class Deflate extends Zlib {}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.zlib;
/**
Compress data using deflate, and do not append a zlib header.
**/
@:jsRequire("zlib", "DeflateRaw")
extern class DeflateRaw extends Zlib {}

View File

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

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.zlib;
/**
Compress data using gzip.
**/
@:jsRequire("zlib", "Gzip")
extern class Gzip extends Zlib {}

View File

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

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.zlib;
/**
Decompress a raw deflate stream.
**/
@:jsRequire("zlib", "InflateRaw")
extern class InflateRaw extends Zlib {}

View File

@ -0,0 +1,29 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.zlib;
/**
Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header.
**/
@:jsRequire("zlib", "Unzip")
extern class Unzip extends Zlib {}

View File

@ -0,0 +1,51 @@
/*
* Copyright (C)2014-2020 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package js.node.zlib;
/**
Not exported by the zlib module.
It is documented here because it is the base class of the compressor/decompressor classes.
**/
extern class Zlib extends js.node.stream.Transform<Zlib> {
/**
Flush pending data.
`kind` defaults to `Zlib.Z_FULL_FLUSH`.
Don't call this frivolously, premature flushes negatively impact the effectiveness of the compression algorithm.
**/
@:overload(function(kind:Int, callback:Void->Void):Void {})
function flush(callback:Void->Void):Void;
/**
Dynamically update the compression level and compression strategy.
Only applicable to deflate algorithm.
**/
function params(level:Int, strategy:Int, callback:Void->Void):Void;
/**
Reset the compressor/decompressor to factory defaults.
Only applicable to the inflate and deflate algorithms.
**/
function reset():Void;
}