New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

http4js

Package Overview
Dependencies
Maintainers
2
Versions
93
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

http4js - npm Package Compare versions

Comparing version 4.0.0 to 4.0.1

core/Body.ts

11

client/HttpClient.js

@@ -41,5 +41,5 @@ "use strict";

}
function wire(request) {
var options = request.uri.asNativeNodeRequest;
var requestOptions = __assign({}, options, { headers: request.headers, method: request.method });
function wire(req) {
var options = req.uri.asNativeNodeRequest;
var requestOptions = __assign({}, options, { headers: req.headers, method: req.method });
return new Promise(function (resolve) {

@@ -55,5 +55,8 @@ var clientRequest = http.request(requestOptions, function (res) {

});
clientRequest.write(request.bodyString());
console.log('client');
var chunk2 = req.bodyString();
console.log(chunk2);
clientRequest.write(chunk2);
clientRequest.end();
});
}

@@ -37,8 +37,8 @@ import * as http from "http";

function wire(request: Req): Promise<Res> {
const options = request.uri.asNativeNodeRequest;
function wire(req: Req): Promise<Res> {
const options = req.uri.asNativeNodeRequest;
const requestOptions = {
...options,
headers: request.headers,
method: request.method,
headers: req.headers,
method: req.method,
};

@@ -56,5 +56,8 @@

});
clientRequest.write(request.bodyString());
console.log('client');
const chunk2 = req.bodyString();
console.log(chunk2);
clientRequest.write(chunk2);
clientRequest.end();
});
}
import { Res } from "./Res";
import { Req } from "./Req";
import { Body } from "./Body";
export declare type KeyValues = {
[key: string]: string;
};
export declare type FormField = string | string[];
export declare type Form = {
[key: string]: string | string[];
[key: string]: FormField;
};

@@ -14,3 +16,3 @@ export declare type HeadersType = {

headers: HeadersType;
body: string;
body: Body;
header(name: string): string;

@@ -17,0 +19,0 @@ withHeader(name: string, value: string): HttpMessage;

import {Res} from "./Res";
import {Req} from "./Req";
import {Body} from "./Body";
export type KeyValues = {[key:string]: string};
export type Form = {[key:string]: string|string[]};
export type FormField = string|string[];
export type Form = {[key:string]: FormField};
export type HeadersType = {[key:string]: string};

@@ -11,3 +13,3 @@

headers: HeadersType;
body: string;
body: Body;

@@ -14,0 +16,0 @@ header(name: string): string;

@@ -0,1 +1,2 @@

/// <reference types="node" />
import { Uri } from "./Uri";

@@ -5,2 +6,5 @@ import { HttpMessage, HeadersType } from "./HttpMessage";

import { Form } from "./HttpMessage";
import { Body } from "./Body";
import { FormField } from "./HttpMessage";
import { Readable } from "stream";
export declare class Req implements HttpMessage {

@@ -10,11 +14,7 @@ uri: Uri;

headers: HeadersType;
body: string;
body: Body;
queries: KeyValues;
pathParams: KeyValues;
form: Form;
error?: {
status: string;
message: string;
};
constructor(method: string, uri: Uri | string, body?: string, headers?: {});
private form;
constructor(method: string, uri: Uri | string, body?: Body | string, headers?: {});
withUri(uri: Uri | string): Req;

@@ -25,13 +25,16 @@ header(name: string): string;

removeHeader(name: string): Req;
withBody(body: string): Req;
withBody(body: Body | Readable | string): Req;
withFormField(name: string, value: string | string[]): Req;
withForm(form: {}): Req;
withForm(form: Form): Req;
formField(name: string): FormField | undefined;
bodyString(): string;
formBodystring(): string;
bodyStream(): Readable;
bodyForm(): Form;
withQuery(name: string, value: string): Req;
withQueries(queries: KeyValues): Req;
query(name: string): string;
private formBodystring;
private getQueryParams;
private static clone;
}
export declare function ReqOf(method: string, uri: Uri | string, body?: string, headers?: {}): Req;
export declare function ReqOf(method: string, uri: Uri | string, body?: Body | string, headers?: {}): Req;

@@ -6,7 +6,7 @@ "use strict";

var Headers_1 = require("./Headers");
var Body_1 = require("./Body");
var Req = /** @class */ (function () {
function Req(method, uri, body, headers) {
if (body === void 0) { body = ""; }
if (body === void 0) { body = ''; }
if (headers === void 0) { headers = {}; }
var _this = this;
this.headers = {};

@@ -24,12 +24,5 @@ this.queries = {};

}
this.body = body;
this.body = typeof body === 'string' ? Body_1.BodyOf(body) : body;
this.headers = headers ? headers : {};
this.queries = this.getQueryParams();
if (this.method == "POST") {
this.body.split("&").map(function (kv) {
var pair = kv.split("=");
if (pair.length > 1)
_this.form[pair[0]] = pair[1];
});
}
return this;

@@ -43,4 +36,3 @@ }

Req.prototype.header = function (name) {
var request = Req.clone(this);
return request.headers[name.toLowerCase()];
return this.headers[name.toLowerCase()];
};

@@ -63,3 +55,3 @@ Req.prototype.withHeader = function (name, value) {

var request = Req.clone(this);
request.headers[name] = value;
request.headers[name.toLowerCase()] = value;
return request;

@@ -74,44 +66,63 @@ };

var request = Req.clone(this);
request.body = body;
request.body = body instanceof Body_1.Body ? body : Body_1.BodyOf(body);
return request;
};
Req.prototype.withFormField = function (name, value) {
var request = Req.clone(this);
if (!request.header(Headers_1.Headers.CONTENT_TYPE))
request.withHeader(Headers_1.Headers.CONTENT_TYPE, Headers_1.HeaderValues.FORM);
if (request.form[name]) {
typeof (request.form[name]) == "string"
? request.form[name] = [request.form[name], value]
: request.form[name].push(value);
var form = this.bodyForm();
if (form[name]) {
if (typeof form[name] === 'string') {
(typeof value === 'string')
? form[name] = [form[name], value]
: form[name] = [form[name]].concat(value);
}
else {
(typeof value === 'string')
? form[name] = form[name].concat([value])
: form[name] = form[name].concat(value);
}
}
else {
request.form[name] = value;
form[name] = value;
}
return request;
return this.withForm(form);
};
Req.prototype.withForm = function (form) {
var request = Req.clone(this);
if (!request.header(Headers_1.Headers.CONTENT_TYPE))
request.withHeader(Headers_1.Headers.CONTENT_TYPE, Headers_1.HeaderValues.FORM);
request.form = form;
return request;
var bodyForm = this.formBodystring(form);
var req = ReqOf(this.method, this.uri, bodyForm, this.headers);
if (!req.header(Headers_1.Headers.CONTENT_TYPE)) {
return req.withHeader(Headers_1.Headers.CONTENT_TYPE, Headers_1.HeaderValues.FORM);
}
return req;
};
Req.prototype.formField = function (name) {
return this.bodyForm()[name];
};
Req.prototype.bodyString = function () {
if (Object.keys(this.form).length > 0) {
return this.formBodystring();
return this.body.bodyString() || '';
};
Req.prototype.bodyStream = function () {
return this.body.bodyStream();
};
Req.prototype.bodyForm = function () {
var form = {};
if (this.bodyString() === '') {
return form;
}
else {
return this.body;
this.bodyString().split("&").map(function (keyvalue) {
var strings = keyvalue.split("=");
var name = strings[0];
var value = strings[1];
if (form[name]) {
typeof (form[name]) === "string"
? (form[name]) = [form[name], value]
: form[name].push(value);
}
else {
form[name] = value;
}
});
}
return form;
};
Req.prototype.formBodystring = function () {
var _this = this;
var reduce = Object.keys(this.form).reduce(function (bodyParts, field) {
typeof (_this.form[field]) === "object"
? _this.form[field].map(function (value) { return bodyParts.push(field + "=" + value); })
: bodyParts.push(field + "=" + _this.form[field]);
return bodyParts;
}, []);
return reduce.join("&");
};
Req.prototype.withQuery = function (name, value) {

@@ -135,2 +146,11 @@ var request = Req.clone(this);

};
Req.prototype.formBodystring = function (form) {
var reduce = Object.keys(form).reduce(function (bodyParts, field) {
typeof (form[field]) === "object"
? form[field].map(function (value) { return bodyParts.push(field + "=" + value); })
: bodyParts.push(field + "=" + form[field]);
return bodyParts;
}, []);
return reduce.join("&");
};
Req.prototype.getQueryParams = function () {

@@ -161,3 +181,3 @@ var _this = this;

function ReqOf(method, uri, body, headers) {
if (body === void 0) { body = ""; }
if (body === void 0) { body = ''; }
if (headers === void 0) { headers = {}; }

@@ -164,0 +184,0 @@ return new Req(method, uri, body, headers);

@@ -7,2 +7,5 @@ import {Uri} from "./Uri";

import {Form} from "./HttpMessage";
import {Body, BodyOf} from "./Body";
import {FormField} from "./HttpMessage";
import {Readable} from "stream";

@@ -14,11 +17,10 @@ export class Req implements HttpMessage {

headers: HeadersType = {};
body: string;
body: Body;
queries: KeyValues = {};
pathParams: KeyValues = {};
form: Form = {};
error?: {status: string, message: string};
private form: Form = {};
constructor(method: string,
uri: Uri | string,
body: string = "",
body: Body | string = '',
headers = {}) {

@@ -32,11 +34,5 @@ this.method = method.toUpperCase();

}
this.body = body;
this.body = typeof body === 'string' ? BodyOf(body) : body;
this.headers = headers ? headers : {};
this.queries = this.getQueryParams();
if (this.method == "POST") {
this.body.split("&").map(kv => {
const pair = kv.split("=");
if (pair.length > 1) this.form[pair[0]] = pair[1];
})
}
return this;

@@ -52,4 +48,3 @@ }

header(name: string): string {
const request = Req.clone(this);
return request.headers[name.toLowerCase()];
return this.headers[name.toLowerCase()];
}

@@ -72,3 +67,3 @@

const request = Req.clone(this);
request.headers[name] = value;
request.headers[name.toLowerCase()] = value;
return request;

@@ -83,5 +78,5 @@ }

withBody(body: string): Req {
withBody(body: Body | Readable | string): Req {
const request = Req.clone(this);
request.body = body;
request.body = body instanceof Body ? body : BodyOf(body);
return request;

@@ -91,39 +86,61 @@ }

withFormField(name: string, value: string | string[]): Req {
const request = Req.clone(this);
if (!request.header(Headers.CONTENT_TYPE)) request.withHeader(Headers.CONTENT_TYPE, HeaderValues.FORM);
if (request.form[name]) {
typeof (request.form[name]) == "string"
? request.form[name] = [request.form[name], value]
: request.form[name].push(value);
const form = this.bodyForm();
if (form[name]) {
if (typeof form[name] === 'string') {
(typeof value === 'string')
? form[name] = [form[name] as string, value as string]
: form[name] = [form[name] as string, ...value as string[]]
} else {
(typeof value === 'string')
? form[name] = [...form[name] as string[], value as string]
: form[name] = [...form[name] as string[], ...value as string[]]
}
} else {
request.form[name] = value;
form[name] = value;
}
return request;
return this.withForm(form)
}
withForm(form: {}): Req {
const request = Req.clone(this);
if (!request.header(Headers.CONTENT_TYPE)) request.withHeader(Headers.CONTENT_TYPE, HeaderValues.FORM);
request.form = form;
return request;
withForm(form: Form): Req {
const bodyForm = this.formBodystring(form);
const req = ReqOf(this.method, this.uri, bodyForm, this.headers);
if (!req.header(Headers.CONTENT_TYPE)) {
return req.withHeader(Headers.CONTENT_TYPE, HeaderValues.FORM);
}
return req;
}
formField(name: string): FormField | undefined {
return this.bodyForm()[name];
}
bodyString(): string {
if (Object.keys(this.form).length > 0) {
return this.formBodystring();
return this.body.bodyString() || '';
}
bodyStream(): Readable {
return this.body.bodyStream();
}
bodyForm(): Form {
const form: Form = {};
if (this.bodyString() === '') {
return form;
} else {
return this.body;
this.bodyString().split("&").map(keyvalue => {
const strings = keyvalue.split("=");
const name = strings[0];
const value = strings[1];
if (form[name]) {
typeof (form[name]) === "string"
? (form[name]) = [(form[name] as string), value]
: (form[name] as string[]).push(value);
} else {
form[name] = value;
}
});
}
return form;
}
formBodystring(): string {
let reduce: string[] = Object.keys(this.form).reduce((bodyParts: string[], field: string) => {
typeof (this.form[field]) === "object"
? (this.form[field] as string[]).map(value => bodyParts.push(`${field}=${value}`))
: bodyParts.push(`${field}=${this.form[field]}`);
return bodyParts;
}, []);
return reduce.join("&")
}
withQuery(name: string, value: string): Req {

@@ -150,2 +167,12 @@ const request = Req.clone(this);

private formBodystring(form: Form): string {
let reduce: string[] = Object.keys(form).reduce((bodyParts: string[], field: string) => {
typeof (form[field]) === "object"
? (form[field] as string[]).map(value => bodyParts.push(`${field}=${value}`))
: bodyParts.push(`${field}=${form[field]}`);
return bodyParts;
}, []);
return reduce.join("&");
}
private getQueryParams(): KeyValues {

@@ -174,5 +201,5 @@ if (isNullOrUndefined(this.uri.queryString())) return {};

uri: Uri | string,
body: string = "",
body: Body | string = '',
headers = {}): Req {
return new Req(method, uri, body, headers);
}
import { HttpMessage, HeadersType } from "./HttpMessage";
import { Body } from "./Body";
export declare class Res implements HttpMessage {
headers: HeadersType;
body: string;
body: Body;
status: number;
constructor(status?: number, body?: string, headers?: HeadersType);
constructor(status?: number, body?: Body | string, headers?: HeadersType);
header(name: string): string;

@@ -13,7 +14,7 @@ withHeader(name: string, value: string): Res;

removeHeader(name: string): Res;
withBody(body: string): Res;
withBody(body: Body | string): Res;
bodyString(): string;
private static clone;
}
export declare function ResOf(status?: number, body?: string, headers?: HeadersType): Res;
export declare function ResOf(status?: number, body?: Body | string, headers?: HeadersType): Res;
export declare function Redirect(status: number, path: string, headers?: HeadersType): Res;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Body_1 = require("./Body");
var Res = /** @class */ (function () {
function Res(status, body, headers) {
if (status === void 0) { status = 200; }
if (body === void 0) { body = ""; }
if (body === void 0) { body = ''; }
if (headers === void 0) { headers = {}; }
this.headers = {};
this.status = status;
this.body = body;
this.body = typeof body === 'string' ? Body_1.BodyOf(body) : body;
this.headers = headers;

@@ -52,7 +53,7 @@ }

var response = Res.clone(this);
response.body = body;
response.body = typeof body === 'string' ? Body_1.BodyOf(body) : body;
return response;
};
Res.prototype.bodyString = function () {
return this.body;
return this.body.bodyString() || '';
};

@@ -67,5 +68,6 @@ Res.clone = function (a) {

if (status === void 0) { status = 200; }
if (body === void 0) { body = ""; }
if (body === void 0) { body = ''; }
if (headers === void 0) { headers = {}; }
return new Res(status, body, headers);
var wrappedBody = typeof body === 'string' ? Body_1.BodyOf(body) : body;
return new Res(status, wrappedBody, headers);
}

@@ -76,4 +78,4 @@ exports.ResOf = ResOf;

if (headers === void 0) { headers = {}; }
return new Res(status, "", headers).withHeader("Location", path);
return new Res(status, Body_1.BodyOf(''), headers).withHeader("Location", path);
}
exports.Redirect = Redirect;
import {HttpMessage, HeadersType} from "./HttpMessage";
import {Body} from "./Body";
import {BodyOf} from "./Body";
export class Res implements HttpMessage {
headers: HeadersType = {};
body: string;
body: Body;
status: number;
constructor(status: number = 200, body: string = "", headers: HeadersType = {}) {
constructor(status: number = 200, body: Body | string = '', headers: HeadersType = {}) {
this.status = status;
this.body = body;
this.body = typeof body === 'string' ? BodyOf(body) : body;
this.headers = headers;

@@ -55,5 +57,5 @@ }

withBody(body: string): Res {
withBody(body: Body | string): Res {
const response = Res.clone(this);
response.body = body;
response.body = typeof body === 'string' ? BodyOf(body) : body;
return response;

@@ -63,3 +65,3 @@ }

bodyString(): string {
return this.body;
return this.body.bodyString() || '';
}

@@ -73,9 +75,10 @@

export function ResOf(status: number = 200, body: string = "", headers: HeadersType = {}): Res {
return new Res(status, body, headers);
export function ResOf(status: number = 200, body: Body | string = '', headers: HeadersType = {}): Res {
const wrappedBody = typeof body === 'string' ? BodyOf(body) : body;
return new Res(status, wrappedBody, headers);
}
export function Redirect(status: number = 301, path: string, headers: HeadersType = {}): Res {
return new Res(status, "", headers).withHeader("Location", path);
return new Res(status, BodyOf(''), headers).withHeader("Location", path);
}

@@ -130,3 +130,4 @@ "use strict";

var matchedHandler = match.handler || this.mountedNotFoundHandler;
if (matchedHandler.path.includes("{"))
var hasPathParam = matchedHandler.path.includes("{");
if (hasPathParam)
req.pathParams = Uri_1.Uri.of(matchedHandler.path).extract(req.uri.path()).matches;

@@ -133,0 +134,0 @@ var filtered = match.routing.filters.reduce(function (prev, next) {

@@ -82,4 +82,4 @@ import {Res} from "./Res";

const matchedHandler = match.handler || this.mountedNotFoundHandler;
if (matchedHandler.path.includes("{"))
req.pathParams = Uri.of(matchedHandler.path).extract(req.uri.path()).matches;
const hasPathParam = matchedHandler.path.includes("{");
if (hasPathParam) req.pathParams = Uri.of(matchedHandler.path).extract(req.uri.path()).matches;
const filtered = match.routing.filters.reduce((prev, next) => {

@@ -86,0 +86,0 @@ return next(prev)

{
"name": "http4js",
"version": "4.0.0",
"version": "4.0.1",
"description": "A lightweight HTTP toolkit",

@@ -9,3 +9,3 @@ "main": "dist/index.js",

"build": "tsc",
"test": "mocha --require ts-node/register 'src/test/**/*.ts'",
"test": "tsc; mocha --require ts-node/register 'src/test/**/*.ts'",
"test-ssl": "tsc; mocha --require ts-node/register 'src/ssl/**/*.ts'",

@@ -25,5 +25,6 @@ "start": "ts-node src/main/index.ts"

"devDependencies": {
"@types/express": "4.16.0",
"@types/koa": "2.0.46",
"@types/mocha": "2.2.47",
"@types/node": "9.4.0",
"@types/node-fetch": "2.1.2",
"body-parser": "1.18.2",

@@ -30,0 +31,0 @@ "express": "4.16.3",

@@ -127,2 +127,6 @@ # http4js

- streaming
- extract building up form when asked for form() or formField()
- servers
- clients
- withOptions

@@ -132,3 +136,2 @@ - convenience response methods eg ok()

- chain withHeaders calls on an http client
- streaming
- client side httpclient (from stu)

@@ -135,0 +138,0 @@ - update example app

@@ -12,3 +12,2 @@ import { Routing } from "../core/Routing";

stop(): Promise<void>;
private createInMemResponse;
}

@@ -39,4 +39,5 @@ "use strict";

var http = require("http");
var stream_1 = require("stream");
var Body_1 = require("../core/Body");
var Req_1 = require("../core/Req");
var Headers_1 = require("../core/Headers");
var NativeHttpServer = /** @class */ (function () {

@@ -53,2 +54,3 @@ function NativeHttpServer(port) {

var headers = req.headers, method = req.method, url = req.url;
var inStream = new stream_1.Readable({ read: function () { } });
var hostHeader = req.headers.host;

@@ -59,9 +61,10 @@ var isLocalhost = req.socket.localAddress === '::ffff:127.0.0.1';

: (isLocalhost ? "http://localhost:" + req.socket.localPort : '');
var chunks = [];
req.on('error', function (err) {
console.error(err);
}).on('data', function (chunk) {
chunks.push(chunk);
inStream.push(chunk);
}).on('end', function () {
var response = _this.createInMemResponse(chunks, method, "" + hostname + url, headers);
inStream.push(null); // No more data
var req = Req_1.ReqOf(method, "" + hostname + url, Body_1.BodyOf(inStream), headers);
var response = _this.routing.serve(req);
response.then(function (response) {

@@ -90,25 +93,4 @@ res.writeHead(response.status, response.headers);

};
NativeHttpServer.prototype.createInMemResponse = function (chunks, method, url, headers) {
var body = Buffer.concat(chunks).toString();
var form = {};
if (headers['content-type'] == Headers_1.HeaderValues.FORM) {
body.split("&").map(function (keyvalue) {
var strings = keyvalue.split("=");
var name = strings[0];
var value = strings[1];
if (form[name]) {
typeof (form[name]) === "string"
? (form[name]) = [form[name], value]
: form[name].push(value);
}
else {
form[name] = value;
}
});
}
var inMemRequest = new Req_1.Req(method, url, body, headers).withForm(form);
return this.routing.serve(inMemRequest);
};
return NativeHttpServer;
}());
exports.NativeHttpServer = NativeHttpServer;

@@ -8,2 +8,6 @@ import * as http from "http";

import {Form, HeadersType} from "../core/HttpMessage";
import { Readable } from 'stream';
import {Stream} from "stream";
import {BodyOf} from "../core/Body";
import {ReqOf} from "../core/Req";

@@ -25,2 +29,3 @@ export class NativeHttpServer implements Http4jsServer {

const {headers, method, url} = req;
const inStream = new Readable({ read() {} });
const hostHeader = req.headers.host;

@@ -31,9 +36,11 @@ const isLocalhost = req.socket.localAddress === '::ffff:127.0.0.1';

: (isLocalhost ? `http://localhost:${req.socket.localPort}` : '');
const chunks: Buffer[] = [];
req.on('error', (err: any) => {
console.error(err);
}).on('data', (chunk: Buffer) => {
chunks.push(chunk);
inStream.push(chunk);
}).on('end', () => {
const response = this.createInMemResponse(chunks, method, `${hostname}${url}`, headers);
inStream.push(null); // No more data
const req = ReqOf(method, `${hostname}${url}`, BodyOf(inStream), headers);
const response = this.routing.serve(req);
response.then(response => {

@@ -55,23 +62,2 @@ res.writeHead(response.status, response.headers);

private createInMemResponse(chunks: Buffer[], method: string, url: string, headers: HeadersType): Promise<Res> {
const body = Buffer.concat(chunks).toString();
const form: Form = {};
if (headers['content-type'] == HeaderValues.FORM) {
body.split("&").map(keyvalue => {
const strings = keyvalue.split("=");
const name = strings[0];
const value = strings[1];
if (form[name]) {
typeof (form[name]) === "string"
? (form[name]) = [(form[name] as string), value]
: (form[name] as string[]).push(value);
} else {
form[name] = value;
}
})
}
const inMemRequest = new Req(method, url, body, headers).withForm(form);
return this.routing.serve(inMemRequest);
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc